continuum-toolkit 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.
Files changed (72) hide show
  1. cli/__init__.py +12 -0
  2. cli/main.py +415 -0
  3. confidence/__init__.py +13 -0
  4. confidence/calculator.py +308 -0
  5. confidence/models.py +40 -0
  6. context/__init__.py +17 -0
  7. context/models.py +108 -0
  8. context/pruner.py +228 -0
  9. context/selector.py +193 -0
  10. continuum_toolkit-1.0.0.dist-info/METADATA +511 -0
  11. continuum_toolkit-1.0.0.dist-info/RECORD +72 -0
  12. continuum_toolkit-1.0.0.dist-info/WHEEL +5 -0
  13. continuum_toolkit-1.0.0.dist-info/entry_points.txt +2 -0
  14. continuum_toolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
  15. continuum_toolkit-1.0.0.dist-info/top_level.txt +13 -0
  16. contradictions/__init__.py +19 -0
  17. contradictions/detector.py +442 -0
  18. contradictions/models.py +75 -0
  19. core/__init__.py +97 -0
  20. core/enums.py +130 -0
  21. core/evidence.py +117 -0
  22. core/interfaces.py +209 -0
  23. core/schema.py +391 -0
  24. core/serializer.py +84 -0
  25. core/state_models.py +530 -0
  26. daemon/__init__.py +12 -0
  27. daemon/service.py +170 -0
  28. extractors/__init__.py +51 -0
  29. extractors/base.py +117 -0
  30. extractors/config/parsers.py +288 -0
  31. extractors/config/secret_sanitizer.py +91 -0
  32. extractors/config_extractor.py +172 -0
  33. extractors/conversation/analyzers.py +193 -0
  34. extractors/conversation/models.py +148 -0
  35. extractors/conversation_extractor.py +166 -0
  36. extractors/git_extractor.py +305 -0
  37. extractors/parsers/base.py +91 -0
  38. extractors/parsers/comment_parser.py +51 -0
  39. extractors/parsers/js_ts_parser.py +171 -0
  40. extractors/parsers/python_parser.py +180 -0
  41. extractors/verification/runners.py +278 -0
  42. extractors/verification_extractor.py +263 -0
  43. extractors/workspace_extractor.py +221 -0
  44. graph/__init__.py +24 -0
  45. graph/diff.py +109 -0
  46. graph/manager.py +473 -0
  47. graph/models.py +62 -0
  48. graph/propagator.py +194 -0
  49. graph/query.py +86 -0
  50. graph/snapshot.py +85 -0
  51. handoff/__init__.py +28 -0
  52. handoff/adapters/__init__.py +45 -0
  53. handoff/adapters/base.py +90 -0
  54. handoff/adapters/claude_adapter.py +176 -0
  55. handoff/adapters/codex_gpt_adapter.py +151 -0
  56. handoff/adapters/gemini_adapter.py +151 -0
  57. handoff/adapters/local_model_adapter.py +130 -0
  58. handoff/models.py +88 -0
  59. handoff/packager.py +288 -0
  60. pipeline/__init__.py +9 -0
  61. pipeline/orchestrator.py +260 -0
  62. resolution/__init__.py +15 -0
  63. resolution/resolver.py +311 -0
  64. storage/__init__.py +18 -0
  65. storage/hooks.py +125 -0
  66. storage/manager.py +127 -0
  67. storage/models.py +39 -0
  68. storage/recovery.py +98 -0
  69. watcher/__init__.py +17 -0
  70. watcher/detector.py +136 -0
  71. watcher/models.py +62 -0
  72. watcher/updater.py +163 -0
@@ -0,0 +1,171 @@
1
+ """
2
+ Project Continuum - JavaScript & TypeScript Source Parser
3
+ =========================================================
4
+ Extracts classes, interfaces, types, functions, arrow functions,
5
+ imports, exports, and comments from JS/TS/JSX/TSX files.
6
+ """
7
+
8
+ import re
9
+ from typing import List, Optional
10
+
11
+ from core.state_models import AstSymbol
12
+ from extractors.parsers.base import (
13
+ ILanguageParser,
14
+ ImportStatement,
15
+ ParserResult
16
+ )
17
+ from extractors.parsers.comment_parser import CommentMarkerParser
18
+
19
+
20
+ class JavaScriptTypeScriptParser(ILanguageParser):
21
+ """
22
+ Parser for JavaScript and TypeScript source files.
23
+ Extracts classes, interfaces, exported functions, arrow functions, and types.
24
+ """
25
+
26
+ @property
27
+ def language_name(self) -> str:
28
+ return "JavaScript/TypeScript"
29
+
30
+ @property
31
+ def supported_extensions(self) -> List[str]:
32
+ return [".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"]
33
+
34
+ # Regex patterns for JS/TS structures
35
+ IMPORT_PATTERN = re.compile(
36
+ r"""(?:import\s+(?:(?:type\s+)?([\w*${}\s,]+)\s+from\s+)?['"]([^'"]+)['"]|require\(['"]([^'"]+)['"]\))"""
37
+ )
38
+
39
+ EXPORT_FUNC_PATTERN = re.compile(
40
+ r"""(?:export\s+(?:default\s+)?)?(?:async\s+)?function(?:\s*\*|\s+)([\w$]+)\s*\(([^)]*)\)(?:\s*:\s*([\w<>\[\],\s]+))?"""
41
+ )
42
+
43
+ EXPORT_ARROW_PATTERN = re.compile(
44
+ r"""(?:export\s+)?(?:const|let|var)\s+([\w$]+)(?:\s*:\s*[\w\.<>\[\],\s]+)?\s*=\s*(?:async\s*)?\(([^)]*)\)(?:\s*:\s*([\w\.<>\[\],\s]+))?\s*=>"""
45
+ )
46
+
47
+ CLASS_PATTERN = re.compile(
48
+ r"""(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([\w$]+)(?:\s+extends\s+([\w$]+))?(?:\s+implements\s+([\w$,\s]+))?"""
49
+ )
50
+
51
+ INTERFACE_PATTERN = re.compile(
52
+ r"""(?:export\s+)?interface\s+([\w$]+)(?:\s+extends\s+([\w$,\s]+))?"""
53
+ )
54
+
55
+ TYPE_ALIAS_PATTERN = re.compile(
56
+ r"""(?:export\s+)?type\s+([\w$]+)\s*="""
57
+ )
58
+
59
+ def parse_source(self, file_path: str, content: str) -> ParserResult:
60
+ result = ParserResult(
61
+ file_path=file_path,
62
+ language=self.language_name,
63
+ line_count=len(content.splitlines())
64
+ )
65
+
66
+ # 1. Markers
67
+ result.markers = CommentMarkerParser.extract_markers(file_path, content)
68
+
69
+ lines = content.splitlines()
70
+
71
+ # 2. Extract Imports
72
+ for idx, line in enumerate(lines, start=1):
73
+ stripped = line.strip()
74
+ if stripped.startswith("import ") or "require(" in stripped:
75
+ match = self.IMPORT_PATTERN.search(line)
76
+ if match:
77
+ raw_names = match.group(1)
78
+ module = match.group(2) or match.group(3) or ""
79
+ names = [n.strip() for n in raw_names.replace("{", "").replace("}", "").split(",")] if raw_names else []
80
+ result.imports.append(ImportStatement(
81
+ module=module,
82
+ imported_names=[n for n in names if n],
83
+ line_number=idx,
84
+ is_type_only="import type" in line
85
+ ))
86
+
87
+ # 3. Extract Functions, Classes, Interfaces, Types
88
+ for idx, line in enumerate(lines, start=1):
89
+ is_export = "export " in line
90
+
91
+ # Classes
92
+ c_match = self.CLASS_PATTERN.search(line)
93
+ if c_match:
94
+ name = c_match.group(1)
95
+ extends_cls = c_match.group(2)
96
+ params = [f"extends {extends_cls}"] if extends_cls else []
97
+ result.symbols.append(AstSymbol(
98
+ name=name,
99
+ kind="class",
100
+ file_path=file_path,
101
+ line_start=idx,
102
+ line_end=idx,
103
+ exported=is_export,
104
+ parameters=params
105
+ ))
106
+ continue
107
+
108
+ # Interfaces
109
+ i_match = self.INTERFACE_PATTERN.search(line)
110
+ if i_match:
111
+ name = i_match.group(1)
112
+ result.symbols.append(AstSymbol(
113
+ name=name,
114
+ kind="interface",
115
+ file_path=file_path,
116
+ line_start=idx,
117
+ line_end=idx,
118
+ exported=is_export
119
+ ))
120
+ continue
121
+
122
+ # Type Aliases
123
+ t_match = self.TYPE_ALIAS_PATTERN.search(line)
124
+ if t_match:
125
+ name = t_match.group(1)
126
+ result.symbols.append(AstSymbol(
127
+ name=name,
128
+ kind="type_alias",
129
+ file_path=file_path,
130
+ line_start=idx,
131
+ line_end=idx,
132
+ exported=is_export
133
+ ))
134
+ continue
135
+
136
+ # Standard Functions
137
+ f_match = self.EXPORT_FUNC_PATTERN.search(line)
138
+ if f_match:
139
+ name = f_match.group(1)
140
+ params = [p.strip() for p in f_match.group(2).split(",") if p.strip()]
141
+ ret_type = f_match.group(3).strip() if f_match.group(3) else None
142
+ result.symbols.append(AstSymbol(
143
+ name=name,
144
+ kind="function",
145
+ file_path=file_path,
146
+ line_start=idx,
147
+ line_end=idx,
148
+ exported=is_export,
149
+ parameters=params,
150
+ return_type=ret_type
151
+ ))
152
+ continue
153
+
154
+ # Arrow Functions
155
+ a_match = self.EXPORT_ARROW_PATTERN.search(line)
156
+ if a_match:
157
+ name = a_match.group(1)
158
+ params = [p.strip() for p in a_match.group(2).split(",") if p.strip()]
159
+ ret_type = a_match.group(3).strip() if a_match.group(3) else None
160
+ result.symbols.append(AstSymbol(
161
+ name=name,
162
+ kind="arrow_function",
163
+ file_path=file_path,
164
+ line_start=idx,
165
+ line_end=idx,
166
+ exported=is_export,
167
+ parameters=params,
168
+ return_type=ret_type
169
+ ))
170
+
171
+ return result
@@ -0,0 +1,180 @@
1
+ """
2
+ Project Continuum - Python Source Code & AST Parser
3
+ ===================================================
4
+ Robust AST parser for Python source files extracting modules, classes,
5
+ methods, async/sync functions, parameter signatures, docstrings, imports,
6
+ and exported symbols. Safely captures syntax errors without crashing.
7
+ """
8
+
9
+ import ast
10
+ import textwrap
11
+ from typing import List, Optional
12
+
13
+ from core.state_models import AstSymbol
14
+ from extractors.parsers.base import (
15
+ ILanguageParser,
16
+ ImportStatement,
17
+ ParseError,
18
+ ParserResult
19
+ )
20
+ from extractors.parsers.comment_parser import CommentMarkerParser
21
+
22
+
23
+ class PythonParser(ILanguageParser):
24
+ """
25
+ AST-based Python source code analyzer.
26
+ """
27
+
28
+ @property
29
+ def language_name(self) -> str:
30
+ return "Python"
31
+
32
+ @property
33
+ def supported_extensions(self) -> List[str]:
34
+ return [".py", ".pyw", ".pyi"]
35
+
36
+ def parse_source(self, file_path: str, content: str) -> ParserResult:
37
+ result = ParserResult(
38
+ file_path=file_path,
39
+ language=self.language_name,
40
+ line_count=len(content.splitlines())
41
+ )
42
+
43
+ # 1. Extract TODO/FIXME markers
44
+ result.markers = CommentMarkerParser.extract_markers(file_path, content)
45
+
46
+ # 2. Parse AST safely
47
+ try:
48
+ tree = ast.parse(textwrap.dedent(content), filename=file_path)
49
+ except SyntaxError as e:
50
+ result.errors.append(ParseError(
51
+ file_path=file_path,
52
+ message=f"SyntaxError: {e.msg}",
53
+ line_number=e.lineno
54
+ ))
55
+ return result
56
+ except Exception as e:
57
+ result.errors.append(ParseError(
58
+ file_path=file_path,
59
+ message=f"ParseError: {str(e)}",
60
+ line_number=None
61
+ ))
62
+ return result
63
+
64
+ # 3. Extract module level __all__ if present
65
+ all_exports: List[str] = []
66
+ for node in tree.body:
67
+ if isinstance(node, ast.Assign):
68
+ for target in node.targets:
69
+ if isinstance(target, ast.Name) and target.id == "__all__":
70
+ if isinstance(node.value, (ast.List, ast.Tuple, ast.Set)):
71
+ for elt in node.value.elts:
72
+ if isinstance(elt, ast.Constant) and isinstance(elt.value, str):
73
+ all_exports.append(elt.value)
74
+ result.exported_symbols = all_exports
75
+
76
+ # 4. Extract symbols and imports
77
+ for node in tree.body:
78
+ if isinstance(node, ast.Import):
79
+ for alias in node.names:
80
+ result.imports.append(ImportStatement(
81
+ module=alias.name,
82
+ alias=alias.asname,
83
+ line_number=node.lineno
84
+ ))
85
+ elif isinstance(node, ast.ImportFrom):
86
+ mod = node.module or ""
87
+ names = [alias.name for alias in node.names]
88
+ result.imports.append(ImportStatement(
89
+ module=mod,
90
+ imported_names=names,
91
+ line_number=node.lineno
92
+ ))
93
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
94
+ symbol = self._parse_function(node, file_path, is_method=False, parent_class=None, all_exports=all_exports)
95
+ result.symbols.append(symbol)
96
+ elif isinstance(node, ast.ClassDef):
97
+ class_symbol, methods = self._parse_class(node, file_path, all_exports=all_exports)
98
+ result.symbols.append(class_symbol)
99
+ result.symbols.extend(methods)
100
+
101
+ return result
102
+
103
+ def _parse_function(
104
+ self,
105
+ node: ast.FunctionDef | ast.AsyncFunctionDef,
106
+ file_path: str,
107
+ is_method: bool,
108
+ parent_class: Optional[str],
109
+ all_exports: List[str]
110
+ ) -> AstSymbol:
111
+ # Parameters
112
+ params: List[str] = []
113
+ for arg in node.args.args:
114
+ arg_str = arg.arg
115
+ if arg.annotation:
116
+ arg_str += f": {ast.unparse(arg.annotation)}"
117
+ params.append(arg_str)
118
+
119
+ # Return annotation
120
+ return_type = ast.unparse(node.returns) if node.returns else None
121
+
122
+ # Docstring
123
+ docstring = ast.get_docstring(node)
124
+
125
+ # Determine export status
126
+ is_exported = False
127
+ if all_exports:
128
+ is_exported = node.name in all_exports
129
+ else:
130
+ # Default python rule: exported if not starting with '_'
131
+ is_exported = not node.name.startswith("_")
132
+
133
+ kind = "method" if is_method else ("async_function" if isinstance(node, ast.AsyncFunctionDef) else "function")
134
+ qualified_name = f"{parent_class}.{node.name}" if parent_class else node.name
135
+
136
+ return AstSymbol(
137
+ name=qualified_name,
138
+ kind=kind,
139
+ file_path=file_path,
140
+ line_start=node.lineno,
141
+ line_end=getattr(node, "end_lineno", node.lineno),
142
+ exported=is_exported,
143
+ docstring=docstring,
144
+ parameters=params,
145
+ return_type=return_type
146
+ )
147
+
148
+ def _parse_class(
149
+ self,
150
+ node: ast.ClassDef,
151
+ file_path: str,
152
+ all_exports: List[str]
153
+ ) -> tuple[AstSymbol, List[AstSymbol]]:
154
+ docstring = ast.get_docstring(node)
155
+ bases = [ast.unparse(b) for b in node.bases]
156
+
157
+ is_exported = False
158
+ if all_exports:
159
+ is_exported = node.name in all_exports
160
+ else:
161
+ is_exported = not node.name.startswith("_")
162
+
163
+ class_symbol = AstSymbol(
164
+ name=node.name,
165
+ kind="class",
166
+ file_path=file_path,
167
+ line_start=node.lineno,
168
+ line_end=getattr(node, "end_lineno", node.lineno),
169
+ exported=is_exported,
170
+ docstring=docstring,
171
+ parameters=bases # Record base classes in parameters
172
+ )
173
+
174
+ methods: List[AstSymbol] = []
175
+ for item in node.body:
176
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
177
+ method_sym = self._parse_function(item, file_path, is_method=True, parent_class=node.name, all_exports=all_exports)
178
+ methods.append(method_sym)
179
+
180
+ return class_symbol, methods
@@ -0,0 +1,278 @@
1
+ """
2
+ Project Continuum - Test & Build Verification Runners & Parsers
3
+ ===============================================================
4
+ Provides safe command execution with timeouts and output capture,
5
+ along with structured test output parsers for PyTest, Unittest,
6
+ Vitest, Jest, Cargo test, Go test, and generic test runners.
7
+ """
8
+
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ import re
12
+ import subprocess
13
+ import time
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+
16
+ from core.enums import Status
17
+ from core.state_models import TestResult
18
+
19
+
20
+ @dataclass
21
+ class ExecutionResult:
22
+ """Raw result of an executed verification command."""
23
+ command: str
24
+ exit_code: int
25
+ stdout: str
26
+ stderr: str
27
+ duration_ms: float
28
+ timed_out: bool = False
29
+ error: Optional[str] = None
30
+
31
+ @property
32
+ def is_success(self) -> bool:
33
+ return self.exit_code == 0 and not self.timed_out
34
+
35
+
36
+ @dataclass
37
+ class ParsedTestSummary:
38
+ """Structured test outcome summary parsed from stdout/stderr."""
39
+ framework: str
40
+ total: int = 0
41
+ passed: int = 0
42
+ failed: int = 0
43
+ errors: int = 0
44
+ skipped: int = 0
45
+ duration_ms: float = 0.0
46
+ individual_tests: List[TestResult] = field(default_factory=list)
47
+ failure_details: List[str] = field(default_factory=list)
48
+
49
+
50
+ class VerificationRunner:
51
+ """
52
+ Safely executes verification and build commands with process timeouts,
53
+ stream capture, and exact duration measurement.
54
+ """
55
+
56
+ @staticmethod
57
+ def run_command(
58
+ command: str | List[str],
59
+ cwd: Path | str,
60
+ timeout_seconds: int = 60,
61
+ env: Optional[Dict[str, str]] = None
62
+ ) -> ExecutionResult:
63
+ cmd_str = command if isinstance(command, str) else " ".join(command)
64
+ start_time = time.time()
65
+
66
+ try:
67
+ res = subprocess.run(
68
+ command,
69
+ cwd=str(cwd),
70
+ stdout=subprocess.PIPE,
71
+ stderr=subprocess.PIPE,
72
+ text=True,
73
+ shell=isinstance(command, str),
74
+ timeout=timeout_seconds,
75
+ env=env,
76
+ encoding="utf-8",
77
+ errors="replace"
78
+ )
79
+ duration_ms = (time.time() - start_time) * 1000.0
80
+ return ExecutionResult(
81
+ command=cmd_str,
82
+ exit_code=res.returncode,
83
+ stdout=res.stdout,
84
+ stderr=res.stderr,
85
+ duration_ms=duration_ms,
86
+ timed_out=False
87
+ )
88
+ except subprocess.TimeoutExpired as e:
89
+ duration_ms = (time.time() - start_time) * 1000.0
90
+ stdout_text = e.stdout if isinstance(e.stdout, str) else (e.stdout.decode("utf-8", "replace") if e.stdout else "")
91
+ stderr_text = e.stderr if isinstance(e.stderr, str) else (e.stderr.decode("utf-8", "replace") if e.stderr else "")
92
+ return ExecutionResult(
93
+ command=cmd_str,
94
+ exit_code=124,
95
+ stdout=stdout_text,
96
+ stderr=stderr_text,
97
+ duration_ms=duration_ms,
98
+ timed_out=True,
99
+ error=f"Command timed out after {timeout_seconds} seconds"
100
+ )
101
+ except FileNotFoundError as e:
102
+ duration_ms = (time.time() - start_time) * 1000.0
103
+ return ExecutionResult(
104
+ command=cmd_str,
105
+ exit_code=127,
106
+ stdout="",
107
+ stderr=str(e),
108
+ duration_ms=duration_ms,
109
+ timed_out=False,
110
+ error=f"Executable not found: {e}"
111
+ )
112
+ except Exception as e:
113
+ duration_ms = (time.time() - start_time) * 1000.0
114
+ return ExecutionResult(
115
+ command=cmd_str,
116
+ exit_code=1,
117
+ stdout="",
118
+ stderr=str(e),
119
+ duration_ms=duration_ms,
120
+ timed_out=False,
121
+ error=str(e)
122
+ )
123
+
124
+
125
+ class TestOutputParser:
126
+ """
127
+ Parses CLI output streams from various test frameworks into structured metrics.
128
+ """
129
+
130
+ # PyTest pattern: "=== 5 passed, 2 failed, 1 skipped in 0.42s ==="
131
+ PYTEST_SUMMARY_PATTERN = re.compile(
132
+ r"(=+)\s*(?:(?P<passed>\d+)\s+passed)?(?:,\s*)?(?:(?P<failed>\d+)\s+failed)?(?:,\s*)?(?:(?P<errors>\d+)\s+errors?)?(?:,\s*)?(?:(?P<skipped>\d+)\s+skipped)?.*in\s+(?P<duration>[\d\.]+)\s*s\s*(=+)",
133
+ re.IGNORECASE
134
+ )
135
+
136
+ # Unittest pattern: "Ran 27 tests in 0.048s\n\nOK" or "FAILED (failures=1, errors=2)"
137
+ UNITTEST_RAN_PATTERN = re.compile(
138
+ r"Ran\s+(?P<total>\d+)\s+tests?\s+in\s+(?P<duration>[\d\.]+)s",
139
+ re.IGNORECASE
140
+ )
141
+ UNITTEST_FAILED_PATTERN = re.compile(
142
+ r"FAILED\s*\((?:failures=(?P<failures>\d+))?(?:,\s*)?(?:errors=(?P<errors>\d+))?\)",
143
+ re.IGNORECASE
144
+ )
145
+
146
+ # Vitest / Jest pattern: "Tests: 3 failed, 12 passed, 15 total"
147
+ JEST_PATTERN = re.compile(
148
+ r"Tests:\s*(?:(?P<failed>\d+)\s+failed,\s*)?(?:(?P<passed>\d+)\s+passed,\s*)?(?:(?P<skipped>\d+)\s+skipped,\s*)?(?P<total>\d+)\s+total",
149
+ re.IGNORECASE
150
+ )
151
+
152
+ # Cargo test pattern: "test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out"
153
+ CARGO_PATTERN = re.compile(
154
+ r"test result:\s*(?P<status>\w+)\.\s*(?P<passed>\d+)\s+passed;\s*(?P<failed>\d+)\s+failed;\s*(?P<ignored>\d+)\s+ignored",
155
+ re.IGNORECASE
156
+ )
157
+
158
+ # Go test pattern: "PASS: TestAuth (0.02s)" or "--- FAIL: TestLogin (0.01s)" or "FAIL\tpkg/auth\t0.035s"
159
+ GO_SUMMARY_PATTERN = re.compile(
160
+ r"(?P<status>PASS|FAIL)\s+(?P<pkg>[\w\.\/\-_]+)\s+(?P<duration>[\d\.]+)s",
161
+ re.IGNORECASE
162
+ )
163
+
164
+ @classmethod
165
+ def parse(cls, stdout: str, stderr: str, exit_code: int, duration_ms: float) -> ParsedTestSummary:
166
+ combined = f"{stdout}\n{stderr}"
167
+
168
+ # 1. Try PyTest
169
+ pytest_match = cls.PYTEST_SUMMARY_PATTERN.search(combined)
170
+ if pytest_match:
171
+ passed = int(pytest_match.group("passed") or 0)
172
+ failed = int(pytest_match.group("failed") or 0)
173
+ errors = int(pytest_match.group("errors") or 0)
174
+ skipped = int(pytest_match.group("skipped") or 0)
175
+ total = passed + failed + errors + skipped
176
+ dur = float(pytest_match.group("duration") or 0.0) * 1000.0
177
+ return ParsedTestSummary(
178
+ framework="pytest",
179
+ total=total,
180
+ passed=passed,
181
+ failed=failed,
182
+ errors=errors,
183
+ skipped=skipped,
184
+ duration_ms=dur or duration_ms,
185
+ failure_details=cls._extract_error_snippets(combined) if failed or errors else []
186
+ )
187
+
188
+ # 2. Try Unittest
189
+ unittest_match = cls.UNITTEST_RAN_PATTERN.search(combined)
190
+ if unittest_match:
191
+ total = int(unittest_match.group("total") or 0)
192
+ dur = float(unittest_match.group("duration") or 0.0) * 1000.0
193
+ failed = 0
194
+ errors = 0
195
+ fail_match = cls.UNITTEST_FAILED_PATTERN.search(combined)
196
+ if fail_match:
197
+ failed = int(fail_match.group("failures") or 0)
198
+ errors = int(fail_match.group("errors") or 0)
199
+ passed = total - failed - errors
200
+ return ParsedTestSummary(
201
+ framework="unittest",
202
+ total=total,
203
+ passed=max(0, passed),
204
+ failed=failed,
205
+ errors=errors,
206
+ skipped=0,
207
+ duration_ms=dur or duration_ms,
208
+ failure_details=cls._extract_error_snippets(combined) if failed or errors else []
209
+ )
210
+
211
+ # 3. Try Jest / Vitest
212
+ jest_match = cls.JEST_PATTERN.search(combined)
213
+ if jest_match:
214
+ total = int(jest_match.group("total") or 0)
215
+ passed = int(jest_match.group("passed") or 0)
216
+ failed = int(jest_match.group("failed") or 0)
217
+ skipped = int(jest_match.group("skipped") or 0)
218
+ return ParsedTestSummary(
219
+ framework="jest/vitest",
220
+ total=total,
221
+ passed=passed,
222
+ failed=failed,
223
+ errors=0,
224
+ skipped=skipped,
225
+ duration_ms=duration_ms,
226
+ failure_details=cls._extract_error_snippets(combined) if failed else []
227
+ )
228
+
229
+ # 4. Try Cargo test
230
+ cargo_match = cls.CARGO_PATTERN.search(combined)
231
+ if cargo_match:
232
+ passed = int(cargo_match.group("passed") or 0)
233
+ failed = int(cargo_match.group("failed") or 0)
234
+ ignored = int(cargo_match.group("ignored") or 0)
235
+ total = passed + failed + ignored
236
+ return ParsedTestSummary(
237
+ framework="cargo-test",
238
+ total=total,
239
+ passed=passed,
240
+ failed=failed,
241
+ errors=0,
242
+ skipped=ignored,
243
+ duration_ms=duration_ms,
244
+ failure_details=cls._extract_error_snippets(combined) if failed else []
245
+ )
246
+
247
+ # 5. Fallback Generic Parser based on exit code
248
+ status = Status.VERIFIED if exit_code == 0 else Status.FAILED
249
+ failed_count = 0 if exit_code == 0 else 1
250
+ passed_count = 1 if exit_code == 0 else 0
251
+ return ParsedTestSummary(
252
+ framework="generic_cli",
253
+ total=1,
254
+ passed=passed_count,
255
+ failed=failed_count,
256
+ errors=0,
257
+ skipped=0,
258
+ duration_ms=duration_ms,
259
+ failure_details=cls._extract_error_snippets(combined) if exit_code != 0 else []
260
+ )
261
+
262
+ @staticmethod
263
+ def _extract_error_snippets(output: str, max_lines: int = 15) -> List[str]:
264
+ """Extracts the most relevant error lines from a failing run."""
265
+ lines = output.splitlines()
266
+ error_lines: List[str] = []
267
+ capture = False
268
+
269
+ for line in lines:
270
+ lower = line.lower()
271
+ if any(k in lower for k in ["fail", "error", "traceback", "assertionerror", "exception"]):
272
+ capture = True
273
+ if capture and line.strip():
274
+ error_lines.append(line.strip())
275
+ if len(error_lines) >= max_lines:
276
+ break
277
+
278
+ return error_lines or [lines[-1].strip()] if lines else ["Unknown execution failure"]