Repository navigation
Expand file tree
/
Copy pathtests.py
More file actions
3050 lines (2861 loc) · 140 KB
/
Copy pathtests.py
File metadata and controls
3050 lines (2861 loc) · 140 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
"""Tests for codeloom. Run with: python3 tests.py"""
import os
import json
import shutil
import subprocess
import sys
import tempfile
import unittest
# Absolute path to this file's directory, computed once at import time.
# subprocess invocations of codeloom.py must resolve it from ANY cwd
# (CI runs `python3 tests.py` from a different directory).
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, TESTS_DIR)
import codeloom # noqa: E402
def force_rmtree(path, attempts=12, delay=0.5):
"""Remove a directory tree, retrying transient failures (Windows).
git leaves short-lived file handles/locks on .git/objects on Windows,
so plain shutil.rmtree can raise PermissionError [WinError 5]. Retry
up to `attempts` times with a growing backoff (0.5s -> 1.0s, ~9s worst
case — enough for a lingering git.exe handle to close), and chmod
read-only entries (git marks .git objects read-only) before giving up.
Missing paths are a no-op (safe replacement for ignore_errors=True).
These are throwaway temp dirs: cleanup is best-effort. After the
retry loop exhausts, a final ignore_errors=True rmtree guarantees a
lingering Windows file lock can NEVER fail a test.
"""
import time
if not path or not os.path.exists(path):
return
for i in range(attempts):
try:
shutil.rmtree(path)
return
except OSError:
if i == attempts - 1:
break
time.sleep(min(delay + i * 0.05, 1.0))
# Last resort: strip read-only bits, then retry each failed unlink /
# rmdir after a short sleep (the lock is usually a lingering git.exe
# handle that closes within a second), then repeat the whole loop.
def _force_remove(func, p, _exc):
try:
os.chmod(p, 0o700)
except OSError:
pass
for _ in range(2):
try:
func(p)
return
except OSError:
time.sleep(0.3)
for i in range(attempts):
try:
shutil.rmtree(path, onerror=_force_remove)
return
except OSError:
if i == attempts - 1:
break
time.sleep(min(delay + i * 0.05, 1.0))
# Absolute final fallback: whatever is still locked stays behind, but
# the test must never fail because cleanup couldn't delete a temp dir.
shutil.rmtree(path, ignore_errors=True)
def make_repo(repo):
"""Create a small fixture repo."""
def j(*parts):
return os.path.join(repo, *parts)
def w(path, content):
with open(path, "w") as f:
f.write(content)
os.makedirs(j("src", "core"))
os.makedirs(j("src", "utils"))
os.makedirs(j("tests"))
w(j("src", "__init__.py"), "")
w(j("src", "cli.py"),
"from core.engine import Engine\n"
"from utils.retry import retry\n"
"\n"
"def main():\n eng = Engine()\n retry(eng.run)\n"
"\n"
"class Parser:\n pass\n")
w(j("src", "core", "__init__.py"), "")
w(j("src", "core", "engine.py"),
"from utils.retry import retry\n"
"\n"
"class Engine:\n def run(self):\n retry(lambda: None)\n")
w(j("src", "utils", "__init__.py"), "")
w(j("src", "utils", "retry.py"),
"def retry(fn, tries=3):\n return fn()\n")
w(j("tests", "test_cli.py"),
"from core.engine import Engine\n"
"def test_x():\n Engine()\n")
w(j("README.md"), "# demo\n")
w(j(".gitignore"), "*.pyc\n.venv/\n__pycache__/\n")
os.makedirs(j(".venv"))
w(j(".venv", "junk.py"), "ignored")
w(j("ignored.pyc"), "ignored")
class TestCodeLoom(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp()
self.repo = os.path.join(self.tmp, "repo")
os.makedirs(self.repo)
make_repo(self.repo)
def tearDown(self):
force_rmtree(self.tmp)
def test_file_count_and_gitignore(self):
m = codeloom.build_map(self.repo, True, 5000)
# .venv/junk.py and ignored.pyc excluded; 9 real files remain
self.assertEqual(m["file_count"], 9)
def test_outline_python(self):
m = codeloom.build_map(self.repo, True, 5000)
text = codeloom.render_text(m)
self.assertIn("def main():", text)
self.assertIn("class Parser:", text)
self.assertIn("class Engine:", text)
def test_entry_points_prefer_root(self):
m = codeloom.build_map(self.repo, True, 5000)
eps = [os.path.basename(e) for e in m["entry_points"]]
self.assertIn("README.md", eps)
def test_json_roundtrip(self):
m = codeloom.build_map(self.repo, True, 5000)
payload = {
"root": m["root"],
"file_count": m["file_count"],
"tree": codeloom.tree_to_json(m["tree"]),
}
import json
json.dumps(payload) # must not raise
def test_cli_runs(self):
r = subprocess.run(
[sys.executable, os.path.join(TESTS_DIR, "codeloom.py"),
"--json", self.repo],
capture_output=True, text=True,
)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("file_count", r.stdout)
def _run_cli(self, *argv, cwd=None, timeout=120):
"""Run codeloom.py as a subprocess in an isolated cwd (default: a
throwaway temp dir so per-repo artifacts like .codeloom-memory never
land in the fixture repo or the codeloom checkout)."""
if cwd is None:
cwd = tempfile.mkdtemp()
r = subprocess.run(
[sys.executable, os.path.join(TESTS_DIR, "codeloom.py")]
+ list(argv),
capture_output=True, text=True, cwd=cwd, timeout=timeout,
)
return r, cwd
def _make_cli_repo(self, base):
"""Tiny 3-file Python repo with a symbol, a dead symbol, and a call."""
repo = os.path.join(base, "repo")
os.makedirs(repo)
with open(os.path.join(repo, "engine.py"), "w") as f:
f.write("from utils.retry import retry\n\n"
"class Engine:\n"
" def run(self):\n"
" return retry(lambda: None)\n\n"
"def main():\n"
" eng = Engine()\n"
" return eng.run()\n")
with open(os.path.join(repo, "utils.py"), "w") as f:
f.write("def retry(fn, tries=3):\n"
" return fn()\n\n"
"def backup():\n"
" return 1\n")
with open(os.path.join(repo, "cli.py"), "w") as f:
f.write("def parse(args):\n return args\n")
return repo
def test_cli_get_symbol_dispatch(self):
# --get-symbol resolves a real symbol (class def + body) to its file
tmp = tempfile.mkdtemp()
try:
repo = self._make_cli_repo(tmp)
r, _ = self._run_cli("--get-symbol", "Engine", repo)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("# get_symbol: Engine", r.stdout)
self.assertRegex(r.stdout, r"engine:\d+")
self.assertIn("class Engine", r.stdout)
finally:
force_rmtree(tmp)
def test_cli_get_symbol_json_contract(self):
# --json --get-symbol emits machine-readable JSON (not human text)
tmp = tempfile.mkdtemp()
try:
repo = self._make_cli_repo(tmp)
r, _ = self._run_cli("--json", "--get-symbol", "Engine", repo)
self.assertEqual(r.returncode, 0, r.stderr)
import json
data = json.loads(r.stdout)
self.assertEqual(data["symbol"], "Engine")
self.assertIn("source", data)
self.assertIn("class Engine", data["source"])
# not-found path is JSON too
r2, _ = self._run_cli("--json", "--get-symbol", "NoSuchSymbol", repo)
self.assertEqual(r2.returncode, 0, r2.stderr)
self.assertFalse(json.loads(r2.stdout)["found"])
finally:
force_rmtree(tmp)
def test_cli_snippet_byte_accuracy(self):
# --snippet is byte-accurate: a multi-byte (UTF-8) file sliced at
# byte offsets must not produce mojibake or off-by-one text
tmp = tempfile.mkdtemp()
try:
repo = os.path.join(tmp, "repo")
os.makedirs(repo)
# 3-byte chars: "é" = 0xC3 0xA9. 10 é's = 30 bytes + newline.
with open(os.path.join(repo, "u.py"), "w", encoding="utf-8") as f:
f.write("é" * 10 + "\n" + "def x():\n return 1\n")
r, _ = self._run_cli("--snippet", "u.py", "0", "31", repo)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("é" * 10, r.stdout)
# reversed range must error, not silently return garbage
r2, _ = self._run_cli("--snippet", "u.py", "31", "0", repo)
self.assertNotEqual(r2.returncode, 0)
finally:
force_rmtree(tmp)
def test_cli_query_dependents_no_crash(self):
# --query dependents on a symbol with no dependents must not crash
tmp = tempfile.mkdtemp()
try:
repo = self._make_cli_repo(tmp)
r, _ = self._run_cli("--query", "dependents backup", repo)
self.assertEqual(r.returncode, 0, r.stderr)
finally:
force_rmtree(tmp)
def test_cli_diff_non_git_honesty(self):
# --diff on a non-git dir must say so, not crash or fabricate
tmp = tempfile.mkdtemp()
try:
repo = os.path.join(tmp, "repo")
os.makedirs(repo)
with open(os.path.join(repo, "a.py"), "w") as f:
f.write("x = 1\n")
r, _ = self._run_cli("--diff", repo)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("not a git", r.stdout.lower())
finally:
force_rmtree(tmp)
def test_js_escape_unit(self):
# _js_escape must neutralize every dangerous character, on all
# platforms (the CLI test below only runs on POSIX because the
# quote character can't exist in a Windows filename at all)
esc = codeloom._js_escape
self.assertEqual(esc('evil"+alert(1)+"'), 'evil\\"+alert(1)+\\"')
self.assertEqual(esc("a\\b"), "a\\\\b")
self.assertEqual(esc("x</script>"), "x<\\/script>")
self.assertEqual(esc("l1\nl2\rl3\tl4"), "l1\\nl2\\rl3\\tl4")
# clean names pass through untouched
self.assertEqual(esc("engine.core"), "engine.core")
@unittest.skipIf(os.name == "nt", "hostile quote filename cannot exist on Windows")
def test_cli_graph_html_escape(self):
# hostile filename must not break out of the JS string literal
tmp = tempfile.mkdtemp()
try:
repo = os.path.join(tmp, "repo")
os.makedirs(repo)
with open(os.path.join(repo, 'evil"+alert(1)+".py'), "w") as f:
f.write("import normal\n\ndef hostile():\n return normal.n()\n")
with open(os.path.join(repo, "normal.py"), "w") as f:
f.write("def n():\n return 1\n")
r, _ = self._run_cli("--graph-html", repo)
self.assertEqual(r.returncode, 0, r.stderr)
html = os.path.join(repo, "codeloom-graph.html")
self.assertTrue(os.path.isfile(html), "--graph-html wrote no file")
with open(html, encoding="utf-8") as fh:
content = fh.read()
# the raw quote must be escaped in the emitted JS
self.assertNotIn('"evil"', content)
self.assertIn("\\\"", content)
finally:
force_rmtree(tmp)
def test_cli_symlink_containment(self):
# a symlink pointing outside the repo must not leak outside content
tmp = tempfile.mkdtemp()
try:
repo = os.path.join(tmp, "repo")
outside = os.path.join(tmp, "outside")
os.makedirs(repo)
os.makedirs(outside)
with open(os.path.join(outside, "secret.py"), "w") as f:
f.write("TOPSECRET = 'leak'\n")
os.symlink(outside, os.path.join(repo, "leakdir"))
r, _ = self._run_cli(repo) # default command = map
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("secret.py", r.stdout)
self.assertNotIn("TOPSECRET", r.stdout)
finally:
force_rmtree(tmp)
def test_cli_session_logs_real_time(self):
# --session must record real wall time and real output bytes
tmp = tempfile.mkdtemp()
try:
repo = os.path.join(tmp, "repo")
os.makedirs(repo)
with open(os.path.join(repo, "a.py"), "w") as f:
f.write("def a():\n return 1\n")
r, _ = self._run_cli("--session", repo)
self.assertEqual(r.returncode, 0, r.stderr)
import json
log = os.path.join(repo, ".codeloom-session.jsonl")
self.assertTrue(os.path.isfile(log))
with open(log, encoding="utf-8") as fh:
entry = json.loads(fh.readline())
self.assertGreater(entry["seconds"], 0.0)
self.assertGreater(entry["bytes"], 0)
finally:
force_rmtree(tmp)
def test_cli_json_write_roundtrip(self):
# --json --write must actually write the JSON payload (was: silent drop)
tmp = tempfile.mkdtemp()
try:
repo = self._make_cli_repo(tmp)
out = os.path.join(tmp, "out.json")
r, _ = self._run_cli("--json", "--write", out, repo)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertTrue(os.path.isfile(out), "JSON payload was not written")
import json
with open(out, encoding="utf-8") as fh:
data = json.load(fh)
self.assertIn("file_count", data)
finally:
force_rmtree(tmp)
def test_cli_pack_dispatch(self):
# --pack emits a single-shot task brief with a ranked reading order
tmp = tempfile.mkdtemp()
try:
repo = self._make_cli_repo(tmp)
r, _ = self._run_cli("--pack", "add retry to engine", repo)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("# TASK: add retry to engine", r.stdout)
self.assertIn("## 1. READ THESE, IN ORDER", r.stdout)
self.assertIn("engine.py", r.stdout)
self.assertIn("## 2. THE RELEVANT CODE", r.stdout)
finally:
force_rmtree(tmp)
def test_cli_decide_query_memory_roundtrip(self):
# --decide writes to .codeloom-memory in the CWD; --query-memory in
# the same CWD reads it back. Runs in a throwaway dir so the repo
# and the codeloom checkout stay clean.
tmp = tempfile.mkdtemp()
try:
r1, wd = self._run_cli("--decide", "Use retry everywhere",
"--reason", "idempotent")
self.assertEqual(r1.returncode, 0, r1.stderr)
self.assertIn("recorded decision", r1.stdout)
self.assertTrue(os.path.isfile(
os.path.join(wd, ".codeloom-memory", "DECISIONS.md")))
r2, _ = self._run_cli("--query-memory", "retry", cwd=wd)
self.assertEqual(r2.returncode, 0, r2.stderr)
self.assertIn('--query-memory "retry"', r2.stdout)
self.assertIn("Use retry everywhere", r2.stdout)
finally:
force_rmtree(tmp)
def test_cli_health_dispatch(self):
# --health prints a score line (avg X/10 across N files)
tmp = tempfile.mkdtemp()
try:
repo = self._make_cli_repo(tmp)
r, _ = self._run_cli("--health", repo)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("code health", r.stdout)
self.assertRegex(r.stdout, r"avg \d+(\.\d+)?/10")
self.assertIn("files", r.stdout)
finally:
force_rmtree(tmp)
def test_cli_risk_dispatch(self):
# --risk on a git commit range exits 0 and prints a score line
tmp = tempfile.mkdtemp()
try:
repo = self._make_cli_repo(tmp)
for c in (["init", "-q"],
["config", "user.email", "t@t"],
["config", "user.name", "t"]):
g = subprocess.run(["git"] + c, cwd=repo, timeout=30,
capture_output=True, text=True)
self.assertEqual(g.returncode, 0, g.stderr)
subprocess.run(["git", "add", "-A"], cwd=repo, timeout=30,
capture_output=True, text=True)
subprocess.run(["git", "commit", "-q", "-m", "init"], cwd=repo, timeout=30,
capture_output=True, text=True)
with open(os.path.join(repo, "engine.py"), "w") as f:
f.write("from utils.retry import retry\n\n"
"class Engine:\n"
" def run(self):\n"
" return retry(lambda: None)\n\n"
"def main():\n"
" eng = Engine()\n"
" return eng.run() + 1\n")
subprocess.run(["git", "add", "-A"], cwd=repo, timeout=30,
capture_output=True, text=True)
subprocess.run(["git", "commit", "-q", "-m", "tweak"], cwd=repo, timeout=30,
capture_output=True, text=True)
r, _ = self._run_cli("--risk", "HEAD~1..HEAD", repo)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("change risk", r.stdout)
self.assertRegex(r.stdout, r"score \d+/100")
finally:
force_rmtree(tmp)
def test_graph_import_edges(self):
m = codeloom.build_map(self.repo, True, 5000)
files = []
# re-walk (build_map doesn't return files list)
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
graph = codeloom.build_graph(files, self.repo)
# src.cli -> src.core.engine and src.utils.retry
self.assertIn("src.core.engine", graph.get("src.cli", set()))
self.assertIn("src.utils.retry", graph.get("src.cli", set()))
# tests.test_cli -> src.core.engine
self.assertIn("src.core.engine", graph.get("tests.test_cli", set()))
def test_graph_focus(self):
m = codeloom.build_map(self.repo, True, 5000)
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
graph = codeloom.build_graph(files, self.repo)
fs = codeloom.focus_subgraph(graph, "src.core.engine")
self.assertIn("src.cli", fs["depended_on_by"])
self.assertIn("tests.test_cli", fs["depended_on_by"])
self.assertIn("src.utils.retry", fs["depends_on"])
def test_graph_focus_missing_neighbor_module(self):
# Regression (a8df4c2): reachable() must NOT KeyError when a module
# named by an edge is absent from the graph keys — build_graph_multi
# omits leaf modules (no deps -> no key), so focusing a chain like
# a -> b -> c walks into the missing 'c'.
graph = {"a": {"b"}, "b": {"c"}}
fs = codeloom.focus_subgraph(graph, "a")
self.assertEqual(fs["module"], "a")
self.assertEqual(fs["depends_on"], ["b", "c"])
self.assertEqual(fs["depended_on_by"], [])
# inverse direction must also survive a missing neighbor
self.assertEqual(codeloom.reachable(graph, "c", "in"), {"a", "b"})
self.assertEqual(codeloom.reachable(graph, "a", "out"), {"b", "c"})
def test_graph_focus_cli_missing_leaf_module(self):
# End-to-end regression (a8df4c2): --graph --focus on a module whose
# transitive neighbor is a leaf absent from the graph keys must exit
# 0 and render the focus (was: unhandled KeyError traceback).
tmp = tempfile.mkdtemp()
try:
repo = os.path.join(tmp, "repo")
os.makedirs(repo)
for n, body in [
("a.py", "import b\n\ndef fa():\n return b.fb()\n"),
("b.py", "import c\n\ndef fb():\n return c.fc()\n"),
("c.py", "def fc():\n return 1\n")]:
with open(os.path.join(repo, n), "w") as f:
f.write(body)
r = subprocess.run(
[sys.executable, os.path.join(TESTS_DIR, "codeloom.py"),
"--graph", "--focus", "a", repo],
capture_output=True, text=True, timeout=120)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn("KeyError", r.stderr)
self.assertIn("## depends_on", r.stdout)
self.assertIn(" b", r.stdout)
self.assertIn(" c", r.stdout)
finally:
force_rmtree(tmp)
def test_call_graph(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
calls = codeloom.build_call_graph(files, self.repo)
# src.cli.main calls retry (function defined in src.utils.retry)
self.assertIn("retry", calls.get("src.cli", {}).get("main", set()))
# src.core.engine.run calls retry
self.assertIn("retry", calls.get("src.core.engine", {}).get("run", set()))
# builtins like len/str should NOT appear (filtered out)
self.assertNotIn("len", calls.get("src.cli", {}).get("main", set()))
def test_multi_lang_call_graph(self):
# JS + Go fixture
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, "app.js"), "w") as f:
f.write("function greet(n) { return n; }\nfunction main() { greet('x'); }\n")
with open(os.path.join(tmp, "main.go"), "w") as f:
f.write("package main\nfunc helper() int { return 1 }\nfunc main() { helper() }\n")
files = [os.path.join(tmp, "app.js"), os.path.join(tmp, "main.go")]
calls = codeloom.build_call_graph_multi(files, tmp)
self.assertIn("greet", calls.get("app", {}).get("main", set()))
self.assertIn("helper", calls.get("main", {}).get("main", set()))
finally:
force_rmtree(tmp)
def test_install_agents(self):
# creates AGENTS.md
msg = codeloom.install_agents(self.repo)
self.assertIn("AGENTS.md", msg)
self.assertTrue(os.path.isfile(os.path.join(self.repo, "AGENTS.md")))
# updates on second call
msg2 = codeloom.install_agents(self.repo)
self.assertIn("updated", msg2)
def test_token_estimate(self):
self.assertGreater(codeloom.estimate_tokens("hello world"), 0)
self.assertEqual(codeloom.estimate_tokens(""), 1)
def test_impact_analysis(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
graph = codeloom.build_graph(files, self.repo)
imp = codeloom.impact_analysis(graph, "src.core.engine")
# src.cli and tests.test_cli depend on engine
self.assertIn("src.cli", imp["direct_dependents"])
self.assertIn("tests.test_cli", imp["direct_dependents"])
# engine depends on retry
self.assertIn("src.utils.retry", imp["depends_on"])
def test_task_relevance(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
results = codeloom.task_relevance(files, self.repo, "retry logic")
self.assertTrue(results)
# retry module should rank first for 'retry' task
self.assertEqual(results[0]["module"], "src.utils.retry")
def test_build_plan(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
plan = codeloom.build_plan(files, self.repo, "add retry to engine")
self.assertIn("Read these files", plan)
# cross-platform: check for the module name, not a hardcoded path separator
self.assertIn("engine.py", plan)
def test_cross_call_graph(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
calls = codeloom.build_cross_call_graph(files, self.repo)
# src.cli.main calls Engine (class in src.core.engine) and retry
self.assertIn("src.core.engine.Engine", calls.get("src.cli", {}).get("main", set()))
self.assertIn("src.utils.retry.retry", calls.get("src.cli", {}).get("main", set()))
# src.core.engine.run calls retry
self.assertIn("src.utils.retry.retry", calls.get("src.core.engine", {}).get("run", set()))
def test_symbol_search(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
index = codeloom.build_symbol_index(files, self.repo)
results = codeloom.search_symbols(index, "Engine")
self.assertTrue(results)
self.assertEqual(results[0]["name"], "Engine")
self.assertEqual(results[0]["kind"], "class")
# search for a method
results2 = codeloom.search_symbols(index, "run")
self.assertTrue(results2)
def test_gitignore_negation_and_anchoring(self):
# create a .gitignore with negation + anchoring
gi = os.path.join(self.repo, ".gitignore")
with open(gi, "w") as f:
f.write("*.pyc\n/build\n!keep.pyc\nnode_modules/\n")
rules = codeloom.parse_gitignore(gi)
# *.pyc ignored
self.assertTrue(codeloom.is_ignored(os.path.join(self.repo, "a.pyc"), rules))
# /build anchored ignores build/out.js
self.assertTrue(codeloom.is_ignored(os.path.join(self.repo, "build", "out.js"), rules))
# node_modules/ dir-only ignores contents
self.assertTrue(codeloom.is_ignored(os.path.join(self.repo, "node_modules", "x.js"), rules))
# !keep.pyc negation keeps it
self.assertFalse(codeloom.is_ignored(os.path.join(self.repo, "keep.pyc"), rules))
def test_incremental_cache(self):
# first run: all files changed
files = [os.path.join(self.repo, "src", "cli.py")]
cache = codeloom.load_cache(self.repo)
changed = codeloom.changed_files(files, cache)
self.assertEqual(len(changed), 1)
# update cache, second run: no changes
codeloom.update_cache(files, cache)
changed2 = codeloom.changed_files(files, cache)
self.assertEqual(len(changed2), 0)
def test_multi_lang_import_graph(self):
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, "app.js"), "w") as f:
f.write('import { helper } from "./util";\nfunction main() { helper(); }\n')
with open(os.path.join(tmp, "util.js"), "w") as f:
f.write("export function helper() { return 1; }\n")
files = [os.path.join(tmp, "app.js"), os.path.join(tmp, "util.js")]
graph = codeloom.build_graph_multi(files, tmp)
self.assertIn("util", graph.get("app", set()))
finally:
force_rmtree(tmp)
def test_verify_sha256(self):
path = os.path.join(self.repo, "src", "cli.py")
digest = codeloom.sha256_file(path)
self.assertEqual(len(digest), 64) # sha256 hex is 64 chars
def test_search_snippet(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
index = codeloom.build_symbol_index(files, self.repo)
results = codeloom.search_symbols(index, "Engine")
self.assertTrue(results)
self.assertIn("snippet", results[0])
self.assertTrue(results[0]["snippet"])
def test_find_usages(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
usages = codeloom.find_usages(files, self.repo, "retry")
# retry is used in src.cli.main and src.core.engine.run
mods = {u["module"] for u in usages}
self.assertIn("src.cli", mods)
self.assertIn("src.core.engine", mods)
def test_tree_sitter_backend(self):
# tree-sitter should catch 'export function' that regex misses
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, "util.js"), "w") as f:
f.write("export function helper() { return 1; }\nfunction main() { helper(); }\n")
files = [os.path.join(tmp, "util.js")]
calls = codeloom.build_call_graph_multi(files, tmp)
# if tree-sitter is available, helper should be found
if codeloom._TS_AVAILABLE:
self.assertIn("helper", calls.get("util", {}).get("main", set()))
finally:
force_rmtree(tmp)
def test_embedding_backend_graceful(self):
# without an embedding backend, task_relevance should still work
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
results = codeloom.task_relevance(files, self.repo, "retry logic")
self.assertTrue(results)
self.assertEqual(results[0]["module"], "src.utils.retry")
def test_grep_search(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
results = codeloom.grep_search(files, self.repo, "retry")
self.assertTrue(results)
# retry appears in src.utils.retry and src.core.engine
mods = {r["module"] for r in results}
self.assertIn("src.utils.retry", mods)
self.assertIn("src.core.engine", mods)
def test_cached_symbols(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
cache = codeloom.load_cache(self.repo)
index1 = codeloom.cached_symbols(files, self.repo, cache)
self.assertIn("Engine", index1)
# second call reuses cache
index2 = codeloom.cached_symbols(files, self.repo, cache)
self.assertIn("Engine", index2)
def test_read_symbol(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
result = codeloom.read_symbol(files, self.repo, "Engine")
self.assertIsNotNone(result)
self.assertEqual(result["kind"], "class")
self.assertIn("class Engine", result["source"])
# method
result2 = codeloom.read_symbol(files, self.repo, "run")
self.assertIsNotNone(result2)
self.assertIn("def run", result2["source"])
def test_read_symbol_multi_lang(self):
# Go via tree-sitter, Java via brace-matching fallback
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, "main.go"), "w") as f:
f.write("package main\nfunc helper() int { return 42 }\n")
with open(os.path.join(tmp, "App.java"), "w") as f:
f.write("public class App {\n public int add(int a, int b) {\n return a + b;\n }\n}\n")
files = [os.path.join(tmp, "main.go"), os.path.join(tmp, "App.java")]
# Go (tree-sitter if available, else brace fallback)
r1 = codeloom.read_symbol(files, tmp, "helper")
self.assertIsNotNone(r1)
self.assertIn("func helper", r1["source"])
# Java (brace-matching fallback)
r2 = codeloom.read_symbol(files, tmp, "add")
self.assertIsNotNone(r2)
self.assertIn("public int add", r2["source"])
finally:
force_rmtree(tmp)
def test_explain_symbol(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
info = codeloom.explain_symbol(files, self.repo, "Engine")
self.assertIsNotNone(info)
self.assertEqual(info["kind"], "class")
self.assertIn("module", info)
def test_similar_symbols(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
results = codeloom.similar_symbols(files, self.repo, "run")
# run has 1 param (self, fn) -> 1 non-self param; find others with 1 param
self.assertIsInstance(results, list)
def test_dead_code(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
dead = codeloom.dead_code(files, self.repo)
self.assertIsInstance(dead, list)
def test_byte_index(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
index = codeloom.build_byte_index(files, self.repo)
self.assertIn("Engine", index)
loc = index["Engine"][0]
self.assertIn("start_byte", loc)
self.assertIn("end_byte", loc)
self.assertGreater(loc["end_byte"], loc["start_byte"])
self.assertIn("tokens", loc)
self.assertGreater(loc["tokens"], 0)
def test_get_symbol(self):
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
loc = codeloom.get_symbol(files, self.repo, "Engine")
self.assertIsNotNone(loc)
self.assertIn("class Engine", loc["source"])
self.assertIn("tokens", loc)
def test_get_snippet_by_offset(self):
path = os.path.join(self.repo, "src", "core", "engine.py")
s = codeloom.get_snippet_by_offset(path, 0, 30)
self.assertIsNotNone(s)
self.assertIn("tokens", s)
self.assertIn("bytes", s)
self.assertGreater(s["bytes"], 0)
def test_nested_gitignore(self):
# a nested .gitignore should exclude files in its directory
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, ".gitignore"), "w") as f:
f.write("*.log\n")
os.makedirs(os.path.join(tmp, "sub"))
with open(os.path.join(tmp, "sub", ".gitignore"), "w") as f:
f.write("secret.txt\n")
with open(os.path.join(tmp, "a.py"), "w") as f:
f.write("x = 1\n")
with open(os.path.join(tmp, "sub", "secret.txt"), "w") as f:
f.write("secret\n")
with open(os.path.join(tmp, "sub", "keep.py"), "w") as f:
f.write("y = 2\n")
rules = codeloom.parse_gitignore(os.path.join(tmp, ".gitignore"))
files = []
codeloom._walk(tmp, rules, 100, files)
rels = [os.path.relpath(f, tmp) for f in files]
self.assertIn("a.py", rels)
self.assertIn(os.path.join("sub", "keep.py"), rels)
self.assertNotIn(os.path.join("sub", "secret.txt"), rels)
finally:
force_rmtree(tmp)
def test_gitignore_cache_invalidation(self):
# changing .gitignore should invalidate the cache (all files changed)
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, ".gitignore"), "w") as f:
f.write("*.log\n")
with open(os.path.join(tmp, "a.py"), "w") as f:
f.write("x = 1\n")
cache = codeloom.load_cache(tmp)
files = [os.path.join(tmp, "a.py")]
# first run: all changed
changed = codeloom.changed_files(files, cache, tmp)
self.assertEqual(len(changed), 1)
codeloom.update_cache(files, cache, tmp)
# second run: no change
changed2 = codeloom.changed_files(files, cache, tmp)
self.assertEqual(len(changed2), 0)
# change .gitignore -> all changed again
with open(os.path.join(tmp, ".gitignore"), "w") as f:
f.write("*.py\n")
changed3 = codeloom.changed_files(files, cache, tmp)
self.assertEqual(len(changed3), 1)
finally:
force_rmtree(tmp)
def test_workspace_roots(self):
# a pyproject.toml with src/ should be detected as a workspace root
tmp = tempfile.mkdtemp()
try:
os.makedirs(os.path.join(tmp, "packages", "foo", "src"))
with open(os.path.join(tmp, "packages", "foo", "pyproject.toml"), "w") as f:
f.write("[project]\nname = 'foo'\n")
roots = codeloom._workspace_roots(tmp)
self.assertIn("packages.foo.src", roots)
finally:
force_rmtree(tmp)
def test_persistent_index(self):
# build + save a persistent index, then load it
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, "a.py"), "w") as f:
f.write("class Foo:\n def bar(self):\n return 1\n")
files = [os.path.join(tmp, "a.py")]
index = codeloom.build_persistent_index(files, tmp)
self.assertIn("Foo", index)
codeloom.save_persistent_index(tmp, index, files)
loaded = codeloom.load_persistent_index(tmp)
self.assertIsNotNone(loaded)
self.assertIn("Foo", loaded["symbols"])
# status should report fresh
status = codeloom.render_index_status(tmp)
self.assertIn("fresh", status)
finally:
force_rmtree(tmp)
def test_summary_retrieval(self):
# summary-first retrieval should be much smaller than full source
# for a LARGE symbol (the huge-symbol case that used to lose tokens)
tmp = tempfile.mkdtemp()
try:
# build a large class (100 methods) so full source is big
with open(os.path.join(tmp, "big.py"), "w") as f:
f.write("class Big:\n")
for i in range(100):
f.write(f" def method_{i}(self):\n return {i}\n")
files = [os.path.join(tmp, "big.py")]
summary = codeloom.render_get_symbol(files, tmp, "Big", summary=True)
full = codeloom.render_get_symbol(files, tmp, "Big", summary=False)
self.assertIn("Signature", summary)
self.assertIn("Docstring", summary)
self.assertIn("Calls", summary)
# summary should be much smaller than full source for a large symbol
self.assertLess(len(summary), len(full) // 10)
finally:
force_rmtree(tmp)
def test_get_symbol_honest_edges_label(self):
# Regression: with no --index/--graph built, the summary must
# advertise that the graph is NOT built (run --index) instead of
# fabricating "Calls (0)". Skipped until the honest-label fix lands.
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, "engine.py"), "w") as f:
f.write("class Engine:\n def run(self):\n return 1\n")
files = [os.path.join(tmp, "engine.py")]
out = codeloom.render_get_symbol(files, tmp, "Engine", summary=True)
if "Calls (0)" in out:
self.skipTest("honest edge-label fix not landed yet; "
"summary still prints 'Calls (0)'")
low = out.lower()
self.assertNotIn("Calls (0)", out)
self.assertTrue("not built" in low or "index" in low,
"expected 'not built'/'run --index' graph label, got:\n" + out)
finally:
force_rmtree(tmp)
def test_scanner_skips_strings_comments(self):
# a call inside a string or comment should NOT be detected
tmp = tempfile.mkdtemp()
try:
with open(os.path.join(tmp, "app.js"), "w") as f:
f.write("function helper() { return 1; }\n"
"function main() {\n"
" // comment mentioning helper() but not a real call\n"
" const msg = 'calling helper() here is a string';\n"
" return helper();\n"
"}\n")
files = [os.path.join(tmp, "app.js")]
calls = codeloom.build_call_graph_multi(files, tmp)
# main should call helper exactly once (the real call)
self.assertIn("helper", calls.get("app", {}).get("main", set()))
# the string/comment references should not create extra edges
self.assertEqual(len(calls.get("app", {}).get("main", set())), 1)
finally:
force_rmtree(tmp)
def test_pack(self):
# --pack emits a code-embedded task brief: reading order + embedded code + impact
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
pack = codeloom.render_pack(files, self.repo, "retry")
self.assertIn("READ THESE, IN ORDER", pack)
self.assertIn("THE RELEVANT CODE", pack)
self.assertIn("IMPACT", pack)
self.assertIn("retry", pack)
def test_resume(self):
# --resume emits a compact structural snapshot for compaction survival
files = []
for root, _, fs in os.walk(self.repo):
for f in fs:
if f.endswith(".py") and "__pycache__" not in root and ".venv" not in root:
files.append(os.path.join(root, f))
resume = codeloom.render_resume(files, self.repo, 1000)
self.assertIn("--resume", resume)
self.assertIn("Entry points", resume)
self.assertIn("Modules", resume)
self.assertIn("Top call sites", resume)
def test_memory_remember_read(self):
# repository memory: remember persists, loom_context returns it
# use a temp dir to avoid polluting the real demo repo
import tempfile, shutil
td = tempfile.mkdtemp()
try:
codeloom.memory_remember(td, "ARCHITECTURE", "auth uses session tokens")
mem = codeloom.memory_read(td)
self.assertIn("session tokens", mem)