forked from hyphen-2025/cyber-pilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli_integration.py
More file actions
5554 lines (4757 loc) · 220 KB
/
test_cli_integration.py
File metadata and controls
5554 lines (4757 loc) · 220 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
"""
Integration tests for CLI commands.
Tests CLI entry point with various command combinations to improve coverage.
"""
import unittest
import sys
import os
import json
import io
import unittest.mock
from pathlib import Path
from tempfile import TemporaryDirectory
from contextlib import redirect_stdout, redirect_stderr
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).parent.parent / "skills" / "cypilot" / "scripts"))
from cypilot.cli import main
def _bootstrap_registry(project_root: Path, *, entries: list) -> None:
(project_root / ".git").mkdir(exist_ok=True)
(project_root / "AGENTS.md").write_text(
'<!-- @cpt:root-agents -->\n```toml\ncypilot_path = "adapter"\n```\n',
encoding="utf-8",
)
adapter_dir = project_root / "adapter"
adapter_dir.mkdir(parents=True, exist_ok=True)
(adapter_dir / "config").mkdir(exist_ok=True)
(adapter_dir / "config" / "AGENTS.md").write_text(
"# Cypilot Adapter: Test\n",
encoding="utf-8",
)
# Write legacy artifacts.json with entries list (tests using old format)
(adapter_dir / "config" / "artifacts.toml").write_text(
_make_artifacts_toml_from_entries(entries),
encoding="utf-8",
)
def _make_artifacts_toml_from_entries(entries: list) -> str:
"""Build minimal artifacts.toml from a list of legacy entry dicts."""
lines = ['version = "1.0"', 'project_root = ".."', '']
for e in entries:
kind = e.get("kind", e.get("type", "UNKNOWN"))
path = e.get("path", "")
system = e.get("system", "Test")
lines.append('[[systems]]')
lines.append(f'name = "{system}"')
lines.append('slug = "test"')
lines.append('kit = "k"')
lines.append('')
lines.append('[[systems.artifacts]]')
lines.append(f'path = "{path}"')
lines.append(f'kind = "{kind}"')
lines.append('traceability = "FULL"')
lines.append('')
if not entries:
lines.append('[[systems]]')
lines.append('name = "Test"')
lines.append('slug = "test"')
lines.append('kit = "k"')
lines.append('')
return '\n'.join(lines) + '\n'
class TestCLIValidateCommand(unittest.TestCase):
"""Test validate command variations."""
def test_validate_default_artifact_is_current_dir(self):
"""Test validate command without --artifact uses current directory."""
# --artifact now defaults to "." (current directory)
# This test just verifies it doesn't raise an error for missing argument
stdout = io.StringIO()
stderr = io.StringIO()
with redirect_stdout(stdout), redirect_stderr(stderr):
# Should not raise SystemExit for missing argument
# (may still fail validation but that's expected)
exit_code = main(["validate"])
# Exit code 0 = PASS, 1 = ERROR (no adapter), 2 = FAIL - all valid
self.assertIn(exit_code, [0, 1, 2])
def test_validate_nonexistent_artifact(self):
"""Test validate command with non-existent artifact."""
with TemporaryDirectory() as tmpdir:
# Use valid artifact name
fake_path = Path(tmpdir) / "DESIGN.md"
stdout = io.StringIO()
with redirect_stdout(stdout):
try:
exit_code = main(["validate", "--artifact", str(fake_path)])
# Should fail with file not found
self.assertNotEqual(exit_code, 0)
output = stdout.getvalue()
self.assertIn("ERROR", output.upper())
except FileNotFoundError:
# Also acceptable - file doesn't exist
pass
def test_validate_dir_with_design_and_specs_flag_fails(self):
"""When --artifact is a directory containing DESIGN.md, unknown --specs must error."""
with TemporaryDirectory() as tmpdir:
feat = Path(tmpdir)
(feat / "DESIGN.md").write_text("# Feature: X\n", encoding="utf-8")
with self.assertRaises(SystemExit):
main(["validate", "--artifact", str(feat), "--specs", "spec-x"])
def test_validate_dir_without_design_uses_code_root_traceability(self):
"""Cover validate branch when --artifact is a directory without DESIGN.md."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["validate", "--artifact", str(root)])
self.assertIn(exit_code, (0, 1, 2))
out = json.loads(stdout.getvalue())
self.assertIn("status", out)
def test_validate_code_root_with_spec_artifacts(self):
"""Cover validation when --artifact is a code root directory with features."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
(root / "src").mkdir(parents=True, exist_ok=True)
(root / "architecture" / "specs").mkdir(parents=True)
# Minimal artifacts for feature-a/feature-b so traceability runs.
(root / "architecture" / "specs" / "feature-a.md").write_text("# Feature: A\n", encoding="utf-8")
(root / "architecture" / "specs" / "feature-b.md").write_text("# Feature: B\n", encoding="utf-8")
_bootstrap_registry(
root,
entries=[
{"kind": "FEATURE", "system": "Test", "path": "architecture/features/feature-a.md", "format": "Cypilot"},
{"kind": "FEATURE", "system": "Test", "path": "architecture/features/feature-b.md", "format": "Cypilot"},
{"kind": "SRC", "system": "Test", "path": "src", "format": "CONTEXT", "traceability_enabled": True, "extensions": [".py"]},
],
)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["validate", "--artifact", str(root)])
self.assertIn(exit_code, (0, 1, 2))
out = json.loads(stdout.getvalue())
self.assertIn("status", out)
def test_validate_spec_dir_with_design_md_runs_codebase_traceability(self):
"""Cover validate branch when --artifact is a feature file under specs/ directory."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir(exist_ok=True)
feat_dir = root / "architecture" / "specs"
feat_dir.mkdir(parents=True)
feat = feat_dir / "feature-x.md"
feat.write_text("# Feature: X\n", encoding="utf-8")
_bootstrap_registry(
root,
entries=[
{"kind": "FEATURE", "system": "Test", "path": "architecture/features/feature-x.md", "format": "Cypilot"},
],
)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["validate", "--artifact", str(feat)])
self.assertIn(exit_code, (0, 1, 2))
out = json.loads(stdout.getvalue())
self.assertIn("status", out)
def test_validate_markerless_constraints_do_not_trigger_legacy_other_kinds_error(self):
"""Regression: when constraints exist, skip legacy 'ID not referenced from other artifact kinds'."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
# Minimal SDLC kit with constraints
(root / "kits" / "sdlc").mkdir(parents=True)
import shutil
src_constraints = Path(__file__).parent.parent / ".bootstrap" / "config" / "kits" / "sdlc" / "constraints.toml"
shutil.copy2(src_constraints, root / "kits" / "sdlc" / "constraints.toml")
# Create markerless DESIGN artifact defining a principle (DESIGN/principle prohibits PRD/ADR refs)
(root / "architecture").mkdir(parents=True)
(root / "architecture" / "DESIGN.md").write_text(
"""#### 2.1: Design Principles\n\n- [ ] `p1` - **ID**: `cpt-test-principle-loose-coupling`\n""",
encoding="utf-8",
)
# Create PRD artifact to ensure there are other kinds present (to provoke legacy error if not skipped)
(root / "architecture" / "PRD.md").write_text(
"""- [ ] `p1` - **ID**: `cpt-test-fr-foo`\n""",
encoding="utf-8",
)
_bootstrap_registry_new_format(
root,
kits={"cypilot": {"format": "Cypilot", "path": "kits/sdlc"}},
systems=[{
"name": "Test",
"kits": "cypilot",
"artifacts": [
{"path": "architecture/DESIGN.md", "kind": "DESIGN"},
{"path": "architecture/PRD.md", "kind": "PRD"},
],
}],
)
cwd = os.getcwd()
try:
os.chdir(str(root))
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["validate", "--verbose"])
self.assertIn(exit_code, [0, 2])
out = json.loads(stdout.getvalue())
errors = out.get("errors", []) or []
# Legacy check should not run when constraints exist
self.assertFalse(any(e.get("message") == "ID not referenced from other artifact kinds" for e in errors))
finally:
os.chdir(cwd)
class TestCLICommandsRulesOnlyKit(unittest.TestCase):
def test_rules_only_kit_markerless_commands_work(self):
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
# Create kit structure with constraints.toml but no template.md (rules-only kit)
kit_root = root / "kits" / "cypilot-sdlc"
(kit_root / "artifacts" / "PRD").mkdir(parents=True)
from _test_helpers import write_constraints_toml
write_constraints_toml(kit_root, {"PRD": {"identifiers": {"fr": {"required": False}}}})
# Create an artifact that includes an ID line; include markers to emulate real artifacts.
(root / "modules" / "a" / "docs").mkdir(parents=True)
(root / "modules" / "a" / "docs" / "PRD.md").write_text(
"# PRD\n\n**ID**: `cpt-root-a-fr-test`\n",
encoding="utf-8",
)
_bootstrap_registry_new_format(
root,
kits={"cypilot-sdlc": {"format": "Cypilot", "path": "kits/cypilot-sdlc"}},
systems=[
{
"name": "root",
"slug": "root",
"kit": "cypilot-sdlc",
"autodetect": [
{
"system_root": "{project_root}/modules/$system",
"artifacts_root": "{system_root}/docs",
"artifacts": {"PRD": {"pattern": "PRD.md", "traceability": "FULL"}},
"validation": {"require_kind_registered_in_kit": True},
}
],
}
],
)
cwd = os.getcwd()
try:
os.chdir(str(root))
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["list-ids"])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertGreaterEqual(int(out.get("count", 0)), 1)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["list-id-kinds"])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertIn("kinds", out)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["where-defined", "--id", "cpt-root-a-fr-test"])
self.assertIn(exit_code, [0, 2])
finally:
os.chdir(cwd)
class TestCLIInitCommand(unittest.TestCase):
def test_init_creates_config_and_adapter_and_allows_agents(self):
with TemporaryDirectory() as tmpdir:
project = Path(tmpdir) / "project"
project.mkdir()
cypilot_core = project / "Cypilot"
cypilot_core.mkdir()
(cypilot_core / "AGENTS.md").write_text("# Cypilot Core\n", encoding="utf-8")
core_dir = cypilot_core / ".core"
core_dir.mkdir()
(core_dir / "requirements").mkdir()
(core_dir / "workflows").mkdir()
(core_dir / "skills" / "cypilot").mkdir(parents=True)
(core_dir / "skills" / "cypilot" / "SKILL.md").write_text(
"---\nname: cypilot\ndescription: Cypilot skill\n---\n# Cypilot\n",
encoding="utf-8",
)
fake_cache = Path(tmpdir) / "cache"
fake_cache.mkdir()
# Create minimal kit source for the mock
fake_kit = Path(tmpdir) / "dl" / "sdlc"
fake_kit.mkdir(parents=True)
stdout = io.StringIO()
with (
patch("cypilot.commands.init.CACHE_DIR", fake_cache),
patch(
"cypilot.commands.kit._download_kit_from_github",
return_value=(fake_kit, "1.0.0"),
),
):
with redirect_stdout(stdout):
exit_code = main([
"init",
"--project-root",
str(project),
"--yes",
])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertEqual(out.get("status"), "PASS")
# Init now creates root AGENTS.md and cypilot/ directory with config/
self.assertTrue((project / "AGENTS.md").exists())
cypilot_dir_path = Path(out.get("cypilot_dir", ""))
self.assertTrue(cypilot_dir_path.is_dir())
self.assertTrue((cypilot_dir_path / "config" / "AGENTS.md").exists())
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main([
"generate-agents",
"--agent",
"windsurf",
"--root",
str(project),
"--cypilot-root",
str(cypilot_core),
"--dry-run",
])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertEqual(out.get("status"), "PASS")
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main([
"generate-agents",
"--openai",
"--root",
str(project),
"--cypilot-root",
str(cypilot_core),
"--dry-run",
])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertEqual(out.get("status"), "PASS")
def test_init_interactive_defaults(self):
with TemporaryDirectory() as tmpdir:
project = Path(tmpdir) / "project"
project.mkdir()
cypilot_core = project / "Cypilot"
cypilot_core.mkdir()
(cypilot_core / "AGENTS.md").write_text("# Cypilot Core\n", encoding="utf-8")
(cypilot_core / "requirements").mkdir()
(cypilot_core / "workflows").mkdir()
fake_cache = Path(tmpdir) / "cache"
fake_cache.mkdir()
orig_cwd = os.getcwd()
try:
os.chdir(project.as_posix())
with patch("cypilot.commands.init.CACHE_DIR", fake_cache), \
unittest.mock.patch("builtins.input", side_effect=["", ""]):
stdout = io.StringIO()
with redirect_stdout(stdout), redirect_stderr(io.StringIO()):
exit_code = main(["init"])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertEqual(out.get("status"), "PASS")
self.assertTrue((project / "AGENTS.md").exists())
cypilot_dir_path = Path(out.get("cypilot_dir", ""))
self.assertTrue(cypilot_dir_path.is_dir())
finally:
os.chdir(orig_cwd)
class TestCLIAgentsCommand(unittest.TestCase):
"""Test agents command for workflow and skill proxy generation."""
def _write_minimal_cypilot_skill(self, root: Path) -> None:
(root / "skills" / "cypilot").mkdir(parents=True, exist_ok=True)
(root / "skills" / "cypilot" / "SKILL.md").write_text(
"---\nname: cypilot\ndescription: Cypilot skill for testing\n---\n# Cypilot\n",
encoding="utf-8",
)
def _write_workflows_with_frontmatter(self, root: Path) -> None:
(root / "workflows").mkdir(parents=True, exist_ok=True)
(root / "workflows" / "generate.md").write_text(
"---\ncypilot: true\ntype: workflow\nname: cypilot-generate\ndescription: Generate Cypilot artifacts\n---\n# Generate\n",
encoding="utf-8",
)
(root / "workflows" / "analyze.md").write_text(
"---\ncypilot: true\ntype: workflow\nname: cypilot-analyze\ndescription: Analyze Cypilot artifacts\n---\n# Analyze\n",
encoding="utf-8",
)
def test_agents_empty_agent_raises(self):
"""Test that empty agent argument raises SystemExit."""
with self.assertRaises(SystemExit):
main(["generate-agents", "--agent", " "])
def test_agents_project_root_not_found(self):
"""Test agents command when no project root found."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
stdout = io.StringIO()
with redirect_stdout(stdout):
code = main(["generate-agents", "--agent", "windsurf", "--root", str(root)])
self.assertEqual(code, 1)
out = json.loads(stdout.getvalue())
self.assertEqual(out.get("status"), "NOT_FOUND")
def test_agents_windsurf_creates_files(self):
"""Test agents command creates workflow and skill files for windsurf."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root)])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertEqual(out.get("status"), "PASS")
agent_r = out.get("results", {}).get("windsurf", out)
self.assertGreater(agent_r.get("workflows", {}).get("counts", {}).get("created", 0), 0)
# Ensure description is always double-quoted in generated skill frontmatter
skill_file = root / ".agents" / "skills" / "cypilot" / "SKILL.md"
self.assertTrue(skill_file.exists())
content = skill_file.read_text(encoding="utf-8")
self.assertRegex(content, r"(?m)^description:\s+\".*\"\s*$", msg="description not quoted in .agents skill output")
def test_agents_claude_skill_description_is_quoted(self):
"""Test claude skill files render description in quoted YAML frontmatter."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
legacy_commands = root / ".claude" / "commands"
legacy_commands.mkdir(parents=True)
(legacy_commands / "cypilot-plan.md").write_text(
"# /cypilot-plan\n\nALWAYS open and follow `{cypilot_path}/.core/workflows/plan.md`\n",
encoding="utf-8",
)
(legacy_commands / "cypilot-workspace.md").write_text(
"# /cypilot-workspace\n\nALWAYS open and follow `{cypilot_path}/.core/workflows/workspace.md`\n",
encoding="utf-8",
)
(legacy_commands / "cypilot-generate.md").write_text(
"# /cypilot-generate\n\nALWAYS open and follow `{cypilot_path}/.core/workflows/generate.md`\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["generate-agents", "--agent", "claude", "--root", str(root), "--cypilot-root", str(root)])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
# One of the generated skill files should contain quoted description
skill = root / ".claude" / "skills" / "cypilot-generate" / "SKILL.md"
self.assertTrue(skill.exists())
txt = skill.read_text(encoding="utf-8")
self.assertRegex(txt, r"(?m)^description:\s+\".*\"\s*$", msg="description not quoted in claude skill file")
plan_skill = root / ".claude" / "skills" / "cypilot-plan" / "SKILL.md"
self.assertTrue(plan_skill.exists())
self.assertRegex(
plan_skill.read_text(encoding="utf-8"),
r"(?m)^description:\s+\".*\"\s*$",
msg="description not quoted in claude plan skill file",
)
workspace_skill = root / ".claude" / "skills" / "cypilot-workspace" / "SKILL.md"
self.assertTrue(workspace_skill.exists())
self.assertRegex(
workspace_skill.read_text(encoding="utf-8"),
r"(?m)^description:\s+\".*\"\s*$",
msg="description not quoted in claude workspace skill file",
)
agent_r = out.get("results", {}).get("claude", out)
deleted = set(agent_r.get("skills", {}).get("deleted", []))
self.assertIn(".claude/commands/cypilot-plan.md", deleted)
self.assertIn(".claude/commands/cypilot-workspace.md", deleted)
self.assertIn(".claude/commands/cypilot-generate.md", deleted)
self.assertFalse((legacy_commands / "cypilot-plan.md").exists())
self.assertFalse((legacy_commands / "cypilot-workspace.md").exists())
self.assertFalse((legacy_commands / "cypilot-generate.md").exists())
def test_agents_dry_run_does_not_write_files(self):
"""Test agents command dry-run mode."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root), "--dry-run"])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
self.assertTrue(out.get("dry_run"))
agent_r = out.get("results", {}).get("windsurf", out)
created = agent_r.get("workflows", {}).get("created", [])
self.assertTrue(all(not Path(p).exists() for p in created))
def test_agents_unknown_agent_uses_builtin_defaults(self):
"""Test agents command with unknown agent uses built-in defaults without creating config file."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["generate-agents", "--agent", "mystery-agent", "--root", str(root), "--cypilot-root", str(root)])
self.assertEqual(exit_code, 0)
# No cypilot-agents.json should be created
cfg_path = root / "cypilot-agents.json"
self.assertFalse(cfg_path.exists())
out = json.loads(stdout.getvalue())
self.assertIsNone(out.get("config_path"))
def test_agents_config_error_invalid_agents(self):
"""Test agents command with invalid agents config."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
cfg_path = root / "bad-config.json"
cfg_path.write_text(
json.dumps({"version": 1, "agents": "bad"}, indent=2) + "\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
code = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--config", str(cfg_path)])
self.assertEqual(code, 1)
out = json.loads(stdout.getvalue())
# Outer status is PARTIAL; per-agent result carries CONFIG_ERROR
self.assertEqual(out.get("status"), "PARTIAL")
self.assertEqual(out["results"]["windsurf"]["status"], "CONFIG_ERROR")
def test_agents_missing_workflow_dir_error(self):
"""Test agents command with missing workflow_dir in config."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
cfg_path = root / "agents-config.json"
cfg_path.write_text(
json.dumps({
"version": 1,
"agents": {
"windsurf": {
"workflows": {"template": ["# test"]},
"skills": {}
}
}
}, indent=2) + "\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
ret = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root), "--config", str(cfg_path)])
# Should return partial status due to workflow error
out = json.loads(stdout.getvalue())
agent_result = out.get("results", {}).get("windsurf", {})
self.assertIn("Missing workflow_dir", str(agent_result.get("errors", [])))
self.assertNotEqual(ret, 0, "should return non-zero on workflow_dir error")
def test_agents_missing_template_error(self):
"""Test agents command with missing template in config."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
cfg_path = root / "agents-config.json"
cfg_path.write_text(
json.dumps({
"version": 1,
"agents": {
"windsurf": {
"workflows": {
"workflow_dir": ".windsurf/workflows",
"template": "not a list"
},
"skills": {}
}
}
}, indent=2) + "\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
ret = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root), "--config", str(cfg_path)])
out = json.loads(stdout.getvalue())
agent_result = out.get("results", {}).get("windsurf", {})
self.assertIn("Missing or invalid template", str(agent_result.get("errors", [])))
self.assertNotEqual(ret, 0, "should return non-zero on template error")
def test_agents_skills_invalid_outputs_error(self):
"""Test agents command with invalid skills outputs config."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
cfg_path = root / "agents-config.json"
cfg_path.write_text(
json.dumps({
"version": 1,
"agents": {
"windsurf": {
"workflows": {},
"skills": {"outputs": "not a list"}
}
}
}, indent=2) + "\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
ret = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root), "--config", str(cfg_path)])
out = json.loads(stdout.getvalue())
agent_result = out.get("results", {}).get("windsurf", {})
self.assertIn("outputs must be an array", str(agent_result.get("errors", [])))
self.assertNotEqual(ret, 0, "should return non-zero on invalid outputs")
def test_agents_skills_missing_path_error(self):
"""Test agents command with missing path in skills output."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
cfg_path = root / "agents-config.json"
cfg_path.write_text(
json.dumps({
"version": 1,
"agents": {
"windsurf": {
"workflows": {},
"skills": {
"outputs": [{"template": ["# test"]}]
}
}
}
}, indent=2) + "\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
ret = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root), "--config", str(cfg_path)])
out = json.loads(stdout.getvalue())
agent_result = out.get("results", {}).get("windsurf", {})
self.assertIn("missing path", str(agent_result.get("errors", [])))
self.assertNotEqual(ret, 0, "should return non-zero on missing path")
def test_agents_skills_missing_template_error(self):
"""Test agents command with missing template in skills output."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
cfg_path = root / "agents-config.json"
cfg_path.write_text(
json.dumps({
"version": 1,
"agents": {
"windsurf": {
"workflows": {},
"skills": {
"outputs": [{"path": ".windsurf/test.md", "template": "not a list"}]
}
}
}
}, indent=2) + "\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
ret = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root), "--config", str(cfg_path)])
out = json.loads(stdout.getvalue())
agent_result = out.get("results", {}).get("windsurf", {})
self.assertIn("invalid template", str(agent_result.get("errors", [])))
self.assertNotEqual(ret, 0, "should return non-zero on invalid template")
def test_agents_updates_existing_files(self):
"""Test agents command updates existing proxy files."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
# First run - create files
stdout = io.StringIO()
with redirect_stdout(stdout):
main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root)])
# Modify a file to trigger update
wf_dir = root / ".windsurf" / "workflows"
if wf_dir.is_dir():
for f in wf_dir.glob("*.md"):
f.write_text("# Modified\n", encoding="utf-8")
break
# Second run - should update
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root)])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
# Should have some updated files
agent_r = out.get("results", {}).get("windsurf", out)
updated = agent_r.get("workflows", {}).get("counts", {}).get("updated", 0)
self.assertGreaterEqual(updated, 0)
def test_agents_recognized_agent_added_to_existing_config(self):
"""Test that a recognized agent is added to existing config passed via --config."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
# Create config with only cursor
cfg_path = root / "agents-config.json"
cfg_path.write_text(
json.dumps({
"version": 1,
"agents": {
"cursor": {"workflows": {}, "skills": {}}
}
}, indent=2) + "\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
code = main(["generate-agents", "--agent", "windsurf", "--root", str(root), "--cypilot-root", str(root), "--config", str(cfg_path)])
self.assertEqual(code, 0)
out = json.loads(stdout.getvalue())
# windsurf should use built-in defaults even when config has only cursor
self.assertEqual(out.get("status"), "PASS")
def test_agents_skills_creates_and_updates_outputs(self):
"""Test agents command creates and updates skill output files."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
cfg_path = root / "agents-config.json"
cfg_path.write_text(
json.dumps({
"version": 1,
"agents": {
"test": {
"workflows": {},
"skills": {
"outputs": [{
"path": ".test/skill.md",
"template": [
"---",
"name: {name}",
"description: {description}",
"---",
"# {name}",
"",
"ALWAYS open and follow `{target_skill_path}`",
]
}]
}
}
}
}, indent=2) + "\n",
encoding="utf-8",
)
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["generate-agents", "--agent", "test", "--root", str(root), "--cypilot-root", str(root), "--config", str(cfg_path)])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
agent_result = out.get("results", {}).get("test", out)
self.assertGreater(len(agent_result.get("skills", {}).get("created", [])), 0)
# Verify file was created
skill_file = root / ".test" / "skill.md"
self.assertTrue(skill_file.exists())
content = skill_file.read_text(encoding="utf-8")
self.assertIn("# cypilot", content)
self.assertRegex(content, r"(?m)^description:\s+\".*\"\s*$", msg="description not quoted in skill output")
# Modify file and run again to test update
skill_file.write_text("# Modified\n", encoding="utf-8")
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["generate-agents", "--agent", "test", "--root", str(root), "--cypilot-root", str(root), "--config", str(cfg_path)])
self.assertEqual(exit_code, 0)
out = json.loads(stdout.getvalue())
agent_result = out.get("results", {}).get("test", out)
self.assertGreater(len(agent_result.get("skills", {}).get("updated", [])), 0)
def test_openai_agent_generates_individual_skill_files(self):
"""Issue #125: openai (codex) agent should generate per-workflow skill files."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
out = self._generate_agent(root, "openai")
openai_result = out.get("results", {}).get("openai", {})
self.assertEqual(openai_result.get("status"), "PASS")
expected_skills = [
root / ".agents" / "skills" / "cypilot" / "SKILL.md",
root / ".agents" / "skills" / "cypilot-generate" / "SKILL.md",
root / ".agents" / "skills" / "cypilot-analyze" / "SKILL.md",
root / ".agents" / "skills" / "cypilot-plan" / "SKILL.md",
root / ".agents" / "skills" / "cypilot-workspace" / "SKILL.md",
]
for skill_file in expected_skills:
self.assertTrue(
skill_file.exists(),
f"Expected skill file not generated: {skill_file.relative_to(root)}",
)
def test_openai_agent_skill_frontmatter_matches_codex_schema(self):
"""Issue #125: generated skill files must use Codex-compatible frontmatter."""
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()
self._write_minimal_cypilot_skill(root)
self._write_workflows_with_frontmatter(root)
self._generate_agent(root, "openai")
from cypilot.commands.agents import _parse_frontmatter
for skill_name in ("cypilot", "cypilot-generate", "cypilot-analyze", "cypilot-plan", "cypilot-workspace"):
skill_file = root / ".agents" / "skills" / skill_name / "SKILL.md"
fm = _parse_frontmatter(skill_file)
self.assertTrue(fm.get("name", "").strip(),
f"{skill_name}/SKILL.md must have a non-empty 'name'")
self.assertTrue(fm.get("description", "").strip(),
f"{skill_name}/SKILL.md must have a non-empty 'description'")
def _generate_agent(self, root: Path, agent: str) -> dict:
stdout = io.StringIO()
with redirect_stdout(stdout):
exit_code = main(["generate-agents", "--agent", agent,
"--root", str(root), "--cypilot-root", str(root)])
self.assertEqual(exit_code, 0, f"generate-agents --agent {agent} failed")
return json.loads(stdout.getvalue())
class TestCLIParseFrontmatter(unittest.TestCase):
"""Test _parse_frontmatter function."""
def test_parse_frontmatter_valid(self):
"""Test parsing valid frontmatter."""
from cypilot.commands.agents import _parse_frontmatter
with TemporaryDirectory() as tmpdir:
f = Path(tmpdir) / "test.md"
f.write_text("---\nname: test\ndescription: A test file\n---\n# Content\n", encoding="utf-8")
result = _parse_frontmatter(f)
self.assertEqual(result.get("name"), "test")
self.assertEqual(result.get("description"), "A test file")
def test_parse_frontmatter_strips_quotes(self):
"""Test parsing frontmatter unquotes quoted scalars."""
from cypilot.commands.agents import _parse_frontmatter
with TemporaryDirectory() as tmpdir:
f = Path(tmpdir) / "test.md"
f.write_text('---\nname: "test"\ndescription: "A test file"\n---\n# Content\n', encoding="utf-8")
result = _parse_frontmatter(f)
self.assertEqual(result.get("name"), "test")
self.assertEqual(result.get("description"), "A test file")
def test_parse_frontmatter_no_frontmatter(self):
"""Test parsing file without frontmatter."""
from cypilot.commands.agents import _parse_frontmatter
with TemporaryDirectory() as tmpdir:
f = Path(tmpdir) / "test.md"
f.write_text("# Just content\n", encoding="utf-8")
result = _parse_frontmatter(f)
self.assertEqual(result, {})
def test_parse_frontmatter_unclosed(self):
"""Test parsing file with unclosed frontmatter."""
from cypilot.commands.agents import _parse_frontmatter
with TemporaryDirectory() as tmpdir:
f = Path(tmpdir) / "test.md"
f.write_text("---\nname: test\n# No closing\n", encoding="utf-8")
result = _parse_frontmatter(f)
self.assertEqual(result, {})
def test_parse_frontmatter_file_not_found(self):
"""Test parsing non-existent file."""
from cypilot.commands.agents import _parse_frontmatter
result = _parse_frontmatter(Path("/tmp/does-not-exist-abc123.md"))
self.assertEqual(result, {})
def test_parse_frontmatter_empty_values_skipped(self):
"""Test that empty values are skipped."""
from cypilot.commands.agents import _parse_frontmatter
with TemporaryDirectory() as tmpdir:
f = Path(tmpdir) / "test.md"
f.write_text("---\nname: test\nempty:\n---\n# Content\n", encoding="utf-8")
result = _parse_frontmatter(f)
self.assertEqual(result.get("name"), "test")
self.assertNotIn("empty", result)
class TestCLIAgentsEdgeCases(unittest.TestCase):
"""Test agents command edge cases for better coverage."""
def _write_minimal_cypilot_skill(self, root: Path) -> None:
(root / "skills" / "cypilot").mkdir(parents=True, exist_ok=True)
(root / "skills" / "cypilot" / "SKILL.md").write_text(
"---\nname: cypilot\ndescription: Cypilot skill\n---\n# Cypilot\n",
encoding="utf-8",
)
def _write_workflows_with_frontmatter(self, root: Path) -> None:
(root / "workflows").mkdir(parents=True, exist_ok=True)
(root / "workflows" / "generate.md").write_text(
"---\ncypilot: true\ntype: workflow\nname: cypilot-generate\ndescription: Generate\n---\n# Generate\n",
encoding="utf-8",
)
def test_agents_renames_misnamed_proxy(self):
"""Test agents command renames misnamed proxy files."""
from cypilot.commands.agents import _safe_relpath
with TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
(root / ".git").mkdir()