8Run the Plan 214 worst-first CRAP probe over the Option C monorepo.
12- Execute each required MAIN-tree subproject suite under coverage.py.
13- Invoke ``python -m oct.complexity`` against MAIN sources through worktree PYTHONPATH.
14- Preserve failed suites as UNMEASURED with their captured output.
15- Generate the full JSON artifact and top-25-per-project Markdown report.
22 L3 - subproject measurement details
27- The probe measures and never gates.
28- Failed suites, parse failures, and never-imported functions are never omitted.
29- Analyzer commands run against MAIN sources with this worktree's instrument.
33- oct.complexity.coverage (coverage suite runner)
34- oct.complexity (not imported; run as python -m oct.complexity for the JSON analysis subprocess)
37from __future__
import annotations
45from dataclasses
import dataclass
46from pathlib
import Path
47from typing
import Sequence
56REPORT_BASENAME =
"crap-probe-2026-08"
59@dataclass(frozen=True, slots=True)
61 """One monorepo subproject and its suite/source boundaries."""
65 pytest_args: tuple[str, ...]
66 source_paths: tuple[str, ...]
73 pytest_args=(
"tests",
"-q"),
74 source_paths=(
"oct/oct",),
77 name=
"oc_diagnostics",
78 project_root=
"oc_diagnostics",
79 pytest_args=(
"tests",
"-q"),
80 source_paths=(
"oc_diagnostics/oc_diagnostics",),
84 project_root=
"oc_chat",
85 pytest_args=(
"oc_chat/tests",
"-q"),
86 source_paths=(
"oc_chat/oc_chat",),
90 project_root=
"oc_pricing",
91 pytest_args=(
"tests",
"-q"),
92 source_paths=(
"oc_pricing/oc_pricing",),
95 name=
"option_c_agent_contracts",
96 project_root=
"contracts/option_c_agent_contracts",
97 pytest_args=(
"tests",
"-q"),
98 source_paths=(
"contracts/option_c_agent_contracts/option_c_agent_contracts",),
101 name=
"option_c_registry_contracts",
102 project_root=
"contracts/option_c_registry_contracts",
103 pytest_args=(
"tests",
"-q"),
105 "contracts/option_c_registry_contracts/option_c_registry_contracts",
112 """Build the probe driver's argument parser."""
113 parser = argparse.ArgumentParser(
114 description=
"Run the Plan 214 monorepo CRAP probe.",
116 parser.add_argument(
"--repo-root", required=
True, type=Path)
117 parser.add_argument(
"--output-dir", required=
True, type=Path)
118 parser.add_argument(
"--data-dir", required=
True, type=Path)
120 "--python-executable",
122 default=Path(sys.executable),
127def main(argv: Sequence[str] |
None =
None) -> int:
128 """Run every probe project and write both committed artifacts."""
129 args =
_parser().parse_args(argv)
130 repo_root = args.repo_root.resolve()
131 output_dir = args.output_dir.resolve()
132 data_dir = args.data_dir.resolve()
133 python_executable = args.python_executable.resolve()
134 output_dir.mkdir(parents=
True, exist_ok=
True)
135 data_dir.mkdir(parents=
True, exist_ok=
True)
141 python_executable=python_executable,
143 for project
in PROJECTS
145 generated_at = dt.datetime.now(dt.timezone.utc).isoformat()
148 "generated_at": generated_at,
149 "base_sha": BASE_SHA,
151 "repo_root": str(repo_root),
152 "projects": projects,
154 json_path = output_dir / f
"{REPORT_BASENAME}.json"
155 markdown_path = output_dir / f
"{REPORT_BASENAME}.md"
156 json_path.write_text(
157 json.dumps(payload, indent=2, sort_keys=
True) +
"\n",
160 markdown_path.write_text(
164 print(f
"Wrote {markdown_path}")
165 print(f
"Wrote {json_path}")
170 project: ProbeProject,
174 python_executable: Path,
175) -> dict[str, object]:
176 """Run one suite, then map its data through the module command."""
177 print(f
"Measuring {project.name}...")
178 project_root = repo_root / project.project_root
179 source_paths = tuple(repo_root / item
for item
in project.source_paths)
180 data_file = data_dir / f
"{project.name}.coverage"
181 suite_env = os.environ.copy()
182 suite_env.pop(
"PYTHONPATH",
None)
183 suite = run_pytest_with_coverage(
184 project_root=project_root,
185 pytest_args=project.pytest_args,
188 python_executable=python_executable,
192 base_record: dict[str, object] = {
193 "name": project.name,
194 "project_root": project.project_root,
195 "source_paths": list(project.source_paths),
196 "suite": suite_record,
198 if suite.returncode != 0:
199 reason = f
"pytest exited {suite.returncode}"
200 if not suite_record[
"output"]:
201 suite_record[
"output"] =
"(no pytest output captured)"
204 "status":
"UNMEASURED",
206 "analysis_command":
None,
211 str(python_executable),
214 *(str(item)
for item
in source_paths),
219 analysis_env = os.environ.copy()
221 analysis = subprocess.run(
229 if analysis.returncode != 0:
230 reason = f
"complexity analysis exited {analysis.returncode}"
233 str(suite_record[
"output"]),
234 failure_output
or "(no complexity output captured)",
238 "status":
"UNMEASURED",
245 analysis_payload = json.loads(analysis.stdout)
246 except json.JSONDecodeError
as exc:
247 reason = f
"complexity JSON decode failed: {exc}"
249 str(suite_record[
"output"]),
255 "status":
"UNMEASURED",
263 for row
in analysis_payload[
"functions"]
267 for row
in analysis_payload[
"parse_errors"]
271 "status":
"MEASURED",
274 "functions": functions,
275 "parse_errors": parse_errors,
280 """Convert a coverage suite result to stable probe JSON."""
283 "returncode": suite.returncode,
284 "output": suite.output,
285 "coverage_data": suite.data_file,
290 """Replace an absolute source filename with a repository-relative path."""
297 row: dict[str, object],
299) -> dict[str, object]:
300 """Replace an absolute parse-error filename with a relative path."""
307 """Return a forward-slash repository-relative path when possible."""
309 return Path(filename).resolve().relative_to(repo_root).as_posix()
311 return Path(filename).as_posix()
315 payload: dict[str, object],
319 """Render the human probe report from the same payload as JSON."""
321 "# CRAP probe - August 2026",
323 "This report is a measurement snapshot, not a gate. It presents data only and makes no recommendations.",
325 f
"- BASE_SHA: `{payload['base_sha']}`",
326 f
"- Generated (UTC): `{payload['generated_at']}`",
327 f
"- MAIN source tree: `{payload['repo_root']}`",
328 f
"- Instrument worktree path: `{payload['instrument_root']}`",
332 "The probe was launched from the MAIN tree with the worktree instrument on `PYTHONPATH`:",
335 f
"$env:PYTHONPATH='{payload['instrument_root']}'",
339 "For each measured project, the exact coverage and analysis commands actually executed are recorded below.",
342 for project
in payload[
"projects"]:
344 return "\n".join(lines).rstrip() +
"\n"
348 """Return the exact top-level probe command for the report."""
349 output_dir = Path(__file__).resolve().parents[3] /
"oc_chat" /
"oc_chat" /
"docs" /
"reports"
353 "oct.complexity.probe",
355 str(payload[
"repo_root"]),
360 "--python-executable",
363 return f
"& {_command_text(command)}"
367 """Render one measured or honestly unmeasured project section."""
368 suite = project[
"suite"]
370 f
"## {project['name']}",
372 f
"Status: **{project['status']}**",
374 f
"- Coverage command: `{suite['command']}`",
375 f
"- Suite return code: `{suite['returncode']}`",
377 if project[
"analysis_command"]:
378 lines.append(f
"- Analysis command: `{project['analysis_command']}`")
380 if project[
"status"] ==
"UNMEASURED":
383 f
"Reason: {project['reason']}",
386 str(suite[
"output"]).rstrip(),
392 functions = project[
"functions"]
395 f
"Measured functions: {len(functions)}. Worst 25 shown.",
397 "| Function | CC | Coverage | CRAP | Status | Span |",
398 "|---|---:|---:|---:|---|---|",
401 for row
in functions[:25]:
402 path = str(row[
"file"])
403 span = f
"{path}:{row['lineno']}-{row['end_lineno']}"
404 link = f
"../../../../{path}#L{row['lineno']}-L{row['end_lineno']}"
406 f
"| {_escape_cell(row['qualname'])} | {row['complexity']} | "
407 f
"{row['coverage'] * 100:.1f}% | {row['crap']:.2f} | "
408 f
"{row['coverage_status']} | [{span}]({link}) |"
411 parse_errors = project[
"parse_errors"]
413 lines.append(
"Parse errors:")
415 for error
in parse_errors:
416 lines.append(f
"- `{error['file']}`: {error['error']}")
419 lines.extend([
"Parse errors: none.",
""])
424 """Escape Markdown table separators in one cell value."""
425 return str(value).replace(
"|",
"\\|")
429 """Return the worktree oct project directory used for PYTHONPATH."""
430 return Path(__file__).resolve().parents[2]
434 """Return a Windows-rerunnable rendering of an argument sequence."""
435 return subprocess.list2cmdline([str(item)
for item
in command])
439 """Join captured output fragments without silently dropping any."""
440 return "\n".join(part.rstrip()
for part
in parts
if part).strip()
443if __name__ ==
"__main__":
444 raise SystemExit(
main())
str _command_text(Sequence[str] command)
int main(Sequence[str]|None argv=None)
dict[str, object] _suite_record(CoverageRun suite)
dict[str, object] _run_project(ProbeProject project, *, Path repo_root, Path data_dir, Path python_executable)
str _joined_output(*str parts)
str _relative_path(str filename, Path repo_root)
str _escape_cell(object value)
argparse.ArgumentParser _parser()
str _probe_command(dict[str, object] payload, Path data_dir)
dict[str, object] _relativize_error(dict[str, object] row, Path repo_root)
list[str] _render_project(dict[str, object] project)
dict[str, object] _relativize_row(dict[str, object] row, Path repo_root)
str _render_markdown(dict[str, object] payload, *, Path data_dir)