devtrace-cli 1.0.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,96 @@
1
+ """Evidence-grounded AI explainer using OpenAI-compatible or local Ollama endpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import urllib.error
8
+ import urllib.request
9
+ from typing import Any
10
+
11
+ from devtrace.core.diagnostics import DiagnosticReport
12
+
13
+ DEFAULT_BASE_URL = "http://localhost:11434/v1"
14
+ DEFAULT_MODEL = "llama3.2"
15
+
16
+
17
+ def build_grounded_prompt(
18
+ snapshot: dict[str, Any],
19
+ diagnostics: DiagnosticReport,
20
+ error_text: str | None = None,
21
+ ) -> str:
22
+ """Construct a strictly evidence-bounded prompt for root-cause explanation."""
23
+ evidence_bundle = {
24
+ "system": snapshot.get("system"),
25
+ "runtimes": snapshot.get("runtimes"),
26
+ "project": snapshot.get("project"),
27
+ "dependencies": snapshot.get("dependencies"),
28
+ "deterministic_findings": diagnostics.to_dict().get("findings", []),
29
+ }
30
+ truncated_error = (error_text or "")[:3000]
31
+
32
+ return (
33
+ "You are DevTrace AI, a cautious developer diagnostics assistant.\n"
34
+ "RULES:\n"
35
+ "1. Rely ONLY on the structured JSON evidence and error excerpt below.\n"
36
+ "2. Cite specific rule_ids or snapshot fields for every claim.\n"
37
+ "3. Do NOT invent missing packages or assume causation without evidence.\n"
38
+ "4. Provide: (a) Probable Root Cause, (b) Exact Verification/Fix Commands, "
39
+ "and (c) Uncertainty / Caveats.\n\n"
40
+ f"=== DETERMINISTIC SNAPSHOT & FINDINGS ===\n"
41
+ f"{json.dumps(evidence_bundle, indent=2)}\n\n"
42
+ f"=== ERROR LOG EXCERPT ===\n"
43
+ f"{truncated_error or 'No error log provided.'}\n"
44
+ )
45
+
46
+
47
+ def request_ai_explanation(
48
+ prompt: str,
49
+ model: str | None = None,
50
+ base_url: str | None = None,
51
+ api_key: str | None = None,
52
+ timeout_seconds: float = 30.0,
53
+ ) -> str:
54
+ """Send grounded diagnostic prompt to an OpenAI-compatible or local Ollama API."""
55
+ resolved_url = (base_url or os.getenv("DEVTRACE_AI_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
56
+ resolved_model = model or os.getenv("DEVTRACE_AI_MODEL") or DEFAULT_MODEL
57
+ resolved_key = api_key or os.getenv("DEVTRACE_AI_API_KEY") or "ollama"
58
+
59
+ endpoint = f"{resolved_url}/chat/completions"
60
+ payload = {
61
+ "model": resolved_model,
62
+ "temperature": 0.1,
63
+ "messages": [
64
+ {
65
+ "role": "system",
66
+ "content": (
67
+ "You explain environment diagnostics strictly from provided JSON evidence."
68
+ ),
69
+ },
70
+ {"role": "user", "content": prompt},
71
+ ],
72
+ }
73
+
74
+ req = urllib.request.Request(
75
+ endpoint,
76
+ data=json.dumps(payload).encode("utf-8"),
77
+ headers={
78
+ "Content-Type": "application/json",
79
+ "Authorization": f"Bearer {resolved_key}",
80
+ },
81
+ method="POST",
82
+ )
83
+
84
+ try:
85
+ with urllib.request.urlopen(req, timeout=timeout_seconds) as resp:
86
+ body = json.loads(resp.read().decode("utf-8"))
87
+ except urllib.error.URLError as exc:
88
+ raise RuntimeError(
89
+ f"Could not reach AI endpoint at {endpoint}. "
90
+ "Start local Ollama or set DEVTRACE_AI_BASE_URL and DEVTRACE_AI_API_KEY."
91
+ ) from exc
92
+
93
+ choices = body.get("choices", [])
94
+ if not choices:
95
+ raise RuntimeError("AI endpoint returned an empty response.")
96
+ return str(choices[0].get("message", {}).get("content", "")).strip()
@@ -0,0 +1,62 @@
1
+ """Capture orchestrator for system, runtime, project, and dependency collectors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from devtrace.collectors.node_deps import collect_node_dependencies
8
+ from devtrace.collectors.node_runtime import collect_node_runtime
9
+ from devtrace.collectors.python_deps import collect_python_dependencies
10
+ from devtrace.collectors.python_runtime import collect_python_runtime
11
+ from devtrace.collectors.system import collect_system_info
12
+ from devtrace.core.models import (
13
+ DependenciesInfo,
14
+ EnvironmentSnapshot,
15
+ RuntimesInfo,
16
+ )
17
+ from devtrace.project.detector import detect_project_info
18
+
19
+
20
+ def capture_environment(
21
+ project_dir: Path,
22
+ tag: str | None = None,
23
+ ) -> EnvironmentSnapshot:
24
+ """Capture a complete, structured snapshot of the development environment."""
25
+ resolved_project = project_dir.resolve()
26
+ project_info, project_warnings = detect_project_info(resolved_project)
27
+
28
+ system_info, system_warnings = collect_system_info()
29
+ python_info, python_warnings = collect_python_runtime()
30
+ node_info, node_warnings = collect_node_runtime()
31
+
32
+ has_python = "python" in project_info.detected_languages
33
+ has_node = "node" in project_info.detected_languages
34
+
35
+ py_deps, py_dep_warnings = collect_python_dependencies(resolved_project, has_python)
36
+ node_deps, node_dep_warnings = collect_node_dependencies(resolved_project, has_node)
37
+
38
+ all_warnings = [
39
+ *project_warnings,
40
+ *system_warnings,
41
+ *python_warnings,
42
+ *node_warnings,
43
+ *py_dep_warnings,
44
+ *node_dep_warnings,
45
+ ]
46
+
47
+ cleaned_tag = tag.strip() if tag and tag.strip() else None
48
+
49
+ return EnvironmentSnapshot(
50
+ system=system_info,
51
+ runtimes=RuntimesInfo(
52
+ python=python_info,
53
+ node=node_info,
54
+ ),
55
+ project=project_info,
56
+ dependencies=DependenciesInfo(
57
+ python=py_deps,
58
+ node=node_deps,
59
+ ),
60
+ tag=cleaned_tag,
61
+ collection_warnings=all_warnings,
62
+ )
@@ -0,0 +1,199 @@
1
+ """Deterministic snapshot comparison engine for DevTrace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict, dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class FieldChange:
13
+ """Represents a single value change between two snapshots."""
14
+
15
+ field: str
16
+ left: Any
17
+ right: Any
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class EcosystemDiff:
22
+ """Dependency differences for a single language ecosystem."""
23
+
24
+ added_installed: dict[str, str] = field(default_factory=dict)
25
+ removed_installed: dict[str, str] = field(default_factory=dict)
26
+ changed_installed: dict[str, dict[str, str]] = field(default_factory=dict)
27
+ declared_changes: dict[str, dict[str, str | None]] = field(default_factory=dict)
28
+ missing_from_env_left: list[str] = field(default_factory=list)
29
+ missing_from_env_right: list[str] = field(default_factory=list)
30
+
31
+ def has_differences(self) -> bool:
32
+ """Return True if any dependency difference exists."""
33
+ return bool(
34
+ self.added_installed
35
+ or self.removed_installed
36
+ or self.changed_installed
37
+ or self.declared_changes
38
+ or self.missing_from_env_left != self.missing_from_env_right
39
+ )
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class SnapshotComparison:
44
+ """Structured diff between two DevTrace environment snapshots."""
45
+
46
+ left_snapshot_id: str
47
+ right_snapshot_id: str
48
+ schema_version: str
49
+ system_changes: list[FieldChange] = field(default_factory=list)
50
+ runtime_changes: list[FieldChange] = field(default_factory=list)
51
+ project_changes: list[FieldChange] = field(default_factory=list)
52
+ python_dependencies: EcosystemDiff = field(default_factory=EcosystemDiff)
53
+ node_dependencies: EcosystemDiff = field(default_factory=EcosystemDiff)
54
+
55
+ def has_differences(self) -> bool:
56
+ """Return True if any meaningful difference was found."""
57
+ return bool(
58
+ self.system_changes
59
+ or self.runtime_changes
60
+ or self.project_changes
61
+ or self.python_dependencies.has_differences()
62
+ or self.node_dependencies.has_differences()
63
+ )
64
+
65
+ def to_dict(self) -> dict[str, Any]:
66
+ """Convert comparison result into a plain JSON-serializable dict."""
67
+ return asdict(self)
68
+
69
+
70
+ def load_snapshot_file(path: Path) -> dict[str, Any]:
71
+ """Load and validate basic structure of a DevTrace snapshot JSON file."""
72
+ if not path.exists():
73
+ raise FileNotFoundError(f"Snapshot file not found: {path}")
74
+ if not path.is_file():
75
+ raise ValueError(f"Snapshot path is not a file: {path}")
76
+
77
+ try:
78
+ data = json.loads(path.read_text(encoding="utf-8"))
79
+ except (OSError, json.JSONDecodeError) as exc:
80
+ raise ValueError(f"Invalid JSON in snapshot {path}: {exc}") from exc
81
+
82
+ if not isinstance(data, dict) or "schema_version" not in data:
83
+ raise ValueError(f"File is not a valid DevTrace snapshot: {path}")
84
+ return data
85
+
86
+
87
+ def _diff_ecosystem(left_eco: dict[str, Any], right_eco: dict[str, Any]) -> EcosystemDiff:
88
+ """Compute dependency differences for one language ecosystem."""
89
+ left_inst: dict[str, str] = left_eco.get("installed", {}) or {}
90
+ right_inst: dict[str, str] = right_eco.get("installed", {}) or {}
91
+
92
+ left_keys = set(left_inst.keys())
93
+ right_keys = set(right_inst.keys())
94
+
95
+ added = {k: right_inst[k] for k in sorted(right_keys - left_keys)}
96
+ removed = {k: left_inst[k] for k in sorted(left_keys - right_keys)}
97
+ changed = {
98
+ k: {"left": left_inst[k], "right": right_inst[k]}
99
+ for k in sorted(left_keys & right_keys)
100
+ if left_inst[k] != right_inst[k]
101
+ }
102
+
103
+ left_decl: dict[str, str] = left_eco.get("declared", {}) or {}
104
+ right_decl: dict[str, str] = right_eco.get("declared", {}) or {}
105
+ all_decl_keys = sorted(set(left_decl.keys()) | set(right_decl.keys()))
106
+ decl_changes = {
107
+ k: {"left": left_decl.get(k), "right": right_decl.get(k)}
108
+ for k in all_decl_keys
109
+ if left_decl.get(k) != right_decl.get(k)
110
+ }
111
+
112
+ return EcosystemDiff(
113
+ added_installed=added,
114
+ removed_installed=removed,
115
+ changed_installed=changed,
116
+ declared_changes=decl_changes,
117
+ missing_from_env_left=list(left_eco.get("missing_from_env", []) or []),
118
+ missing_from_env_right=list(right_eco.get("missing_from_env", []) or []),
119
+ )
120
+
121
+
122
+ def compare_snapshots(
123
+ left: dict[str, Any],
124
+ right: dict[str, Any],
125
+ ) -> SnapshotComparison:
126
+ """Compare two loaded DevTrace snapshot dictionaries."""
127
+ left_schema = str(left.get("schema_version", ""))
128
+ right_schema = str(right.get("schema_version", ""))
129
+ if left_schema != right_schema:
130
+ raise ValueError(f"Incompatible snapshot schema versions: {left_schema} vs {right_schema}")
131
+
132
+ system_changes: list[FieldChange] = []
133
+ left_sys = left.get("system", {}) or {}
134
+ right_sys = right.get("system", {}) or {}
135
+ for key in ("os", "os_release", "architecture"):
136
+ if left_sys.get(key) != right_sys.get(key):
137
+ system_changes.append(
138
+ FieldChange(
139
+ field=f"system.{key}",
140
+ left=left_sys.get(key),
141
+ right=right_sys.get(key),
142
+ )
143
+ )
144
+
145
+ runtime_changes: list[FieldChange] = []
146
+ left_rt = left.get("runtimes", {}) or {}
147
+ right_rt = right.get("runtimes", {}) or {}
148
+ for lang in ("python", "node"):
149
+ l_info = left_rt.get(lang, {}) or {}
150
+ r_info = right_rt.get(lang, {}) or {}
151
+ if l_info.get("available") != r_info.get("available"):
152
+ runtime_changes.append(
153
+ FieldChange(
154
+ field=f"runtimes.{lang}.available",
155
+ left=l_info.get("available"),
156
+ right=r_info.get(lang, {}).get("available"),
157
+ )
158
+ )
159
+ if l_info.get("version") != r_info.get("version"):
160
+ runtime_changes.append(
161
+ FieldChange(
162
+ field=f"runtimes.{lang}.version",
163
+ left=l_info.get("version"),
164
+ right=r_info.get("version"),
165
+ )
166
+ )
167
+
168
+ project_changes: list[FieldChange] = []
169
+ left_proj = left.get("project", {}) or {}
170
+ right_proj = right.get("project", {}) or {}
171
+ for key in ("detected_languages", "metadata_files"):
172
+ if left_proj.get(key) != right_proj.get(key):
173
+ project_changes.append(
174
+ FieldChange(
175
+ field=f"project.{key}",
176
+ left=left_proj.get(key),
177
+ right=right_proj.get(key),
178
+ )
179
+ )
180
+
181
+ left_deps = left.get("dependencies", {}) or {}
182
+ right_deps = right.get("dependencies", {}) or {}
183
+
184
+ return SnapshotComparison(
185
+ left_snapshot_id=str(left.get("snapshot_id", "unknown")),
186
+ right_snapshot_id=str(right.get("snapshot_id", "unknown")),
187
+ schema_version=left_schema,
188
+ system_changes=system_changes,
189
+ runtime_changes=runtime_changes,
190
+ project_changes=project_changes,
191
+ python_dependencies=_diff_ecosystem(
192
+ left_deps.get("python", {}) or {},
193
+ right_deps.get("python", {}) or {},
194
+ ),
195
+ node_dependencies=_diff_ecosystem(
196
+ left_deps.get("node", {}) or {},
197
+ right_deps.get("node", {}) or {},
198
+ ),
199
+ )
@@ -0,0 +1,216 @@
1
+ """Deterministic, evidence-based diagnostic rule engine for DevTrace."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import asdict, dataclass, field
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class DiagnosticFinding:
13
+ """Single evidence-backed diagnostic finding."""
14
+
15
+ rule_id: str
16
+ severity: str # "error" | "warning" | "info"
17
+ title: str
18
+ explanation: str
19
+ evidence: list[str]
20
+ next_check: str
21
+ uncertainty: str
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class DiagnosticReport:
26
+ """Collection of deterministic findings for a snapshot and optional error log."""
27
+
28
+ snapshot_id: str
29
+ error_file_analyzed: bool
30
+ findings: list[DiagnosticFinding] = field(default_factory=list)
31
+
32
+ def to_dict(self) -> dict[str, Any]:
33
+ """Convert report into a JSON-serializable dictionary."""
34
+ return asdict(self)
35
+
36
+
37
+ _PY_MISSING_MOD_RE = re.compile(
38
+ r"(?:ModuleNotFoundError|ImportError):\s+No module named ['\"]([^'\"]+)['\"]"
39
+ )
40
+ _NODE_MISSING_MOD_RE = re.compile(r"Error:\s+Cannot find module ['\"]([^'\"./][^'\"]*)['\"]")
41
+
42
+
43
+ def _normalize_py(name: str) -> str:
44
+ return re.sub(r"[-_.]+", "-", name).lower().strip()
45
+
46
+
47
+ def run_diagnostics(
48
+ snapshot: dict[str, Any],
49
+ error_text: str | None = None,
50
+ ) -> DiagnosticReport:
51
+ """Evaluate deterministic diagnostic rules against a snapshot and error text."""
52
+ findings: list[DiagnosticFinding] = []
53
+ deps = snapshot.get("dependencies", {}) or {}
54
+ py_deps = deps.get("python", {}) or {}
55
+ node_deps = deps.get("node", {}) or {}
56
+
57
+ py_missing: list[str] = list(py_deps.get("missing_from_env", []) or [])
58
+ py_undeclared: list[str] = list(py_deps.get("undeclared_in_manifest", []) or [])
59
+ py_installed: dict[str, str] = dict(py_deps.get("installed", {}) or {})
60
+
61
+ node_missing: list[str] = list(node_deps.get("missing_from_env", []) or [])
62
+ node_undeclared: list[str] = list(node_deps.get("undeclared_in_manifest", []) or [])
63
+ node_installed: dict[str, str] = dict(node_deps.get("installed", {}) or {})
64
+
65
+ # Rule ENV-PY-001: Python dependencies declared in manifest but not installed
66
+ if py_missing:
67
+ findings.append(
68
+ DiagnosticFinding(
69
+ rule_id="ENV-PY-001",
70
+ severity="error",
71
+ title="Declared Python dependencies missing from active environment",
72
+ explanation=(
73
+ "One or more packages declared in Python project manifests "
74
+ "were not found in the active Python environment."
75
+ ),
76
+ evidence=[f"Missing packages: {', '.join(py_missing)}"],
77
+ next_check="Activate the intended virtualenv and install project dependencies.",
78
+ uncertainty=(
79
+ "A missing package is a likely cause of import failures, "
80
+ "though optional extras may not be required for all workflows."
81
+ ),
82
+ )
83
+ )
84
+
85
+ # Rule ENV-PY-002: Silent Python drift (installed locally, missing in manifest)
86
+ if py_undeclared:
87
+ findings.append(
88
+ DiagnosticFinding(
89
+ rule_id="ENV-PY-002",
90
+ severity="warning",
91
+ title="Undeclared Python packages installed in active environment",
92
+ explanation=(
93
+ "Packages exist in the active Python environment that are not "
94
+ "declared in pyproject.toml or requirements.txt."
95
+ ),
96
+ evidence=[f"Undeclared packages: {', '.join(py_undeclared)}"],
97
+ next_check=(
98
+ "Verify whether these are transitive dependencies or missing "
99
+ "from your manifest before sharing with teammates."
100
+ ),
101
+ uncertainty=(
102
+ "Transitive dependencies installed by pip often appear here "
103
+ "and do not necessarily indicate a bug."
104
+ ),
105
+ )
106
+ )
107
+
108
+ # Rule ENV-NODE-001: Node dependencies declared in package.json but absent
109
+ if node_missing:
110
+ findings.append(
111
+ DiagnosticFinding(
112
+ rule_id="ENV-NODE-001",
113
+ severity="error",
114
+ title="Declared Node.js dependencies missing from node_modules",
115
+ explanation=(
116
+ "Packages declared in package.json were not found in local node_modules."
117
+ ),
118
+ evidence=[f"Missing Node packages: {', '.join(node_missing)}"],
119
+ next_check="Run your Node package manager install command (e.g., npm ci).",
120
+ uncertainty=(
121
+ "If dependencies are hoisted in a monorepo root, local "
122
+ "node_modules may intentionally omit them."
123
+ ),
124
+ )
125
+ )
126
+
127
+ # Rule ENV-NODE-002: Silent Node drift
128
+ if node_undeclared:
129
+ findings.append(
130
+ DiagnosticFinding(
131
+ rule_id="ENV-NODE-002",
132
+ severity="warning",
133
+ title="Undeclared packages present in node_modules",
134
+ explanation=(
135
+ "Top-level directories in node_modules do not match "
136
+ "dependencies in package.json."
137
+ ),
138
+ evidence=[f"Undeclared Node packages: {', '.join(node_undeclared)}"],
139
+ next_check="Check package-lock.json consistency or prune unused modules.",
140
+ uncertainty="Hoisted or local linked packages may be intentional.",
141
+ )
142
+ )
143
+
144
+ # Error-log rules (if crash/stack-trace text is provided)
145
+ if error_text:
146
+ for raw_mod in sorted(set(_PY_MISSING_MOD_RE.findall(error_text))):
147
+ top_pkg = _normalize_py(raw_mod.split(".")[0])
148
+ in_env = top_pkg in py_installed
149
+ findings.append(
150
+ DiagnosticFinding(
151
+ rule_id="ERR-PY-IMPORT",
152
+ severity="error",
153
+ title=f"Python import failure for module '{raw_mod}'",
154
+ explanation=(
155
+ f"Stack trace reports missing module '{raw_mod}'. "
156
+ f"Top-level package '{top_pkg}' installed in snapshot: {in_env}."
157
+ ),
158
+ evidence=[
159
+ f"Trace match: No module named '{raw_mod}'",
160
+ f"Snapshot python.installed['{top_pkg}']: "
161
+ f"{py_installed.get(top_pkg, 'not installed')}",
162
+ ],
163
+ next_check=(
164
+ f"Ensure '{top_pkg}' is installed in the same Python interpreter "
165
+ "used to run the failing command."
166
+ ),
167
+ uncertainty=(
168
+ "Import name and PyPI distribution name can differ "
169
+ "(e.g., 'cv2' vs 'opencv-python')."
170
+ ),
171
+ )
172
+ )
173
+
174
+ for raw_node_mod in sorted(set(_NODE_MISSING_MOD_RE.findall(error_text))):
175
+ pkg_name = (
176
+ "/".join(raw_node_mod.split("/")[:2])
177
+ if raw_node_mod.startswith("@")
178
+ else raw_node_mod.split("/")[0]
179
+ )
180
+ in_node = pkg_name in node_installed
181
+ findings.append(
182
+ DiagnosticFinding(
183
+ rule_id="ERR-NODE-MODULE",
184
+ severity="error",
185
+ title=f"Node.js module resolution failure for '{raw_node_mod}'",
186
+ explanation=(
187
+ f"Error log reports missing module '{raw_node_mod}'. "
188
+ f"Package '{pkg_name}' in node_modules: {in_node}."
189
+ ),
190
+ evidence=[
191
+ f"Trace match: Cannot find module '{raw_node_mod}'",
192
+ f"Snapshot node.installed['{pkg_name}']: "
193
+ f"{node_installed.get(pkg_name, 'not installed')}",
194
+ ],
195
+ next_check=f"Install '{pkg_name}' or verify NODE_PATH resolution.",
196
+ uncertainty="Path aliases or workspace symlinks may affect resolution.",
197
+ )
198
+ )
199
+
200
+ return DiagnosticReport(
201
+ snapshot_id=str(snapshot.get("snapshot_id", "unknown")),
202
+ error_file_analyzed=error_text is not None,
203
+ findings=findings,
204
+ )
205
+
206
+
207
+ def load_error_file(path: Path) -> str:
208
+ """Safely read an error log or stack-trace text file."""
209
+ if not path.exists():
210
+ raise FileNotFoundError(f"Error log file not found: {path}")
211
+ if not path.is_file():
212
+ raise ValueError(f"Error log path is not a file: {path}")
213
+ try:
214
+ return path.read_text(encoding="utf-8", errors="replace")
215
+ except OSError as exc:
216
+ raise ValueError(f"Could not read error log {path}: {exc}") from exc