-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsplit_coder.py
More file actions
1496 lines (1334 loc) · 60.6 KB
/
Copy pathsplit_coder.py
File metadata and controls
1496 lines (1334 loc) · 60.6 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 a monolithic Python program into an executable, source-complete package.
The splitter preserves every top-level statement, stores the real source in the
owning module, and generates a small runtime that initializes those statements
in their original order. The ordered initialization is important for legacy
monoliths whose modules form cycles or whose registries are built by top-level
loops. The generated package never imports or reads the original monolith.
"""
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 tempfile
import textwrap
import unicodedata
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from pathlib import Path
GENERATOR_VERSION = "3.0"
GENERATED_HEADER = (
"# Auto-generated by split_coder.py v3 — do not edit manually.\n"
"# Re-run run_split.py to regenerate.\n"
"# flake8: noqa: F821\n"
"# ruff: noqa: F821\n"
)
@dataclass
class NodeInfo:
"""One source module top-level statement."""
order: int
name: str
kind: str
lineno: int
end_lineno: int
source_start: int
source_end: int
source_hash: str = ""
target_module: str = ""
bound_names: list[str] = field(default_factory=list)
bases: list[str] = field(default_factory=list)
generated_ast_index: int = -1
@dataclass
class ManifestEntry:
order: int
name: str
kind: str
lineno: int
end_lineno: int
source_start: int
source_end: int
source_hash: str
target_module: str
bound_names: list[str] = field(default_factory=list)
generated_ast_index: int = -1
@dataclass
class SplitManifest:
source_path: str
source_hash: str
output_dir: str
package_name: str
generator_version: str = GENERATOR_VERSION
source_statement_count: int = 0
nodes: list[ManifestEntry] = field(default_factory=list)
layout_config: str = ""
FILENAME = ".split_manifest.json"
def save(self, output_dir: Path) -> None:
(output_dir / self.FILENAME).write_text(
json.dumps(asdict(self), indent=2, ensure_ascii=False),
encoding="utf-8",
)
@classmethod
def load(cls, output_dir: Path) -> SplitManifest | None:
path = output_dir / cls.FILENAME
if not path.exists():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
if str(data.get("generator_version", "")) != GENERATOR_VERSION:
return None
data["nodes"] = [ManifestEntry(**row) for row in data.get("nodes", [])]
return cls(**data)
except Exception:
return None
@dataclass(frozen=True)
class ImportAlias:
name: str
asname: str | None = None
@property
def bound_name(self) -> str:
return self.asname or self.name.split(".")[0]
@dataclass
class ImportStatement:
kind: str
lineno: int
end_lineno: int
bound_names: set[str] = field(default_factory=set)
# Exact symbols reflect the current Clouds_Coder architecture. Regex rules are
# deliberately ordered from specific subsystems to the general constants bin.
DEFAULT_LAYOUT: dict[str, list[str]] = {
"__init__.py": [],
"app/__init__.py": [],
"app/main.py": ["main", "~^_main_guard_"],
"app/context.py": ["AppContext"],
"app/services.py": ["TelemetryStore", "ApplicationRegistry"],
"admin/__init__.py": [],
"admin/auth.py": ["AdminAuthError", "AdminAuthStore", "trusted_client_ip"],
"admin/config.py": ["~^_admin_"],
"admin/constants.py": ["~^ADMIN_"],
"config/__init__.py": [],
"config/paths.py": [
"SCRIPT_DIR", "WORKDIR", "CODES_ROOT", "LLM_CONFIG_PATH", "REPO_ROOT",
"_resolve_default_agent_workdir", "_migrate_legacy_runtime_roots", "detect_repo_root",
],
"config/settings.py": [
"~^(?:normalize|extract|infer|load|looks_like|parse|merge|resolve|select|supported|backend|runtime_environment|model_language|default_multimodal|set_web_search)_",
"_to_bool_like", "_detect_os_shell_instruction", "_count_skill_markdown_files",
"extract_single_no_plan_todo_settings", "_single_no_plan_todo_setting_sections",
"_single_no_plan_todo_setting_present", "user_memory_enabled_from_mode",
"task_complexity_rank", "task_complexity_at_least", "max_task_complexity",
],
"web/__init__.py": [],
"web/assets.py": ["INDEX_HTML", "APP_CSS", "APP_JS", "APP_TS"],
"web/skills_assets.py": ["SKILLS_INDEX_HTML", "SKILLS_EXTRA_CSS", "SKILLS_APP_JS"],
"web/admin_assets.py": ["ADMIN_INDEX_HTML", "ADMIN_CSS", "ADMIN_JS"],
"ide/__init__.py": [],
"ide/assets.py": ["IDE_INDEX_HTML", "IDE_CSS", "IDE_JS"],
"ide/handler.py": ["IdeHandler"],
"utils/__init__.py": [],
"utils/http.py": [
"_URL_OPEN_ORIGINAL", "_HTTP_SSL_CONTEXT", "_shared_http_ssl_context", "urlopen",
"json_response_bytes", "read_http_json_body", "close_if_http_request_body_unread",
],
"utils/errors.py": ["~(?:Error|Exception)$"],
"utils/text.py": [
"trim", "display_clean", "short_title_from", "filter_runtime_noise_lines",
"normalize_embedded_newlines", "_map_todo_status_token", "split_todo_status_text",
"extract_todo_rows_from_text", "decode_structured_todo_container",
"infer_todo_status_from_text", "split_structured_todo_content", "normalize_work_text",
"_fmt_export_ts", "_html_esc", "_text_to_minimal_pdf", "make_unified_diff",
"make_numbered_diff", "render_numbered_diff_text", "_skip_row", "_row_is_hot",
"_hotspot_index", "_compress_rows_keep_hotspot", "_focused_diff_rows_from_opcodes",
"safe_utf8_bytes", "escape_invalid_utf8_text", "sanitize_utf8_surrogates",
"decode_utf8_replace", "MAX_TOOL_OUTPUT", "SOCKET_NOISE_LINE_PATTERNS",
],
"utils/json_utils.py": [
"json_dumps", "parse_json_object", "extract_json_object_from_text",
"parse_tool_arguments", "repair_truncated_json_object", "parse_tool_arguments_with_error",
"_is_valid_json_object", "_scan_top_level_json_objects", "reconstruct_streamed_tool_args",
"_json_default_copy", "_read_json_file", "_write_json_file", "JSON_FSYNC_ENABLED",
],
"utils/files.py": [
"safe_path", "try_read_text", "_normalize_js_lib_asset_ref",
"~^(?:_?sha256|_?safe_js|_?download_http|offline_js|load_offline_js|ensure_offline_js|cache_external_js|is_external_js|match_offline_js|_normalize_external_js|_resolve_js|_discover_extra_js|_offline_js|_archive_member|_path_size|_extract_archive|_package_|_postprocess_offline|_ensure_offline|_render_offline_js)",
],
"utils/media.py": ["guess_mime_from_name", "guess_ext_from_mime", "_convert_image_to_safe_format"],
"utils/compress.py": ["compress_text_blob", "decompress_text_blob"],
"utils/crypto.py": ["CryptoBox"],
"utils/misc.py": [
"now_ts", "make_id", "sanitize_profile_id", "user_id_from_ip", "_meta_string_list",
"_module_exists", "is_benign_socket_error", "_socket_error_code",
"_log_benign_socket_error_limited", "swallow_benign_socket_error",
"normalize_timeout_seconds", "detect_local_lan_ip", "detect_local_lan_ip_cached",
"_LOCAL_LAN_IP_CACHE", "_benign_socket_log_lock", "_benign_socket_log_state",
],
"llm/__init__.py": [],
"llm/constants.py": [
"DEFAULT_OLLAMA_BASE_URL", "DEFAULT_OLLAMA_MODEL", "OPENAI_COMPAT_PROVIDER_NAMES",
"OPENAI_LIKE_PROVIDER_NAMES", "~^(?:EFFORT_|TASK_LEVEL_EFFORT|ROLE_EFFORT|COORDINATION_EFFORT)",
],
"llm/client.py": ["OllamaError", "OllamaClient"],
"llm/utils.py": [
"~^(?:probe_ollama|list_ollama|resolve_ollama|infer_thinking|split_thinking|strip_thinking|check_ollama|list_loaded_ollama|wake_ollama|try_pull_ollama|ordered_model|pick_working_ollama|extract_base_url|complete_chat_endpoint|normalize_openai|is_openai|openai_compat|extract_openai|clamp_effort|model_reasoning|resolve_reasoning|_is_http_url|_resolve_local_path)",
"_OLLAMA_TAG_CACHE", "_OLLAMA_TAG_CACHE_LOCK",
],
"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"],
"agent/tools.py": [
"tool_def", "TOOLS", "TOOL_REQUIRED_ARGS", "TOOL_SPEC_BY_NAME", "TOOL_NAME_FUZZY_MAP",
"is_todo_resume_tool_name", "canonicalize_tool_name", "filter_tool_specs_for_runtime",
"DEVELOPER_TOOL_DROP", "AGENT_TOOL_ALLOWLIST",
],
"agent/errors.py": ["CircuitBreakerTriggered"],
"skills/__init__.py": [],
"skills/embedded.py": [
"EMBEDDED_SKILLS_ARCHIVE_B64", "EMBEDDED_SKILLS_ARCHIVE_SHA256",
"EMBEDDED_SKILLS_ARCHIVE_FILES", "EMBEDDED_CLAWHUB_SKILLS_ARCHIVE_B64",
"BUILTIN_CLAWHUB_SKILLS_VERSION", "MCP_BUILDER_SKILL_MD", "SKILL_PROTOCOL_SPECS",
"SKILL_PROTOCOL_LOCAL", "SKILL_PROTOCOL_CLAWHUB", "SKILL_PROTOCOL_HTTP_JSON",
],
"skills/provisioning.py": ["~^(?:ensure_|detect_upload|_render_cap|_write_text|_skill_knowledge|analyze_skill|_sanitize_skill|_build_skills)"],
"skills/store.py": ["_BUILTIN_SKILLS", "SkillStore"],
"mcp/__init__.py": [],
"mcp/constants.py": ["~^MCP_", "~^_MCP_"],
"mcp/driver.py": ["~^mcp_", "MCPServerProcess", "MCPManager"],
"mcp/service.py": ["McpServiceHandler"],
"session/__init__.py": [],
"session/state.py": ["SessionState"],
"session/manager.py": ["SessionCreationLimitExceeded", "SessionManager"],
"rag/__init__.py": [],
"rag/constants.py": ["~^(?:RAG_|CODE_LIBRARY_|WEB_SEARCH_|USER_MEMORY_)"],
"rag/assets.py": [
"RAG_ADMIN_INDEX_HTML", "RAG_ADMIN_CSS", "RAG_ADMIN_JS",
"CODE_ADMIN_INDEX_HTML", "CODE_ADMIN_CSS", "CODE_ADMIN_JS",
],
"rag/web_search.py": ["~^_agent_web_", "AgentWebHTMLParser", "AgentWebSearchEngine"],
"rag/parsers.py": [
"~^_rag_(?:safe|detect|cjk|is_noise|entity|filter|filename|apply|choose|tokenize|expand|extract|classify|chunk)",
"~^_code_(?:language|is_test)", "_CallCollector", "_ALGO_COMPLEXITY_RE", "_ALGO_STEP_RE",
"_ALGO_MATH_VARS", "_ALGO_DOC_KEYWORDS", "_detect_algo_chunk",
"CodeContentParser", "RAGContentParser", "normalize_rel_preview_path",
"is_code_preview_candidate", "preview_kind_for_path", "build_code_preview_rows",
],
"rag/index.py": ["TFGraphIDFIndex", "CodeGraphIndex", "~^_code_(?:module|choose|query)"],
"rag/store.py": [
"RAGLibraryStore", "WikiStore", "UserMemoryStore", "UserInteractionOptimizer",
"UserIntentProfiler", "WorkflowMemoryStore", "CodeLibraryStore",
],
"rag/ingestion.py": [
"RAGIngestionService", "CodeIngestionService", "_rag_parse_file_worker",
"~^_rag_(?:trigram|jaccard|mmr|embed|window|focused|query|parse_segments|boundary)",
],
"server/__init__.py": [],
"server/http.py": ["AgentHTTPServer", "Handler"],
"server/skills.py": ["SkillsHandler"],
"server/rag_admin.py": ["RagAdminHandler", "CodeAdminHandler"],
# Specific regex buckets above run before this general constant rule.
"config/constants.py": ["~^[A-Z][A-Z0-9_]{2,}$", "_SHELL_AUTO_CONFIRM_PATTERNS", "_TOOL_TIMEOUT_MAP", "_DEFAULT_TOOL_TIMEOUT"],
"_unclassified.py": [],
}
class _TopLevelBindingCollector(ast.NodeVisitor):
"""Collect names stored by one statement without entering nested scopes."""
def __init__(self) -> None:
self.names: list[str] = []
self._seen: set[str] = set()
def add(self, name: str) -> None:
if name and name not in self._seen:
self._seen.add(name)
self.names.append(name)
def visit_Name(self, node: ast.Name) -> None:
if isinstance(node.ctx, (ast.Store, ast.Del)):
self.add(node.id)
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
self.add(node.name)
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
self.add(node.name)
def visit_ClassDef(self, node: ast.ClassDef) -> None:
self.add(node.name)
def visit_Lambda(self, node: ast.Lambda) -> None:
return
# Python 3 comprehensions own a nested scope; their loop variables do not
# survive as module attributes.
def visit_ListComp(self, node: ast.ListComp) -> None:
return
def visit_SetComp(self, node: ast.SetComp) -> None:
return
def visit_DictComp(self, node: ast.DictComp) -> None:
return
def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None:
return
def visit_Import(self, node: ast.Import) -> None:
for alias in node.names:
self.add(alias.asname or alias.name.split(".")[0])
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
for alias in node.names:
if alias.name != "*":
self.add(alias.asname or alias.name)
def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
# An ``except ... as name`` binding is deleted when the handler exits;
# it is not a persistent module export.
for child in node.body:
self.visit(child)
def top_level_bound_names(node: ast.AST) -> list[str]:
collector = _TopLevelBindingCollector()
collector.visit(node)
return collector.names
class ArchitectureAnalyzer:
def __init__(self, source_path: Path) -> None:
self.source_path = source_path
self.source_text = ""
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]:
self.source_text = self.source_path.read_text(encoding="utf-8")
self.source_lines = self.source_text.splitlines(keepends=True)
print(f" Parsing {len(self.source_lines):,} lines with AST...")
self.tree = ast.parse(self.source_text, filename=str(self.source_path))
self.nodes = []
self.import_statements = []
previous_end = 0
body = list(self.tree.body)
for order, raw_node in enumerate(body):
node_end = int(getattr(raw_node, "end_lineno", None) or raw_node.lineno)
source_end = node_end
if order == len(body) - 1:
source_end = len(self.source_lines)
source_start = previous_end + 1
previous_end = node_end
info = self._make_info(order, raw_node, source_start, source_end)
self.nodes.append(info)
if isinstance(raw_node, (ast.Import, ast.ImportFrom, ast.Try)) and info.kind == "import":
self.import_statements.append(
ImportStatement(info.kind, info.lineno, info.end_lineno, set(info.bound_names))
)
return self.nodes
def _make_info(self, order: int, node: ast.AST, source_start: int, source_end: int) -> NodeInfo:
bound = top_level_bound_names(node)
bases: list[str] = []
if isinstance(node, ast.ClassDef):
name, kind = node.name, "class"
bases = [self._name_of(base) for base in node.bases]
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
name, kind = node.name, "function"
elif isinstance(node, (ast.Import, ast.ImportFrom)):
name, kind = f"_import_{node.lineno}", "import"
elif isinstance(node, ast.Try) and self._is_import_try(node):
name, kind = f"_try_import_{node.lineno}", "import"
elif isinstance(node, (ast.Assign, ast.AnnAssign, ast.AugAssign)):
name = bound[0] if bound else f"_assignment_{node.lineno}"
kind = "constant" if re.match(r"^[A-Z][A-Z0-9_]{2,}$", name) else "assignment"
elif isinstance(node, ast.Expr):
name, kind = self._expression_name(node), "expression"
elif isinstance(node, ast.If) and self._is_main_guard(node):
name, kind = f"_main_guard_{node.lineno}", "main_guard"
else:
name = f"_{type(node).__name__.lower()}_{node.lineno}"
kind = "statement"
lineno = int(getattr(node, "lineno", source_start))
end_lineno = int(getattr(node, "end_lineno", lineno) or lineno)
chunk = self.get_source_lines(source_start, source_end)
return NodeInfo(
order=order,
name=name,
kind=kind,
lineno=lineno,
end_lineno=end_lineno,
source_start=source_start,
source_end=source_end,
source_hash=hashlib.sha256(chunk.encode("utf-8")).hexdigest()[:16],
bound_names=bound,
bases=bases,
)
@staticmethod
def _name_of(node: ast.AST) -> str:
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Attribute):
return node.attr
try:
return ast.unparse(node)
except Exception:
return ""
@staticmethod
def _is_import_try(node: ast.Try) -> bool:
return any(isinstance(child, (ast.Import, ast.ImportFrom)) for child in ast.walk(node))
@staticmethod
def _is_main_guard(node: ast.If) -> bool:
test = node.test
return bool(
isinstance(test, ast.Compare)
and 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__"
)
def _expression_name(self, node: ast.Expr) -> str:
value = node.value
if isinstance(value, ast.Call):
try:
raw = ast.unparse(value.func)
except Exception:
raw = "call"
anchor = self._slug(raw) or "call"
return f"_call_{anchor}_{node.lineno}"
if isinstance(value, ast.Constant) and isinstance(value.value, str):
return f"_module_docstring_{node.lineno}"
return f"_expression_{node.lineno}"
@staticmethod
def _slug(value: object) -> str:
raw = str(value or "").strip()
norm = unicodedata.normalize("NFKD", raw).encode("ascii", "ignore").decode("ascii")
norm = re.sub(r"[^a-zA-Z0-9]+", "_", norm).strip("_").lower()
return norm[:48]
def get_source_lines(self, start: int, end: int) -> str:
return "".join(self.source_lines[start - 1:end])
def get_node_source(self, node: NodeInfo) -> str:
return self.get_source_lines(node.source_start, node.source_end)
class AutoLayoutGenerator:
"""Architecture heuristics used for new symbols not in the explicit map."""
CLASS_RULES: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"(?:Handler|HTTPServer)$"), "server/http.py"),
(re.compile(r"^(?:RAG|Code).*(?:Store|Index)$"), "rag/store.py"),
(re.compile(r"^(?:RAG|Code).*Ingestion"), "rag/ingestion.py"),
(re.compile(r"^AgentWeb"), "rag/web_search.py"),
(re.compile(r"^Ollama"), "llm/client.py"),
(re.compile(r"^Session"), "session/manager.py"),
(re.compile(r"^Skill"), "skills/store.py"),
]
def generate(self, nodes: list[NodeInfo]) -> dict[str, list[str]]:
layout: dict[str, list[str]] = {key: [] for key in DEFAULT_LAYOUT if key.endswith("__init__.py")}
for node in nodes:
if node.kind == "import":
continue
layout.setdefault(self._classify(node), []).append(node.name)
return layout
def _classify(self, node: NodeInfo) -> str:
name = node.name
if name == "main" or node.kind == "main_guard":
return "app/main.py"
if node.kind == "class":
for regex, module in self.CLASS_RULES:
if regex.search(name):
return module
if name.startswith("_rag_") or name.startswith("RAG"):
return "rag/parsers.py" if node.kind == "function" else "rag/constants.py"
if name.startswith("_agent_web_"):
return "rag/web_search.py"
if name.startswith("mcp_") or name.startswith("MCP"):
return "mcp/driver.py"
if name.startswith("ensure_") and "skill" in name:
return "skills/provisioning.py"
if node.kind == "constant":
return "config/constants.py"
return "_unclassified.py"
class ModuleRouter:
def __init__(self, layout: dict[str, list[str]]) -> None:
self.layout = layout
self.fallback = AutoLayoutGenerator()
self.rules: list[tuple[str, list[tuple[str, object]]]] = []
for module, patterns in layout.items():
compiled: list[tuple[str, object]] = []
for pattern in patterns:
if pattern.startswith("~"):
compiled.append(("regex", re.compile(pattern[1:])))
else:
compiled.append(("exact", pattern))
self.rules.append((module, compiled))
def route(self, node: NodeInfo) -> str:
if node.kind == "import":
return "_imports.py"
for module, matchers in self.rules:
if any(kind == "exact" and node.name == matcher for kind, matcher in matchers):
return module
for module, matchers in self.rules:
for kind, matcher in matchers:
if kind == "regex" and matcher.search(node.name):
return module
return self.fallback._classify(node)
def assign_all(self, nodes: list[NodeInfo]) -> None:
for node in nodes:
node.target_module = self.route(node)
for index, node in enumerate(nodes):
if node.target_module != "_unclassified.py" or node.kind not in {"expression", "statement"}:
continue
nearby = self._context_module(nodes, index)
if nearby:
node.target_module = nearby
@staticmethod
def _context_module(nodes: list[NodeInfo], index: int) -> str:
candidates: list[tuple[int, int, str]] = []
current = nodes[index]
for direction, bias in ((-1, 0), (1, 1)):
cursor = index + direction
while 0 <= cursor < len(nodes):
other = nodes[cursor]
if other.kind != "import" and other.target_module != "_unclassified.py":
gap = (
max(0, current.lineno - other.end_lineno)
if direction < 0 else max(0, other.lineno - current.end_lineno)
)
candidates.append((gap, bias, other.target_module))
break
cursor += direction
if not candidates:
return ""
if len(candidates) == 2 and candidates[0][2] == candidates[1][2]:
return candidates[0][2]
candidates.sort()
return candidates[0][2] if candidates[0][0] <= 240 else ""
class DependencyAnalyzer:
def __init__(self, analyzer: ArchitectureAnalyzer, nodes: list[NodeInfo]) -> None:
self.analyzer = analyzer
self.nodes = nodes
self.symbol_to_module: dict[str, str] = {}
for node in nodes:
if node.kind == "import":
continue
for name in node.bound_names:
self.symbol_to_module[name] = node.target_module
def compute_dependency_map(self, module: str, nodes: list[NodeInfo]) -> dict[str, set[str]]:
deps: dict[str, set[str]] = defaultdict(set)
for node in nodes:
for name in self._referenced_names(node):
owner = self.symbol_to_module.get(name)
if owner and owner not in {module, "_imports.py"}:
deps[owner].add(name)
return deps
def _referenced_names(self, node: NodeInfo) -> set[str]:
source = self.analyzer.get_node_source(node)
try:
table = symtable.symtable(source, str(self.analyzer.source_path), "exec")
except SyntaxError:
return set()
out: set[str] = set()
self._walk_symbols(table, out)
return out
def _walk_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" or symbol.is_global() or symbol.is_free() or symbol.is_nonlocal():
out.add(symbol.get_name())
for child in table.get_children():
self._walk_symbols(child, out)
class CodeGenerator:
RUNTIME_MODULE = "_runtime.py"
IMPORTS_MODULE = "_imports.py"
def __init__(self, analyzer: ArchitectureAnalyzer, package_name: str) -> None:
self.analyzer = analyzer
self.package_name = package_name
def generate_source_module(self, module_path: str, nodes: list[NodeInfo]) -> str:
parts = [GENERATED_HEADER.rstrip(), "", "from __future__ import annotations", ""]
for ast_index, node in enumerate(nodes, start=1):
node.generated_ast_index = ast_index
parts.append(
f"# split-source: order={node.order} original-lines={node.source_start}-{node.source_end} hash={node.source_hash}"
)
source = self._rewrite_context_sensitive_source(
node,
self.analyzer.get_node_source(node),
)
parts.append(source.rstrip("\n"))
parts.append("")
return "\n".join(parts).rstrip() + "\n"
@staticmethod
def _rewrite_context_sensitive_source(node: NodeInfo, source: str) -> str:
"""Make monolith-only ``__file__`` operations package-native."""
if node.name == "_admin_supervised_restart":
source = source.replace(
"script_path = str(Path(__file__).resolve())",
"script_path = str(_SPLIT_PACKAGE_ROOT / '__main__.py')",
)
source = source.replace(
"command = [sys.executable, script_path, *_admin_config_to_argv(config)]",
"command = [*_SPLIT_ENTRY_COMMAND, *_admin_config_to_argv(config)]",
)
source = source.replace(
"[sys.executable, script_path, *_admin_config_to_argv(fallback_config)]",
"[*_SPLIT_ENTRY_COMMAND, *_admin_config_to_argv(fallback_config)]",
)
if node.name == "AppContext":
source = source.replace(
'zf.writestr("Clouds_Coder.py", Path(__file__).read_text(encoding="utf-8"))',
"for _split_rel, _split_data in _split_package_source_files():\n"
" zf.writestr(f\"Code_Structure/{_split_rel}\", _split_data)",
)
source = source.replace(
'"Run: python Clouds_Coder.py --host 0.0.0.0 --port 8080\\n"',
'"Run: python -m Code_Structure --host 0.0.0.0 --port 8080\\n"',
)
return source
def runtime_plan(self, nodes: list[NodeInfo]) -> list[dict]:
return [
{
"order": node.order,
"module": node.target_module,
"ast_index": node.generated_ast_index,
"exports": node.bound_names,
"source_hash": node.source_hash,
"original_lines": [node.source_start, node.source_end],
}
for node in sorted(nodes, key=lambda item: item.order)
]
def generate_runtime(self, nodes: list[NodeInfo]) -> str:
plan_repr = repr(self.runtime_plan(nodes))
source_filename = self.analyzer.source_path.name
template = r'''__HEADER__
from __future__ import annotations
import ast
import builtins
import importlib.machinery
import sys
import threading
import types
from pathlib import Path
_PACKAGE = __package__
_PACKAGE_ROOT = Path(__file__).resolve().parent
_SOURCE_FILENAME = __SOURCE_FILENAME__
_PLAN = __PLAN__
_LOCK = threading.RLock()
_READY = False
_SHARED = {
"__builtins__": builtins.__dict__,
"__name__": _PACKAGE,
"__package__": "",
# Relocated code should resolve paths from the generated package, never
# from the original monolith's directory. The original filename remains
# available above only as a provenance label in the runtime plan.
"__file__": str(_PACKAGE_ROOT / "__main__.py"),
}
def _split_package_source_files():
"""Return the generated package source tree for source-bundle export."""
rows = []
for path in sorted(_PACKAGE_ROOT.rglob("*")):
if not path.is_file() or "__pycache__" in path.parts:
continue
if path.suffix not in {".py", ".md", ".json"}:
continue
rows.append((path.relative_to(_PACKAGE_ROOT).as_posix(), path.read_bytes()))
return rows
_SPLIT_PACKAGE_NAME = _PACKAGE
_SPLIT_PACKAGE_ROOT = _PACKAGE_ROOT
_SPLIT_ENTRY_COMMAND = (sys.executable, "-m", _PACKAGE)
_SHARED.update({
"_SPLIT_PACKAGE_NAME": _SPLIT_PACKAGE_NAME,
"_SPLIT_PACKAGE_ROOT": _SPLIT_PACKAGE_ROOT,
"_SPLIT_ENTRY_COMMAND": _SPLIT_ENTRY_COMMAND,
"_split_package_source_files": _split_package_source_files,
})
class _SplitSourceModule(types.ModuleType):
"""A module view over the shared legacy-global namespace."""
def __getattribute__(self, name):
namespace = types.ModuleType.__getattribute__(self, "__dict__")
exports = namespace.get("_split_export_names", ())
shared = namespace.get("_split_shared", {})
if name in exports and name in shared:
return shared[name]
return types.ModuleType.__getattribute__(self, name)
def __setattr__(self, name, value):
namespace = types.ModuleType.__getattribute__(self, "__dict__")
if name in namespace.get("_split_export_names", ()):
namespace.get("_split_shared", {})[name] = value
types.ModuleType.__setattr__(self, name, value)
def __dir__(self):
namespace = types.ModuleType.__getattribute__(self, "__dict__")
return sorted(set(namespace) | set(namespace.get("_split_export_names", ())))
def _ensure_package(relative: str):
parent = sys.modules[_PACKAGE]
if not relative:
return parent
current_name = _PACKAGE
current_path = _PACKAGE_ROOT
for part in relative.split("/"):
current_name += "." + part
current_path /= part
module = sys.modules.get(current_name)
if module is None:
module = types.ModuleType(current_name)
module.__file__ = str(current_path / "__init__.py")
module.__package__ = current_name
module.__path__ = [str(current_path)]
spec = importlib.machinery.ModuleSpec(current_name, loader=None, is_package=True)
spec.submodule_search_locations = [str(current_path)]
module.__spec__ = spec
sys.modules[current_name] = module
setattr(parent, part, module)
parent = module
return parent
def _ensure_source_module(relative_file: str):
relative = relative_file[:-3] if relative_file.endswith(".py") else relative_file
parts = relative.split("/")
package_rel = "/".join(parts[:-1])
parent = _ensure_package(package_rel)
full_name = _PACKAGE + "." + ".".join(parts)
module = sys.modules.get(full_name)
if module is None:
module = _SplitSourceModule(full_name)
module.__file__ = str(_PACKAGE_ROOT / relative_file)
module.__package__ = full_name.rpartition(".")[0]
module.__spec__ = importlib.machinery.ModuleSpec(full_name, loader=None, origin=module.__file__)
module._split_export_names = set()
module._split_shared = _SHARED
sys.modules[full_name] = module
setattr(parent, parts[-1], module)
return module
def bootstrap():
global _READY
if _READY:
return _SHARED
with _LOCK:
if _READY:
return _SHARED
source_modules = {}
parsed = {}
for entry in _PLAN:
relative = entry["module"]
source_modules[relative] = _ensure_source_module(relative)
for relative, module in source_modules.items():
path = _PACKAGE_ROOT / relative
text = path.read_text(encoding="utf-8")
parsed[relative] = (path, ast.parse(text, filename=str(path)))
future_flags = __import__("__future__").annotations.compiler_flag
for entry in _PLAN:
relative = entry["module"]
module = source_modules[relative]
path, tree = parsed[relative]
ast_index = int(entry["ast_index"])
if ast_index < 0 or ast_index >= len(tree.body):
raise ImportError(
f"split plan is stale for {relative}: AST index {ast_index} is unavailable"
)
source_node = tree.body[ast_index]
_SHARED["__name__"] = module.__name__
try:
code = compile(
ast.Module(body=[source_node], type_ignores=[]),
str(path),
"exec",
flags=future_flags,
dont_inherit=True,
)
exec(code, _SHARED, _SHARED)
except BaseException as exc:
start, end = entry.get("original_lines", [0, 0])
raise ImportError(
f"failed to initialize split statement {entry['order']} "
f"from original lines {start}-{end} in {relative}"
) from exc
exports = module._split_export_names
for name in entry.get("exports", ()):
exports.add(name)
_SHARED["__name__"] = _PACKAGE
for module in source_modules.values():
names = sorted(module._split_export_names)
module.__all__ = names
for name in names:
if name in _SHARED:
types.ModuleType.__setattr__(module, name, _SHARED[name])
_READY = True
return _SHARED
def export_into(relative_file: str, namespace: dict):
"""Compatibility helper for unusual direct-loader integrations."""
bootstrap()
relative = relative_file[:-3] if relative_file.endswith(".py") else relative_file
full_name = _PACKAGE + "." + relative.replace("/", ".")
module = sys.modules[full_name]
for name in module.__all__:
namespace[name] = getattr(module, name)
return namespace
'''
return (
template.replace("__HEADER__", GENERATED_HEADER.rstrip())
.replace("__SOURCE_FILENAME__", repr(source_filename))
.replace("__PLAN__", plan_repr)
.rstrip()
+ "\n"
)
def generate_root_init(self) -> str:
return (
GENERATED_HEADER
+ '"""Architecture-aware split of the original Clouds_Coder application."""\n\n'
+ "from ._runtime import bootstrap as _bootstrap\n\n"
+ "_bootstrap()\n"
+ "del _bootstrap\n"
)
def generate_package_init(self, relative_dir: str) -> str:
dotted = relative_dir.replace("/", ".")
return GENERATED_HEADER + f'"""{dotted} subsystem."""\n'
def generate_main_wrapper(self) -> str:
return (
GENERATED_HEADER
+ "from .app.main import main\n\n"
+ 'if __name__ == "__main__":\n'
+ " main()\n"
)
class FrameworkReportGenerator:
def __init__(
self,
source_path: Path,
output_dir: Path,
modules: dict[str, list[NodeInfo]],
dependency_analyzer: DependencyAnalyzer,
) -> None:
self.source_path = source_path
self.output_dir = output_dir
self.modules = modules
self.dependency_analyzer = dependency_analyzer
def generate(self) -> str:
source_modules = sorted(self.modules)
real_nodes = [node for rows in self.modules.values() for node in rows]
unclassified = self.modules.get("_unclassified.py", [])
lines = [
f"# {self.output_dir.name} Framework",
"",
"## Overview",
"",
f"- Source snapshot: `{self.source_path.name}` ({len(real_nodes)} top-level statements)",
f"- Generated source modules: {len(source_modules)}",
f"- Unclassified statements: {len(unclassified)}",
"- Execution model: real source fragments initialized in original top-level order",
"- Runtime dependency on original monolith: none",
"",
"The generated modules contain the actual Python source. `_runtime.py` only preserves the original",
"global initialization order and shared-global semantics required by this legacy monolith's circular",
"dependency graph; it does not import or read `Clouds_Coder.py`.",
"",
"## Package Tree",
"",
"```text",
]
paths = set(source_modules) | {"__init__.py", "__main__.py", "_runtime.py"}
lines.extend(self._tree_lines(sorted(paths)))
lines.extend([
"```",
"",
"## Module Summary",
"",
"| Module | Statements | Exported names | Dependencies | Original line span |",
"| --- | ---: | ---: | --- | --- |",
])
for module in source_modules:
nodes = self.modules[module]
exports = {name for node in nodes for name in node.bound_names}
deps = self.dependency_analyzer.compute_dependency_map(module, nodes)
dep_text = ", ".join(f"`{name}`" for name in sorted(deps)) or "—"
span = f"{min(n.source_start for n in nodes)}–{max(n.source_end for n in nodes)}"
lines.append(f"| `{module}` | {len(nodes)} | {len(exports)} | {dep_text} | {span} |")
if unclassified:
lines.extend(["", "## Unclassified Statements", ""])
for node in unclassified:
lines.append(
f"- `{node.name}` ({node.kind}, original lines {node.source_start}-{node.source_end})"
)
lines.extend(["", "## Source Mapping", ""])
for module in source_modules:
lines.extend([f"### `{module}`", ""])
for node in self.modules[module]:
exports = ", ".join(f"`{name}`" for name in node.bound_names) or "—"
lines.append(
f"- order {node.order}: `{node.name}` ({node.kind}), lines "
f"{node.source_start}-{node.source_end}, exports {exports}"
)
lines.append("")
return "\n".join(lines).rstrip() + "\n"
def _tree_lines(self, paths: list[str]) -> list[str]:
tree: dict[str, dict] = {}
for path in paths:
cursor = tree
for part in path.split("/"):
cursor = cursor.setdefault(part, {})
out = [f"{self.output_dir.name}/"]
def render(branch: dict[str, dict], prefix: str = "") -> None:
items = sorted(branch.items(), key=lambda row: (not bool(row[1]), row[0]))
for index, (name, children) in enumerate(items):
last = index == len(items) - 1
out.append(prefix + ("└── " if last else "├── ") + name)
if children:
render(children, prefix + (" " if last else "│ "))
render(tree)
return out
class FileWriter:
def __init__(self, output_dir: Path, dry_run: bool = False) -> None:
self.output_dir = output_dir
self.dry_run = dry_run
self.written: list[str] = []
self.skipped: list[str] = []
def write(self, relative: str, content: str) -> bool:
path = self.output_dir / relative
if self.dry_run:
print(f" [DRY-RUN] Would write: {relative} ({len(content):,} bytes)")
self.written.append(relative)
return True
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists() and path.read_text(encoding="utf-8") == content: