forked from hyphen-2025/cyber-pilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_workspace.py
More file actions
3715 lines (3005 loc) · 143 KB
/
test_workspace.py
File metadata and controls
3715 lines (3005 loc) · 143 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 multi-repo workspace support.
Tests cover:
- WorkspaceConfig loading and validation
- SourceEntry parsing
- find_workspace_config() discovery
- WorkspaceConfig.save() / add_source() mutations
- WorkspaceContext loading
- is_workspace() helper
- Source path resolution
- Cross-repo ID aggregation
"""
import argparse
import json
import pytest
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import MagicMock, patch
sys.path.insert(0, str(Path(__file__).parent.parent / "skills" / "cypilot" / "scripts"))
from cypilot.utils import toml_utils
from cypilot.utils.workspace import (
SourceEntry,
TraceabilityConfig,
NamespaceRule,
ResolveConfig,
ValidationConfig,
WorkspaceConfig,
find_workspace_config,
validate_source_name,
VALID_ROLES,
)
from cypilot.utils.context import (
CypilotContext,
WorkspaceContext,
SourceContext,
resolve_adapter_context,
get_expanded_meta,
determine_target_source,
set_context,
get_context,
is_workspace,
get_primary_context,
_load_reachable_source,
)
from cypilot.utils.artifacts_meta import ArtifactsMeta, Kit
from cypilot.utils.git_utils import (
is_worktree_dirty,
_parse_git_url,
_apply_template,
_lookup_namespace,
_redact_url,
_run_git,
resolve_git_source,
sync_git_source,
)
from cypilot.commands.workspace_init import (
_is_project_dir,
_find_adapter_path,
_compute_source_path,
_infer_role,
_sanitize_source_name,
_scan_nested_repos,
_write_standalone,
_write_inline,
_check_existing_workspace,
_human_workspace_init,
cmd_workspace_init,
)
from cypilot.commands.workspace_info import (
_probe_source_adapter,
_build_source_info,
_enrich_with_artifact_counts,
_human_workspace_info,
cmd_workspace_info,
)
from cypilot.commands.workspace_add import (
_add_to_standalone,
_add_to_inline,
_human_workspace_add,
cmd_workspace_add,
)
from cypilot.commands.workspace_sync import (
_human_workspace_sync,
cmd_workspace_sync,
)
# ---------------------------------------------------------------------------
# Shared test helpers
# ---------------------------------------------------------------------------
def _make_mock_meta(project_root: str = "..") -> MagicMock:
"""Create a standard ArtifactsMeta mock for tests."""
meta = MagicMock(spec=ArtifactsMeta)
meta.project_root = project_root
meta.kits = {}
meta.systems = []
meta.get_all_system_prefixes.return_value = set()
meta.iter_all_artifacts.return_value = []
return meta
def _make_mock_ctx(tmpdir: Path, *, project_root_meta: str = "..") -> CypilotContext:
"""Create a standard CypilotContext with mock meta."""
return CypilotContext(
adapter_dir=tmpdir / "adapter",
project_root=tmpdir,
meta=_make_mock_meta(project_root_meta),
kits={},
registered_systems=set(),
)
def _setup_config_dir(root: Path, content: str = "") -> Path:
"""Create cypilot/config/core.toml scaffold, return config_dir."""
config_dir = root / "cypilot" / "config"
config_dir.mkdir(parents=True, exist_ok=True)
(config_dir / "core.toml").write_text(content)
return config_dir
def _clone_side_effect(args, cwd=None):
"""Simulate successful git clone by creating directory + .git."""
if args[0] == "clone":
clone_path = Path(args[-1])
clone_path.mkdir(parents=True, exist_ok=True)
(clone_path / ".git").mkdir()
return (0, "", "")
def _parse_json(capsys) -> dict:
"""Parse JSON from captured stdout."""
return json.loads(capsys.readouterr().out)
def _make_inline_args(name: str = "x", path: str = "../x", role: str = "full",
adapter=None, force: bool = False, **kwargs) -> argparse.Namespace:
"""Create argparse.Namespace for _add_to_inline tests."""
return argparse.Namespace(name=name, path=path, role=role, adapter=adapter, force=force, **kwargs)
def _make_ws_cfg(tmpdir, sources_dict=None):
"""Create a WorkspaceConfig with sources and workspace_file set."""
if sources_dict is None:
sources_dict = {"docs": SourceEntry(name="docs", path=str(tmpdir / "repo"), role="artifacts")}
return WorkspaceConfig(
sources=sources_dict,
workspace_file=Path(tmpdir) / ".cypilot-workspace.toml",
)
def _make_standalone_ws_mock(tmpdir):
"""Create a MagicMock representing a standalone workspace config."""
ws = MagicMock()
ws.is_inline = False
ws.workspace_file = Path(tmpdir) / ".cypilot-workspace.toml"
ws.save.return_value = None
return ws
def _make_git_source(url="https://gitlab.com/team/lib.git", branch="main"):
"""Create a SourceEntry for git source tests."""
return SourceEntry(name="r", path="", url=url, branch=branch)
def _make_gitlab_resolve_cfg(workdir=".ws"):
"""Create a ResolveConfig with gitlab.com namespace rule."""
return ResolveConfig(
workdir=workdir,
namespace=[NamespaceRule(host="gitlab.com", template="{org}/{repo}")],
)
def _run_workspace_info(capsys, ws_cfg, tmpdir, *, ctx_return=None):
"""Run cmd_workspace_info with mocked project root, config, adapter, and context."""
with patch("cypilot.utils.files.find_project_root", return_value=Path(tmpdir)):
with patch("cypilot.utils.workspace.find_workspace_config", return_value=(ws_cfg, None)):
with patch("cypilot.commands.workspace_info._probe_source_adapter", return_value=None):
with patch("cypilot.utils.context.get_context", return_value=ctx_return):
rc = cmd_workspace_info([])
data = json.loads(capsys.readouterr().out)
return rc, data
def _make_docs_ws_cfg(tmpdir, src_dir):
"""Create a WorkspaceConfig with a single 'docs' source."""
return WorkspaceConfig(
sources={"docs": SourceEntry(name="docs", path=str(src_dir), role="artifacts")},
workspace_file=Path(tmpdir) / ".cypilot-workspace.toml",
)
def _setup_repo_with_adapter(root: Path, name: str = "sub-repo") -> Path:
"""Create a sub-repo directory with .git and cypilot adapter."""
repo = root / name
repo.mkdir()
(repo / ".git").mkdir()
adapter = repo / "cypilot"
adapter.mkdir()
(adapter / "config").mkdir()
return repo
class TestValidateSourceName:
"""Tests for validate_source_name()."""
def test_valid_simple(self):
assert validate_source_name("my-repo") is None
def test_valid_with_dots_and_underscores(self):
assert validate_source_name("my.repo_v2") is None
def test_valid_numeric_start(self):
assert validate_source_name("2fast") is None
def test_empty_name(self):
assert validate_source_name("") is not None
def test_path_separator(self):
assert validate_source_name("foo/bar") is not None
def test_backslash(self):
assert validate_source_name("foo\\bar") is not None
def test_double_dot(self):
assert validate_source_name("foo..bar") is not None
def test_leading_dot(self):
assert validate_source_name(".hidden") is not None
def test_leading_hyphen(self):
assert validate_source_name("-bad") is not None
def test_space_in_name(self):
assert validate_source_name("my repo") is not None
def test_special_chars(self):
assert validate_source_name("repo@v1") is not None
assert validate_source_name("repo[0]") is not None
class TestSanitizeSourceName:
"""Tests for _sanitize_source_name()."""
def test_clean_name_unchanged(self):
assert _sanitize_source_name("my-repo") == "my-repo"
def test_spaces_replaced(self):
assert _sanitize_source_name("my repo") == "my-repo"
def test_slashes_replaced(self):
assert _sanitize_source_name("org/repo") == "org-repo"
def test_leading_special_stripped(self):
assert _sanitize_source_name(".hidden") == "hidden"
def test_consecutive_hyphens_collapsed(self):
assert _sanitize_source_name("a@#b") == "a-b"
def test_empty_fallback(self):
assert _sanitize_source_name("@#$") == "source"
class TestSourceEntry:
"""Tests for SourceEntry dataclass."""
def test_from_dict_basic(self):
entry = SourceEntry.from_dict("docs", {"path": "../docs-repo", "role": "artifacts"})
assert entry.name == "docs"
assert entry.path == "../docs-repo"
assert entry.role == "artifacts"
assert entry.adapter is None
def test_from_dict_with_adapter(self):
entry = SourceEntry.from_dict("code", {
"path": "../code-repo",
"adapter": ".cypilot-adapter",
"role": "codebase",
})
assert entry.adapter == ".cypilot-adapter"
assert entry.role == "codebase"
def test_from_dict_null_adapter(self):
entry = SourceEntry.from_dict("kits", {"path": "../kits", "adapter": None})
assert entry.adapter is None
def test_from_dict_invalid_role_raises(self):
with pytest.raises(ValueError, match="invalid role"):
SourceEntry.from_dict("x", {"path": "../x", "role": "invalid"})
def test_constructor_invalid_role_raises(self):
with pytest.raises(ValueError, match="invalid role"):
SourceEntry(name="x", path="../x", role="invalid")
def test_from_dict_missing_role_defaults_full(self):
entry = SourceEntry.from_dict("x", {"path": "../x"})
assert entry.role == "full"
def test_to_dict_minimal(self):
entry = SourceEntry(name="x", path="../x")
d = entry.to_dict()
assert d == {"path": "../x"}
def test_to_dict_with_adapter_and_role(self):
entry = SourceEntry(name="x", path="../x", adapter=".adapter", role="kits")
d = entry.to_dict()
assert d == {"path": "../x", "adapter": ".adapter", "role": "kits"}
def test_post_init_normalizes_empty_path_to_none(self):
"""Direct SourceEntry(path='') should normalize to None, matching from_dict behavior."""
entry = SourceEntry(name="x", path="")
assert entry.path is None
def test_post_init_normalizes_whitespace_path_to_none(self):
entry = SourceEntry(name="x", path=" ")
assert entry.path is None
def test_post_init_normalizes_empty_url_to_none(self):
entry = SourceEntry(name="x", path="../x", url="")
assert entry.url is None
def test_post_init_normalizes_empty_branch_to_none(self):
entry = SourceEntry(name="x", url="https://example.com/repo.git", branch="")
assert entry.branch is None
def test_post_init_strips_path_whitespace(self):
entry = SourceEntry(name="x", path=" ../x ")
assert entry.path == "../x"
def test_post_init_preserves_valid_values(self):
entry = SourceEntry(name="x", path="../x", url="https://example.com/repo.git", branch="main")
assert entry.path == "../x"
assert entry.url == "https://example.com/repo.git"
assert entry.branch == "main"
class TestWorkspaceConfig:
"""Tests for WorkspaceConfig."""
def test_from_dict_basic(self):
data = {
"version": "1.0",
"sources": {
"docs": {"path": "../docs", "role": "artifacts"},
"code": {"path": "../code"},
},
}
cfg = WorkspaceConfig.from_dict(data)
assert cfg.version == "1.0"
assert len(cfg.sources) == 2
assert "docs" in cfg.sources
assert cfg.sources["docs"].role == "artifacts"
assert cfg.sources["code"].role == "full"
def test_from_dict_with_traceability(self):
data = {
"version": "1.0",
"sources": {"a": {"path": "."}},
"traceability": {"cross_repo": False, "resolve_remote_ids": False},
}
cfg = WorkspaceConfig.from_dict(data)
assert cfg.traceability.cross_repo is False
assert cfg.traceability.resolve_remote_ids is False
def test_from_dict_empty_sources(self):
cfg = WorkspaceConfig.from_dict({"version": "1.0", "sources": {}})
assert len(cfg.sources) == 0
def test_from_dict_sources_not_mapping_raises(self):
with pytest.raises(ValueError, match="'sources' must be a mapping"):
WorkspaceConfig.from_dict({"version": "1.0", "sources": 42})
def test_from_dict_source_entry_not_table_raises(self):
with pytest.raises(ValueError, match="Source 'bad' must be a table, got str"):
WorkspaceConfig.from_dict({
"version": "1.0",
"sources": {"bad": "not-a-table"},
})
def test_to_dict_roundtrip(self):
original = {
"version": "1.0",
"sources": {
"docs": {"path": "../docs", "role": "artifacts"},
},
}
cfg = WorkspaceConfig.from_dict(original)
result = cfg.to_dict()
assert result["version"] == "1.0"
assert "docs" in result["sources"]
assert result["sources"]["docs"]["role"] == "artifacts"
def test_validate_empty_sources_ok(self):
"""Empty workspace is valid — sources can be added later via workspace-add."""
cfg = WorkspaceConfig(sources={})
errors = cfg.validate()
assert errors == []
def test_validate_empty_path(self):
cfg = WorkspaceConfig(sources={"x": SourceEntry(name="x", path="")})
errors = cfg.validate()
assert any("must have either" in e.lower() for e in errors)
def test_validate_path_with_branch_rejected(self):
"""path + branch is forbidden — branch only valid with url (schema oneOf)."""
cfg = WorkspaceConfig(sources={"x": SourceEntry(name="x", path="../foo", branch="main")})
errors = cfg.validate()
assert any("path" in e and "branch" in e for e in errors)
def test_validate_url_with_branch_ok(self):
"""url + branch is allowed by schema."""
cfg = WorkspaceConfig(sources={"x": SourceEntry(name="x", url="https://example.com/repo.git", branch="main")})
errors = cfg.validate()
assert not any("branch" in e for e in errors)
def test_add_source(self):
cfg = WorkspaceConfig()
cfg.add_source("new-repo", "../new-repo", role="codebase", adapter=".adapter")
assert "new-repo" in cfg.sources
assert cfg.sources["new-repo"].path == "../new-repo"
assert cfg.sources["new-repo"].role == "codebase"
def test_load_valid_file(self):
with TemporaryDirectory() as tmpdir:
ws_path = Path(tmpdir) / ".cypilot-workspace.toml"
toml_utils.dump({
"version": "1.0",
"sources": {"test": {"path": "."}},
}, ws_path)
cfg, err = WorkspaceConfig.load(ws_path)
assert err is None
assert cfg is not None
assert cfg.version == "1.0"
assert "test" in cfg.sources
def test_load_missing_file(self):
cfg, err = WorkspaceConfig.load(Path("/nonexistent/.cypilot-workspace.toml"))
assert cfg is None
assert "not found" in err.lower()
def test_load_invalid_toml(self):
with TemporaryDirectory() as tmpdir:
ws_path = Path(tmpdir) / ".cypilot-workspace.toml"
ws_path.write_text("[invalid\nbroken toml =", encoding="utf-8")
cfg, err = WorkspaceConfig.load(ws_path)
assert cfg is None
assert err is not None
def test_load_invalid_role_returns_error(self):
"""load() catches ValueError from invalid role in source."""
with TemporaryDirectory() as tmpdir:
ws_path = Path(tmpdir) / ".cypilot-workspace.toml"
toml_utils.dump({
"version": "1.0",
"sources": {"bad": {"path": "../bad", "role": "bogus"}},
}, ws_path)
cfg, err = WorkspaceConfig.load(ws_path)
assert cfg is None
assert "invalid role" in err.lower()
def test_save_inline_rejects_invalid_existing_config(self):
"""save() for inline workspace returns error when existing file is not a dict."""
with TemporaryDirectory() as tmpdir:
config_path = Path(tmpdir) / "core.toml"
# Write a bare value (not a table) — toml_utils wraps it, but
# we can simulate by writing raw TOML that parses to a non-dict
# via a direct file write.
config_path.write_text('"just a string"', encoding="utf-8")
cfg = WorkspaceConfig(
sources={"x": SourceEntry(name="x", path="../x")},
workspace_file=config_path,
is_inline=True,
)
err = cfg.save()
assert err is not None
def test_save_and_reload(self):
with TemporaryDirectory() as tmpdir:
ws_path = Path(tmpdir) / ".cypilot-workspace.toml"
cfg = WorkspaceConfig(
sources={"docs": SourceEntry(name="docs", path="../docs", role="artifacts")},
workspace_file=ws_path,
)
err = cfg.save()
assert err is None
loaded, load_err = WorkspaceConfig.load(ws_path)
assert load_err is None
assert loaded is not None
assert "docs" in loaded.sources
def test_save_inline_preserves_other_sections(self):
"""Saving an inline workspace must not clobber other core.toml sections."""
with TemporaryDirectory() as tmpdir:
config_path = Path(tmpdir) / "core.toml"
# Seed core.toml with non-workspace sections
toml_utils.dump(
{
"project_root": "..",
"kits": [{"name": "sdlc", "version": "1.0"}],
"ignore": ["node_modules"],
},
config_path,
)
cfg = WorkspaceConfig(
sources={"docs": SourceEntry(name="docs", path="../docs", role="artifacts")},
workspace_file=config_path,
is_inline=True,
)
err = cfg.save()
assert err is None
# Reload full file and verify all sections survived
reloaded = toml_utils.load(config_path)
assert reloaded["project_root"] == ".."
assert reloaded["kits"] == [{"name": "sdlc", "version": "1.0"}]
assert reloaded["ignore"] == ["node_modules"]
# Workspace section is present
assert "workspace" in reloaded
assert "docs" in reloaded["workspace"]["sources"]
def test_resolve_source_path(self):
with TemporaryDirectory() as tmpdir:
ws_file = Path(tmpdir) / ".cypilot-workspace.toml"
cfg = WorkspaceConfig(
sources={"repo": SourceEntry(name="repo", path="sub/repo")},
workspace_file=ws_file,
)
resolved = cfg.resolve_source_path("repo")
assert resolved == (Path(tmpdir) / "sub" / "repo").resolve()
def test_resolve_source_path_unknown(self):
with TemporaryDirectory() as tmpdir:
cfg = WorkspaceConfig(workspace_file=Path(tmpdir) / "ws.toml")
assert cfg.resolve_source_path("nonexistent") is None
def test_resolve_source_adapter_returns_path(self):
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
repo = tmp / "repo"
repo.mkdir()
adapter = repo / ".my-adapter"
adapter.mkdir()
cfg = WorkspaceConfig(
sources={"repo": SourceEntry(name="repo", path="repo", adapter=".my-adapter")},
workspace_file=tmp / "ws.toml",
)
result = cfg.resolve_source_adapter("repo")
assert result == adapter.resolve()
def test_resolve_source_adapter_none_when_no_adapter(self):
with TemporaryDirectory() as tmpdir:
cfg = WorkspaceConfig(
sources={"repo": SourceEntry(name="repo", path="repo")},
workspace_file=Path(tmpdir) / "ws.toml",
)
assert cfg.resolve_source_adapter("repo") is None
def test_resolve_source_adapter_none_for_unknown_source(self):
cfg = WorkspaceConfig()
assert cfg.resolve_source_adapter("nonexistent") is None
class TestFindWorkspaceConfig:
"""Tests for find_workspace_config() discovery."""
def test_no_workspace_returns_none(self):
with TemporaryDirectory() as tmpdir:
cfg, err = find_workspace_config(Path(tmpdir))
assert cfg is None
assert err is None
def _setup_v3_project(self, project_root: Path, core_toml_data: dict) -> None:
"""Helper: create a v3-style project with AGENTS.md + config/core.toml."""
import tomllib # noqa: F401 - just to verify availability
# Create AGENTS.md with root-agents marker and cypilot_path
agents_md = project_root / "AGENTS.md"
agents_md.write_text(
"<!-- @cpt:root-agents -->\n"
"# Project\n\n"
"```toml\n"
'cypilot_path = ".cypilot"\n'
"```\n"
"<!-- @cpt:root-agents -->\n",
encoding="utf-8",
)
# Create config/core.toml
config_dir = project_root / ".cypilot" / "config"
config_dir.mkdir(parents=True, exist_ok=True)
toml_utils.dump(core_toml_data, config_dir / "core.toml")
def test_inline_dict_workspace(self):
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
self._setup_v3_project(tmp, {
"workspace": {
"version": "1.0",
"sources": {"docs": {"path": "../docs"}},
},
})
cfg, err = find_workspace_config(tmp)
assert err is None
assert cfg is not None
assert cfg.is_inline is True
assert "docs" in cfg.sources
def test_inline_workspace_invalid_role_returns_error(self):
"""Inline workspace with invalid role returns error instead of silently defaulting."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
self._setup_v3_project(tmp, {
"workspace": {
"version": "1.0",
"sources": {"bad": {"path": "../bad", "role": "bogus"}},
},
})
cfg, err = find_workspace_config(tmp)
assert cfg is None
assert err is not None
assert "invalid role" in err.lower()
def test_inline_workspace_resolves_relative_to_project_root(self):
"""CR-2: Inline workspace source paths must resolve relative to project root,
not relative to core.toml's parent directory."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
# Create nested docs dir
docs_dir = tmp / "docs"
docs_dir.mkdir()
project_dir = tmp / "code"
project_dir.mkdir()
self._setup_v3_project(project_dir, {
"workspace": {
"version": "1.0",
"sources": {"docs": {"path": "../docs"}},
},
})
cfg, err = find_workspace_config(project_dir)
assert err is None
assert cfg is not None
assert cfg.is_inline is True
# Path should resolve relative to project root (code/), not core.toml parent
resolved = cfg.resolve_source_path("docs")
assert resolved == docs_dir.resolve()
def test_string_ref_workspace(self):
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
# Create the workspace file one level up
ws_path = tmp / "workspace.toml"
toml_utils.dump({
"version": "1.0",
"sources": {"code": {"path": "./code"}},
}, ws_path)
# Create v3 project config referencing external workspace file
project_dir = tmp / "code"
project_dir.mkdir()
self._setup_v3_project(project_dir, {
"workspace": "../workspace.toml",
})
cfg, err = find_workspace_config(project_dir)
assert err is None
assert cfg is not None
assert cfg.is_inline is False
assert "code" in cfg.sources
def test_parse_failure_returns_error(self):
"""Malformed core.toml returns (None, error_message) instead of silent (None, None)."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
agents_md = tmp / "AGENTS.md"
agents_md.write_text(
"<!-- @cpt:root-agents -->\n"
"```toml\n"
'cypilot_path = ".cypilot"\n'
"```\n"
"<!-- @cpt:root-agents -->\n",
encoding="utf-8",
)
config_dir = tmp / ".cypilot" / "config"
config_dir.mkdir(parents=True, exist_ok=True)
(config_dir / "core.toml").write_text("{{invalid toml", encoding="utf-8")
cfg, err = find_workspace_config(tmp)
assert cfg is None
assert err is not None
assert "Failed to parse" in err
def test_standalone_file_discovered_at_project_root(self):
"""Standalone .cypilot-workspace.toml at project root is discovered without core.toml reference."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
ws_path = tmp / ".cypilot-workspace.toml"
toml_utils.dump({
"version": "1.0",
"sources": {"lib": {"path": "../lib"}},
}, ws_path)
cfg, err = find_workspace_config(tmp)
assert err is None
assert cfg is not None
assert cfg.is_inline is False
assert "lib" in cfg.sources
def test_standalone_file_not_discovered_at_parent(self):
"""Standalone .cypilot-workspace.toml one level above project root is NOT discovered (no parent walk-up)."""
with TemporaryDirectory() as tmpdir:
parent = Path(tmpdir)
ws_path = parent / ".cypilot-workspace.toml"
toml_utils.dump({
"version": "1.0",
"sources": {"docs": {"path": "./docs"}},
}, ws_path)
project_dir = parent / "repo-a"
project_dir.mkdir()
cfg, err = find_workspace_config(project_dir)
assert err is None
assert cfg is None
def test_core_toml_workspace_takes_precedence_over_standalone(self):
"""core.toml workspace key takes priority over standalone file on disk."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
# Create standalone file with "stale" source
toml_utils.dump({
"version": "1.0",
"sources": {"stale": {"path": "../stale"}},
}, tmp / ".cypilot-workspace.toml")
# Create core.toml with inline workspace
self._setup_v3_project(tmp, {
"workspace": {
"version": "1.0",
"sources": {"primary": {"path": "../primary"}},
},
})
cfg, err = find_workspace_config(tmp)
assert err is None
assert cfg is not None
assert cfg.is_inline is True
assert "primary" in cfg.sources
assert "stale" not in cfg.sources
def test_malformed_workspace_value_returns_error(self):
"""Non-string, non-dict workspace value returns config error instead of silent fallback."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
self._setup_v3_project(tmp, {"workspace": 42})
cfg, err = find_workspace_config(tmp)
assert cfg is None
assert err is not None
assert "Malformed" in err
assert "42" in err
def test_empty_string_workspace_returns_error(self):
"""workspace = '' is malformed, not absent."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
self._setup_v3_project(tmp, {"workspace": ""})
cfg, err = find_workspace_config(tmp)
assert cfg is None
assert err is not None
assert "Malformed" in err
class TestWorkspaceContext:
"""Tests for WorkspaceContext."""
def teardown_method(self, method):
set_context(None)
@staticmethod
def _make_primary_context(tmpdir: Path) -> CypilotContext:
meta = _make_mock_meta()
meta.get_all_system_prefixes.return_value = {"myapp"}
return CypilotContext(
adapter_dir=tmpdir / "adapter",
project_root=tmpdir,
meta=meta,
kits={},
registered_systems={"myapp"},
)
@patch("cypilot.utils.workspace.find_workspace_config")
def test_load_returns_none_no_workspace(self, mock_find):
mock_find.return_value = (None, None)
with TemporaryDirectory() as tmpdir:
ctx = self._make_primary_context(Path(tmpdir))
ws = WorkspaceContext.load(ctx)
assert ws is None
@patch("cypilot.utils.workspace.find_workspace_config")
def test_load_with_workspace(self, mock_find):
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
source_dir = tmp / "other-repo"
source_dir.mkdir()
ws_cfg = WorkspaceConfig(
sources={"other": SourceEntry(name="other", path="other-repo")},
workspace_file=tmp / ".cypilot-workspace.toml",
)
mock_find.return_value = (ws_cfg, None)
ctx = self._make_primary_context(tmp)
ws = WorkspaceContext.load(ctx)
assert ws is not None
assert "other" in ws.sources
assert ws.sources["other"].reachable is True
@patch("cypilot.utils.workspace.find_workspace_config")
def test_unreachable_source(self, mock_find):
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
ws_cfg = WorkspaceConfig(
sources={"missing": SourceEntry(name="missing", path="does-not-exist")},
workspace_file=tmp / ".cypilot-workspace.toml",
)
mock_find.return_value = (ws_cfg, None)
ctx = self._make_primary_context(tmp)
ws = WorkspaceContext.load(ctx)
assert ws is not None
sc = ws.sources["missing"]
assert sc.reachable is False
assert sc.name == "missing"
assert sc.error is not None
assert "does-not-exist" in sc.error
def test_primary_properties_delegate(self):
with TemporaryDirectory() as tmpdir:
ctx = self._make_primary_context(Path(tmpdir))
ws = WorkspaceContext(primary=ctx)
assert ws.adapter_dir == ctx.adapter_dir
assert ws.project_root == ctx.project_root
assert ws.meta is ctx.meta
assert ws.registered_systems == ctx.registered_systems
def test_resolve_artifact_path_no_source(self):
"""Artifact without source resolves relative to fallback_root."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
ctx = self._make_primary_context(tmp)
ws = WorkspaceContext(primary=ctx)
artifact = MagicMock()
artifact.path = "docs/DESIGN.md"
artifact.source = None
result = ws.resolve_artifact_path(artifact, tmp)
assert result == (tmp / "docs/DESIGN.md").resolve()
def test_resolve_artifact_path_reachable_source(self):
"""Artifact with source pointing to a reachable source resolves via that source."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
source_dir = tmp / "other-repo"
source_dir.mkdir()
ctx = self._make_primary_context(tmp)
sc = SourceContext(
name="other",
path=source_dir,
role="full",
reachable=True,
)
ws = WorkspaceContext(primary=ctx, sources={"other": sc})
artifact = MagicMock()
artifact.path = "docs/DESIGN.md"
artifact.source = "other"
result = ws.resolve_artifact_path(artifact, tmp)
assert result == (source_dir / "docs/DESIGN.md").resolve()
def test_resolve_artifact_path_missing_source_returns_none(self):
"""Artifact with source not in workspace returns None instead of falling back."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
ctx = self._make_primary_context(tmp)
ws = WorkspaceContext(primary=ctx, sources={})
artifact = MagicMock()
artifact.path = "docs/DESIGN.md"
artifact.source = "nonexistent"
result = ws.resolve_artifact_path(artifact, tmp)
assert result is None
def test_resolve_artifact_path_unreachable_source_returns_none(self):
"""Artifact with source pointing to an unreachable source returns None."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
ctx = self._make_primary_context(tmp)
sc = SourceContext(
name="down",
path=tmp / "missing-dir",
role="full",
reachable=False,
error="Source directory not found",
)
ws = WorkspaceContext(primary=ctx, sources={"down": sc})
artifact = MagicMock()
artifact.path = "docs/DESIGN.md"
artifact.source = "down"
result = ws.resolve_artifact_path(artifact, tmp)
assert result is None
def test_get_all_registered_systems(self):
with TemporaryDirectory() as tmpdir:
ctx = self._make_primary_context(Path(tmpdir))
sc = SourceContext(
name="other",
path=Path(tmpdir) / "other",
role="full",
reachable=True,
registered_systems={"other-system"},
)
ws = WorkspaceContext(primary=ctx, sources={"other": sc})
all_systems = ws.get_all_registered_systems()
assert "myapp" in all_systems
assert "other-system" in all_systems
def test_resolve_remote_ids_false_skips_remote_sources(self):
"""get_all_artifact_ids must ignore remote sources when resolve_remote_ids=False."""
with TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
# Create a primary artifact file with a definition
(tmp / "PRIMARY.md").write_text("**ID**: `cpt-primary-id`\n", encoding="utf-8")
# Create a remote artifact file with a different definition
remote_dir = tmp / "remote"
remote_dir.mkdir()
(remote_dir / "REMOTE.md").write_text("**ID**: `cpt-remote-id`\n", encoding="utf-8")
# Primary context with one artifact pointing to PRIMARY.md
primary_artifact = MagicMock()
primary_artifact.path = "PRIMARY.md"
primary_artifact.source = None
meta = _make_mock_meta(".")
meta.iter_all_artifacts.return_value = [(primary_artifact, None)]
primary_ctx = CypilotContext(
adapter_dir=tmp / "adapter", project_root=tmp,
meta=meta, kits={}, registered_systems=set(),
)
# Remote source with one artifact pointing to REMOTE.md
remote_artifact = MagicMock()
remote_artifact.path = "REMOTE.md"
remote_meta = MagicMock(spec=ArtifactsMeta)
remote_meta.iter_all_artifacts.return_value = [(remote_artifact, None)]
remote_sc = SourceContext(
name="remote",
path=remote_dir,
role="full",
reachable=True,
meta=remote_meta,
registered_systems=set(),
)
# Case 1: resolve_remote_ids=True — both IDs collected
ws_enabled = WorkspaceContext(
primary=primary_ctx,
sources={"remote": remote_sc},
cross_repo=True,
resolve_remote_ids=True,
)