pacodexion 0.1.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tristan-gscn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: pacodexion
3
+ Version: 0.1.0
4
+ Summary: Runner and validator for Codexion project test cases.
5
+ Author: pacodexion
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # pacodexion
13
+
14
+ Installable CLI package that runs Codexion test scenarios against `./codexion` and validates output consistency.
@@ -0,0 +1,3 @@
1
+ # pacodexion
2
+
3
+ Installable CLI package that runs Codexion test scenarios against `./codexion` and validates output consistency.
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pacodexion"
7
+ version = "0.1.0"
8
+ description = "Runner and validator for Codexion project test cases."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "pacodexion" }]
13
+ dependencies = []
14
+
15
+ [project.scripts]
16
+ pacodexion = "pacodexion.__main__:main"
17
+
18
+ [tool.setuptools]
19
+ package-dir = { "" = "src" }
20
+
21
+ [tool.setuptools.packages.find]
22
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, List, Sequence, Tuple
4
+
5
+ from .TestCase import TestCase
6
+
7
+
8
+ class CaseRegistry:
9
+ def __init__(self) -> None:
10
+ self._cases = self._build_cases()
11
+
12
+ def _build_cases(self) -> Dict[str, TestCase]:
13
+ cases = [
14
+ TestCase("1", "basic_fifo", ("4", "800", "200", "200", "200", "5", "10", "fifo")),
15
+ TestCase("2", "basic_edf", ("4", "800", "200", "200", "200", "5", "10", "edf")),
16
+ TestCase("3", "success_fifo", ("10", "10000", "100", "100", "100", "5", "50", "fifo")),
17
+ TestCase("4", "large_edf", ("20", "5000", "500", "500", "500", "10", "100", "edf")),
18
+ TestCase("5", "low_cooldown", ("5", "2000", "100", "100", "100", "20", "1", "fifo")),
19
+ TestCase("6", "long_actions", ("3", "10000", "2000", "2000", "2000", "2", "100", "fifo")),
20
+ TestCase("big", "big_test", ("100", "10000", "66", "24", "87", "10", "10", "fifo")),
21
+ TestCase("starvation", "starvation_case", ("3", "1000", "600", "10", "10", "5", "100", "fifo")),
22
+ TestCase("starvation2", "starvation_case", ("3", "1000", "600", "10", "10", "5", "100", "edf")),
23
+ TestCase("one_compiler_fifo", "one_compiler_fifo", ("1", "1000", "200", "200", "200", "5", "50", "fifo")),
24
+ TestCase("one_compiler_edf", "one_compiler_edf", ("1", "1000", "200", "200", "200", "5", "50", "edf")),
25
+ TestCase("zero_compile", "zero_compiles", ("5", "1000", "200", "200", "200", "0", "10", "fifo")),
26
+ TestCase("immediate_burnout", "immediate_burnout", ("2", "1", "200", "200", "200", "5", "10", "fifo")),
27
+ TestCase("cooldown_hell", "cooldown_hell", ("2", "1000", "100", "100", "100", "5", "2000", "fifo")),
28
+ TestCase("max_coders", "max_coders", ("300", "10000", "100", "100", "100", "5", "10", "edf")),
29
+ TestCase("toomany_compiler", "toomany_compiler", ("999", "1000", "200", "200", "200", "5", "50", "fifo")),
30
+ TestCase("error_arg1", "error_coder", ("banana", "200", "300", "400", "500", "5", "10", "fifo"), True),
31
+ TestCase("error_arg2", "error_coder", ("10", "banana", "300", "400", "500", "5", "10", "fifo"), True),
32
+ TestCase("error_arg3", "error_coder", ("10", "200", "banana", "400", "500", "5", "10", "fifo"), True),
33
+ TestCase("error_arg4", "error_coder", ("10", "200", "300", "banana", "500", "5", "10", "fifo"), True),
34
+ TestCase("error_arg5", "error_coder", ("10", "200", "300", "400", "banana", "5", "10", "fifo"), True),
35
+ TestCase("error_arg6", "error_coder", ("10", "200", "300", "400", "500", "banana", "10", "fifo"), True),
36
+ TestCase("error_arg7", "error_coder", ("10", "200", "300", "400", "500", "5", "banana", "fifo"), True),
37
+ TestCase("error_arg8", "error_coder", ("10", "200", "300", "400", "500", "5", "10", "banana"), True),
38
+ TestCase("error_arg9", "error_coder", ("10", "200", "300", "-400", "500", "5", "10", "edf"), True),
39
+ TestCase("error_arg10", "error_coder", ("too", "10", "200", "300", "400", "500", "5", "10", "edf"), True),
40
+ TestCase("error_missing_args", "error_missing_args", ("10", "200", "300", "400", "500", "5", "10"), True),
41
+ TestCase("error_no_args", "error_no_args", (), True),
42
+ ]
43
+ return {case.key: case for case in cases}
44
+
45
+ def select_cases(self, tokens: Sequence[str]) -> Tuple[List[TestCase], List[str]]:
46
+ if not tokens:
47
+ return list(self._cases.values()), []
48
+ selected: List[TestCase] = []
49
+ unknown: List[str] = []
50
+ for token in tokens:
51
+ case = self._cases.get(token)
52
+ if case is None:
53
+ unknown.append(token)
54
+ else:
55
+ selected.append(case)
56
+ return selected, unknown
@@ -0,0 +1,97 @@
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+ import time
5
+ from typing import Callable, List, Optional, Tuple
6
+
7
+ from .OutputValidator import OutputValidator
8
+ from .TestCase import TestCase
9
+
10
+ CaseResult = Tuple[TestCase, bool, str]
11
+
12
+
13
+ class CaseRunner:
14
+ def __init__(self) -> None:
15
+ self.validator = OutputValidator()
16
+ self.last_stdout = ""
17
+ self.last_stderr = ""
18
+
19
+ def run_all(self, binary: str, cases: List[TestCase], timeout: float) -> Tuple[List[CaseResult], bool]:
20
+ results: List[CaseResult] = []
21
+ any_fail = False
22
+ for case in cases:
23
+ ok, detail = self.run_case(binary, case, timeout)
24
+ results.append((case, ok, detail))
25
+ if not ok:
26
+ any_fail = True
27
+ return results, any_fail
28
+
29
+ def run_case(self, binary: str, case: TestCase, timeout: float) -> Tuple[bool, str]:
30
+ return self.run_case_with_progress(binary, case, timeout)
31
+
32
+ def run_case_with_progress(
33
+ self,
34
+ binary: str,
35
+ case: TestCase,
36
+ timeout: float,
37
+ on_tick: Optional[Callable[[float], None]] = None,
38
+ ) -> Tuple[bool, str]:
39
+ try:
40
+ process = subprocess.Popen(
41
+ [binary, *case.args],
42
+ stdout=subprocess.PIPE,
43
+ stderr=subprocess.PIPE,
44
+ text=True,
45
+ )
46
+ except OSError as exc:
47
+ self.last_stdout = ""
48
+ self.last_stderr = str(exc)
49
+ return False, f"execution error: {exc}"
50
+
51
+ started = time.monotonic()
52
+ stdout_data = ""
53
+ stderr_data = ""
54
+ while True:
55
+ try:
56
+ stdout_data, stderr_data = process.communicate(timeout=0.1)
57
+ break
58
+ except subprocess.TimeoutExpired:
59
+ elapsed = time.monotonic() - started
60
+ if on_tick is not None:
61
+ on_tick(elapsed)
62
+ if elapsed >= timeout:
63
+ process.kill()
64
+ stdout_data, stderr_data = process.communicate()
65
+ self.last_stdout = stdout_data
66
+ self.last_stderr = stderr_data
67
+ return (
68
+ False,
69
+ f"timeout after {timeout:.1f}s\n"
70
+ f"partial_stdout={self._preview(stdout_data or '<empty>')}\n"
71
+ f"partial_stderr={self._preview(stderr_data or '<empty>')}",
72
+ )
73
+
74
+ self.last_stdout = stdout_data
75
+ self.last_stderr = stderr_data
76
+
77
+ completed = subprocess.CompletedProcess(
78
+ args=[binary, *case.args],
79
+ returncode=process.returncode or 0,
80
+ stdout=stdout_data,
81
+ stderr=stderr_data,
82
+ )
83
+
84
+ if case.expect_invalid_args:
85
+ return self.validator.validate_error_case(completed)
86
+ return self.validator.validate_regular_case(completed, case.args)
87
+
88
+ def get_last_output(self) -> str:
89
+ if self.last_stdout.strip():
90
+ return self.last_stdout
91
+ return self.last_stderr
92
+
93
+ def _preview(self, text: str, max_len: int = 240) -> str:
94
+ cleaned = text.replace("\n", "\\n")
95
+ if len(cleaned) <= max_len:
96
+ return cleaned
97
+ return f"{cleaned[:max_len]}...(truncated)"
@@ -0,0 +1,42 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ from .TestCase import TestCase
6
+
7
+
8
+ class KoTraceWriter:
9
+ def __init__(self, trace_dir: str = "traces") -> None:
10
+ self.trace_path = Path(trace_dir)
11
+
12
+ def write(self, case: TestCase, codexion_output: str, detail: str) -> Path:
13
+ self.trace_path.mkdir(parents=True, exist_ok=True)
14
+ file_path = self.trace_path / self._file_name(case)
15
+ content = self._build_content(codexion_output, detail)
16
+ file_path.write_text(content, encoding="utf-8")
17
+ return file_path
18
+
19
+ def _file_name(self, case: TestCase) -> str:
20
+ safe_name = "".join(ch if ch.isalnum() or ch in ("-", "_") else "_" for ch in case.name)
21
+ return f"{case.key}_{safe_name}.log"
22
+
23
+ def _build_content(self, codexion_output: str, detail: str) -> str:
24
+ lines = codexion_output.splitlines()
25
+ if not lines:
26
+ return "PROBLEM HERE >>>\n"
27
+
28
+ line_no = self._extract_field(detail, "line")
29
+ idx = 0
30
+ if line_no is not None and line_no.isdigit():
31
+ candidate = int(line_no) - 1
32
+ if 0 <= candidate < len(lines):
33
+ idx = candidate
34
+ lines[idx] = f"PROBLEM HERE >>> {lines[idx]}"
35
+ return "\n".join(lines) + "\n"
36
+
37
+ def _extract_field(self, detail: str, key: str) -> str | None:
38
+ prefix = f"{key}="
39
+ for line in detail.splitlines():
40
+ if line.startswith(prefix):
41
+ return line[len(prefix) :]
42
+ return None
@@ -0,0 +1,319 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import subprocess
5
+ from typing import Dict, List, Optional, Tuple
6
+
7
+
8
+ class OutputValidator:
9
+ LOG_RE = re.compile(
10
+ r"^(?P<ts>\d+)\s+(?P<coder>\d+)\s+"
11
+ r"(?P<state>has taken a dongle|is compiling|is debugging|is refactoring|burned out)$"
12
+ )
13
+
14
+ def read_lines(self, output: str) -> List[str]:
15
+ return [line.strip() for line in output.splitlines() if line.strip()]
16
+
17
+ def validate_error_case(self, completed: subprocess.CompletedProcess[str]) -> Tuple[bool, str]:
18
+ merged = (completed.stdout or "") + "\n" + (completed.stderr or "")
19
+ lines = self.read_lines(merged)
20
+ has_error_word = any(
21
+ ("error" in line.lower()) or ("invalid" in line.lower()) or ("usage" in line.lower())
22
+ for line in lines
23
+ )
24
+ if completed.returncode != 0 or has_error_word:
25
+ return True, "invalid argument rejection detected"
26
+ return (
27
+ False,
28
+ "expected invalid-argument rejection but command looked successful\n"
29
+ f"return_code={completed.returncode}\n"
30
+ f"stdout={self._preview(completed.stdout or '<empty>')}\n"
31
+ f"stderr={self._preview(completed.stderr or '<empty>')}",
32
+ )
33
+
34
+ def validate_regular_case(self, completed: subprocess.CompletedProcess[str], raw_args: Tuple[str, ...]) -> Tuple[bool, str]:
35
+ parsed_args, parse_error = self._parse_regular_args(raw_args)
36
+ if parse_error is not None or parsed_args is None:
37
+ return False, parse_error or "invalid test case definition"
38
+
39
+ (
40
+ n_coders,
41
+ time_to_burnout,
42
+ time_to_compile,
43
+ time_to_debug,
44
+ time_to_refactor,
45
+ compiles_required,
46
+ _dongle_cooldown,
47
+ _scheduler,
48
+ ) = parsed_args
49
+
50
+ if completed.returncode != 0:
51
+ return (
52
+ False,
53
+ "unexpected non-zero exit code\n"
54
+ f"return_code={completed.returncode}\n"
55
+ f"stdout={self._preview(completed.stdout or '<empty>')}\n"
56
+ f"stderr={self._preview(completed.stderr or '<empty>')}",
57
+ )
58
+
59
+ lines = self.read_lines(completed.stdout or "")
60
+ if not lines:
61
+ if compiles_required == 0:
62
+ return True, "no log line emitted (accepted for required_compiles=0)"
63
+ return False, "empty output while compiles are required"
64
+
65
+ last_ts = -1
66
+ burnouts = 0
67
+ burnout_coder: Optional[int] = None
68
+ taken_counts = self._build_counter(n_coders)
69
+ compile_counts = self._build_counter(n_coders)
70
+ last_compile_start = {coder_id: 0 for coder_id in range(1, n_coders + 1)}
71
+ last_debug_start: Dict[int, Optional[int]] = {coder_id: None for coder_id in range(1, n_coders + 1)}
72
+ last_refactor_start: Dict[int, Optional[int]] = {coder_id: None for coder_id in range(1, n_coders + 1)}
73
+ last_state: Dict[int, str] = {coder_id: "init" for coder_id in range(1, n_coders + 1)}
74
+
75
+ for idx, line in enumerate(lines, start=1):
76
+ match = self.LOG_RE.match(line)
77
+ if not match:
78
+ return (
79
+ False,
80
+ "invalid log format\n"
81
+ f"line={idx}\n"
82
+ f"value={self._preview(line)}\n"
83
+ "expected_format='<timestamp_ms> <coder_id> <state>'\n"
84
+ "allowed_states=['has taken a dongle', 'is compiling', "
85
+ "'is debugging', 'is refactoring', 'burned out']",
86
+ )
87
+
88
+ ts = int(match.group("ts"))
89
+ coder = int(match.group("coder"))
90
+ state = match.group("state")
91
+
92
+ if ts < last_ts:
93
+ return (
94
+ False,
95
+ "non-monotonic timestamps\n"
96
+ f"line={idx}\n"
97
+ f"previous_timestamp={last_ts}\n"
98
+ f"current_timestamp={ts}\n"
99
+ f"line_value={self._preview(line)}",
100
+ )
101
+ last_ts = ts
102
+
103
+ if coder < 1 or coder > n_coders:
104
+ return (
105
+ False,
106
+ "coder id out of expected range\n"
107
+ f"line={idx}\n"
108
+ f"coder_id={coder}\n"
109
+ f"expected_range=1..{n_coders}\n"
110
+ f"line_value={self._preview(line)}",
111
+ )
112
+
113
+ if self._transition_invalid(last_state[coder], state, taken_counts[coder]):
114
+ return (
115
+ False,
116
+ "invalid state transition sequence\n"
117
+ f"line={idx}\n"
118
+ f"coder_id={coder}\n"
119
+ f"previous_state={last_state[coder]}\n"
120
+ f"current_state={state}\n"
121
+ f"line_value={self._preview(line)}",
122
+ )
123
+
124
+ if state == "has taken a dongle":
125
+ taken_counts[coder] += 1
126
+ if taken_counts[coder] > 2:
127
+ return (
128
+ False,
129
+ "more than 2 dongles taken before compile\n"
130
+ f"line={idx}\n"
131
+ f"coder_id={coder}\n"
132
+ f"dongles_seen_before_compile={taken_counts[coder]}\n"
133
+ f"line_value={self._preview(line)}",
134
+ )
135
+ if last_refactor_start[coder] is not None:
136
+ waited = ts - last_refactor_start[coder]
137
+ if waited < time_to_refactor:
138
+ return (
139
+ False,
140
+ "refactor phase ended too early before taking dongles\n"
141
+ f"line={idx}\n"
142
+ f"coder_id={coder}\n"
143
+ f"expected_min_refactor_ms={time_to_refactor}\n"
144
+ f"actual_refactor_ms={waited}\n"
145
+ f"line_value={self._preview(line)}",
146
+ )
147
+ elif state == "is compiling":
148
+ if taken_counts[coder] < 2:
149
+ return (
150
+ False,
151
+ "compile started without 2 prior dongle acquisitions\n"
152
+ f"line={idx}\n"
153
+ f"coder_id={coder}\n"
154
+ f"dongles_seen_before_compile={taken_counts[coder]}\n"
155
+ f"line_value={self._preview(line)}",
156
+ )
157
+ taken_counts[coder] = 0
158
+ compile_counts[coder] += 1
159
+ last_compile_start[coder] = ts
160
+ last_debug_start[coder] = None
161
+ last_refactor_start[coder] = None
162
+ elif state == "is debugging":
163
+ elapsed_compile = ts - last_compile_start[coder]
164
+ if elapsed_compile < time_to_compile:
165
+ return (
166
+ False,
167
+ "compile phase ended too early before debugging\n"
168
+ f"line={idx}\n"
169
+ f"coder_id={coder}\n"
170
+ f"expected_min_compile_ms={time_to_compile}\n"
171
+ f"actual_compile_ms={elapsed_compile}\n"
172
+ f"line_value={self._preview(line)}",
173
+ )
174
+ last_debug_start[coder] = ts
175
+ elif state == "is refactoring":
176
+ debug_start = last_debug_start[coder]
177
+ if debug_start is None:
178
+ return (
179
+ False,
180
+ "refactoring started without debugging start\n"
181
+ f"line={idx}\n"
182
+ f"coder_id={coder}\n"
183
+ f"line_value={self._preview(line)}",
184
+ )
185
+ elapsed_debug = ts - debug_start
186
+ if elapsed_debug < time_to_debug:
187
+ return (
188
+ False,
189
+ "debug phase ended too early before refactoring\n"
190
+ f"line={idx}\n"
191
+ f"coder_id={coder}\n"
192
+ f"expected_min_debug_ms={time_to_debug}\n"
193
+ f"actual_debug_ms={elapsed_debug}\n"
194
+ f"line_value={self._preview(line)}",
195
+ )
196
+ last_refactor_start[coder] = ts
197
+ elif state == "burned out":
198
+ burnouts += 1
199
+ burnout_coder = coder
200
+ deadline = last_compile_start[coder] + time_to_burnout
201
+ lateness = ts - deadline
202
+ if lateness < 0:
203
+ return (
204
+ False,
205
+ "burned out before burnout deadline\n"
206
+ f"line={idx}\n"
207
+ f"coder_id={coder}\n"
208
+ f"deadline_ms={deadline}\n"
209
+ f"actual_burnout_ms={ts}\n"
210
+ f"line_value={self._preview(line)}",
211
+ )
212
+ if lateness > 10:
213
+ return (
214
+ False,
215
+ "burnout detection delayed beyond 10ms requirement\n"
216
+ f"line={idx}\n"
217
+ f"coder_id={coder}\n"
218
+ f"deadline_ms={deadline}\n"
219
+ f"actual_burnout_ms={ts}\n"
220
+ f"delay_ms={lateness}\n"
221
+ f"line_value={self._preview(line)}",
222
+ )
223
+ if idx != len(lines):
224
+ next_line = lines[idx] if idx < len(lines) else "<none>"
225
+ return (
226
+ False,
227
+ "burned out event is not the last log line\n"
228
+ f"line={idx}\n"
229
+ f"burned_out_line={self._preview(line)}\n"
230
+ f"next_line={self._preview(next_line)}",
231
+ )
232
+
233
+ last_state[coder] = state
234
+
235
+ if burnouts > 1:
236
+ return False, f"multiple burned out events detected\ncount={burnouts}"
237
+
238
+ if burnouts == 0:
239
+ if compiles_required > 0:
240
+ not_done = [str(coder_id) for coder_id, count in compile_counts.items() if count < compiles_required]
241
+ if not_done:
242
+ return (
243
+ False,
244
+ "simulation ended before all coders reached required compile count\n"
245
+ f"required_compiles={compiles_required}\n"
246
+ f"coders_not_done={','.join(not_done[:20])}"
247
+ f"{'...' if len(not_done) > 20 else ''}",
248
+ )
249
+ else:
250
+ if compiles_required > 0 and all(count >= compiles_required for count in compile_counts.values()):
251
+ return (
252
+ False,
253
+ "burnout happened even though all coders reached required compile count\n"
254
+ f"burnout_coder={burnout_coder}",
255
+ )
256
+
257
+ return True, "logs are coherent"
258
+
259
+ def _build_counter(self, n_coders: int) -> Dict[int, int]:
260
+ return {coder_id: 0 for coder_id in range(1, n_coders + 1)}
261
+
262
+ def _preview(self, text: str, max_len: int = 240) -> str:
263
+ cleaned = text.replace("\n", "\\n")
264
+ if len(cleaned) <= max_len:
265
+ return cleaned
266
+ return f"{cleaned[:max_len]}...(truncated)"
267
+
268
+ def _parse_regular_args(
269
+ self, raw_args: Tuple[str, ...]
270
+ ) -> Tuple[Optional[Tuple[int, int, int, int, int, int, int, str]], Optional[str]]:
271
+ if len(raw_args) != 8:
272
+ return None, f"invalid test case definition: expected 8 args, got {len(raw_args)}"
273
+
274
+ values = list(raw_args[:7])
275
+ parsed: List[int] = []
276
+ for idx, value in enumerate(values, start=1):
277
+ if not self._is_integer(value):
278
+ return None, f"invalid numeric argument in case definition\narg_index={idx}\nvalue={self._preview(value)}"
279
+ parsed.append(int(value))
280
+
281
+ scheduler = raw_args[7]
282
+ if scheduler not in ("fifo", "edf"):
283
+ return None, f"invalid scheduler in case definition\nvalue={self._preview(scheduler)}"
284
+
285
+ if parsed[0] <= 0:
286
+ return None, f"number_of_coders must be > 0\nvalue={parsed[0]}"
287
+ if parsed[5] < 0:
288
+ return None, f"number_of_compiles_required must be >= 0\nvalue={parsed[5]}"
289
+ for idx, value in enumerate(parsed[1:], start=2):
290
+ if idx == 6:
291
+ continue
292
+ if value < 0:
293
+ return None, f"time/cooldown arguments must be >= 0\narg_index={idx}\nvalue={value}"
294
+
295
+ return (parsed[0], parsed[1], parsed[2], parsed[3], parsed[4], parsed[5], parsed[6], scheduler), None
296
+
297
+ def _transition_invalid(self, previous_state: str, current_state: str, taken_count: int) -> bool:
298
+ if current_state == "burned out":
299
+ return False
300
+ if previous_state == "init":
301
+ return current_state != "has taken a dongle"
302
+ if previous_state == "has taken a dongle":
303
+ if current_state == "has taken a dongle":
304
+ return taken_count >= 2
305
+ return current_state != "is compiling"
306
+ if previous_state == "is compiling":
307
+ return current_state != "is debugging"
308
+ if previous_state == "is debugging":
309
+ return current_state != "is refactoring"
310
+ if previous_state == "is refactoring":
311
+ return current_state != "has taken a dongle"
312
+ return False
313
+
314
+ def _is_integer(self, value: str) -> bool:
315
+ if not value:
316
+ return False
317
+ if value[0] in "+-":
318
+ return value[1:].isdigit()
319
+ return value.isdigit()
@@ -0,0 +1,96 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+ from typing import List, Sequence
7
+
8
+ from .CaseRegistry import CaseRegistry
9
+ from .CaseRunner import CaseRunner
10
+ from .KoTraceWriter import KoTraceWriter
11
+ from .ResultFormatter import ResultFormatter
12
+ from .TestCase import TestCase
13
+
14
+
15
+ class PacodexionCLI:
16
+ def __init__(self) -> None:
17
+ self.registry = CaseRegistry()
18
+ self.runner = CaseRunner()
19
+ self.trace_writer = KoTraceWriter()
20
+ self.use_color = sys.stdout.isatty()
21
+ self.formatter = ResultFormatter(use_color=self.use_color)
22
+
23
+ def parse_args(self, argv: Sequence[str]) -> argparse.Namespace:
24
+ parser = argparse.ArgumentParser(
25
+ prog="pacodexion",
26
+ description="Run Codexion scenarios against ./codexion and validate logs.",
27
+ )
28
+ parser.add_argument(
29
+ "cases",
30
+ nargs="*",
31
+ help="Case keys to run (example: 1 big error_arg3). If omitted, run all.",
32
+ )
33
+ parser.add_argument(
34
+ "--binary",
35
+ default="./codexion",
36
+ help="Path to codexion binary (default: ./codexion).",
37
+ )
38
+ parser.add_argument(
39
+ "--timeout",
40
+ type=float,
41
+ default=60.0,
42
+ help="Per-test timeout in seconds (default: 60).",
43
+ )
44
+ return parser.parse_args(argv)
45
+
46
+ def run(self, argv: Sequence[str]) -> int:
47
+ args = self.parse_args(argv)
48
+ selected, unknown = self.registry.select_cases(args.cases)
49
+
50
+ if unknown:
51
+ for token in unknown:
52
+ print(f"[FAIL] unknown test key: {token}", file=sys.stderr)
53
+ return 2
54
+
55
+ if not os.path.exists(args.binary):
56
+ print(f"[FAIL] binary not found: {args.binary}", file=sys.stderr)
57
+ return 2
58
+ if not os.access(args.binary, os.X_OK):
59
+ print(f"[FAIL] binary is not executable: {args.binary}", file=sys.stderr)
60
+ return 2
61
+
62
+ results = self._run_cases_live(args.binary, selected, args.timeout)
63
+ any_fail = any(not ok for _, ok, _ in results)
64
+ print(self.formatter.render_summary(results))
65
+ return 1 if any_fail else 0
66
+
67
+ def _run_cases_live(self, binary: str, selected: List[TestCase], timeout: float) -> List[tuple[TestCase, bool, str]]:
68
+ results: List[tuple[TestCase, bool, str]] = []
69
+ spinner_frames = ["|", "/", "-", "\\"]
70
+
71
+ for case in selected:
72
+ spinner_index = 0
73
+ started_line = False
74
+
75
+ def on_tick(_: float) -> None:
76
+ nonlocal spinner_index, started_line
77
+ if not sys.stdout.isatty():
78
+ if not started_line:
79
+ print(self.formatter.render_running(case, spinner_frames[0]))
80
+ started_line = True
81
+ return
82
+ frame = spinner_frames[spinner_index % len(spinner_frames)]
83
+ spinner_index += 1
84
+ print(self.formatter.render_running(case, frame), end="", flush=True)
85
+ started_line = True
86
+
87
+ ok, detail = self.runner.run_case_with_progress(binary, case, timeout, on_tick=on_tick)
88
+ if started_line and sys.stdout.isatty():
89
+ print("\r" + " " * 100 + "\r", end="")
90
+ print(self.formatter.render_result(case, ok, detail))
91
+ if not ok:
92
+ trace_file = self.trace_writer.write(case, self.runner.get_last_output(), detail)
93
+ print(f" trace: {trace_file}")
94
+ results.append((case, ok, detail))
95
+
96
+ return results
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable, Tuple
4
+
5
+ from .TestCase import TestCase
6
+
7
+ CaseResult = Tuple[TestCase, bool, str]
8
+
9
+
10
+ class ResultFormatter:
11
+ RESET = "\033[0m"
12
+ BOLD = "\033[1m"
13
+ GREEN = "\033[32m"
14
+ RED = "\033[31m"
15
+ CYAN = "\033[36m"
16
+
17
+ def __init__(self, use_color: bool) -> None:
18
+ self.use_color = use_color
19
+
20
+ def _color(self, text: str, color: str) -> str:
21
+ if not self.use_color:
22
+ return text
23
+ return f"{color}{text}{self.RESET}"
24
+
25
+ def _bold(self, text: str) -> str:
26
+ if not self.use_color:
27
+ return text
28
+ return f"{self.BOLD}{text}{self.RESET}"
29
+
30
+ def render_result(self, case: TestCase, ok: bool, detail: str) -> str:
31
+ raw_status = "OK" if ok else "KO"
32
+ color = self.GREEN if ok else self.RED
33
+ status = self._color(raw_status, color)
34
+ header = f"[{status}] {case.key} ({case.name})"
35
+ if ok:
36
+ return header
37
+ trace = self._color(detail, self.RED)
38
+ return f"{header}\n{trace}\n"
39
+
40
+ def render_results(self, results: Iterable[CaseResult]) -> Iterable[str]:
41
+ for case, ok, detail in results:
42
+ yield self.render_result(case, ok, detail)
43
+
44
+ def render_summary(self, results: Iterable[CaseResult]) -> str:
45
+ result_list = list(results)
46
+ passed = sum(1 for _, ok, _ in result_list if ok)
47
+ total = len(result_list)
48
+ summary = f"Summary: {passed}/{total} passed"
49
+ if passed == total:
50
+ return self._bold(self._color(summary, self.GREEN))
51
+ return self._bold(self._color(summary, self.RED))
52
+
53
+ def render_running(self, case: TestCase, frame: str) -> str:
54
+ if self.use_color:
55
+ return f"\r{self._color(frame, self.CYAN)} Running {case.key} ({case.name})..."
56
+ return f"Running {case.key} ({case.name})..."
@@ -0,0 +1,10 @@
1
+ from dataclasses import dataclass
2
+ from typing import Tuple
3
+
4
+
5
+ @dataclass(frozen=True)
6
+ class TestCase:
7
+ key: str
8
+ name: str
9
+ args: Tuple[str, ...]
10
+ expect_invalid_args: bool = False
@@ -0,0 +1,3 @@
1
+ __all__ = ["__version__"]
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,13 @@
1
+ import sys
2
+ from typing import Sequence
3
+
4
+ from .PacodexionCLI import PacodexionCLI
5
+
6
+
7
+ def main(argv: Sequence[str] | None = None) -> int:
8
+ cli = PacodexionCLI()
9
+ return cli.run(argv if argv is not None else sys.argv[1:])
10
+
11
+
12
+ if __name__ == "__main__":
13
+ raise SystemExit(main())
@@ -0,0 +1,14 @@
1
+ Metadata-Version: 2.4
2
+ Name: pacodexion
3
+ Version: 0.1.0
4
+ Summary: Runner and validator for Codexion project test cases.
5
+ Author: pacodexion
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: license-file
11
+
12
+ # pacodexion
13
+
14
+ Installable CLI package that runs Codexion test scenarios against `./codexion` and validates output consistency.
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/pacodexion/CaseRegistry.py
5
+ src/pacodexion/CaseRunner.py
6
+ src/pacodexion/KoTraceWriter.py
7
+ src/pacodexion/OutputValidator.py
8
+ src/pacodexion/PacodexionCLI.py
9
+ src/pacodexion/ResultFormatter.py
10
+ src/pacodexion/TestCase.py
11
+ src/pacodexion/__init__.py
12
+ src/pacodexion/__main__.py
13
+ src/pacodexion.egg-info/PKG-INFO
14
+ src/pacodexion.egg-info/SOURCES.txt
15
+ src/pacodexion.egg-info/dependency_links.txt
16
+ src/pacodexion.egg-info/entry_points.txt
17
+ src/pacodexion.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pacodexion = pacodexion.__main__:main
@@ -0,0 +1 @@
1
+ pacodexion