-
Notifications
You must be signed in to change notification settings - Fork 12.3k
Expand file tree
/
Copy pathtest_artifact_command.py
More file actions
2819 lines (2506 loc) · 105 KB
/
Copy pathtest_artifact_command.py
File metadata and controls
2819 lines (2506 loc) · 105 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
"""Unit and contract tests for the `specify artifact` command group.
Covers the pure-logic layer (:class:`ArtifactCatalog`) plus the CLI wiring
(``specify artifact list``, ``specify artifact info``) exercised through
Typer's ``CliRunner``.
"""
from __future__ import annotations
import json
import os
import re
import shutil
from datetime import date
from pathlib import Path
import pytest
import yaml
from typer.testing import CliRunner
from specify_cli import app
from specify_cli.artifacts import (
AmbiguousArtifactError,
Artifact,
ArtifactCatalog,
ArtifactKind,
ArtifactNotFoundError,
ArtifactResolutionError,
ContributionNotFoundError,
HookArtifact,
NotASpecKitProjectError,
)
from specify_cli.artifacts.resolution import _preset_display_name
from specify_cli.extensions import CORE_COMMAND_NAMES, ExtensionRegistry
from specify_cli.presets import PresetRegistry, PresetResolver
from tests.conftest import install_preset
ERROR_REGEX = re.compile(
r"^(unknown artifact |unknown contribution |ambiguous artifact |"
r"artifact resolution failed|not a Spec Kit project)"
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def spec_kit_project(tmp_path: Path) -> Path:
"""Create a minimal but valid Spec Kit project layout."""
root = tmp_path / "proj"
root.mkdir()
(root / ".specify").mkdir()
(root / ".specify" / "presets").mkdir()
(root / ".specify" / "extensions").mkdir()
(root / ".specify" / "templates").mkdir()
return root
@pytest.fixture
def non_project(tmp_path: Path) -> Path:
"""A directory that intentionally lacks ``.specify/``."""
root = tmp_path / "not-proj"
root.mkdir()
return root
# ---------------------------------------------------------------------------
# Contract tests — matching artifact-list.schema.json
# ---------------------------------------------------------------------------
class TestListArtifactsContract:
def test_returns_list_of_artifact(self, spec_kit_project: Path):
rows = ArtifactCatalog(spec_kit_project).list_artifacts()
assert all(isinstance(r, (Artifact, HookArtifact)) for r in rows)
def test_every_row_has_required_fields(self, spec_kit_project: Path):
for row in ArtifactCatalog(spec_kit_project).list_artifacts():
d = row.to_json_dict()
assert set(d.keys()) == {"id", "name", "kind", "description"}
assert isinstance(d["description"], str) # never None; empty string OK
def test_id_grammar(self, spec_kit_project: Path):
pattern = re.compile(
r"^(?:(?:command|template|script):[^:]+|hook:[^:]+:[^:]+)$"
)
for row in ArtifactCatalog(spec_kit_project).list_artifacts():
assert pattern.match(row.id), f"bad id: {row.id!r}"
def test_name_never_contains_colon(self, spec_kit_project: Path):
for row in ArtifactCatalog(spec_kit_project).list_artifacts():
if row.kind != "hook":
assert ":" not in row.name
def test_kind_is_from_fixed_enum(self, spec_kit_project: Path):
for row in ArtifactCatalog(spec_kit_project).list_artifacts():
assert row.kind in ("command", "template", "script", "hook")
def test_rows_are_unique(self, spec_kit_project: Path):
rows = ArtifactCatalog(spec_kit_project).list_artifacts()
ids = [r.id for r in rows]
assert len(ids) == len(set(ids))
def test_every_core_command_is_listed_and_resolvable(
self, spec_kit_project: Path
):
catalog = ArtifactCatalog(spec_kit_project)
listed = {
row.name for row in catalog.list_artifacts() if row.kind == "command"
}
expected = {f"speckit.{name}" for name in CORE_COMMAND_NAMES}
assert expected <= listed
for name in expected:
info = catalog.get_artifact_info(f"command:{name}")
assert info["id"] == f"command:{name}"
assert info["kind"] == "command"
assert info["stack"]
@pytest.mark.parametrize(
("requested", "runtime_dir"),
[("sh", "bash"), ("ps", "powershell"), ("py", "python")],
)
def test_core_scripts_follow_existing_project_runtime_selection(
self, spec_kit_project: Path, requested: str, runtime_dir: str
):
(spec_kit_project / ".specify" / "init-options.json").write_text(
json.dumps({"script": requested}),
encoding="utf-8",
)
catalog = ArtifactCatalog(spec_kit_project)
scripts = [row for row in catalog.list_artifacts() if row.kind == "script"]
assert {row.name for row in scripts} == {
"check-prerequisites",
"resolve-template",
"setup-plan",
"setup-tasks",
}
selected_paths = catalog._selected_core_script_paths()
assert set(selected_paths) == {row.name for row in scripts}
assert all(path.parent.name == runtime_dir for path in selected_paths.values())
for script in scripts:
info = catalog.get_artifact_info(script.id)
assert info["stack"][-1]["layer"] is None
assert info["stack"][-1]["sourceId"] is None
assert info["stack"][-1]["lookupId"] is None
assert info["stack"][-1]["sourcePath"] is None
def test_core_scripts_reuse_existing_runtime_fallback(
self, spec_kit_project: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
commands_dir = tmp_path / "commands"
scripts_dir = tmp_path / "scripts"
commands_dir.mkdir()
(scripts_dir / "bash").mkdir(parents=True)
(commands_dir / "demo.md").write_text(
"---\n"
"scripts:\n"
" sh: scripts/bash/demo.sh\n"
"---\n",
encoding="utf-8",
)
script = scripts_dir / "bash" / "demo.sh"
script.write_text("#!/bin/sh\n", encoding="utf-8")
(spec_kit_project / ".specify" / "init-options.json").write_text(
json.dumps({"script": "ps"}),
encoding="utf-8",
)
monkeypatch.setattr(
"specify_cli.artifacts.catalog._locate_shared_asset_dir",
lambda subdir: {
"commands": commands_dir,
"scripts": scripts_dir,
"templates": None,
}[subdir],
)
assert ArtifactCatalog(spec_kit_project)._selected_core_script_paths() == {
"demo": script
}
@pytest.mark.parametrize(
"reference_kind",
[
"absolute",
"windows-drive",
"unc",
"traversal",
],
)
def test_core_scripts_reject_unsafe_references(
self,
spec_kit_project: Path,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
reference_kind: str,
):
commands_dir = tmp_path / "commands"
scripts_dir = tmp_path / "scripts"
commands_dir.mkdir()
(scripts_dir / "bash").mkdir(parents=True)
outside = tmp_path / "outside.sh"
outside.write_text(
"#!/bin/sh\n# Must not be read\n", encoding="utf-8"
)
script_reference = {
"absolute": outside.resolve().as_posix(),
"windows-drive": "C:/outside/demo.sh",
"unc": "//server/share/demo.sh",
"traversal": "scripts/bash/../../outside.sh",
}[reference_kind]
(commands_dir / "demo.md").write_text(
"---\n"
"scripts:\n"
f" sh: {script_reference}\n"
"---\n",
encoding="utf-8",
)
monkeypatch.setattr(
"specify_cli.artifacts.catalog._locate_shared_asset_dir",
lambda subdir: {
"commands": commands_dir,
"scripts": scripts_dir,
"templates": None,
}[subdir],
)
catalog = ArtifactCatalog(spec_kit_project)
assert catalog._selected_core_script_paths() == {}
assert all(row.id != "script:outside" for row in catalog.list_artifacts())
def test_core_scripts_reject_symlinks_escaping_script_root(
self, spec_kit_project: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
commands_dir = tmp_path / "commands"
scripts_dir = tmp_path / "scripts"
commands_dir.mkdir()
(scripts_dir / "bash").mkdir(parents=True)
outside = tmp_path / "outside.sh"
outside.write_text("#!/bin/sh\n# Must not be read\n", encoding="utf-8")
link = scripts_dir / "bash" / "demo.sh"
try:
link.symlink_to(outside)
except OSError:
pytest.skip("symlink creation is not available")
(commands_dir / "demo.md").write_text(
"---\n"
"scripts:\n"
" sh: scripts/bash/demo.sh\n"
"---\n",
encoding="utf-8",
)
monkeypatch.setattr(
"specify_cli.artifacts.catalog._locate_shared_asset_dir",
lambda subdir: {
"commands": commands_dir,
"scripts": scripts_dir,
"templates": None,
}[subdir],
)
assert ArtifactCatalog(spec_kit_project)._selected_core_script_paths() == {}
def test_excludes_disabled_and_unusable_manifest_contributions(
self, spec_kit_project: Path
):
extensions_dir = spec_kit_project / ".specify" / "extensions"
for extension_id, artifact_name, enabled, file_name in (
(
"disabled-ext",
"disabled-template",
False,
"templates/disabled-template.md",
),
(
"missing-file-ext",
"missing-template",
True,
"templates/missing-template.md",
),
):
extension_dir = extensions_dir / extension_id
extension_dir.mkdir()
(extension_dir / "extension.yml").write_text(
yaml.safe_dump(
{
"schema_version": "1.0",
"extension": {
"id": extension_id,
"name": extension_id,
"version": "1.0.0",
"description": "test",
"author": "test",
"repository": "https://example.com",
"license": "MIT",
},
"requires": {"speckit_version": ">=0.2.0"},
"provides": {
"templates": [
{
"name": artifact_name,
"file": file_name,
"description": "Should not be listed",
}
]
},
}
),
encoding="utf-8",
)
if not enabled:
template = extension_dir / file_name
template.parent.mkdir()
template.write_text("# Disabled\n", encoding="utf-8")
ExtensionRegistry(extensions_dir).add(
extension_id, {"version": "1.0.0", "enabled": enabled}
)
names = {row.name for row in ArtifactCatalog(spec_kit_project).list_artifacts()}
assert "disabled-template" not in names
assert "missing-template" not in names
def test_unregistered_extension_installed_id_identifies_lookup(
self, spec_kit_project: Path
):
ext_dir = spec_kit_project / ".specify" / "extensions" / "renamed"
ext_dir.mkdir()
(ext_dir / "commands").mkdir()
(ext_dir / "commands" / "actual.md").write_text(
"---\ndescription: Manifest identity wins\n---\nbody\n",
encoding="utf-8",
)
(ext_dir / "commands" / "speckit.renamed.convention.md").write_text(
"---\ndescription: Convention identity uses directory\n---\nbody\n",
encoding="utf-8",
)
(ext_dir / "extension.yml").write_text(
yaml.safe_dump(
{
"schema_version": "1.0",
"extension": {
"id": "original",
"name": "Original Id",
"version": "1.0.0",
"description": "test",
"author": "test",
"repository": "https://example.com",
"license": "MIT",
},
"requires": {"speckit_version": ">=0.2.0"},
"provides": {
"commands": [
{
"name": "speckit.original.hello",
"file": "commands/actual.md",
"description": "manifest declared command",
}
]
},
}
),
encoding="utf-8",
)
catalog = ArtifactCatalog(spec_kit_project)
assert "command:speckit.original.hello" in {
row.id for row in catalog.list_artifacts()
}
info = catalog.get_artifact_info("speckit.original.hello")
assert info["stack"][0]["sourceId"] == "renamed"
assert info["stack"][0]["lookupId"] == (
"extension:renamed:command:speckit.original.hello"
)
resolver_layer = PresetResolver(spec_kit_project).collect_all_layers(
"speckit.original.hello", "command"
)[0]
assert "lookupId" not in resolver_layer
# Provenance uses the installed directory identity and path even when
# the manifest declares a different logical ID.
assert (
info["stack"][0]["manifestPath"]
== ".specify/extensions/renamed/extension.yml"
)
contribution = catalog.get_contribution_info(
info["stack"][0]["lookupId"]
)
assert contribution["id"] == info["stack"][0]["lookupId"]
assert contribution["layer"] == "extension"
assert contribution["sourceId"] == "renamed"
assert contribution["kind"] == "command"
assert contribution["name"] == "speckit.original.hello"
assert contribution["contribution"]["file"] == "commands/actual.md"
convention = catalog.get_artifact_info("speckit.renamed.convention")[
"stack"
][0]
assert convention["sourceId"] == "renamed"
assert convention["lookupId"] == (
"extension:renamed:command:speckit.renamed.convention"
)
assert convention["manifestPath"] is None
with pytest.raises(ContributionNotFoundError):
catalog.get_contribution_info(convention["lookupId"])
def test_duplicate_extension_manifest_ids_resolve_each_installed_layer(
self, spec_kit_project: Path
):
for installed_id, description in (
("a-copy", "First declaration"),
("b-copy", "Second declaration"),
):
ext_dir = (
spec_kit_project / ".specify" / "extensions" / installed_id
)
(ext_dir / "commands").mkdir(parents=True)
(ext_dir / "commands" / "shared.md").write_text(
description, encoding="utf-8"
)
(ext_dir / "extension.yml").write_text(
yaml.safe_dump(
{
"schema_version": "1.0",
"extension": {
"id": "shared",
"name": "Shared",
"version": "1.0.0",
"description": "test",
"author": "test",
"repository": "https://example.com",
"license": "MIT",
},
"requires": {"speckit_version": ">=0.2.0"},
"provides": {
"commands": [
{
"name": "speckit.shared.command",
"file": "commands/shared.md",
"description": description,
}
]
},
}
),
encoding="utf-8",
)
catalog = ArtifactCatalog(spec_kit_project)
stack = catalog.get_artifact_info("speckit.shared.command")["stack"]
extension_layers = [
layer for layer in stack if layer["layer"] == "extension"
]
assert [layer["sourceId"] for layer in extension_layers] == [
"a-copy",
"b-copy",
]
assert [layer["lookupId"] for layer in extension_layers] == [
"extension:a-copy:command:speckit.shared.command",
"extension:b-copy:command:speckit.shared.command",
]
resolved = [
catalog.get_contribution_info(layer["lookupId"])
for layer in extension_layers
]
assert [
contribution["contribution"]["description"]
for contribution in resolved
] == ["First declaration", "Second declaration"]
assert [contribution["manifestPath"] for contribution in resolved] == [
".specify/extensions/a-copy/extension.yml",
".specify/extensions/b-copy/extension.yml",
]
def test_includes_project_local_core_assets(self, spec_kit_project: Path):
templates_dir = spec_kit_project / ".specify" / "templates"
(templates_dir / "legacy-template.md").write_text(
"---\ndescription: Local template\n---\n", encoding="utf-8"
)
commands_dir = templates_dir / "commands"
commands_dir.mkdir()
(commands_dir / "local-command.md").write_text(
"---\ndescription: Local command\n---\n", encoding="utf-8"
)
scripts_dir = templates_dir / "scripts"
scripts_dir.mkdir()
(scripts_dir / "legacy-script.sh").write_text(
"# Local script\n", encoding="utf-8"
)
catalog = ArtifactCatalog(spec_kit_project)
artifacts = {artifact.id: artifact for artifact in catalog.list_artifacts()}
assert artifacts["template:legacy-template"].description == "Local template"
assert artifacts["command:speckit.local-command"].description == "Local command"
assert artifacts["script:legacy-script"].description == "Local script"
for name in ("speckit.local-command", "legacy-template", "legacy-script"):
layer = catalog.get_artifact_info(name)["stack"][0]
assert layer["layer"] is None
assert layer["sourceId"] is None
assert layer["lookupId"] is None
assert layer["sourcePath"] is None
def test_includes_root_level_pack_templates(
self, spec_kit_project: Path
):
extension_dir = spec_kit_project / ".specify" / "extensions" / "legacy"
extension_dir.mkdir()
(extension_dir / "legacy-root.md").write_text(
"---\ndescription: Legacy root template\n---\n",
encoding="utf-8",
)
(extension_dir / "README.md").write_text("# Packaging notes\n", encoding="utf-8")
catalog = ArtifactCatalog(spec_kit_project)
names = {row.name for row in catalog.list_artifacts()}
assert "legacy-root" in names
assert "README" in names
assert next(
row for row in catalog.list_artifacts() if row.name == "legacy-root"
).description == "Legacy root template"
def test_extension_registry_missing_collection_key_uses_existing_normalization(
self, spec_kit_project: Path
):
registry_path = spec_kit_project / ".specify" / "extensions" / ".registry"
registry_path.write_text('{"schema_version": "1.0"}', encoding="utf-8")
assert ArtifactCatalog(spec_kit_project).list_artifacts()
@pytest.mark.skipif(os.name == "nt", reason="':' filenames are unsupported on Windows")
def test_skips_invalid_colon_names_in_project_local_inventory(self, spec_kit_project: Path):
templates_dir = spec_kit_project / ".specify" / "templates"
commands_dir = templates_dir / "commands"
scripts_dir = templates_dir / "scripts"
overrides_dir = templates_dir / "overrides"
override_scripts_dir = overrides_dir / "scripts"
commands_dir.mkdir(parents=True)
scripts_dir.mkdir(parents=True)
overrides_dir.mkdir(parents=True)
override_scripts_dir.mkdir(parents=True)
(templates_dir / "bad:template.md").write_text("---\ndescription: bad\n---\n", encoding="utf-8")
(commands_dir / "bad:command.md").write_text("---\ndescription: bad\n---\n", encoding="utf-8")
(scripts_dir / "bad:script.sh").write_text("# bad\n", encoding="utf-8")
(overrides_dir / "bad:override.md").write_text("override", encoding="utf-8")
(override_scripts_dir / "bad:override-script.sh").write_text("# bad\n", encoding="utf-8")
artifacts = ArtifactCatalog(spec_kit_project).list_artifacts()
assert all(":" not in artifact.name for artifact in artifacts)
def test_preserves_prefixed_project_local_command_names(self, spec_kit_project: Path):
commands_dir = spec_kit_project / ".specify" / "templates" / "commands"
commands_dir.mkdir()
(commands_dir / "speckit.local-prefixed.md").write_text(
"---\ndescription: Local prefixed command\n---\n", encoding="utf-8"
)
artifacts = {artifact.id: artifact for artifact in ArtifactCatalog(spec_kit_project).list_artifacts()}
assert "command:speckit.local-prefixed" in artifacts
assert "command:speckit.speckit.local-prefixed" not in artifacts
def test_prefers_exact_core_command_name(self, spec_kit_project: Path):
commands_dir = spec_kit_project / ".specify" / "templates" / "commands"
commands_dir.mkdir()
(commands_dir / "foo.md").write_text(
"---\ndescription: Stripped fallback\n---\n", encoding="utf-8"
)
exact_path = commands_dir / "speckit.foo.md"
exact_path.write_text(
"---\ndescription: Exact logical name\n---\n", encoding="utf-8"
)
assert PresetResolver(spec_kit_project).resolve("speckit.foo", "command") == exact_path
info = ArtifactCatalog(spec_kit_project).get_artifact_info("speckit.foo")
assert info["description"] == "Exact logical name"
def test_active_preset_description_overrides_hidden_core_description(
self, spec_kit_project: Path
):
"""A preset that overrides a core command must win the description too.
Regression test: descriptions used to be merged "first non-empty
wins", and core rows were inserted before contributions — so an
active preset's replacement of a core command still reported the
(now-inactive) core description.
"""
commands_dir = spec_kit_project / ".specify" / "templates" / "commands"
commands_dir.mkdir(parents=True)
(commands_dir / "speckit.constitution.md").write_text(
"---\ndescription: Core description\n---\n", encoding="utf-8"
)
pack = install_preset(
spec_kit_project,
"override-preset",
{
"commands": [
{"name": "speckit.constitution", "description": "Preset description"}
]
},
)
(pack / "commands").mkdir()
(pack / "commands" / "speckit.constitution.md").write_text(
"# Preset\n", encoding="utf-8"
)
artifacts = {
artifact.id: artifact
for artifact in ArtifactCatalog(spec_kit_project).list_artifacts()
}
assert artifacts["command:speckit.constitution"].description == "Preset description"
def test_higher_precedence_preset_description_wins(self, spec_kit_project: Path):
"""When two presets both provide an artifact, the winner's description wins.
Lower ``priority`` number means higher precedence (see
``PresetResolver.collect_all_layers``); the loser's description must
not leak through just because it happens to be enumerated first
alphabetically.
"""
pack_low = install_preset(
spec_kit_project,
"aaa-low-priority-preset",
{"templates": [{"name": "shared-artifact", "description": "Loser description"}]},
priority=20,
)
(pack_low / "templates").mkdir()
(pack_low / "templates" / "shared-artifact.md").write_text(
"# Loser\n", encoding="utf-8"
)
pack_high = install_preset(
spec_kit_project,
"zzz-high-priority-preset",
{"templates": [{"name": "shared-artifact", "description": "Winner description"}]},
priority=5,
)
(pack_high / "templates").mkdir()
(pack_high / "templates" / "shared-artifact.md").write_text(
"# Winner\n", encoding="utf-8"
)
artifacts = {
artifact.id: artifact
for artifact in ArtifactCatalog(spec_kit_project).list_artifacts()
}
assert artifacts["template:shared-artifact"].description == "Winner description"
class TestListSorting:
"""Deterministic ordering for the flat inventory."""
def test_kind_grouping(self, spec_kit_project: Path):
rows = ArtifactCatalog(spec_kit_project).list_artifacts()
kinds_seen = [r.kind for r in rows]
# kinds must appear as contiguous groups in the fixed order
first_idx = {
k: next((i for i, x in enumerate(kinds_seen) if x == k), None)
for k in ("command", "template", "script", "hook")
}
indices = [v for v in first_idx.values() if v is not None]
assert indices == sorted(indices)
def test_name_sorted_within_kind(self, spec_kit_project: Path):
rows = ArtifactCatalog(spec_kit_project).list_artifacts()
by_kind: dict[str, list[str]] = {}
for r in rows:
if r.kind == "hook":
continue
by_kind.setdefault(r.kind, []).append(r.name)
for _, names in by_kind.items():
assert names == sorted(names)
class TestEmptyProject:
def test_empty_stack_returns_empty_list(self, tmp_path: Path):
# A .specify/ dir with no presets/extensions and no accessible core.
# We can't easily wipe the core baseline in this process, so instead
# verify list_artifacts is at least callable and returns a list.
root = tmp_path / "empty"
root.mkdir()
(root / ".specify").mkdir()
rows = ArtifactCatalog(root).list_artifacts()
assert isinstance(rows, list)
# ---------------------------------------------------------------------------
# get_artifact_info contract
# ---------------------------------------------------------------------------
class TestInfoContract:
def test_stack_ordered_highest_first(self, spec_kit_project: Path):
info = ArtifactCatalog(spec_kit_project).get_artifact_info("speckit.constitution")
assert info["stack"], "expected at least one stack layer"
def test_exactly_one_active_row(self, spec_kit_project: Path):
info = ArtifactCatalog(spec_kit_project).get_artifact_info("speckit.constitution")
actives = [layer for layer in info["stack"] if layer["active"]]
assert len(actives) == 1
def test_active_is_index_zero(self, spec_kit_project: Path):
info = ArtifactCatalog(spec_kit_project).get_artifact_info("speckit.constitution")
assert info["stack"][0]["active"] is True
for layer in info["stack"][1:]:
assert layer["active"] is False
def test_builtin_row_shape(self, spec_kit_project: Path):
resolver_layer = PresetResolver(spec_kit_project).collect_all_layers(
"speckit.constitution", "command"
)[-1]
assert resolver_layer["source"] == "core (bundled)"
assert "lookupId" not in resolver_layer
info = ArtifactCatalog(spec_kit_project).get_artifact_info("speckit.constitution")
assert info["id"] == "command:speckit.constitution"
builtin = next(layer for layer in info["stack"] if layer["layer"] is None)
assert builtin["sourceId"] is None
assert builtin["presetId"] is None
assert builtin["presetName"] is None
assert builtin["manifestPath"] is None
assert builtin["strategy"] == "replace"
assert builtin["lookupId"] is None
assert builtin["sourcePath"] is None
def test_project_override_row_shape(self, spec_kit_project: Path):
overrides = spec_kit_project / ".specify" / "templates" / "overrides"
overrides.mkdir()
(overrides / "speckit.constitution.md").write_text("override", encoding="utf-8")
info = ArtifactCatalog(spec_kit_project).get_artifact_info(
"command:speckit.constitution"
)
project = next(layer for layer in info["stack"] if layer["layer"] == "project")
assert project["presetId"] is None
assert project["presetName"] is None
assert project["manifestPath"] is None
assert project["sourcePath"] is None
assert project["strategy"] == "replace"
assert project["sourceId"] == "_"
assert re.match(r"^project:_:(command|template|script):[^:]+$", project["lookupId"])
def test_lookup_id_grammar(self, spec_kit_project: Path):
info = ArtifactCatalog(spec_kit_project).get_artifact_info("speckit.constitution")
for layer in info["stack"]:
if layer["lookupId"] is None:
assert layer["layer"] is None
assert layer["sourceId"] is None
continue
assert re.match(
r"^(project|preset|extension):[^:]+:(command|template|script):[^:]+(:[0-9a-f]{12})?$",
layer["lookupId"],
)
def test_id_matches_list(self, spec_kit_project: Path):
cat = ArtifactCatalog(spec_kit_project)
info = cat.get_artifact_info("speckit.constitution")
assert info["id"] == "command:speckit.constitution"
def test_every_stack_row_carries_id(self, spec_kit_project: Path):
"""Every stack row carries a non-null ``id``, including built-in rows.
``id`` is the source-agnostic round-trip key; it does not depend on
the row having a ``lookupId`` (manifest-backed layer provenance).
"""
overrides = spec_kit_project / ".specify" / "templates" / "overrides"
overrides.mkdir()
(overrides / "speckit.constitution.md").write_text("override", encoding="utf-8")
info = ArtifactCatalog(spec_kit_project).get_artifact_info(
"command:speckit.constitution"
)
assert len(info["stack"]) >= 2
for layer in info["stack"]:
assert layer["id"] == "command:speckit.constitution"
# ---------------------------------------------------------------------------
# Error conditions — pinned strings for the artifact-error contract
# ---------------------------------------------------------------------------
class TestErrors:
def test_unknown_artifact_message(self, spec_kit_project: Path):
with pytest.raises(ArtifactNotFoundError) as excinfo:
ArtifactCatalog(spec_kit_project).get_artifact_info("no.such.thing")
assert excinfo.value.message == "unknown artifact no.such.thing"
assert ERROR_REGEX.match(excinfo.value.message)
def test_not_a_project(self, non_project: Path):
with pytest.raises(NotASpecKitProjectError) as excinfo:
ArtifactCatalog(non_project).list_artifacts()
assert excinfo.value.message == "not a Spec Kit project: no .specify/ directory found"
assert ERROR_REGEX.match(excinfo.value.message)
def test_ambiguous_artifact_message(self, spec_kit_project: Path):
"""When both a command and a template share the same bare name."""
# Register a preset that contributes 'shared-name' as both a
# template and a script — the info lookup with no kind hint should
# then be ambiguous.
pack = install_preset(
spec_kit_project,
"test-ambig",
{
"templates": [
{"type": "template", "name": "shared-name", "description": "t"},
{"type": "script", "name": "shared-name", "description": "s"},
],
},
)
(pack / "templates").mkdir()
(pack / "templates" / "shared-name.md").write_text("# Template\n")
(pack / "scripts").mkdir()
(pack / "scripts" / "shared-name.sh").write_text("#!/usr/bin/env bash\n")
with pytest.raises(AmbiguousArtifactError) as excinfo:
ArtifactCatalog(spec_kit_project).get_artifact_info("shared-name")
assert excinfo.value.message.startswith("ambiguous artifact shared-name: matches kinds")
assert ERROR_REGEX.match(excinfo.value.message)
def test_resolution_error_message(self):
assert ArtifactResolutionError().message == "artifact resolution failed"
def test_info_rejects_corrupt_extension_registry(self, spec_kit_project: Path):
registry = spec_kit_project / ".specify" / "extensions" / ".registry"
registry.write_text("{invalid", encoding="utf-8")
with pytest.raises(ArtifactResolutionError):
ArtifactCatalog(spec_kit_project).get_artifact_info("command:speckit.constitution")
class TestKindHint:
def test_kind_flag_disambiguates(self, spec_kit_project: Path):
install_preset(
spec_kit_project,
"test-kind",
{"templates": [{"name": "dup", "description": "t"}],
"scripts": [{"name": "dup", "description": "s"}]},
)
# No stack file backs these contributions on disk so the info call
# will raise unknown after resolving kind — either way it should
# not raise ambiguous when a kind is supplied.
try:
ArtifactCatalog(spec_kit_project).get_artifact_info("dup", kind="template")
except ArtifactNotFoundError:
pass # expected: manifest declared it but no file to compose
def test_shorthand_grammar(self, spec_kit_project: Path):
# Even with core commands, the shorthand should route correctly.
info = ArtifactCatalog(spec_kit_project).get_artifact_info("command:speckit.constitution")
assert info["kind"] == "command"
def test_conflicting_shorthand_and_flag(self, spec_kit_project: Path):
with pytest.raises(ArtifactNotFoundError):
ArtifactCatalog(spec_kit_project).get_artifact_info(
"template:speckit.constitution", kind="command"
)
@pytest.mark.parametrize(
("kind", "name"),
(
("template", "../../outside"),
("command", "template:foo"),
("script", "script:name"),
),
)
def test_kind_hint_rejects_invalid_name_components(
self, spec_kit_project: Path, kind: ArtifactKind, name: str
):
with pytest.raises(ArtifactNotFoundError):
ArtifactCatalog(spec_kit_project).get_artifact_info(name, kind=kind)
def test_id_form_round_trips_to_same_artifact(self, spec_kit_project: Path):
"""``artifact info`` accepts the public ``id`` form (``kind:name``).
Given either the bare name or its ``id``, the resolved artifact is
the same — ``id`` is the source-agnostic round-trip key.
"""
cat = ArtifactCatalog(spec_kit_project)
by_bare = cat.get_artifact_info("speckit.plan")
by_id = cat.get_artifact_info("command:speckit.plan")
assert by_id == by_bare
def test_id_form_resolves_template_despite_same_named_command(
self, spec_kit_project: Path
):
"""``kind:name`` disambiguates when a command shares a template's name."""
pack_dir = install_preset(
spec_kit_project,
"collide-pack",
{"commands": [{"name": "spec-template", "description": "cmd"}]},
)
(pack_dir / "commands").mkdir(parents=True, exist_ok=True)
(pack_dir / "commands" / "spec-template.md").write_text(
"colliding command body", encoding="utf-8"
)
# Sanity check: without a kind hint, the bare name is ambiguous
# because both a command and a template named "spec-template" exist.
with pytest.raises(AmbiguousArtifactError):
ArtifactCatalog(spec_kit_project).get_artifact_info("spec-template")
info = ArtifactCatalog(spec_kit_project).get_artifact_info("template:spec-template")
assert info["kind"] == "template"
assert info["id"] == "template:spec-template"
# ---------------------------------------------------------------------------
# Skills exclusion
# ---------------------------------------------------------------------------
class TestSkillsExcluded:
def test_no_skills_in_list(self, spec_kit_project: Path):
skills_dir = spec_kit_project / ".github" / "skills" / "speckit-my-skill"
skills_dir.mkdir(parents=True)
(skills_dir / "SKILL.md").write_text("---\nname: my-skill\n---\nbody", encoding="utf-8")
rows = ArtifactCatalog(spec_kit_project).list_artifacts()
assert not any("skill" in r.name.lower() for r in rows)
# ---------------------------------------------------------------------------
# CLI wiring — Typer CliRunner
# ---------------------------------------------------------------------------
class TestCLI:
def test_list_requires_json_flag(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch):
monkeypatch.chdir(spec_kit_project)
runner = CliRunner()
result = runner.invoke(app, ["artifact", "list"])
assert result.exit_code == 2
assert result.stdout == ""
def test_list_json_emits_array(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch):
monkeypatch.chdir(spec_kit_project)
runner = CliRunner()
result = runner.invoke(app, ["artifact", "list", "--json"])
assert result.exit_code == 0, result.stderr
payload = json.loads(result.stdout)
assert isinstance(payload, list)
assert result.stdout.endswith("\n")
def test_list_json_rows_include_stack(self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch):
monkeypatch.chdir(spec_kit_project)
runner = CliRunner()
result = runner.invoke(app, ["artifact", "list", "--json"])
assert result.exit_code == 0, result.stderr
payload = json.loads(result.stdout)
assert payload, "expected at least one artifact"
row = payload[0]
assert set(row.keys()) == {"id", "name", "kind", "description", "stack"}
assert isinstance(row["stack"], list)
info_result = runner.invoke(app, ["artifact", "info", row["id"], "--json"])
assert info_result.exit_code == 0, info_result.stderr
info = json.loads(info_result.stdout)
assert row["stack"] == info["stack"]
def test_lookup_json_cross_references_manifest_contribution(
self, spec_kit_project: Path, monkeypatch: pytest.MonkeyPatch
):
monkeypatch.chdir(spec_kit_project)
pack = install_preset(
spec_kit_project,
"lookup-pack",
{
"templates": [
{
"type": "template",
"name": "lookup-template",
"file": "templates/lookup.md",
"description": "Lookup target",
}
]
},
)
(pack / "templates").mkdir()
(pack / "templates" / "lookup.md").write_text("body", encoding="utf-8")
lookup_id = ArtifactCatalog(spec_kit_project).get_artifact_info(
"template:lookup-template"
)["stack"][0]["lookupId"]
result = CliRunner().invoke(
app, ["artifact", "lookup", lookup_id, "--json"]
)
assert result.exit_code == 0, result.stderr
payload = json.loads(result.stdout)
assert payload["id"] == lookup_id
assert payload["contribution"]["description"] == "Lookup target"
assert payload["sourcePath"] == (
".specify/presets/lookup-pack/templates/lookup.md"
)