Skip to content

Commit 24ba751

Browse files
🧹 [Code Health] Reduce cyclomatic complexity in main function
🎯 What: Refactored the `main` function in `src/main.py` by extracting command handling logic into individual helper functions and using a dispatch dictionary (`COMMAND_HANDLERS`). 💡 Why: The `main` function previously contained a long, complex chain of `if args.command == ...:` statements, resulting in high cyclomatic complexity. This refactoring greatly improves maintainability, readability, and testability by separating concerns and reducing the cognitive load required to understand the entry point. It also optimizes performance by lazily building `manifest` only for commands that need it. ✅ Verification: Ran `ruff format` and `ruff check` to ensure clean code. Executed `PYTHONPATH=. python3 -m unittest discover tests` to confirm no existing functionality was broken. ✨ Result: The `main` function is now clean and concise, and the code health issue regarding cyclomatic complexity is fully resolved. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
1 parent 27c415a commit 24ba751

36 files changed

Lines changed: 1161 additions & 658 deletions

.github/scripts/check_doc_source_of_truth.py

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,39 +7,39 @@
77

88
ROOT = Path(__file__).resolve().parents[2]
99
FILES = [
10-
ROOT / 'README.md',
11-
ROOT / 'USAGE.md',
12-
ROOT / 'PARITY.md',
13-
ROOT / 'PHILOSOPHY.md',
14-
ROOT / 'ROADMAP.md',
15-
ROOT / '.github' / 'FUNDING.yml',
10+
ROOT / "README.md",
11+
ROOT / "USAGE.md",
12+
ROOT / "PARITY.md",
13+
ROOT / "PHILOSOPHY.md",
14+
ROOT / "ROADMAP.md",
15+
ROOT / ".github" / "FUNDING.yml",
1616
]
17-
FILES.extend(sorted((ROOT / 'docs').rglob('*.md')) if (ROOT / 'docs').exists() else [])
17+
FILES.extend(sorted((ROOT / "docs").rglob("*.md")) if (ROOT / "docs").exists() else [])
1818

1919
FORBIDDEN = {
20-
r'github\.com/Yeachan-Heo/claw-code(?!-parity)': 'replace old claw-code GitHub links with ultraworkers/claw-code',
21-
r'github\.com/code-yeongyu/claw-code': 'replace stale alternate claw-code GitHub links with ultraworkers/claw-code',
22-
r'discord\.gg/6ztZB9jvWq': 'replace the stale UltraWorkers Discord invite with the current invite',
23-
r'api\.star-history\.com/svg\?repos=Yeachan-Heo/claw-code': 'update star-history embeds to ultraworkers/claw-code',
24-
r'star-history\.com/#Yeachan-Heo/claw-code': 'update star-history links to ultraworkers/claw-code',
25-
r'assets/clawd-hero\.jpeg': 'rename stale hero asset references to assets/claw-hero.jpeg',
26-
r'assets/instructkr\.png': 'remove stale instructkr image references',
20+
r"github\.com/Yeachan-Heo/claw-code(?!-parity)": "replace old claw-code GitHub links with ultraworkers/claw-code",
21+
r"github\.com/code-yeongyu/claw-code": "replace stale alternate claw-code GitHub links with ultraworkers/claw-code",
22+
r"discord\.gg/6ztZB9jvWq": "replace the stale UltraWorkers Discord invite with the current invite",
23+
r"api\.star-history\.com/svg\?repos=Yeachan-Heo/claw-code": "update star-history embeds to ultraworkers/claw-code",
24+
r"star-history\.com/#Yeachan-Heo/claw-code": "update star-history links to ultraworkers/claw-code",
25+
r"assets/clawd-hero\.jpeg": "rename stale hero asset references to assets/claw-hero.jpeg",
26+
r"assets/instructkr\.png": "remove stale instructkr image references",
2727
}
2828

2929
errors: list[str] = []
3030
for path in FILES:
3131
if not path.exists():
3232
continue
33-
text = path.read_text(encoding='utf-8')
33+
text = path.read_text(encoding="utf-8")
3434
for pattern, message in FORBIDDEN.items():
3535
for match in re.finditer(pattern, text):
36-
line = text.count('\n', 0, match.start()) + 1
37-
errors.append(f'{path.relative_to(ROOT)}:{line}: {message}')
36+
line = text.count("\n", 0, match.start()) + 1
37+
errors.append(f"{path.relative_to(ROOT)}:{line}: {message}")
3838

3939
if errors:
40-
print('doc source-of-truth check failed:', file=sys.stderr)
40+
print("doc source-of-truth check failed:", file=sys.stderr)
4141
for error in errors:
42-
print(f' - {error}', file=sys.stderr)
42+
print(f" - {error}", file=sys.stderr)
4343
sys.exit(1)
4444

45-
print('doc source-of-truth check passed')
45+
print("doc source-of-truth check passed")

patch_pr.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
import sys
22

3+
34
def replace_in_file(filepath, search_str, replace_str):
4-
with open(filepath, 'r') as f:
5+
with open(filepath, "r") as f:
56
content = f.read()
67

78
if search_str in content:
89
content = content.replace(search_str, replace_str)
9-
with open(filepath, 'w') as f:
10+
with open(filepath, "w") as f:
1011
f.write(content)
1112
print("Replacement successful.")
1213
else:
1314
print("Search string not found.")
1415

16+
1517
search = """fn agent_detail(agent: &AgentSummary) -> String {
1618
let mut parts = vec![agent.name.as_str()];
1719
if let Some(description) = &agent.description {
@@ -39,4 +41,4 @@ def replace_in_file(filepath, search_str, replace_str):
3941
parts.join(" · ")
4042
}"""
4143

42-
replace_in_file('rust/crates/commands/src/lib.rs', search, replace)
44+
replace_in_file("rust/crates/commands/src/lib.rs", search, replace)

rust/scripts/run_mock_parity_diff.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,11 @@ def main() -> int:
6666

6767
should_run = "--no-run" not in sys.argv[1:]
6868
report = run_harness(rust_root) if should_run else None
69-
report_by_name = {
70-
entry["name"]: entry for entry in report.get("scenarios", [])
71-
} if report else {}
69+
report_by_name = (
70+
{entry["name"]: entry for entry in report.get("scenarios", [])}
71+
if report
72+
else {}
73+
)
7274

7375
print("Mock parity diff checklist")
7476
print(f"Repo root: {repo_root}")
@@ -79,7 +81,9 @@ def main() -> int:
7981
for entry in manifest:
8082
scenario_name = entry["name"]
8183
scenario_report = report_by_name.get(scenario_name)
82-
status = "PASS" if scenario_report else ("MAPPED" if not should_run else "MISSING")
84+
status = (
85+
"PASS" if scenario_report else ("MAPPED" if not should_run else "MISSING")
86+
)
8387
print(f"[{status}] {scenario_name} ({entry['category']})")
8488
print(f" description: {entry['description']}")
8589
print(f" parity refs: {' | '.join(entry['parity_refs'])}")

src/QueryEngine.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,16 @@
77
class QueryEngineRuntime(QueryEnginePort):
88
def route(self, prompt: str, limit: int = 5) -> str:
99
matches = PortRuntime().route_prompt(prompt, limit=limit)
10-
lines = ['# Query Engine Route', '', f'Prompt: {prompt}', '']
10+
lines = ["# Query Engine Route", "", f"Prompt: {prompt}", ""]
1111
if not matches:
12-
lines.append('No mirrored command/tool matches found.')
13-
return '\n'.join(lines)
14-
lines.append('Matches:')
15-
lines.extend(f'- [{match.kind}] {match.name} ({match.score}) — {match.source_hint}' for match in matches)
16-
return '\n'.join(lines)
12+
lines.append("No mirrored command/tool matches found.")
13+
return "\n".join(lines)
14+
lines.append("Matches:")
15+
lines.extend(
16+
f"- [{match.kind}] {match.name} ({match.score}) — {match.source_hint}"
17+
for match in matches
18+
)
19+
return "\n".join(lines)
1720

1821

19-
__all__ = ['QueryEnginePort', 'QueryEngineRuntime']
22+
__all__ = ["QueryEnginePort", "QueryEngineRuntime"]

src/Tool.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,6 @@ class ToolDefinition:
1010

1111

1212
DEFAULT_TOOLS = (
13-
ToolDefinition('port_manifest', 'Summarize the active Python workspace'),
14-
ToolDefinition('query_engine', 'Render a Python-first porting summary'),
13+
ToolDefinition("port_manifest", "Summarize the active Python workspace"),
14+
ToolDefinition("query_engine", "Render a Python-first porting summary"),
1515
)

src/__init__.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,20 @@
1010
from .tools import PORTED_TOOLS, build_tool_backlog
1111

1212
__all__ = [
13-
'ParityAuditResult',
14-
'PortManifest',
15-
'PortRuntime',
16-
'QueryEnginePort',
17-
'RuntimeSession',
18-
'StoredSession',
19-
'TurnResult',
20-
'PORTED_COMMANDS',
21-
'PORTED_TOOLS',
22-
'build_command_backlog',
23-
'build_port_manifest',
24-
'build_system_init_message',
25-
'build_tool_backlog',
26-
'load_session',
27-
'run_parity_audit',
28-
'save_session',
13+
"ParityAuditResult",
14+
"PortManifest",
15+
"PortRuntime",
16+
"QueryEnginePort",
17+
"RuntimeSession",
18+
"StoredSession",
19+
"TurnResult",
20+
"PORTED_COMMANDS",
21+
"PORTED_TOOLS",
22+
"build_command_backlog",
23+
"build_port_manifest",
24+
"build_system_init_message",
25+
"build_tool_backlog",
26+
"load_session",
27+
"run_parity_audit",
28+
"save_session",
2929
]

src/bootstrap_graph.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,20 @@ class BootstrapGraph:
88
stages: tuple[str, ...]
99

1010
def as_markdown(self) -> str:
11-
lines = ['# Bootstrap Graph', '']
12-
lines.extend(f'- {stage}' for stage in self.stages)
13-
return '\n'.join(lines)
11+
lines = ["# Bootstrap Graph", ""]
12+
lines.extend(f"- {stage}" for stage in self.stages)
13+
return "\n".join(lines)
1414

1515

1616
def build_bootstrap_graph() -> BootstrapGraph:
1717
return BootstrapGraph(
1818
stages=(
19-
'top-level prefetch side effects',
20-
'warning handler and environment guards',
21-
'CLI parser and pre-action trust gate',
22-
'setup() + commands/agents parallel load',
23-
'deferred init after trust',
24-
'mode routing: local / remote / ssh / teleport / direct-connect / deep-link',
25-
'query engine submit loop',
19+
"top-level prefetch side effects",
20+
"warning handler and environment guards",
21+
"CLI parser and pre-action trust gate",
22+
"setup() + commands/agents parallel load",
23+
"deferred init after trust",
24+
"mode routing: local / remote / ssh / teleport / direct-connect / deep-link",
25+
"query engine submit loop",
2626
)
2727
)

src/command_graph.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,18 +17,29 @@ def flattened(self) -> tuple[PortingModule, ...]:
1717

1818
def as_markdown(self) -> str:
1919
lines = [
20-
'# Command Graph',
21-
'',
22-
f'Builtins: {len(self.builtins)}',
23-
f'Plugin-like commands: {len(self.plugin_like)}',
24-
f'Skill-like commands: {len(self.skill_like)}',
20+
"# Command Graph",
21+
"",
22+
f"Builtins: {len(self.builtins)}",
23+
f"Plugin-like commands: {len(self.plugin_like)}",
24+
f"Skill-like commands: {len(self.skill_like)}",
2525
]
26-
return '\n'.join(lines)
26+
return "\n".join(lines)
2727

2828

2929
def build_command_graph() -> CommandGraph:
3030
commands = get_commands()
31-
builtins = tuple(module for module in commands if 'plugin' not in module.source_hint.lower() and 'skills' not in module.source_hint.lower())
32-
plugin_like = tuple(module for module in commands if 'plugin' in module.source_hint.lower())
33-
skill_like = tuple(module for module in commands if 'skills' in module.source_hint.lower())
34-
return CommandGraph(builtins=builtins, plugin_like=plugin_like, skill_like=skill_like)
31+
builtins = tuple(
32+
module
33+
for module in commands
34+
if "plugin" not in module.source_hint.lower()
35+
and "skills" not in module.source_hint.lower()
36+
)
37+
plugin_like = tuple(
38+
module for module in commands if "plugin" in module.source_hint.lower()
39+
)
40+
skill_like = tuple(
41+
module for module in commands if "skills" in module.source_hint.lower()
42+
)
43+
return CommandGraph(
44+
builtins=builtins, plugin_like=plugin_like, skill_like=skill_like
45+
)

src/context.py

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,30 +18,34 @@ class PortContext:
1818

1919
def build_port_context(base: Path | None = None) -> PortContext:
2020
root = base or Path(__file__).resolve().parent.parent
21-
source_root = root / 'src'
22-
tests_root = root / 'tests'
23-
assets_root = root / 'assets'
24-
archive_root = root / 'archive' / 'claude_code_ts_snapshot' / 'src'
21+
source_root = root / "src"
22+
tests_root = root / "tests"
23+
assets_root = root / "assets"
24+
archive_root = root / "archive" / "claude_code_ts_snapshot" / "src"
2525
return PortContext(
2626
source_root=source_root,
2727
tests_root=tests_root,
2828
assets_root=assets_root,
2929
archive_root=archive_root,
30-
python_file_count=sum(1 for path in source_root.rglob('*.py') if path.is_file()),
31-
test_file_count=sum(1 for path in tests_root.rglob('*.py') if path.is_file()),
32-
asset_file_count=sum(1 for path in assets_root.rglob('*') if path.is_file()),
30+
python_file_count=sum(
31+
1 for path in source_root.rglob("*.py") if path.is_file()
32+
),
33+
test_file_count=sum(1 for path in tests_root.rglob("*.py") if path.is_file()),
34+
asset_file_count=sum(1 for path in assets_root.rglob("*") if path.is_file()),
3335
archive_available=archive_root.exists(),
3436
)
3537

3638

3739
def render_context(context: PortContext) -> str:
38-
return '\n'.join([
39-
f'Source root: {context.source_root}',
40-
f'Test root: {context.tests_root}',
41-
f'Assets root: {context.assets_root}',
42-
f'Archive root: {context.archive_root}',
43-
f'Python files: {context.python_file_count}',
44-
f'Test files: {context.test_file_count}',
45-
f'Assets: {context.asset_file_count}',
46-
f'Archive available: {context.archive_available}',
47-
])
40+
return "\n".join(
41+
[
42+
f"Source root: {context.source_root}",
43+
f"Test root: {context.tests_root}",
44+
f"Assets root: {context.assets_root}",
45+
f"Archive root: {context.archive_root}",
46+
f"Python files: {context.python_file_count}",
47+
f"Test files: {context.test_file_count}",
48+
f"Assets: {context.asset_file_count}",
49+
f"Archive available: {context.archive_available}",
50+
]
51+
)

src/cost_tracker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@ class CostTracker:
1010

1111
def record(self, label: str, units: int) -> None:
1212
self.total_units += units
13-
self.events.append(f'{label}:{units}')
13+
self.events.append(f"{label}:{units}")

0 commit comments

Comments
 (0)