-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathsplit_coder.py
More file actions
2080 lines (1848 loc) · 85.3 KB
/
split_coder.py
File metadata and controls
2080 lines (1848 loc) · 85.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
split_coder.py — Architecture-aware Python file splitter with incremental update support.
Analyzes a large monolithic Python file using AST, automatically identifies
architectural components, and splits it into a proper Python package structure.
Usage:
python split_coder.py <source.py>
python split_coder.py <source.py> --output-dir ./my_package
python split_coder.py <source.py> --dry-run # preview without writing
python split_coder.py <source.py> --update # incremental update
python split_coder.py <source.py> --show-tree # print tree after split
python split_coder.py <source.py> --dump-layout # print detected layout as JSON
"""
from __future__ import annotations
import argparse
import ast
import hashlib
import json
import py_compile
import re
import shutil
import subprocess
import symtable
import sys
import textwrap
import unicodedata
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple
# ─── Data Structures ─────────────────────────────────────────────────────────
@dataclass
class NodeInfo:
"""Metadata for one top-level AST node."""
name: str # Symbol name (class/function name, or synthetic expression label)
kind: str # "class" | "function" | "constant" | "assignment" | "expression" | "other"
lineno: int # Start line (1-based)
end_lineno: int # End line (1-based)
source_hash: str = "" # SHA256 of the source lines
target_module: str = "" # Output module path (relative to package root)
bases: List[str] = field(default_factory=list) # For classes: base class names
@dataclass
class ManifestEntry:
"""Per-node record stored in the manifest."""
name: str
kind: str
lineno: int
end_lineno: int
source_hash: str
target_module: str
@dataclass
class SplitManifest:
"""Tracks the state of a split for incremental updates."""
source_path: str
source_hash: str
output_dir: str
package_name: str
nodes: List[ManifestEntry] = field(default_factory=list)
layout_config: str = "" # Path to custom layout config, if any
FILENAME = ".split_manifest.json"
def save(self, output_dir: Path) -> None:
path = output_dir / self.FILENAME
path.write_text(json.dumps(asdict(self), indent=2), encoding="utf-8")
@classmethod
def load(cls, output_dir: Path) -> Optional["SplitManifest"]:
path = output_dir / cls.FILENAME
if not path.exists():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
data["nodes"] = [ManifestEntry(**n) for n in data.get("nodes", [])]
return cls(**data)
except Exception:
return None
@dataclass(frozen=True)
class ImportAlias:
"""One imported alias from an import statement."""
name: str
asname: Optional[str] = None
@property
def bound_name(self) -> str:
return self.asname or self.name.split(".")[0]
def render(self) -> str:
if self.asname:
return f"{self.name} as {self.asname}"
return self.name
@dataclass
class ImportStatement:
"""Metadata for one top-level import statement or try-import block."""
kind: str
lineno: int
end_lineno: int
aliases: List[ImportAlias] = field(default_factory=list)
module: Optional[str] = None
level: int = 0
source: str = ""
bound_names: Set[str] = field(default_factory=set)
always_include: bool = False
# ─── Default Layout Rules ────────────────────────────────────────────────────
#
# Each key is a relative module path within the output package.
# Values are lists of symbol names or regex patterns (prefix with "~").
#
# The layout is tried in order; the FIRST match wins.
# Special rules:
# "~^[A-Z][A-Z0-9_]{3,}$" → matches ALL_CAPS constants
# "_unclassified.py" → fallback for unmatched symbols
DEFAULT_LAYOUT: Dict[str, List[str]] = {
# ── Package root ──────────────────────────────────────────────────────
"__init__.py": [],
"__main__.py": ["main", "~^_main_guard_"],
# ── Configuration & constants ─────────────────────────────────────────
"config/__init__.py": [],
"config/constants.py": [
# UPPER_CASE constants
"~^[A-Z][A-Z0-9_]{3,}$",
"APP_VERSION",
"_SHELL_AUTO_CONFIRM_PATTERNS",
"_TOOL_TIMEOUT_MAP",
"_DEFAULT_TOOL_TIMEOUT",
"RUNTIME_CONTROL_HINT_PREFIXES",
"RETRY_RUNTIME_HINT_PREFIXES",
],
"config/paths.py": [
"_resolve_default_agent_workdir", "_migrate_legacy_runtime_roots",
"WORKDIR", "CODES_ROOT", "LLM_CONFIG_PATH", "SCRIPT_DIR",
"REPO_ROOT", "detect_repo_root",
],
"config/settings.py": [
"normalize_ui_language", "normalize_ui_style", "supported_ui_languages_payload",
"backend_i18n_text", "backend_role_label",
"infer_user_complexity_value", "normalize_task_complexity",
"task_complexity_rank", "task_complexity_at_least", "max_task_complexity",
"normalize_execution_mode", "model_language_instruction", "_detect_os_shell_instruction",
"resolve_web_ui_dir_path", "resolve_optional_file_path", "resolve_skills_root_path",
"_count_skill_markdown_files", "select_preferred_skills_root",
"load_web_ui_config_file", "extract_show_upload_list_setting",
"extract_ui_style_setting", "default_multimodal_capabilities", "_to_bool_like",
"infer_model_multimodal_capabilities", "parse_capability_overrides",
"merge_multimodal_capabilities", "parse_media_endpoints",
"load_llm_config_from_source", "~^load_llm_config",
"looks_like_llm_config", "parse_llm_config_profiles",
],
# ── Utilities ─────────────────────────────────────────────────────────
"utils/__init__.py": [],
"utils/errors.py": [
"EmptyActionError", "CircuitBreakerTriggered", "~Error$", "~Exception$",
],
"utils/text.py": [
"MAX_TOOL_OUTPUT", "SOCKET_NOISE_LINE_PATTERNS",
"trim", "_fmt_export_ts", "_html_esc", "_text_to_minimal_pdf",
"normalize_embedded_newlines", "_map_todo_status_token",
"split_todo_status_text", "extract_todo_rows_from_text",
"infer_todo_status_from_text", "split_structured_todo_content",
"normalize_work_text", "filter_runtime_noise_lines",
"parse_front_matter", "make_numbered_diff", "make_unified_diff", "render_numbered_diff_text",
"_compress_rows_keep_hotspot", "_hotspot_index", "_row_is_hot", "_skip_row",
"_focused_diff_rows_from_opcodes",
],
"utils/http.py": [
"_URL_OPEN_ORIGINAL",
"_HTTP_SSL_CONTEXT",
"_shared_http_ssl_context",
"urlopen",
],
"utils/media.py": [
"guess_mime_from_name", "_convert_image_to_safe_format", "guess_ext_from_mime",
],
"utils/compress.py": ["compress_text_blob", "decompress_text_blob"],
"utils/json_utils.py": [
"JSON_FSYNC_ENABLED",
"json_dumps", "parse_json_object", "extract_json_object_from_text",
"repair_truncated_json_object", "parse_tool_arguments", "parse_tool_arguments_with_error",
"_json_default_copy", "_read_json_file", "_write_json_file",
"tool_def", "canonicalize_tool_name",
"TOOLS", "TOOL_REQUIRED_ARGS", "TOOL_SPEC_BY_NAME", "TOOL_NAME_FUZZY_MAP",
],
"utils/files.py": [
"safe_path", "_safe_js_filename", "_sha256_bytes", "_sha256_file",
"_normalize_js_lib_asset_ref", "_resolve_js_lib_asset_path",
"_discover_extra_js_lib_files", "_download_http_bytes",
"_offline_js_entry_relative_path", "_archive_member_relative_path",
"_path_size_bytes", "_extract_archive_to_dir",
"_package_required_paths", "_package_install_ready",
"_postprocess_offline_js_package", "_ensure_offline_js_package",
"offline_js_lib_root", "_render_offline_js_catalog_md",
"load_offline_js_lib_index", "ensure_offline_js_libs",
"_normalize_external_js_url", "is_external_js_src",
"match_offline_js_catalog_by_url", "cache_external_js_url",
"try_read_text",
],
"utils/misc.py": [
"DEFAULT_TIMEOUT_SECONDS", "MIN_TIMEOUT_SECONDS", "MAX_TIMEOUT_SECONDS",
"BENIGN_SOCKET_DEBUG_LOG_ENABLED", "BENIGN_SOCKET_LOG_INTERVAL_SECONDS",
"now_ts", "make_id", "sanitize_profile_id", "detect_repo_root",
"detect_local_lan_ip", "is_benign_socket_error", "_socket_error_code",
"_log_benign_socket_error_limited", "swallow_benign_socket_error",
"normalize_timeout_seconds", "BENIGN_SOCKET_DEBUG_LOG_ENABLED",
"BENIGN_SOCKET_LOG_INTERVAL_SECONDS",
"_benign_socket_log_lock", "_benign_socket_log_state",
"_module_exists", "_meta_string_list", "user_id_from_ip",
],
"utils/crypto.py": ["CryptoBox"],
# ── LLM / Ollama ──────────────────────────────────────────────────────
"llm/__init__.py": [],
"llm/client.py": ["OllamaError", "OllamaClient"],
"llm/utils.py": [
"probe_ollama_environment", "list_ollama_models", "list_ollama_models_cached",
"resolve_ollama_model", "infer_thinking_model", "split_thinking_content",
"strip_thinking_content", "check_ollama_model_ready", "list_loaded_ollama_models",
"wake_ollama_model", "try_pull_ollama_model", "ordered_model_candidates",
"pick_working_ollama_model", "extract_base_url", "complete_chat_endpoint",
"normalize_openai_compat_provider_name", "is_openai_compat_provider",
"is_openai_like_provider", "openai_compat_probe_headers",
"openai_compat_model_list_urls", "extract_openai_compat_model_ids",
"_is_http_url", "_resolve_local_path",
"_OLLAMA_TAG_CACHE", "_OLLAMA_TAG_CACHE_LOCK",
],
# ── Agent subsystems ──────────────────────────────────────────────────
"agent/__init__.py": [],
"agent/events.py": ["EventHub"],
"agent/todo.py": ["TodoManager"],
"agent/tasks.py": ["TaskManager"],
"agent/background.py": ["BackgroundManager"],
"agent/bus.py": ["MessageBus"],
"agent/worktree.py": ["WorktreeManager"],
# ── Skills ────────────────────────────────────────────────────────────
"skills/__init__.py": [],
"skills/store.py": [
"SkillStore",
"_BUILTIN_SKILLS",
"_build_skills_gen_skill_content",
"_sanitize_skill_slug",
"_skill_knowledge_files",
"analyze_skill_building_knowledge",
"ensure_embedded_clawhub_skills",
"ensure_embedded_skills",
"ensure_embedded_skills_at_root",
"detect_upload_parser_capabilities",
"_render_cap_markdown",
"ensure_runtime_skills",
"~^ensure_generated_",
"~^_write_text_if_changed",
],
# ── Session ───────────────────────────────────────────────────────────
"session/__init__.py": [],
"session/state.py": ["SessionState"],
"session/manager.py": ["SessionManager"],
# ── RAG / Knowledge ───────────────────────────────────────────────────
"rag/__init__.py": [],
"rag/parsers.py": [
"CodeContentParser", "RAGContentParser",
"_rag_safe_name", "_rag_detect_language", "_rag_cjk_ngrams", "_rag_is_noise_token",
"_rag_entity_allowed", "_rag_filter_entities", "_rag_filename_entity_aliases",
"_rag_apply_filename_entity_policy", "_rag_choose_community", "_rag_tokenize",
"_rag_expand_tokens", "_rag_extract_entities", "_rag_classify_document", "_rag_chunk_text",
"_code_language_from_name", "_code_is_test_path",
"build_code_preview_rows", "is_code_preview_candidate",
"normalize_rel_preview_path", "preview_kind_for_path",
"_CallCollector", "_ALGO_COMPLEXITY_RE", "_ALGO_STEP_RE",
"_ALGO_MATH_VARS", "_ALGO_DOC_KEYWORDS", "_detect_algo_chunk",
],
"rag/index.py": [
"TFGraphIDFIndex", "CodeGraphIndex",
"_code_choose_community", "_code_is_test_path", "_code_language_from_name",
"_code_module_name", "_code_query_terms",
],
"rag/store.py": ["RAGLibraryStore", "CodeLibraryStore", "WikiStore", "WorkflowMemoryStore"],
"rag/ingestion.py": [
"RAGIngestionService", "CodeIngestionService",
"~^_rag_",
],
# ── App ───────────────────────────────────────────────────────────────
"app/__init__.py": [],
"app/context.py": ["AppContext"],
# ── HTTP Server ───────────────────────────────────────────────────────
"server/__init__.py": [],
"server/handlers.py": [
"AgentHTTPServer", "Handler", "SkillsHandler",
"RagAdminHandler", "CodeAdminHandler", "user_id_from_ip",
],
# ── Catch-all ─────────────────────────────────────────────────────────
"_unclassified.py": [],
}
# ─── Architecture Analyzer ───────────────────────────────────────────────────
class ArchitectureAnalyzer:
"""Parses the source file with AST and extracts top-level node metadata."""
def __init__(self, source_path: Path) -> None:
self.source_path = source_path
self.source_lines: List[str] = []
self.tree: ast.Module | None = None
self.nodes: List[NodeInfo] = []
self.import_statements: List[ImportStatement] = []
def analyze(self) -> List[NodeInfo]:
"""Parse and classify all top-level nodes."""
text = self.source_path.read_text(encoding="utf-8")
self.source_lines = text.splitlines(keepends=True)
print(f" Parsing {len(self.source_lines):,} lines with AST...")
self.tree = ast.parse(text, filename=str(self.source_path))
self.nodes = []
self.import_statements = []
for node in self.tree.body:
self._register_top_level_import(node)
infos = self._extract_node_info(node)
self.nodes.extend(infos)
return self.nodes
def _extract_node_info(self, node: ast.AST) -> List[NodeInfo]:
"""Convert one AST body node into NodeInfo records."""
results: List[NodeInfo] = []
if isinstance(node, (ast.ClassDef,)):
bases = [self._name_of(b) for b in node.bases]
info = NodeInfo(
name=node.name,
kind="class",
lineno=node.lineno,
end_lineno=node.end_lineno or node.lineno,
bases=bases,
)
info.source_hash = self._hash_lines(info.lineno, info.end_lineno)
results.append(info)
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
info = NodeInfo(
name=node.name,
kind="function",
lineno=node.lineno,
end_lineno=node.end_lineno or node.lineno,
)
info.source_hash = self._hash_lines(info.lineno, info.end_lineno)
results.append(info)
elif isinstance(node, ast.Assign):
# Capture top-level assignments (constants, config dicts, etc.)
for target in node.targets:
name = self._name_of(target)
if name:
end = node.end_lineno or node.lineno
kind = "constant" if re.match(r"^[A-Z][A-Z0-9_]{2,}$", name) else "assignment"
info = NodeInfo(
name=name,
kind=kind,
lineno=node.lineno,
end_lineno=end,
)
info.source_hash = self._hash_lines(info.lineno, info.end_lineno)
results.append(info)
elif isinstance(node, ast.AnnAssign):
name = self._name_of(node.target)
if name:
end = node.end_lineno or node.lineno
kind = "constant" if re.match(r"^[A-Z][A-Z0-9_]{2,}$", name) else "assignment"
info = NodeInfo(
name=name,
kind=kind,
lineno=node.lineno,
end_lineno=end,
)
info.source_hash = self._hash_lines(info.lineno, info.end_lineno)
results.append(info)
elif isinstance(node, (ast.Import, ast.ImportFrom)):
# Track the first import block as a special node
info = NodeInfo(
name=f"_import_{node.lineno}",
kind="import",
lineno=node.lineno,
end_lineno=node.end_lineno or node.lineno,
)
info.source_hash = self._hash_lines(info.lineno, info.end_lineno)
results.append(info)
elif isinstance(node, ast.If):
# Handle `if __name__ == "__main__":` blocks
if self._is_main_guard(node):
info = NodeInfo(
name=f"_main_guard_{node.lineno}",
kind="main_guard",
lineno=node.lineno,
end_lineno=node.end_lineno or node.lineno,
)
info.source_hash = self._hash_lines(info.lineno, info.end_lineno)
results.append(info)
elif isinstance(node, ast.Expr):
# Top-level expression statements: dict updates, docstrings, registry calls, etc.
end = node.end_lineno or node.lineno
info = NodeInfo(
name=self._expression_node_name(node),
kind="expression",
lineno=node.lineno,
end_lineno=end,
)
info.source_hash = self._hash_lines(info.lineno, info.end_lineno)
results.append(info)
elif isinstance(node, ast.Try):
# top-level try (e.g. `try: import yaml`)
end = node.end_lineno or node.lineno
# Collect names assigned in except handlers
names = []
for handler in node.handlers:
if handler.name:
names.append(handler.name)
for child in ast.walk(node):
if isinstance(child, (ast.Import, ast.ImportFrom)):
for alias in child.names:
names.append(alias.asname or alias.name.split(".")[0])
name = "_try_import_" + "_".join(names) if names else f"_try_{node.lineno}"
info = NodeInfo(
name=name,
kind="import",
lineno=node.lineno,
end_lineno=end,
)
info.source_hash = self._hash_lines(info.lineno, info.end_lineno)
results.append(info)
return results
@staticmethod
def _name_of(node: ast.AST) -> str:
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Attribute):
return node.attr
return ""
def _expression_node_name(self, node: ast.Expr) -> str:
base = self._expression_anchor_label(node)
return f"{base}_l{node.lineno}"
def _expression_anchor_label(self, node: ast.Expr) -> str:
value = node.value
if (
self.tree is not None
and self.tree.body
and self.tree.body[0] is node
and isinstance(value, ast.Constant)
and isinstance(value.value, str)
):
return "module_docstring"
if isinstance(value, ast.Call):
tokens = self._anchor_tokens(value.func)
return "call_" + "_".join(tokens or ["anonymous"])
if isinstance(value, ast.Constant):
return self._literal_expression_label(value.value)
if isinstance(value, ast.Dict):
return "dict_literal"
if isinstance(value, ast.List):
return "list_literal"
if isinstance(value, ast.Tuple):
return "tuple_literal"
if isinstance(value, ast.Set):
return "set_literal"
if isinstance(value, ast.JoinedStr):
return "formatted_string"
if isinstance(value, ast.Compare):
return "comparison"
if isinstance(value, ast.BoolOp):
return "boolean_operation"
if isinstance(value, ast.BinOp):
return "binary_operation"
if isinstance(value, ast.UnaryOp):
return "unary_operation"
return f"{self._slugify_fragment(type(value).__name__) or 'value'}_expression"
def _anchor_tokens(self, node: ast.AST, depth: int = 0) -> List[str]:
if depth > 6:
return []
if isinstance(node, ast.Name):
token = self._slugify_fragment(node.id)
return [token] if token else []
if isinstance(node, ast.Attribute):
return self._merge_anchor_tokens(
self._anchor_tokens(node.value, depth + 1),
self._slugify_fragment(node.attr),
)
if isinstance(node, ast.Subscript):
return self._merge_anchor_tokens(
self._anchor_tokens(node.value, depth + 1),
self._anchor_tokens(node.slice, depth + 1),
)
if isinstance(node, ast.Call):
return self._merge_anchor_tokens(self._anchor_tokens(node.func, depth + 1), "result")
if isinstance(node, ast.Constant):
token = self._constant_anchor_token(node.value)
return [token] if token else []
if isinstance(node, (ast.Tuple, ast.List)):
tokens: List[str] = []
for elt in node.elts[:2]:
tokens = self._merge_anchor_tokens(tokens, self._anchor_tokens(elt, depth + 1))
return tokens
if isinstance(node, ast.Dict):
return ["dict"]
if isinstance(node, ast.Slice):
return ["slice"]
return []
@staticmethod
def _merge_anchor_tokens(*parts: object) -> List[str]:
merged: List[str] = []
for part in parts:
if not part:
continue
if isinstance(part, list):
items = part
else:
items = [part]
for item in items:
token = str(item or "").strip("_")
if not token:
continue
if merged and merged[-1] == token:
continue
merged.append(token)
if len(merged) >= 6:
return merged
return merged
@staticmethod
def _literal_expression_label(value: object) -> str:
if isinstance(value, str):
return "string_literal"
if isinstance(value, bytes):
return "bytes_literal"
if isinstance(value, bool):
return "boolean_literal"
if isinstance(value, (int, float, complex)):
return "numeric_literal"
if value is None:
return "none_literal"
return "literal_value"
def _constant_anchor_token(self, value: object) -> str:
if isinstance(value, str):
token = self._slugify_fragment(value)
return token if token and token != "value" else "string"
if isinstance(value, bytes):
return "bytes"
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (int, float)):
return self._slugify_fragment(value)
if value is None:
return "none"
return self._slugify_fragment(type(value).__name__) or "value"
@staticmethod
def _slugify_fragment(value: object) -> str:
text = str(value or "").strip()
if not text:
return ""
normalized = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
normalized = normalized.lower()
normalized = re.sub(r"[^a-z0-9_]+", "_", normalized)
normalized = re.sub(r"_+", "_", normalized).strip("_")
if not normalized:
digest = hashlib.sha1(text.encode("utf-8")).hexdigest()[:8]
return f"u_{digest}"
if normalized[0].isdigit():
normalized = f"n_{normalized}"
return normalized[:48]
@staticmethod
def _is_main_guard(node: ast.If) -> bool:
test = node.test
if isinstance(test, ast.Compare):
if (isinstance(test.left, ast.Name) and test.left.id == "__name__"
and len(test.ops) == 1 and isinstance(test.ops[0], ast.Eq)
and len(test.comparators) == 1
and isinstance(test.comparators[0], ast.Constant)
and test.comparators[0].value == "__main__"):
return True
return False
def _hash_lines(self, start: int, end: int) -> str:
chunk = "".join(self.source_lines[start - 1:end])
return hashlib.sha256(chunk.encode()).hexdigest()[:16]
def get_source_lines(self, start: int, end: int) -> str:
"""Extract source lines (1-based, inclusive)."""
return "".join(self.source_lines[start - 1:end])
def get_all_import_lines(self) -> str:
"""Return all top-level import statements as a block."""
lines = []
for node in self.nodes:
if node.kind == "import":
lines.append(self.get_source_lines(node.lineno, node.end_lineno))
return "\n".join(lines)
def select_import_lines(self, referenced_names: Set[str]) -> List[str]:
"""Return only the import lines required by the given referenced names."""
lines: List[str] = []
for stmt in self.import_statements:
if stmt.always_include:
lines.append(self._render_import_statement(stmt))
continue
if stmt.kind == "try":
if stmt.bound_names & referenced_names:
lines.append(stmt.source.rstrip("\n"))
continue
aliases = [alias for alias in stmt.aliases if alias.bound_name in referenced_names]
if aliases:
lines.append(self._render_import_statement(stmt, aliases))
return lines
def _register_top_level_import(self, node: ast.AST) -> None:
if isinstance(node, ast.Import):
aliases = [ImportAlias(alias.name, alias.asname) for alias in node.names]
self.import_statements.append(
ImportStatement(
kind="import",
lineno=node.lineno,
end_lineno=node.end_lineno or node.lineno,
aliases=aliases,
source=self.get_source_lines(node.lineno, node.end_lineno or node.lineno),
bound_names={alias.bound_name for alias in aliases},
)
)
return
if isinstance(node, ast.ImportFrom):
aliases = [ImportAlias(alias.name, alias.asname) for alias in node.names]
self.import_statements.append(
ImportStatement(
kind="from",
lineno=node.lineno,
end_lineno=node.end_lineno or node.lineno,
aliases=aliases,
module=node.module,
level=node.level,
source=self.get_source_lines(node.lineno, node.end_lineno or node.lineno),
bound_names={alias.bound_name for alias in aliases},
always_include=node.module == "__future__",
)
)
return
if isinstance(node, ast.Try):
bound_names: Set[str] = set()
for child in ast.walk(node):
if isinstance(child, (ast.Import, ast.ImportFrom)):
for alias in child.names:
bound_names.add(alias.asname or alias.name.split(".")[0])
if bound_names:
self.import_statements.append(
ImportStatement(
kind="try",
lineno=node.lineno,
end_lineno=node.end_lineno or node.lineno,
source=self.get_source_lines(node.lineno, node.end_lineno or node.lineno),
bound_names=bound_names,
)
)
@staticmethod
def _render_import_statement(
stmt: ImportStatement,
aliases: Optional[List[ImportAlias]] = None,
) -> str:
selected = aliases or stmt.aliases
if stmt.kind == "import":
return "import " + ", ".join(alias.render() for alias in selected)
if stmt.kind == "from":
dots = "." * stmt.level
module = stmt.module or ""
origin = f"{dots}{module}" if module else dots
return f"from {origin} import " + ", ".join(alias.render() for alias in selected)
return stmt.source.rstrip("\n")
# ─── Module Router ────────────────────────────────────────────────────────────
class ModuleRouter:
"""Routes each NodeInfo to an output module path using layout rules."""
def __init__(self, layout: Dict[str, List[str]]) -> None:
self.layout = layout
self._fallback_classifier = AutoLayoutGenerator()
# Pre-compile: list of (module_path, list_of_matchers)
self._rules: List[Tuple[str, List[Tuple[str, object]]]] = []
for mod_path, patterns in layout.items():
matchers: List[Tuple[str, object]] = []
for pat in patterns:
if pat.startswith("~"):
matchers.append(("regex", re.compile(pat[1:])))
else:
matchers.append(("exact", pat))
self._rules.append((mod_path, matchers))
def route(self, node: NodeInfo) -> str:
"""Return the target module path for a node."""
# Import nodes always go to a special _imports collector
if node.kind == "import":
return "_imports"
name = node.name
for mod_path, matchers in self._rules:
for kind, matcher in matchers:
if kind == "exact" and name == matcher:
return mod_path
# Broad regex buckets only apply after exact-name routing.
for mod_path, matchers in self._rules:
if not matchers:
continue
for kind, matcher in matchers:
if kind == "regex" and matcher.search(name):
return mod_path
fallback_module = self._fallback_classifier._classify(node)
if fallback_module != "_unclassified.py":
return fallback_module
return "_unclassified.py"
def assign_all(self, nodes: List[NodeInfo]) -> None:
"""Assign target_module to all nodes in-place."""
for node in nodes:
node.target_module = self.route(node)
self._adopt_contextual_expression_nodes(nodes)
def _adopt_contextual_expression_nodes(self, nodes: List[NodeInfo]) -> None:
"""Attach anonymous top-level expressions to the nearest classified neighbor."""
for index, node in enumerate(nodes):
if node.target_module != "_unclassified.py":
continue
if node.kind != "expression":
continue
contextual_module = self._nearest_contextual_module(nodes, index)
if contextual_module:
node.target_module = contextual_module
def _nearest_contextual_module(self, nodes: List[NodeInfo], index: int) -> str:
current = nodes[index]
prev_node = self._nearest_classified_neighbor(nodes, index, -1)
next_node = self._nearest_classified_neighbor(nodes, index, 1)
if prev_node and next_node and prev_node.target_module == next_node.target_module:
return prev_node.target_module
candidates: List[Tuple[int, int, str]] = []
if prev_node and prev_node.target_module:
gap = max(0, current.lineno - prev_node.end_lineno)
candidates.append((gap, 0, prev_node.target_module))
if next_node and next_node.target_module:
gap = max(0, next_node.lineno - current.end_lineno)
candidates.append((gap, 1, next_node.target_module))
if not candidates:
return ""
candidates.sort()
closest_gap, _, module = candidates[0]
return module if closest_gap <= 240 or len(candidates) == 1 else ""
@staticmethod
def _nearest_classified_neighbor(
nodes: List[NodeInfo],
index: int,
direction: int,
) -> Optional[NodeInfo]:
cursor = index + direction
while 0 <= cursor < len(nodes):
candidate = nodes[cursor]
if candidate.kind == "import":
cursor += direction
continue
if candidate.target_module and candidate.target_module != "_unclassified.py":
return candidate
cursor += direction
return None
# ─── Dependency Analyzer ──────────────────────────────────────────────────────
class DependencyAnalyzer:
"""Analyzes cross-module name dependencies with scope awareness."""
def __init__(self, analyzer: ArchitectureAnalyzer, nodes: List[NodeInfo]) -> None:
self.analyzer = analyzer
self.nodes = nodes
# Build symbol → module map (only non-import nodes)
self.symbol_to_module: Dict[str, str] = {}
for n in nodes:
if n.kind not in ("import",) and not n.name.startswith("_import_") and not n.name.startswith("_try_"):
self.symbol_to_module[n.name] = n.target_module
def compute_dependency_map(self, module_path: str, module_nodes: List[NodeInfo]) -> Dict[str, Set[str]]:
"""Return dependency module -> symbols for one generated module."""
deps: Dict[str, Set[str]] = defaultdict(set)
for node in module_nodes:
if node.kind == "import":
continue
for name in self._node_referenced_symbols(node):
source_mod = self.symbol_to_module.get(name)
if source_mod and source_mod != module_path and source_mod != "_imports":
deps[source_mod].add(name)
return deps
def compute_imports(self, module_path: str, module_nodes: List[NodeInfo]) -> List[str]:
"""
For a given output module, compute the correct relative `from .X import Y`
statements needed to satisfy cross-module references.
Returns sorted list of import lines.
"""
deps = self.compute_dependency_map(module_path, module_nodes)
import_lines = []
for dep_mod, names in sorted(deps.items()):
if not names:
continue
rel = self._relative_import(module_path, dep_mod)
names_str = ", ".join(sorted(names))
import_lines.append(f"from {rel} import {names_str}")
return import_lines
def compute_referenced_names(self, module_nodes: List[NodeInfo]) -> Set[str]:
"""Return all referenced names across nodes in one generated module."""
referenced: Set[str] = set()
for node in module_nodes:
if node.kind == "import":
continue
referenced.update(self._node_referenced_symbols(node))
return referenced
def _node_referenced_symbols(self, node: NodeInfo) -> Set[str]:
source = self.analyzer.get_source_lines(node.lineno, node.end_lineno)
if not source.strip():
return set()
try:
table = symtable.symtable(source, str(self.analyzer.source_path), "exec")
except SyntaxError:
return set()
referenced: Set[str] = set()
self._collect_referenced_symbols(table, referenced)
return referenced
def _collect_referenced_symbols(self, table: symtable.SymbolTable, out: Set[str]) -> None:
table_type = table.get_type()
for symbol in table.get_symbols():
if not symbol.is_referenced() or symbol.is_imported() or symbol.is_parameter():
continue
if table_type == "module":
out.add(symbol.get_name())
continue
if symbol.is_global() or symbol.is_free() or symbol.is_nonlocal():
out.add(symbol.get_name())
for child in table.get_children():
self._collect_referenced_symbols(child, out)
@staticmethod
def _relative_import(current_module: str, dep_module: str) -> str:
"""
Compute the correct relative import prefix.
Examples:
config/constants.py → config/paths.py => .paths
session/state.py → agent/events.py => ..agent.events
rag/store.py → config/constants.py => ..config.constants
"""
cur_parts = current_module.replace(".py", "").split("/")
dep_parts = dep_module.replace(".py", "").split("/")
cur_pkg = cur_parts[:-1] # directory parts only
dep_pkg = dep_parts[:-1]
dep_file = dep_parts[-1]
# Find common ancestor package depth
common = 0
for a, b in zip(cur_pkg, dep_pkg):
if a == b:
common += 1
else:
break
# Number of levels to go up from current package
levels_up = len(cur_pkg) - common
dots = "." * (levels_up + 1) # "." = same pkg, ".." = parent, etc.
remaining = dep_pkg[common:]
if remaining:
path = ".".join(remaining) + "." + dep_file
else:
path = dep_file
return f"{dots}{path}"
# ─── Code Generator ───────────────────────────────────────────────────────────
class CodeGenerator:
"""Generates the content of each output module file."""
HEADER_TEMPLATE = '''\
# Auto-generated by split_coder.py — do not edit manually.
# Re-run split_coder.py to regenerate.
'''
SOURCE_BRIDGE_MODULE = "_source_bridge.py"
def __init__(
self,
analyzer: ArchitectureAnalyzer,
dep_analyzer: DependencyAnalyzer,
package_name: str,
source_path: str,
) -> None:
self.analyzer = analyzer
self.dep_analyzer = dep_analyzer
self.package_name = package_name
self.source_path = str(Path(source_path).resolve())
self.source_dir = str(Path(self.source_path).parent.resolve())
def generate_source_bridge(self) -> str:
return self.HEADER_TEMPLATE + f'''
from __future__ import annotations
import importlib.util
import sys
import threading
from pathlib import Path
_SPLIT_SOURCE_PATH = Path({self.source_path!r}).resolve()
_SPLIT_SOURCE_MODULE_NAME = "_clouds_coder_split_source_" + str(abs(hash(str(_SPLIT_SOURCE_PATH))))
_SPLIT_SOURCE_LOCK = threading.RLock()
_SPLIT_SOURCE_MODULE = None
def _split_source_module():
global _SPLIT_SOURCE_MODULE
if _SPLIT_SOURCE_MODULE is not None:
return _SPLIT_SOURCE_MODULE
with _SPLIT_SOURCE_LOCK:
if _SPLIT_SOURCE_MODULE is not None:
return _SPLIT_SOURCE_MODULE
spec = importlib.util.spec_from_file_location(_SPLIT_SOURCE_MODULE_NAME, str(_SPLIT_SOURCE_PATH))
if spec is None or spec.loader is None:
raise ImportError(f"cannot load split source: {{_SPLIT_SOURCE_PATH}}")
module = importlib.util.module_from_spec(spec)
sys.modules[_SPLIT_SOURCE_MODULE_NAME] = module
spec.loader.exec_module(module)
_SPLIT_SOURCE_MODULE = module
return module
def _split_source_symbol(name: str, default=None):
return getattr(_split_source_module(), str(name), default)
'''
@staticmethod
def _compact_imports(raw: str) -> str: