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