Debian Codegraph @

tests/unit_tests/test_skill.py

raw
1 """The Agent Skill hsql ships, and the properties that keep it loadable.
2
3 The skill is the first thing an agent reads about hsql, and unlike the CLI it
4 has no way to fail loudly: a frontmatter key the standard does not define makes
5 the file unloadable in half the harnesses that read it, and a body that has
6 grown into a manual still loads and still costs every session that triggers it.
7 Neither shows up in a test of what hsql does, so they are asserted here.
8
9 The flag guard in `test_documented_flags.py` covers the other half -- that every
10 command line the skill types is one hsql would accept.
11 """
12
13 from __future__ import annotations
14
15 import re
16 import subprocess
17 from pathlib import Path
18 from typing import Any, Callable
19
20 import pytest
21 import yaml
22 from click.testing import CliRunner, Result
23
24 from harlequin.hsql.cli import build_cli
25 from harlequin.hsql.diagnostics import ExitCode
26 from harlequin.hsql.modes import skill as skill_mode
27
28 Hsql = Callable[..., Result]
29
30 PORTABLE_FIELDS = {
31 "name",
32 "description",
33 "license",
34 "compatibility",
35 "metadata",
36 "allowed-tools",
37 }
38 """The six fields the Agent Skills standard defines.
39
40 Claude Code accepts extension keys on top of these; the claude.ai upload and the
41 Skills API reject an unknown key outright. A skill whose whole argument is that
42 it works in any harness does not get to use one.
43 """
44
45 MAX_BODY_BYTES = 4096
46 MAX_BODY_LINES = 200
47 """What the skill's text costs every session that triggers it, capped.
48
49 The references are not capped the same way: they are read on demand, by the
50 agent that needed one, and never enter a context that did not ask for them.
51 """
52
53 REFERENCE_NAMES = {"config.md", "queries.md", "scripting.md", "troubleshooting.md"}
54
55
56 @pytest.fixture
57 def hsql(no_discovered_config: None) -> Hsql:
58 runner = CliRunner()
59
60 def _run(*args: str, **kwargs: Any) -> Result:
61 argv = [str(arg) for arg in args]
62 return runner.invoke(build_cli(argv), argv, catch_exceptions=False, **kwargs)
63
64 return _run
65
66
67 def _split(text: str) -> tuple[dict[str, Any], str]:
68 """One skill file as its frontmatter and its body."""
69 match = re.match(r"^---\n(.*?)\n---\n(.*)$", text, re.DOTALL)
70 assert match is not None, "SKILL.md must open with a YAML frontmatter block"
71 frontmatter = yaml.safe_load(match.group(1))
72 assert isinstance(frontmatter, dict)
73 return frontmatter, match.group(2)
74
75
76 @pytest.fixture
77 def frontmatter() -> dict[str, Any]:
78 return _split(skill_mode.text().decode("utf-8"))[0]
79
80
81 @pytest.fixture
82 def body() -> str:
83 return _split(skill_mode.text().decode("utf-8"))[1]
84
85
86 # --- the file, as a skill ----------------------------------------------------
87
88
89 def test_the_shipped_skill_has_lf_line_endings() -> None:
90 """`--skill` copies these bytes out verbatim, so their line endings are part
91 of what it promises, and a CRLF checkout is what takes them away: the same
92 hsql would print different bytes on Windows, and the frontmatter would stop
93 parsing. `.gitattributes` pins the directory to LF, and this is what fails,
94 naming the cause, if that pin goes missing.
95 """
96 shipped = [
97 skill_mode.SKILL_DIR / skill_mode.FILENAME,
98 *skill_mode.reference_paths(),
99 ]
100 for path in shipped:
101 assert b"\r" not in path.read_bytes(), (
102 f"{path.name} has CRLF line endings; check the .gitattributes pin on "
103 "src/harlequin/hsql/skill/"
104 )
105
106
107 def test_the_frontmatter_uses_only_the_portable_fields(
108 frontmatter: dict[str, Any],
109 ) -> None:
110 """What keeps the file loadable outside Claude Code."""
111 unknown = sorted(set(frontmatter) - PORTABLE_FIELDS)
112 assert not unknown, f"not in the Agent Skills standard: {unknown}"
113
114
115 def test_the_frontmatter_names_and_describes_the_skill(
116 frontmatter: dict[str, Any],
117 ) -> None:
118 """The description is the only part always in context, and it is what
119 decides whether the skill loads at all."""
120 assert frontmatter["name"] == "hsql"
121 assert frontmatter["description"].strip()
122
123
124 def test_the_description_names_the_contexts_as_well_as_the_capability(
125 frontmatter: dict[str, Any],
126 ) -> None:
127 """The failure mode is under-triggering, so a description that says only
128 what hsql is will not fire on the queries that should reach it."""
129 description = frontmatter["description"].lower()
130 for context in ("sql", "database", ".sql", "connection string", "export"):
131 assert context in description, f"the description never mentions {context}"
132
133
134 def test_the_granted_tools_are_the_ones_that_only_read(
135 frontmatter: dict[str, Any],
136 ) -> None:
137 """Deciding whether to run a query is the human's; deciding whether to read
138 a catalog is not. A blanket `Bash(hsql *)` would pre-approve both."""
139 granted = frontmatter["allowed-tools"]
140 assert "Bash(hsql *)" not in granted
141 for grant in granted:
142 mode = grant.removeprefix("Bash(hsql ").split()[0].rstrip("*)")
143 assert mode in {
144 "--help",
145 "--version",
146 "--info",
147 "--spec",
148 "--catalog",
149 "--catalog-search",
150 }, f"{grant} pre-approves more than introspection"
151
152
153 def test_the_body_stays_a_skill_rather_than_a_manual(body: str) -> None:
154 assert len(body.encode("utf-8")) <= MAX_BODY_BYTES
155 assert body.count("\n") <= MAX_BODY_LINES
156
157
158 def test_the_body_points_at_every_reference_that_ships(body: str) -> None:
159 """A pointer the shipped tree cannot satisfy is worse than no pointer: the
160 agent reading it cannot tell a missing file from one that never existed."""
161 shipped = {path.name for path in skill_mode.reference_paths()}
162 assert shipped == REFERENCE_NAMES
163 for name in shipped:
164 assert name in body, f"SKILL.md never mentions references/{name}"
165
166
167 def test_every_reference_is_reachable_from_the_skill_directory() -> None:
168 """`references/` is the name SKILL.md types, so it is the name it keeps."""
169 for path in skill_mode.reference_paths():
170 assert path.parent == skill_mode.SKILL_DIR / skill_mode.REFERENCES
171
172
173 # --- the mode ----------------------------------------------------------------
174
175
176 def test_skill_writes_the_packaged_file_verbatim(hsql: Hsql) -> None:
177 """The bytes are the contract, applied to the one output that is not rows."""
178 res = hsql("--skill")
179 assert res.exit_code == ExitCode.OK
180 assert res.stdout.encode("utf-8") == skill_mode.text()
181
182
183 def test_a_file_output_installs_the_whole_skill(hsql: Hsql, tmp_path: Path) -> None:
184 """The documented one-liner, and it has to leave a skill rather than a file:
185 `SKILL.md` alone would ship four pointers that resolve to nothing."""
186 destination = tmp_path / "skills" / "hsql" / "SKILL.md"
187 res = hsql("--skill", "-o", str(destination))
188 assert res.exit_code == ExitCode.OK
189 assert res.stdout == ""
190 assert destination.read_bytes() == skill_mode.text()
191 installed = {path.name for path in (destination.parent / "references").iterdir()}
192 assert installed == REFERENCE_NAMES
193
194
195 def test_a_directory_output_installs_the_whole_skill(
196 hsql: Hsql, tmp_path: Path
197 ) -> None:
198 """The other spelling of the same intent, and it lands in the same place."""
199 destination = tmp_path / "skills" / "hsql"
200 res = hsql("--skill", "-o", f"{destination}/")
201 assert res.exit_code == ExitCode.OK
202 assert (destination / "SKILL.md").read_bytes() == skill_mode.text()
203 installed = {path.name for path in (destination / "references").iterdir()}
204 assert installed == REFERENCE_NAMES
205
206
207 def test_the_install_names_every_file_it_wrote(hsql: Hsql, tmp_path: Path) -> None:
208 """The caller named one path and got five files; the other four are the one
209 thing about the run that stdout cannot carry."""
210 res = hsql("--skill", "-o", f"{tmp_path}/hsql/")
211 assert "SKILL.md" in res.stderr
212 for name in REFERENCE_NAMES:
213 assert f"references/{name}" in res.stderr
214
215
216 def test_writing_it_produces_the_same_bytes_as_printing_it(
217 hsql: Hsql, tmp_path: Path
218 ) -> None:
219 destination = tmp_path / "SKILL.md"
220 hsql("--skill", "-o", str(destination))
221 assert destination.read_bytes() == hsql("--skill").stdout.encode("utf-8")
222
223
224 def test_format_none_writes_nothing(hsql: Hsql, tmp_path: Path) -> None:
225 res = hsql("--skill", "--format", "none")
226 assert res.exit_code == ExitCode.OK
227 assert res.stdout == ""
228
229
230 def test_a_format_it_cannot_honor_says_so(hsql: Hsql) -> None:
231 """Silence would read as a format that was applied."""
232 res = hsql("--skill", "--csv")
233 assert res.exit_code == ExitCode.OK
234 assert res.stdout.encode("utf-8") == skill_mode.text()
235 assert "had no effect" in res.stderr
236
237
238 def test_skill_does_not_run_sql(hsql: Hsql) -> None:
239 res = hsql("--skill", "-c", "select 1")
240 assert res.exit_code == ExitCode.USAGE
241 assert res.stdout == ""
242 assert "--skill does not run SQL" in res.stderr
243
244
245 def test_skill_is_one_mode(hsql: Hsql) -> None:
246 res = hsql("--skill", "--info")
247 assert res.exit_code == ExitCode.USAGE
248 assert "two modes" in res.stderr
249
250
251 def test_skill_imports_no_adapter_and_reads_no_config(
252 run_python: Callable[[str], subprocess.CompletedProcess[str]],
253 ) -> None:
254 """Printing a packaged file should cost what printing a packaged file costs.
255
256 It is the one mode with nothing to look up: no adapter to ask about its
257 options, no config file to resolve a profile from, no database.
258 """
259 proc = run_python(
260 "import sys\n"
261 "sys.argv = ['hsql', '--skill']\n"
262 "from harlequin.hsql import main\n"
263 "try:\n"
264 " main()\n"
265 "except SystemExit:\n"
266 " pass\n"
267 "print(','.join(sorted({m.split('.')[0] for m in sys.modules "
268 "if m.startswith('harlequin_')})), file=sys.stderr)\n"
269 "print(','.join(m for m in ('duckdb', 'pyarrow', 'tomlkit') "
270 "if m in sys.modules), file=sys.stderr)\n"
271 )
272 adapters, forbidden = proc.stderr.split("\n")[:2]
273 assert not adapters
274 assert not forbidden