Repository navigation
Expand file tree
/
Copy pathtest_kit.py
More file actions
2865 lines (2496 loc) · 127 KB
/
Copy pathtest_kit.py
File metadata and controls
2865 lines (2496 loc) · 127 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
"""
Tests for commands/kit.py — kit install, update, generate-resources, validate-kits, dispatcher.
Scenario-based tests covering all CLI subcommands and the core install_kit logic.
"""
import io
import json
import os
import shutil
import sys
import unittest
from contextlib import redirect_stdout, redirect_stderr
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).parent.parent / "skills" / "cypilot" / "scripts"))
def _make_kit_source(td: Path, slug: str = "testkit") -> Path:
"""Create a minimal kit source directory with blueprints/ and conf.toml."""
kit_src = td / slug
bp = kit_src / "blueprints"
bp.mkdir(parents=True)
(bp / "feature.md").write_text(
"<!-- @cpt:blueprint -->\n```toml\n"
f'artifact = "FEATURE"\nkit = "{slug}"\nversion = 1\n'
"```\n<!-- /@cpt:blueprint -->\n\n"
"<!-- @cpt:heading -->\n# Feature Spec\n<!-- /@cpt:heading -->\n",
encoding="utf-8",
)
from cypilot.utils import toml_utils
toml_utils.dump({"version": 1, "blueprints": {"feature": 1}}, kit_src / "conf.toml")
return kit_src
def _bootstrap_project(root: Path, adapter_rel: str = "cypilot") -> Path:
"""Set up a minimal initialized project for kit commands."""
root.mkdir(parents=True, exist_ok=True)
(root / ".git").mkdir(exist_ok=True)
(root / "AGENTS.md").write_text(
f'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "{adapter_rel}"\n```\n<!-- /@cpt:root-agents -->\n',
encoding="utf-8",
)
adapter = root / adapter_rel
config = adapter / "config"
gen = adapter / ".gen"
for d in [adapter, config, gen, adapter / ".core"]:
d.mkdir(parents=True, exist_ok=True)
(config / "AGENTS.md").write_text("# Test\n", encoding="utf-8")
from cypilot.utils import toml_utils
toml_utils.dump({
"version": "1.0",
"project_root": "..",
"system": {"name": "Test", "slug": "test", "kit": "cypilot-sdlc"},
"kits": {},
}, config / "core.toml")
return adapter
# =========================================================================
# install_kit (core function)
# =========================================================================
class TestInstallKit(unittest.TestCase):
"""Core install_kit function scenarios."""
def test_install_kit_no_blueprints_returns_fail(self):
"""Kit source without blueprints/ returns FAIL."""
from cypilot.commands.kit import install_kit
with TemporaryDirectory() as td:
kit_src = Path(td) / "empty_kit"
kit_src.mkdir()
cypilot_dir = Path(td) / "project" / "cypilot"
cypilot_dir.mkdir(parents=True)
result = install_kit(kit_src, cypilot_dir, "empty")
self.assertEqual(result["status"], "FAIL")
self.assertTrue(result["errors"])
def test_install_kit_success(self):
"""Successful kit install copies blueprints, generates resources."""
from cypilot.commands.kit import install_kit
with TemporaryDirectory() as td:
td_p = Path(td)
kit_src = _make_kit_source(td_p, "mykit")
root = td_p / "project"
adapter = _bootstrap_project(root)
result = install_kit(kit_src, adapter, "mykit")
self.assertIn(result["status"], ["PASS", "WARN"])
self.assertEqual(result["kit"], "mykit")
# Reference copy should exist
self.assertTrue((adapter / "kits" / "mykit" / "blueprints").is_dir())
# User blueprints copied
self.assertTrue((adapter / "config" / "kits" / "mykit" / "blueprints").is_dir())
def test_install_kit_with_scripts(self):
"""Kit with scripts/ directory copies scripts to .gen/."""
from cypilot.commands.kit import install_kit
with TemporaryDirectory() as td:
td_p = Path(td)
kit_src = _make_kit_source(td_p, "scripted")
scripts = kit_src / "scripts"
scripts.mkdir()
(scripts / "helper.py").write_text("# helper\n", encoding="utf-8")
root = td_p / "project"
adapter = _bootstrap_project(root)
result = install_kit(kit_src, adapter, "scripted")
self.assertIn(result["status"], ["PASS", "WARN"])
self.assertTrue((adapter / ".gen" / "kits" / "scripted" / "scripts" / "helper.py").is_file())
def test_install_kit_with_skill_and_workflow(self):
"""Kit with @cpt:skill and @cpt:workflow markers generates SKILL.md and workflow files."""
from cypilot.commands.kit import install_kit
with TemporaryDirectory() as td:
td_p = Path(td)
kit_src = td_p / "richkit"
bp_dir = kit_src / "blueprints"
bp_dir.mkdir(parents=True)
(bp_dir / "FEAT.md").write_text(
"`@cpt:blueprint`\n```toml\n"
'artifact = "FEAT"\nkit = "richkit"\nversion = 1\n'
"```\n`@/cpt:blueprint`\n\n"
"`@cpt:heading`\n```toml\nid = \"h1\"\nlevel = 1\n"
"template = \"Feature\"\n```\n`@/cpt:heading`\n\n"
"`@cpt:skill`\n```markdown\nUse this for features.\n```\n`@/cpt:skill`\n\n"
"`@cpt:workflow`\n```toml\nname = \"feat-review\"\n"
'description = "Review features"\nversion = "1"\n'
'purpose = "QA"\n```\n'
"```markdown\n## Steps\n1. Check\n```\n`@/cpt:workflow`\n",
encoding="utf-8",
)
from cypilot.utils import toml_utils
toml_utils.dump({"version": 1, "blueprints": {"FEAT": 1}}, kit_src / "conf.toml")
root = td_p / "project"
adapter = _bootstrap_project(root)
result = install_kit(kit_src, adapter, "richkit")
self.assertIn(result["status"], ["PASS", "WARN"])
# SKILL.md should be generated
skill_path = adapter / ".gen" / "kits" / "richkit" / "SKILL.md"
self.assertTrue(skill_path.is_file())
skill_content = skill_path.read_text(encoding="utf-8")
self.assertIn("Artifacts: FEAT", skill_content)
self.assertIn("Workflows: feat-review", skill_content)
# Workflow file should be generated
wf_path = adapter / ".gen" / "kits" / "richkit" / "workflows" / "feat-review.md"
self.assertTrue(wf_path.is_file())
wf_content = wf_path.read_text(encoding="utf-8")
self.assertIn("type: workflow", wf_content)
self.assertIn('description: Review features', wf_content)
self.assertIn('version: 1', wf_content)
self.assertIn('purpose: QA', wf_content)
# =========================================================================
# cmd_kit dispatcher
# =========================================================================
class TestCmdKitDispatcher(unittest.TestCase):
"""Kit CLI dispatcher: handles subcommands and errors."""
def test_no_subcommand(self):
from cypilot.commands.kit import cmd_kit
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit([])
self.assertEqual(rc, 1)
out = json.loads(buf.getvalue())
self.assertEqual(out["status"], "ERROR")
self.assertIn("subcommand", out["message"].lower())
def test_unknown_subcommand(self):
from cypilot.commands.kit import cmd_kit
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit(["frobnicate"])
self.assertEqual(rc, 1)
out = json.loads(buf.getvalue())
self.assertIn("Unknown", out["message"])
# =========================================================================
# cmd_kit_install
# =========================================================================
class TestCmdKitInstall(unittest.TestCase):
"""CLI kit install command scenarios."""
def test_install_missing_blueprints_dir(self):
"""Install from source with no blueprints/ returns FAIL."""
from cypilot.commands.kit import cmd_kit_install
with TemporaryDirectory() as td:
kit_src = Path(td) / "nokit"
kit_src.mkdir()
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_install([str(kit_src)])
self.assertEqual(rc, 2)
out = json.loads(buf.getvalue())
self.assertEqual(out["status"], "FAIL")
def test_install_empty_blueprints(self):
"""Install from source with empty blueprints/ returns FAIL."""
from cypilot.commands.kit import cmd_kit_install
with TemporaryDirectory() as td:
bp = Path(td) / "kit" / "blueprints"
bp.mkdir(parents=True)
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_install([str(Path(td) / "kit")])
self.assertEqual(rc, 2)
def test_install_no_project_root(self):
"""Install outside a project root returns error."""
from cypilot.commands.kit import cmd_kit_install
with TemporaryDirectory() as td:
kit_src = _make_kit_source(Path(td), "k1")
cwd = os.getcwd()
try:
empty = Path(td) / "empty"
empty.mkdir()
os.chdir(str(empty))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_install([str(kit_src)])
self.assertEqual(rc, 1)
finally:
os.chdir(cwd)
def test_install_no_cypilot_var(self):
"""Install in project without cypilot_path in AGENTS.md returns error."""
from cypilot.commands.kit import cmd_kit_install
with TemporaryDirectory() as td:
root = Path(td) / "proj"
root.mkdir()
(root / ".git").mkdir()
(root / "AGENTS.md").write_text("# no toml block\n", encoding="utf-8")
kit_src = _make_kit_source(Path(td), "k2")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_install([str(kit_src)])
self.assertEqual(rc, 1)
finally:
os.chdir(cwd)
def test_install_already_exists_without_force(self):
"""Installing a kit that already exists without --force returns FAIL."""
from cypilot.commands.kit import cmd_kit_install
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
kit_src = _make_kit_source(Path(td), "dup")
# Pre-create the kit reference
(adapter / "kits" / "dup").mkdir(parents=True)
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_install([str(kit_src)])
self.assertEqual(rc, 2)
out = json.loads(buf.getvalue())
self.assertEqual(out["status"], "FAIL")
self.assertIn("already installed", out["message"])
finally:
os.chdir(cwd)
def test_install_dry_run(self):
"""--dry-run prints plan without writing files."""
from cypilot.commands.kit import cmd_kit_install
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
kit_src = _make_kit_source(Path(td), "drykit")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_install([str(kit_src), "--dry-run"])
self.assertEqual(rc, 0)
out = json.loads(buf.getvalue())
self.assertEqual(out["status"], "DRY_RUN")
finally:
os.chdir(cwd)
def test_install_full_success(self):
"""Successful kit install via CLI."""
from cypilot.commands.kit import cmd_kit_install
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
kit_src = _make_kit_source(Path(td), "goodkit")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_install([str(kit_src)])
self.assertEqual(rc, 0)
out = json.loads(buf.getvalue())
self.assertIn(out["status"], ["PASS", "WARN"])
finally:
os.chdir(cwd)
# =========================================================================
# cmd_kit_update
# =========================================================================
class TestCmdKitUpdate(unittest.TestCase):
"""CLI kit update command scenarios."""
def test_update_no_project_root(self):
from cypilot.commands.kit import cmd_kit_update
with TemporaryDirectory() as td:
cwd = os.getcwd()
try:
os.chdir(td)
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_update([])
self.assertEqual(rc, 1)
finally:
os.chdir(cwd)
def test_update_no_cypilot_dir(self):
from cypilot.commands.kit import cmd_kit_update
with TemporaryDirectory() as td:
root = Path(td)
(root / ".git").mkdir()
(root / "AGENTS.md").write_text("# no toml\n", encoding="utf-8")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_update([])
self.assertEqual(rc, 1)
finally:
os.chdir(cwd)
def test_update_no_kits_dir(self):
from cypilot.commands.kit import cmd_kit_update
with TemporaryDirectory() as td:
root = Path(td) / "proj"
_bootstrap_project(root)
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_update([])
self.assertEqual(rc, 2)
out = json.loads(buf.getvalue())
self.assertIn("No kits", out["message"])
finally:
os.chdir(cwd)
def test_update_specific_kit_not_found(self):
from cypilot.commands.kit import cmd_kit_update
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
(adapter / "kits").mkdir()
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_update(["--kit", "nosuch"])
self.assertEqual(rc, 2)
finally:
os.chdir(cwd)
def test_update_dry_run(self):
from cypilot.commands.kit import cmd_kit_update, install_kit
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
kit_src = _make_kit_source(Path(td), "upkit")
install_kit(kit_src, adapter, "upkit")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_update(["--dry-run"])
self.assertEqual(rc, 0)
out = json.loads(buf.getvalue())
self.assertEqual(out["status"], "PASS")
finally:
os.chdir(cwd)
def test_update_force(self):
from cypilot.commands.kit import cmd_kit_update, install_kit
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
kit_src = _make_kit_source(Path(td), "forcekit")
install_kit(kit_src, adapter, "forcekit")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_update(["--force"])
self.assertEqual(rc, 0)
out = json.loads(buf.getvalue())
self.assertIn(out["status"], ["PASS", "WARN"])
self.assertGreaterEqual(out["kits_updated"], 1)
finally:
os.chdir(cwd)
def test_update_missing_ref_blueprints(self):
"""Kit reference with no blueprints/ → error recorded."""
from cypilot.commands.kit import cmd_kit_update
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
(adapter / "kits" / "broken").mkdir(parents=True)
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_kit_update([])
# Should still complete, but with errors/warnings
self.assertEqual(rc, 0)
out = json.loads(buf.getvalue())
self.assertIn(out["status"], ["PASS", "WARN"])
finally:
os.chdir(cwd)
# =========================================================================
# cmd_generate_resources
# =========================================================================
class TestCmdGenerateResources(unittest.TestCase):
"""CLI generate-resources command scenarios."""
def test_no_project_root(self):
from cypilot.commands.kit import cmd_generate_resources
with TemporaryDirectory() as td:
cwd = os.getcwd()
try:
os.chdir(td)
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_generate_resources([])
self.assertEqual(rc, 1)
finally:
os.chdir(cwd)
def test_no_cypilot_dir(self):
from cypilot.commands.kit import cmd_generate_resources
with TemporaryDirectory() as td:
root = Path(td)
(root / ".git").mkdir()
(root / "AGENTS.md").write_text("# nothing\n", encoding="utf-8")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_generate_resources([])
self.assertEqual(rc, 1)
finally:
os.chdir(cwd)
def test_no_kits_with_blueprints(self):
from cypilot.commands.kit import cmd_generate_resources
with TemporaryDirectory() as td:
root = Path(td) / "proj"
_bootstrap_project(root)
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_generate_resources([])
self.assertEqual(rc, 2)
finally:
os.chdir(cwd)
def test_generate_success(self):
from cypilot.commands.kit import cmd_generate_resources, install_kit
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
kit_src = _make_kit_source(Path(td), "genkit")
install_kit(kit_src, adapter, "genkit")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_generate_resources([])
self.assertEqual(rc, 0)
out = json.loads(buf.getvalue())
self.assertIn(out["status"], ["PASS", "WARN"])
self.assertGreaterEqual(out["kits_processed"], 1)
finally:
os.chdir(cwd)
def test_generate_dry_run(self):
from cypilot.commands.kit import cmd_generate_resources, install_kit
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
kit_src = _make_kit_source(Path(td), "drygenkit")
install_kit(kit_src, adapter, "drygenkit")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_generate_resources(["--dry-run"])
self.assertEqual(rc, 0)
finally:
os.chdir(cwd)
def test_generate_specific_kit(self):
from cypilot.commands.kit import cmd_generate_resources, install_kit
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
kit_src = _make_kit_source(Path(td), "speckit")
install_kit(kit_src, adapter, "speckit")
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_generate_resources(["--kit", "speckit"])
self.assertEqual(rc, 0)
finally:
os.chdir(cwd)
def test_generate_missing_bp_dir(self):
"""Specified kit exists but blueprints dir doesn't → error recorded."""
from cypilot.commands.kit import cmd_generate_resources
with TemporaryDirectory() as td:
root = Path(td) / "proj"
adapter = _bootstrap_project(root)
(adapter / "config" / "kits" / "nokit").mkdir(parents=True)
cwd = os.getcwd()
try:
os.chdir(str(root))
buf = io.StringIO()
with redirect_stdout(buf):
rc = cmd_generate_resources(["--kit", "nokit"])
# Should fail since blueprints dir missing
self.assertIn(rc, [0, 2])
finally:
os.chdir(cwd)
# =========================================================================
# _read_kit_version + _register_kit_in_core_toml
# =========================================================================
class TestKitHelpers(unittest.TestCase):
def test_read_kit_version_valid(self):
from cypilot.commands.kit import _read_kit_version
from cypilot.utils import toml_utils
with TemporaryDirectory() as td:
p = Path(td) / "conf.toml"
toml_utils.dump({"version": 2}, p)
self.assertEqual(_read_kit_version(p), "2")
def test_read_kit_version_missing(self):
from cypilot.commands.kit import _read_kit_version
self.assertEqual(_read_kit_version(Path("/nonexistent/conf.toml")), "")
def test_read_kit_version_no_key(self):
from cypilot.commands.kit import _read_kit_version
from cypilot.utils import toml_utils
with TemporaryDirectory() as td:
p = Path(td) / "conf.toml"
toml_utils.dump({"other": "data"}, p)
self.assertEqual(_read_kit_version(p), "")
def test_register_kit_in_core_toml(self):
from cypilot.commands.kit import _register_kit_in_core_toml
from cypilot.utils import toml_utils
with TemporaryDirectory() as td:
config_dir = Path(td) / "config"
config_dir.mkdir()
toml_utils.dump({"version": "1.0", "kits": {}}, config_dir / "core.toml")
_register_kit_in_core_toml(config_dir, "mykit", "1", Path(td))
import tomllib
with open(config_dir / "core.toml", "rb") as f:
data = tomllib.load(f)
self.assertIn("mykit", data["kits"])
self.assertEqual(data["kits"]["mykit"]["path"], ".gen/kits/mykit")
def test_register_kit_no_core_toml(self):
"""No core.toml → does nothing, no error."""
from cypilot.commands.kit import _register_kit_in_core_toml
with TemporaryDirectory() as td:
_register_kit_in_core_toml(Path(td), "nokit", "1", Path(td))
def test_register_kit_corrupt_core_toml(self):
"""Corrupt core.toml → does nothing, no error."""
from cypilot.commands.kit import _register_kit_in_core_toml
with TemporaryDirectory() as td:
config_dir = Path(td)
(config_dir / "core.toml").write_text("{{invalid", encoding="utf-8")
_register_kit_in_core_toml(config_dir, "nokit", "1", Path(td))
# =========================================================================
# _parse_segments / _three_way_merge_blueprint
# =========================================================================
class TestParseSegments(unittest.TestCase):
"""Tests for the segment parser."""
def test_text_only(self):
from cypilot.commands.kit import _parse_segments
segs = _parse_segments("# Hello\n\nSome text.\n")
self.assertEqual(len(segs), 1)
self.assertEqual(segs[0].kind, "text")
def test_single_marker(self):
from cypilot.commands.kit import _parse_segments
text = "# Title\n\n`@cpt:blueprint`\n```toml\nkit = \"sdlc\"\n```\n`@/cpt:blueprint`\n\nEnd.\n"
segs = _parse_segments(text)
types = [s.kind for s in segs]
self.assertEqual(types, ["text", "marker", "text"])
self.assertEqual(segs[1].marker_type, "blueprint")
self.assertEqual(segs[1].marker_key, "blueprint#0")
def test_workflow_identity(self):
from cypilot.commands.kit import _parse_segments
text = (
'`@cpt:workflow`\n```toml\nname = "pr-review"\n```\ncontent\n`@/cpt:workflow`\n'
'`@cpt:workflow`\n```toml\nname = "pr-status"\n```\ncontent2\n`@/cpt:workflow`\n'
)
segs = _parse_segments(text)
markers = [s for s in segs if s.kind == "marker"]
self.assertEqual(len(markers), 2)
self.assertEqual(markers[0].marker_key, "workflow:pr-review#0")
self.assertEqual(markers[1].marker_key, "workflow:pr-status#0")
def test_heading_identity(self):
from cypilot.commands.kit import _parse_segments
text = '`@cpt:heading`\n```toml\nlevel = 1\ntemplate = "Context"\n```\n`@/cpt:heading`\n'
segs = _parse_segments(text)
markers = [s for s in segs if s.kind == "marker"]
self.assertEqual(markers[0].marker_key, "heading:L1#0")
def test_duplicate_keys_disambiguated(self):
from cypilot.commands.kit import _parse_segments
text = (
'`@cpt:heading`\n```toml\nlevel = 2\n```\n`@/cpt:heading`\n'
'`@cpt:heading`\n```toml\nlevel = 2\n```\n`@/cpt:heading`\n'
)
segs = _parse_segments(text)
markers = [s for s in segs if s.kind == "marker"]
self.assertEqual(len(markers), 2)
self.assertNotEqual(markers[0].marker_key, markers[1].marker_key)
self.assertIn("heading:L2#0", markers[0].marker_key)
self.assertIn("heading:L2#1", markers[1].marker_key)
def test_unclosed_marker_treated_as_text(self):
from cypilot.commands.kit import _parse_segments
text = '`@cpt:skill`\nSome content without close\n'
segs = _parse_segments(text)
self.assertEqual(len(segs), 1)
self.assertEqual(segs[0].kind, "text")
class TestThreeWayMerge(unittest.TestCase):
"""Tests for marker-level three-way merge."""
def test_unchanged_marker_gets_updated(self):
"""If user didn't change a marker, it should be updated from new ref."""
from cypilot.commands.kit import _three_way_merge_blueprint
old_ref = '`@cpt:heading`\n```toml\ntemplate = "Title"\n```\nOld content\n`@/cpt:heading`\n'
new_ref = '`@cpt:heading`\n```toml\ntemplate = "Title"\n```\nNew content\n`@/cpt:heading`\n'
user = '`@cpt:heading`\n```toml\ntemplate = "Title"\n```\nOld content\n`@/cpt:heading`\n'
merged, report = _three_way_merge_blueprint(old_ref, new_ref, user)
self.assertIn("New content", merged)
self.assertNotIn("Old content", merged)
self.assertEqual(len(report["updated"]), 1)
self.assertEqual(len(report["skipped"]), 0)
def test_customized_marker_skipped(self):
"""If user customized a marker, it should NOT be updated."""
from cypilot.commands.kit import _three_way_merge_blueprint
old_ref = '`@cpt:heading`\n```toml\ntemplate = "Title"\n```\nOriginal\n`@/cpt:heading`\n'
new_ref = '`@cpt:heading`\n```toml\ntemplate = "Title"\n```\nUpdated\n`@/cpt:heading`\n'
user = '`@cpt:heading`\n```toml\ntemplate = "Title"\n```\nMy custom text\n`@/cpt:heading`\n'
merged, report = _three_way_merge_blueprint(old_ref, new_ref, user)
self.assertIn("My custom text", merged)
self.assertNotIn("Updated", merged)
self.assertEqual(len(report["skipped"]), 1)
self.assertEqual(len(report["updated"]), 0)
def test_deleted_marker_not_readded(self):
"""If user deleted a marker, it should NOT be re-added."""
from cypilot.commands.kit import _three_way_merge_blueprint
old_ref = (
'Intro\n'
'`@cpt:heading`\n```toml\ntemplate = "A"\n```\nContent A\n`@/cpt:heading`\n'
'`@cpt:heading`\n```toml\ntemplate = "B"\n```\nContent B\n`@/cpt:heading`\n'
)
new_ref = (
'Intro\n'
'`@cpt:heading`\n```toml\ntemplate = "A"\n```\nContent A v2\n`@/cpt:heading`\n'
'`@cpt:heading`\n```toml\ntemplate = "B"\n```\nContent B v2\n`@/cpt:heading`\n'
)
# User deleted marker B
user = (
'Intro\n'
'`@cpt:heading`\n```toml\ntemplate = "A"\n```\nContent A\n`@/cpt:heading`\n'
)
merged, report = _three_way_merge_blueprint(old_ref, new_ref, user)
self.assertIn("Content A v2", merged)
self.assertNotIn("Content B", merged)
self.assertEqual(len(report["updated"]), 1)
def test_text_between_markers_preserved(self):
"""Non-marker text (prose) is always preserved."""
from cypilot.commands.kit import _three_way_merge_blueprint
old_ref = 'Intro text\n\n`@cpt:skill`\nOld skill\n`@/cpt:skill`\n\nFooter\n'
new_ref = 'Intro text\n\n`@cpt:skill`\nNew skill\n`@/cpt:skill`\n\nFooter\n'
user = 'Intro text\n\n`@cpt:skill`\nOld skill\n`@/cpt:skill`\n\nFooter\n'
merged, _ = _three_way_merge_blueprint(old_ref, new_ref, user)
self.assertIn("Intro text"
10BC8
;, merged)
self.assertIn("New skill", merged)
self.assertIn("Footer", merged)
def test_mixed_updated_and_skipped(self):
"""Some markers updated, some skipped (customized)."""
from cypilot.commands.kit import _three_way_merge_blueprint
old_ref = (
'`@cpt:blueprint`\n```toml\nkit = "x"\n```\n`@/cpt:blueprint`\n'
'`@cpt:skill`\nOld skill\n`@/cpt:skill`\n'
)
new_ref = (
'`@cpt:blueprint`\n```toml\nkit = "x"\nartifact = "Y"\n```\n`@/cpt:blueprint`\n'
'`@cpt:skill`\nNew skill\n`@/cpt:skill`\n'
)
# User customized blueprint, didn't touch skill
user = (
'`@cpt:blueprint`\n```toml\nkit = "x"\ncustom = true\n```\n`@/cpt:blueprint`\n'
'`@cpt:skill`\nOld skill\n`@/cpt:skill`\n'
)
merged, report = _three_way_merge_blueprint(old_ref, new_ref, user)
self.assertIn("custom = true", merged) # customized — kept
self.assertIn("New skill", merged) # unchanged — updated
self.assertEqual(report["skipped"], ["blueprint#0"])
self.assertEqual(report["updated"], ["skill#0"])
def test_no_changes_when_refs_identical(self):
"""If old_ref == new_ref, nothing changes."""
from cypilot.commands.kit import _three_way_merge_blueprint
same = '`@cpt:skill`\nSame\n`@/cpt:skill`\n'
merged, report = _three_way_merge_blueprint(same, same, same)
self.assertEqual(report["updated"], [])
self.assertEqual(report["skipped"], [])
self.assertEqual(report["kept"], ["skill#0"])
# =========================================================================
# migrate_kit (core function)
# =========================================================================
class TestMigrateKit(unittest.TestCase):
"""Tests for the migrate_kit function with marker-level merge."""
def _setup_kit(self, td_p, old_heading="Feature v1", new_heading="Feature v2",
user_heading="Feature v1", ref_ver=2, user_ver=1, with_prev=True):
"""Create a project with old ref (.prev/), new ref, and user config."""
root = td_p / "proj"
adapter = _bootstrap_project(root)
from cypilot.utils import toml_utils
bp_template = (
'`@cpt:blueprint`\n```toml\nkit = "sdlc"\nartifact = "FEAT"\n```\n`@/cpt:blueprint`\n\n'
'`@cpt:heading`\n```toml\nlevel = 1\ntemplate = "{heading}"\n```\n`@/cpt:heading`\n'
)
# New reference
ref_dir = adapter / "kits" / "sdlc"
ref_bp = ref_dir / "blueprints"
ref_bp.mkdir(parents=True)
(ref_bp / "FEAT.md").write_text(
bp_template.format(heading=new_heading), encoding="utf-8",
)
toml_utils.dump({"version": ref_ver}, ref_dir / "conf.toml")
# Old reference (.prev/)
if with_prev:
prev_bp = ref_dir / ".prev" / "blueprints"
prev_bp.mkdir(parents=True)
(prev_bp / "FEAT.md").write_text(
bp_template.format(heading=old_heading), encoding="utf-8",
)
# User config
config_kit = adapter / "config" / "kits" / "sdlc"
user_bp = config_kit / "blueprints"
user_bp.mkdir(parents=True)
(user_bp / "FEAT.md").write_text(
bp_template.format(heading=user_heading), encoding="utf-8",
)
toml_utils.dump({"version": user_ver}, config_kit / "conf.toml")
gen_kits = adapter / ".gen" / "kits"
return root, adapter, ref_dir, config_kit, gen_kits
def test_unchanged_marker_updated_via_prev(self):
"""Marker unchanged by user → updated from new ref (three-way via .prev/)."""
from cypilot.commands.kit import migrate_kit
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=False)
self.assertEqual(result["status"], "migrated")
bp = result["blueprints"][0]
self.assertEqual(bp["action"], "merged")
self.assertTrue(any("heading" in k for k in bp.get("markers_updated", [])))
user_text = (config_kit / "blueprints" / "FEAT.md").read_text()
self.assertIn("Feature v2", user_text)
def test_customized_marker_skipped(self):
"""Marker customized by user → skipped during merge."""
from cypilot.commands.kit import migrate_kit
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(
Path(td), user_heading="My Custom Heading",
)
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=False)
bp = result["blueprints"][0]
# blueprint marker is unchanged → updated; heading is customized → skipped
self.assertTrue(any("heading" in k for k in bp.get("markers_skipped", [])))
user_text = (config_kit / "blueprints" / "FEAT.md").read_text()
self.assertIn("My Custom Heading", user_text)
def test_no_migration_when_current(self):
from cypilot.commands.kit import migrate_kit
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(
Path(td), ref_ver=1, user_ver=1,
old_heading="Feature v1", new_heading="Feature v1",
user_heading="Feature v1",
)
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=False)
self.assertEqual(result["status"], "current")
def test_updates_conf_toml(self):
from cypilot.commands.kit import migrate_kit
import tomllib
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
migrate_kit("sdlc", ref_dir, config_kit, interactive=False)
with open(config_kit / "conf.toml", "rb") as f:
data = tomllib.load(f)
self.assertEqual(data["version"], 2)
def test_dry_run_does_not_write(self):
from cypilot.commands.kit import migrate_kit
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
result = migrate_kit("sdlc", ref_dir, config_kit, dry_run=True)
# Should report migration but not write
user_text = (config_kit / "blueprints" / "FEAT.md").read_text()
self.assertIn("Feature v1", user_text)
def test_fallback_without_prev_preserves_user(self):
"""Without .prev/, user customizations must NOT be overwritten."""
from cypilot.commands.kit import migrate_kit
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(
Path(td), with_prev=False,
user_heading="My Custom Heading",
)
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=False)
self.assertEqual(result["status"], "migrated")
# User customization MUST survive
user_text = (config_kit / "blueprints" / "FEAT.md").read_text()
self.assertIn("My Custom Heading", user_text)
self.assertNotIn("Feature v2", user_text)
def test_kit_version_drift(self):
from cypilot.commands.kit import migrate_kit
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(
Path(td), ref_ver=2, user_ver=2,
old_heading="Feature v2", new_heading="Feature v2", user_heading="Feature v2",
)
from cypilot.utils import toml_utils
toml_utils.dump({"version": 3}, ref_dir / "conf.toml")
toml_utils.dump({"version": 2}, config_kit / "conf.toml")
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=False)
self.assertEqual(result["status"], "migrated")
self.assertIn("kit_version", result)
def test_prev_cleaned_after_migration(self):
from cypilot.commands.kit import migrate_kit
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
migrate_kit("sdlc", ref_dir, config_kit, interactive=False)
self.assertFalse((ref_dir / ".prev").exists())
def test_interactive_approve_updates(self):
"""Interactive mode: user says 'y' → changes applied."""
from cypilot.commands.kit import migrate_kit
from unittest.mock import patch
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
with patch("builtins.input", return_value="y"):
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=True)
bp = result["blueprints"][0]
self.assertEqual(bp["action"], "merged")
user_text = (config_kit / "blueprints" / "FEAT.md").read_text()
self.assertIn("Feature v2", user_text)
def test_interactive_decline_updates(self):
"""Interactive mode: user says 'N' → changes NOT applied."""
from cypilot.commands.kit import migrate_kit
from unittest.mock import patch
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
with patch("builtins.input", return_value="n"):
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=True)
bp = result["blueprints"][0]
self.assertEqual(bp["action"], "declined")
user_text = (config_kit / "blueprints" / "FEAT.md").read_text()
self.assertIn("Feature v1", user_text)
def test_declined_does_not_bump_conf_toml(self):
"""Declining all changes must NOT bump conf.toml version (re-prompt on next update)."""
from cypilot.commands.kit import migrate_kit
from unittest.mock import patch
import tomllib
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
with patch("builtins.input", return_value="n"):
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=True)
# conf.toml must still have old version
with open(config_kit / "conf.toml", "rb") as f:
data = tomllib.load(f)
self.assertEqual(data["version"], 1, "conf.toml version should NOT be bumped when all declined")
def test_declined_preserves_prev(self):
"""Declining all changes must preserve .prev/ for three-way merge on retry."""
from cypilot.commands.kit import migrate_kit
from unittest.mock import patch
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
with patch("builtins.input", return_value="n"):
migrate_kit("sdlc", ref_dir, config_kit, interactive=True)
self.assertTrue((ref_dir / ".prev").is_dir(),
".prev/ should be preserved when all declined")
def test_interactive_all_auto_approves(self):
"""Interactive mode: user says 'all' → all files auto-approved."""
from cypilot.commands.kit import migrate_kit
from unittest.mock import patch
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(Path(td))
with patch("builtins.input", return_value="all"):
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=True)
bp = result["blueprints"][0]
self.assertEqual(bp["action"], "merged")
def test_interactive_approve_overwrites_customized(self):
"""Interactive mode: user says 'y' → customized markers overwritten."""
from cypilot.commands.kit import migrate_kit
from unittest.mock import patch
with TemporaryDirectory() as td:
_, _, ref_dir, config_kit, _ = self._setup_kit(
Path(td), user_heading="My Custom",
)
with patch("builtins.input", return_value="y"):
result = migrate_kit("sdlc", ref_dir, config_kit, interactive=True)
bp = result["blueprints"][0]
self.assertEqual(bp["action"], "merged")
user_text = (config_kit / "blueprints" / "FEAT.md").read_text()
# Customized marker overwritten with reference
self.assertIn("Feature v2", user_text)
self.assertNotIn("My Custom", user_text)
def test_interactive_ref_removed_approved(self):
"""Interactive mode: marker removed from ref, user approves → removed from config."""
from cypilot.commands.kit import migrate_kit
from unittest.mock import patch
from cypilot.utils import toml_utils
with TemporaryDirectory() as td:
td_p = Path(td)
root = td_p / "proj"
adapter = _bootstrap_project(root)