diff --git a/dokimi/README.md b/dokimi/README.md index 415209c0c..8985530f9 100644 --- a/dokimi/README.md +++ b/dokimi/README.md @@ -206,7 +206,7 @@ The default static benchmark is configured in `benchmarks/spec.v1.yaml` and curr | `readability` | Estimates text readability with a Flesch-Kincaid-style score. | | `example_pass_rate` | Executes supported fenced code examples in isolation. | -Weights are normalized across enabled metrics. The benchmark also supports soft gates, hard gates, critical bands, and regression thresholds. Hard gates and critical bands are enforced only when `--strict` is passed. With `--strict`, a spec without a `golden_manifest` also exits 1 when no document was measured. A spec with one, as `spec.v1.yaml` has, exits 2 with or without `--strict` when fewer documents than its `min_docs` match, none included. An empty or absolute `include` pattern exits 2 as well. With `--strict`, a critical band the gate cannot read (an unknown condition, or a `None` metric) exits 2 too. Exit 1 is not only the `--strict` verdict: a document that cannot be read, or an `--out` or `--out-md` path that cannot be written, also exits 1, with an `Error:` or `❌` line on stderr saying which. +Weights are normalized across enabled metrics. The benchmark also supports soft gates, hard gates, critical bands, and regression thresholds. Hard gates and critical bands are enforced only when `--strict` is passed. With `--strict`, a spec without a `golden_manifest` also exits 1 when no document was measured. A spec with one, as `spec.v1.yaml` has, exits 2 with or without `--strict` when fewer documents than its `min_docs` match, none included. An empty or absolute `include` pattern exits 2 as well, and so does a directory an `include` pattern has to list that cannot be listed (the error names it), since the documents under it would otherwise be missing from the count. With `--strict`, a critical band the gate cannot read (an unknown condition, or a `None` metric) exits 2 too. Exit 1 is not only the `--strict` verdict: a document that cannot be read, or an `--out` or `--out-md` path that cannot be written, also exits 1, with an `Error:` or `❌` line on stderr saying which. ## LLM and treatment evaluation workflow diff --git a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md new file mode 100644 index 000000000..3d731b065 --- /dev/null +++ b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A `golden_manifest` `include` pattern that has to list a directory it cannot list is an error, not a smaller document set** — `select_docs` skipped such a directory (mode `0o111`, non-root), so `docs/**/*.md` with an unlistable `docs/sub` selected `docs/top.md` alone and counted that against `min_docs` and `max_docs`. It now raises `DocSelectionError` naming the directory (`benchmark run` exits 2). The walk follows `Path.glob`: a directory a wildcard part reaches through a link is listed too, while a directory the pattern never lists (outside the root, under an `exclude` entry that drops everything below it such as `docs/sub/**`, or one whose pattern matches every document the include can still select below it such as `docs/*.md` for `docs/**/*.md`, not one for a single file name such as `docs/*/x`, or only named by a literal part such as the `sub` of `docs/sub/a.md` or the `a.md` of `docs/*/a.md`) is still not an error, except that a directory with a link to a directory below it, or an include with a `..` part left to walk, is not left out for an `exclude` entry, since the entry is judged on the name the walk reaches the path by and the selection on where the link or the `..` leads (#1383). diff --git a/dokimi/changelog.d/20261204_100100_skill-links-unlistable.md b/dokimi/changelog.d/20261204_100100_skill-links-unlistable.md new file mode 100644 index 000000000..7e057dcd6 --- /dev/null +++ b/dokimi/changelog.d/20261204_100100_skill-links-unlistable.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A skill folder that cannot be listed is refused by the skill arm's link check, not left unchecked** — `check_skill` walked the skill without an `onerror`, so a link out of the skill inside a hidden or vendored folder, or any folder under `__pycache__`, it could not list (mode `0o111`, non-root) went unchecked, and `build_plugin` then failed in the copy with a `shutil.Error`. `check_skill` and `build_plugin` now raise a `ValueError` naming the folder before the copy, from the link check and from the loop check. A folder `load_skill` already refuses keeps its error (#1479). diff --git a/dokimi/changelog.d/20261204_100200_provenance-unlistable.md b/dokimi/changelog.d/20261204_100200_provenance-unlistable.md new file mode 100644 index 000000000..013a6d3d8 --- /dev/null +++ b/dokimi/changelog.d/20261204_100200_provenance-unlistable.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **`catalog provenance` exits 2 for a directory under `--root` that cannot be listed, instead of a smaller table** — the scan's error row for such a directory has no `SKILL.md`, and the command skipped it without a word, so the skills under it were missing from the table and its summary. It now exits 2 naming the directory and prints no table. A `SKILL.md` that is a link out of `--root` counts as none, since the command does not read it. A manifest entry with no file is still skipped, as `catalog check` reports it (#1480). diff --git a/dokimi/docs/coding-harnesses.md b/dokimi/docs/coding-harnesses.md index fe4f51781..38ba45f6f 100644 --- a/dokimi/docs/coding-harnesses.md +++ b/dokimi/docs/coding-harnesses.md @@ -1001,7 +1001,9 @@ The arms differ by the skill and one notice, and by nothing else: copied as the files they point to, and only when they point inside the skill directory and outside its `evals/`: a link out of the skill could ship a task's `solution/` and `tests/`, and a link to an ancestor would copy - the checkout into itself. Such a skill fails the cell before the image build. + the checkout into itself. Such a skill fails the cell before the image build, + and so does one with a folder that cannot be listed (a hidden or vendored one, + or one under `__pycache__`, where a link would go unchecked and the copy would fail on it). - `$CLAUDE_CONFIG_DIR/skills` does not work here: it is not loaded under `--setting-sources ""` (measured, Claude Code 2.1.286). - `--setting-sources project` would also read the task tree's own diff --git a/dokimi/docs/external-content.md b/dokimi/docs/external-content.md index 0a90501a6..37f7e4112 100644 --- a/dokimi/docs/external-content.md +++ b/dokimi/docs/external-content.md @@ -604,6 +604,7 @@ directory name, is the name for a `similar` match. A checkout that lacks blobs o partial clone) reports `history: partial` with `missing_blobs`; fetch them for an exact count. When a manifest leaves the head of the matched path unspecified, the behind column reads `unknown`. Its JSON fields `at_head`, `behind_commits`, and `behind_months` are null. `--format json` adds the upstreams, one row per skill and a `summary`. +A directory under `--root` that cannot be listed and holds no `SKILL.md`, above the skills, exits 2 and names the directory (`--root: cannot be listed (Permission denied), so the skills under it may be missing`) with no table, since the table would describe a smaller tree. ### Upstream findings in `catalog check` (`--upstream`, `--upstream-manifest`) diff --git a/dokimi/dokimi/commands/catalog_provenance.py b/dokimi/dokimi/commands/catalog_provenance.py index 46c79c4f7..e82d334c7 100644 --- a/dokimi/dokimi/commands/catalog_provenance.py +++ b/dokimi/dokimi/commands/catalog_provenance.py @@ -82,6 +82,30 @@ def _skill_file(entry, root: Path) -> Path | None: return path +def _holds_skill_file(folder: Path, root: Path) -> bool: + """Whether ``folder/SKILL.md`` is a file under *root*; a folder that cannot even be searched (mode 000) holds none we can load. + + A directory, a dangling link or a link out of *root* named ``SKILL.md`` is no file for :func:`_skill_file`, so it hides the skills beside it. + """ + skill_file = folder / "SKILL.md" + try: + return skill_file.is_file() and skill_file.resolve().is_relative_to(root.resolve()) + except OSError: + return False + + +def _refuse_unlisted(entries: list, root: Path) -> None: + """Refuse the scan's error row of a directory above the skills that cannot be listed (#1480). + + The row has no ``SKILL.md`` under its path, so :func:`_skill_file` gives None for it; the table would describe a + smaller tree than ``--root``. A row of a skill that does load or fails its own load is not one. + """ + for entry in entries: + folder = entry.path + if entry.unlisted and entry.error and folder is not None and folder.is_dir() and not _holds_skill_file(folder, root): + raise InputError(f"--root: {entry.error}") + + def cmd_catalog_provenance(args: argparse.Namespace) -> None: from dokimi.external import read_skill_manifest from dokimi.external import upstream @@ -98,10 +122,13 @@ def cmd_catalog_provenance(args: argparse.Namespace) -> None: entries = read_skill_manifest(root) except ValueError as exc: raise InputError(f"skills.yaml: {exc}") from exc + _refuse_unlisted(entries, root) if (root / "skills.yaml").is_file(): # The manifest lists some skills; every other SKILL.md under --root is still a copy to report. listed = {f.resolve() for f in (_skill_file(e, root) for e in entries) if f is not None} - entries = [*entries, *(e for e in _scan_skill_files(root) + scanned = _scan_skill_files(root) + _refuse_unlisted(scanned, root) + entries = [*entries, *(e for e in scanned if (f := _skill_file(e, root)) is not None and f.resolve() not in listed)] rows = [] for entry in entries: diff --git a/dokimi/dokimi/harnesses/skill_treatment.py b/dokimi/dokimi/harnesses/skill_treatment.py index a54bb886d..c4e7fcc34 100644 --- a/dokimi/dokimi/harnesses/skill_treatment.py +++ b/dokimi/dokimi/harnesses/skill_treatment.py @@ -46,6 +46,7 @@ from typing import Any, Iterator, Optional from dokimi.skills import load_skill +from dokimi.skills.loader import _not_listed_as_resource from dokimi.skills.listing import listing_description, listing_text_chars from dokimi.frontmatter import parse_frontmatter @@ -139,6 +140,19 @@ def check_skill(skill_dir: Path) -> str: return skill.name +def _refuse_unlisted(exc: OSError, skill_dir: Path) -> None: + """``os.walk``'s ``onerror`` and the loop check's: a folder that cannot be listed is a ``ValueError`` (#1479). + + A link in it would go unchecked, and the copy would then fail on it with a ``shutil.Error``. A folder + :func:`load_skill` refuses (not under a dot-named, vendored or ``__pycache__`` one it leaves out) is left to it. + """ + folder = Path(str(exc.filename)) + inside = [folder, *folder.parents][:len(folder.relative_to(skill_dir).parts)] # up to the skill, not above it + if any(_not_listed_as_resource(p) for p in inside): + raise ValueError(f"skill folder {folder} cannot be listed ({exc.strerror}), " + "so the links in it are not checked and the copy would fail") + + def _check_links(skill_dir: Path) -> None: """Refuse a link that leaves the skill, points into its ``evals/``, loops, or dangles. @@ -148,7 +162,7 @@ def _check_links(skill_dir: Path) -> None: the checkout into itself until ``ELOOP``. """ root = skill_dir.resolve() - for dirpath, dirnames, filenames in os.walk(skill_dir): # does not descend into links + for dirpath, dirnames, filenames in os.walk(skill_dir, onerror=lambda exc: _refuse_unlisted(exc, skill_dir)): # does not descend into links here = Path(dirpath) if here == skill_dir: # the top-level evals/ is not copied, see build_plugin dirnames[:] = [d for d in dirnames if d != "evals"] @@ -183,8 +197,9 @@ def visit(directory: Path, real: Path, stack: tuple[Path, ...]) -> None: with os.scandir(directory) as entries: children = [Path(e.path) for e in entries if e.is_dir() and not (directory == skill_dir and e.name == "evals")] - except OSError: - return # unreadable, as os.walk would have skipped it: the copy reports it + except OSError as exc: + _refuse_unlisted(exc, skill_dir) + return # one load_skill refuses next, naming it for child in children: target = child.resolve() if not target.is_relative_to(root) or target in done: diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index ae5b7898d..023d60489 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -11,9 +11,11 @@ from __future__ import annotations +import errno import fnmatch import itertools import os +import re from pathlib import Path import yaml @@ -117,6 +119,53 @@ def _is_excluded(rel_path: str, patterns: list[str]) -> bool: return False +def _excludes_subtree(rel_dir: str, patterns: list[str]) -> bool: + """Whether the exclude ``patterns`` drop every file below the directory ``rel_dir``, not only one name in it. + + A pattern does when it names the directory or a parent (``docs/sub``, ``docs/sub/**``), or one of its forms ends in + ``*``, which crosses ``/`` in fnmatch, and matches the directory (``docs/s*``) or the directory and a ``/`` + (``docs/sub/*``). ``docs/*/x`` drops one file name below it, not the subtree; nor does ``docs/sub?/**``, whose + form ``docs/sub?`` matches ``docs/sub/`` through the ``?`` but no file below it. + """ + for pattern in patterns: + prefix = pattern.rstrip("/").removesuffix("/**").rstrip("/") + if rel_dir == prefix or rel_dir.startswith(prefix + "/"): + return True + if any(form.endswith("*") and fnmatch.fnmatch(rel_dir + "/", form) for form in _zero_dir_forms(pattern)): + return True + return False # mutation-ok[return-none]: None is as false as False + + +# fnmatch's class: ``[``, an optional ``!``, an optional ``]`` that is a member, the rest up to the closing ``]`` +_BRACKET_OR_WILDCARD = re.compile(r"\[!?\]?[^\]]*\]|[*?]") + + +def _can_rename(directory: Path, parts: tuple[str, ...]) -> bool: + """Whether a path below ``directory`` can resolve to another name than the one the walk reaches it by. + + An exclude is judged on the resolved name of a document, so it drops a directory's documents by that directory's + name only when no link to a directory (it may lead out or to a sibling) and no ``..`` part of the include is left. + """ + if ".." in parts: + return True + # a directory it cannot list is skipped: it shows no link + return any((Path(here) / name).is_symlink() for here, dirs, _files in os.walk(directory) for name in dirs) + + +def _excludes_selection(rel_dir: str, parts: tuple[str, ...], patterns: list[str]) -> bool: + """Whether the exclude ``patterns`` drop every file the include ``parts`` can still select below ``rel_dir``. + + A form of an exclude pattern made of literals and ``*`` covers a form of the include when it matches that form with + each of the include's wildcards replaced by a character no literal of the exclude has: the ``*`` of the exclude + take the place of whatever the wildcards match. ``docs/*.md`` covers ``docs/restricted/**/*.md``. A form with ``?`` + or ``[`` is never taken to cover, so that the directory is refused as before. + """ + include_forms = {f"{rel_dir}/{form}" if rel_dir else form for form in _zero_dir_forms("/".join(parts))} + samples = {"/".join(_BRACKET_OR_WILDCARD.sub("\0", seg) for seg in form.split("/")) for form in include_forms} + forms = {form for pattern in patterns for form in _zero_dir_forms(pattern) if not any(c in form for c in "?[")} + return any(all(fnmatch.fnmatchcase(sample, form) for sample in samples) for form in forms) + + def _literal_prefix(root: Path, pattern: str) -> Path: """The leading path of ``pattern`` without wildcards, cut at the first part that is a symlink.""" base = Path() @@ -181,6 +230,79 @@ def _symlink_note(root: Path, include: list[str], exclude: list[str], escaped: l return (" " + "; ".join(notes) + ".") if notes else "" +def _refuse_unlistable(root: Path, pattern: str, exclude: list[str]) -> None: + """Raise :class:`DocSelectionError` for a directory the include ``pattern`` has to list and cannot (#1383). + + ``Path.glob`` skips such a directory, so the documents under it would be missing from a set that is then + counted against ``min_docs``. Only a directory a wildcard part lists is an error: one the exclude list drops with + everything below it (``docs/sub`` or ``docs/sub/**``, not ``docs/[s]ub``, which drops the directory and no file), one + outside ``root``, one whose every document the include can still select an exclude pattern drops (``docs/*.md`` + for the ``docs/**/*.md`` below ``docs/sub``), one only named (a literal part, however it is reached) and a path that is not there are not. + A literal part is followed also outside ``root`` and through an excluded directory, since ``..`` or a link can lead + back in; only a directory a wildcard lists is pruned, and not one with a link to a directory below it or a ``..`` + part of the include left (:func:`_can_rename`). + """ + root_resolved = root.resolve() + seen: set[tuple[Path, tuple[str, ...]]] = set() + + def walk(directory: Path, parts: tuple[str, ...]) -> None: + try: + real = directory.resolve() + except (RuntimeError, OSError): # a loop of links leads nowhere + return + lists = any(c in parts[0] for c in "*?[") # a name is only looked up, so it needs no pruning + # mutation-ok[drop-clause]: ``seen`` only keeps ``**/**`` from walking a directory twice + if (lists and not real.is_relative_to(root_resolved)) or (real, parts) in seen: # outside: never selected + return + seen.add((real, parts)) # mutation-ok[delete-statement]: see above + if lists: + rel = "" if real == root_resolved else real.relative_to(root_resolved).as_posix() + dropped = (rel and _excludes_subtree(rel, exclude)) or _excludes_selection(rel, parts, exclude) + if dropped and not _can_rename(real, parts): # a link or a ``..`` below is judged by where it leads + return + for child, remaining in _next_steps(directory, parts): + walk(child, remaining) + + walk(root, Path(pattern).parts) + + +def _next_steps(directory: Path, parts: tuple[str, ...]) -> list[tuple[Path, tuple[str, ...]]]: + """Where ``Path.glob`` goes from ``directory`` with ``parts``: a name is entered, a wildcard lists, ``**`` skips links.""" + head, rest = parts[0], parts[1:] + recursive = head == "**" + if not any(c in head for c in "*?["): # ``**`` has a ``*`` + return [(directory / head, rest)] if rest else [] # the last name is looked up, not listed + steps = [] + for entry in _scan(directory): + if recursive and _is_dir(entry, follow_symlinks=False): + steps.append((Path(entry.path), parts)) + elif not recursive and rest and fnmatch.fnmatch(entry.name, head) and _is_dir(entry): + steps.append((Path(entry.path), rest)) + # mutation-ok[drop-clause]: a wildcard part walking its own directory again lists only what it listed already + if recursive and rest: # ``**`` also matches no directory + steps.append((directory, rest)) + return steps + + +def _scan(directory: Path) -> list[os.DirEntry[str]]: + """The entries of ``directory``; none for a path that is not there, :class:`DocSelectionError` if it cannot be listed.""" + try: + with os.scandir(directory) as entries: + return list(entries) + except OSError as exc: + if exc.errno in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP): + return [] + raise DocSelectionError(f"cannot list {exc.filename}: {exc.strerror}") from exc + + +def _is_dir(entry: os.DirEntry[str], follow_symlinks: bool = True) -> bool: + """``entry.is_dir``, false for a link whose target cannot be reached (``Path.glob`` leaves it out too).""" + try: + return entry.is_dir(follow_symlinks=follow_symlinks) + except OSError: + return False # mutation-ok[return-none]: None is as false as False + + def select_docs(root: Path, manifest: dict) -> list[Path]: """Resolve and bound the document set from a ``golden_manifest``. @@ -200,6 +322,7 @@ def select_docs(root: Path, manifest: dict) -> list[Path]: matches = list(root.glob(pattern)) except (ValueError, NotImplementedError) as exc: # an empty or absolute pattern raise DocSelectionError(f"golden_manifest include pattern {pattern!r}: {exc}") from exc + _refuse_unlistable(root, pattern, exclude) for p in matches: # Reject matches that escape root (e.g. via ".." in a pattern). if not p.is_file(): diff --git a/dokimi/tests/test_provenance_unlistable.py b/dokimi/tests/test_provenance_unlistable.py new file mode 100644 index 000000000..4320a427f --- /dev/null +++ b/dokimi/tests/test_provenance_unlistable.py @@ -0,0 +1,113 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1480: ``catalog provenance`` exits 2 for a directory above the skills that cannot be listed, where it skipped the +scan's error row for it and printed a smaller table. The directories have mode 111.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from dokimi.cli import build_parser +from dokimi.files import InputError +from tests.test_unlistable_sites import FRONTMATTER, unlistable + + +def _root(tmp_path: Path, files: dict[str, str]) -> Path: + root = tmp_path / "root" + for rel, text in files.items(): + (root / rel).parent.mkdir(parents=True, exist_ok=True) + (root / rel).write_text(text, encoding="utf-8") + return root + + +def _provenance(tmp_path: Path, root: Path, capsys: pytest.CaptureFixture[str]) -> list[str]: + manifest = tmp_path / "up.json" + manifest.write_text(json.dumps({ + "schema": "dokimi.upstream.v1", "name": "acme", + "head": {"commit": "abc123", "date": "2026-06-01T00:00:00+00:00"}, + "skills": [{"path": "skills/demo/SKILL.md", "content": FRONTMATTER}], + }), encoding="utf-8") + args = build_parser().parse_args(["catalog", "provenance", "--root", str(root), "--upstream-manifest", + str(manifest), "--format", "json"]) + args.func(args) + return sorted(row["skill"] for row in json.loads(capsys.readouterr().out)["skills"]) + + +def test_provenance_of_a_listable_root_gives_one_row_per_skill(tmp_path: Path, capsys: pytest.CaptureFixture[str]): + root = _root(tmp_path, {"a/SKILL.md": FRONTMATTER, "sub/x/SKILL.md": FRONTMATTER}) + assert _provenance(tmp_path, root, capsys) == ["a", "sub/x"] + + +@pytest.mark.parametrize("mode", [0o111, 0o000]) +@pytest.mark.parametrize("manifest", [False, True]) +def test_provenance_refuses_a_directory_above_the_skills_that_cannot_be_listed( + tmp_path: Path, capsys: pytest.CaptureFixture[str], manifest: bool, mode: int): + root = _root(tmp_path, {"a/SKILL.md": FRONTMATTER, "sub/x/SKILL.md": FRONTMATTER}) + if manifest: + (root / "skills.yaml").write_text("skills:\n - name: demo\n catalog_path: a\n", encoding="utf-8") + with unlistable(root / "sub", mode), pytest.raises(InputError, match=r"--root: .*root/sub cannot be listed"): + _provenance(tmp_path, root, capsys) + assert capsys.readouterr().out == "" + + +@pytest.mark.parametrize("manifest", [False, True]) +@pytest.mark.parametrize("kind", ["directory", "dangling link"]) +def test_provenance_refuses_an_unlistable_folder_whose_skill_md_is_no_file( + tmp_path: Path, capsys: pytest.CaptureFixture[str], manifest: bool, kind: str): + root = _root(tmp_path, {"a/SKILL.md": FRONTMATTER, "sub/x/SKILL.md": FRONTMATTER}) + if kind == "directory": + (root / "sub/SKILL.md").mkdir() + else: + (root / "sub/SKILL.md").symlink_to("nowhere") + if manifest: + (root / "skills.yaml").write_text("skills:\n - name: demo\n catalog_path: a\n", encoding="utf-8") + with unlistable(root / "sub"), pytest.raises(InputError, match=r"--root: .*root/sub cannot be listed"): + _provenance(tmp_path, root, capsys) + assert capsys.readouterr().out == "" + + +@pytest.mark.parametrize("manifest", [False, True]) +def test_provenance_refuses_an_unlistable_folder_whose_skill_md_is_a_link_out_of_the_root( + tmp_path: Path, capsys: pytest.CaptureFixture[str], manifest: bool): + root = _root(tmp_path, {"a/SKILL.md": FRONTMATTER, "sub/x/SKILL.md": FRONTMATTER}) + outside = tmp_path / "outside.md" + outside.write_text(FRONTMATTER, encoding="utf-8") + (root / "sub/SKILL.md").symlink_to(outside) + if manifest: + (root / "skills.yaml").write_text("skills:\n - name: demo\n catalog_path: a\n", encoding="utf-8") + with unlistable(root / "sub"), pytest.raises(InputError, match=r"--root: .*root/sub cannot be listed"): + _provenance(tmp_path, root, capsys) + assert capsys.readouterr().out == "" + + +def test_provenance_refuses_an_unlistable_folder_when_the_skill_md_lookup_raises( + tmp_path: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch): + """Python 3.11 and 3.12 raise PermissionError from ``is_file`` for a name inside a folder with mode 000.""" + root = _root(tmp_path, {"a/SKILL.md": FRONTMATTER, "sub/x/SKILL.md": FRONTMATTER}) + is_file = Path.is_file + + def raising(self: Path) -> bool: + if self.name == "SKILL.md" and self.parent.name == "sub": + raise PermissionError(13, "Permission denied", str(self)) + return is_file(self) + + monkeypatch.setattr(Path, "is_file", raising) + with unlistable(root / "sub"), pytest.raises(InputError, match=r"--root: .*root/sub cannot be listed"): + _provenance(tmp_path, root, capsys) + + +def test_provenance_keeps_a_skill_whose_own_folder_cannot_be_listed(tmp_path: Path, capsys: pytest.CaptureFixture[str]): + root = _root(tmp_path, {"a/SKILL.md": FRONTMATTER, "a/references/r.md": "r"}) + with unlistable(root / "a/references"): + assert _provenance(tmp_path, root, capsys) == ["a"] + + +def test_provenance_skips_a_manifest_entry_with_no_file(tmp_path: Path, capsys: pytest.CaptureFixture[str]): + root = _root(tmp_path, {"a/SKILL.md": FRONTMATTER}) + (root / "skills.yaml").write_text( + "skills:\n - name: demo\n catalog_path: a\n - name: gone\n catalog_path: gone\n", encoding="utf-8") + assert _provenance(tmp_path, root, capsys) == ["a"] diff --git a/dokimi/tests/test_select_docs_link_loops.py b/dokimi/tests/test_select_docs_link_loops.py new file mode 100644 index 000000000..a2b36303e --- /dev/null +++ b/dokimi/tests/test_select_docs_link_loops.py @@ -0,0 +1,55 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1383: a link that loops, or that ``resolve`` cannot follow, leads nowhere: ``select_docs`` does not take it for an +unlistable directory its pattern walks, and the ``min_docs`` error comes out as before. The helper is called itself +for the ``resolve`` failure, as ``_outside_links`` on this base does not guard it.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from dokimi.runner.spec import DocSelectionError, _refuse_unlistable, select_docs + + +def _link(path: Path, target: Path) -> None: + try: + path.symlink_to(target, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + + +def _failing_resolve(monkeypatch: pytest.MonkeyPatch, name: str, exc: Exception) -> None: + real = Path.resolve + + def resolve(self: Path, *args, **kwargs): + if self.name == name: + raise exc + return real(self, *args, **kwargs) + + monkeypatch.setattr(Path, "resolve", resolve) + + +@pytest.mark.parametrize("exc", [RuntimeError("Symlink loop from 'docs'"), OSError(40, "Too many levels of links")]) +def test_the_unlistable_check_walks_nothing_under_a_docs_link_resolve_cannot_follow( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, exc: Exception +): + _link(tmp_path / "docs", tmp_path / "docs") + _failing_resolve(monkeypatch, "docs", exc) + _refuse_unlistable(tmp_path, "docs/**/*.md", []) + + +def test_select_docs_min_docs_error_on_a_loop_below_the_pattern_base_is_a_selection_error(tmp_path: Path): + (tmp_path / "docs").mkdir() + _link(tmp_path / "docs" / "sub", tmp_path / "docs" / "sub") + with pytest.raises(DocSelectionError, match="fewer than min_docs=1"): + select_docs(tmp_path, {"include": ["docs/**/*.md"], "min_docs": 1}) + + +def test_select_docs_keeps_the_documents_beside_a_loop_below_the_pattern_base(tmp_path: Path): + (tmp_path / "docs").mkdir() + (tmp_path / "docs" / "a.md").write_text("a", encoding="utf-8") + _link(tmp_path / "docs" / "sub", tmp_path / "docs" / "sub") + assert [p.name for p in select_docs(tmp_path, {"include": ["docs/**/*.md"], "min_docs": 1})] == ["a.md"] diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py new file mode 100644 index 000000000..c9f1a6b5c --- /dev/null +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -0,0 +1,343 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1383: ``select_docs`` raises for a directory its include pattern has to list and cannot, where ``Path.glob`` left +the directory out and the smaller set was counted against ``min_docs``. The directories have mode 111.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from dokimi.runner.spec import DocSelectionError, select_docs +from tests.test_unlistable_sites import unlistable + + +def _docs(tmp_path: Path) -> Path: + root = tmp_path / "root" + for rel in ("docs/top.md", "docs/sub/a.md", "docs/sub/deep/x.md", "other/o.md"): + (root / rel).parent.mkdir(parents=True, exist_ok=True) + (root / rel).write_text(rel, encoding="utf-8") + return root + + +def _names(root: Path, include: list[str], exclude: list[str] | None = None) -> list[str]: + return sorted(p.name for p in select_docs(root, {"include": include, "exclude": exclude or []})) + + +def test_select_docs_of_a_listable_tree_gives_every_document(tmp_path: Path): + assert _names(_docs(tmp_path), ["docs/**/*.md"]) == ["a.md", "top.md", "x.md"] + + +def test_select_docs_names_a_directory_the_pattern_walks_and_cannot_list(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub: \S"): + select_docs(root, {"include": ["docs/**/*.md"], "exclude": [], "min_docs": 1}) + + +def test_select_docs_does_not_count_the_smaller_set_against_min_docs(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match="cannot list") as caught: + select_docs(root, {"include": ["docs/**/*.md"], "min_docs": 3}) + assert "min_docs" not in str(caught.value) + + +def test_select_docs_ignores_an_unlistable_directory_outside_the_pattern(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "other"): + assert _names(root, ["docs/**/*.md"]) == ["a.md", "top.md", "x.md"] + + +def test_select_docs_ignores_an_unlistable_directory_no_match_can_lie_under(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub/deep"): + assert _names(root, ["docs/*/a.md"]) == ["a.md"] + + +def test_select_docs_looks_up_a_literal_last_name_in_a_directory_it_cannot_list(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"): + assert _names(root, ["docs/*/a.md"]) == ["a.md"] + with pytest.raises(DocSelectionError, match="docs/sub"): + select_docs(root, {"include": ["docs/sub/*.md"]}) + + +def test_select_docs_ignores_an_unlistable_directory_the_exclude_list_drops(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"): + assert _names(root, ["docs/**/*.md"], ["docs/sub/**"]) == ["top.md"] + assert _names(root, ["docs/**/*.md"], ["docs/sub"]) == ["top.md"] + + +def test_select_docs_refuses_a_directory_the_exclude_list_drops_without_the_files_below_it(tmp_path: Path): + root = _docs(tmp_path) + assert _names(root, ["docs/**/*.md"], ["docs/[s]ub"]) == ["a.md", "top.md", "x.md"] + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub"): + select_docs(root, {"include": ["docs/**/*.md"], "exclude": ["docs/[s]ub"]}) + + +def test_select_docs_refuses_a_directory_an_exclude_of_one_file_name_below_it_leaves_documents_in(tmp_path: Path): + root = _docs(tmp_path) + assert _names(root, ["docs/**/*.md"], ["docs/*/x"]) == ["a.md", "top.md", "x.md"] + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub"): + select_docs(root, {"include": ["docs/**/*.md"], "exclude": ["docs/*/x"]}) + + +def test_select_docs_ignores_an_unlistable_directory_a_trailing_wildcard_exclude_drops(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"): + assert _names(root, ["docs/**/*.md"], ["docs/s*"]) == ["top.md"] + + +def test_select_docs_ignores_an_unlistable_directory_an_exclude_of_everything_in_it_drops(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"): + assert _names(root, ["docs/**/*.md"], ["docs/sub/*"]) == ["top.md"] + assert _names(root, ["docs/**/*.md"], ["docs/*/*"]) == ["top.md"] + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub"): + select_docs(root, {"include": ["docs/**/*.md"], "exclude": ["docs/sub/a*"]}) + + +def test_select_docs_refuses_a_directory_only_a_non_wildcard_form_of_an_exclude_matches(tmp_path: Path): + root = _docs(tmp_path) + assert _names(root, ["docs/**/*.md"], ["docs/sub?/**"]) == ["a.md", "top.md", "x.md"] + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub"): + select_docs(root, {"include": ["docs/**/*.md"], "exclude": ["docs/sub?/**"]}) + + +def test_select_docs_ignores_an_unlistable_directory_whose_every_selectable_document_an_exclude_drops(tmp_path: Path): + root = _docs(tmp_path) + (root / "README.md").write_text("readme", encoding="utf-8") + include = ["README.md", "docs/**/*.md"] + with unlistable(root / "docs/sub"): + assert _names(root, include, ["docs/*.md"]) == ["README.md"] + assert _names(root, ["docs/sub/*.md"], ["docs/*.md"]) == [] + for exclude in (["docs/*.txt"], ["docs/a*.md"], ["docs/?.md"], ["docs/sub/?*.md"], ["docs/sub/a.md"], ["docs/sub/*/*.md"]): + with pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub"): + select_docs(root, {"include": include, "exclude": exclude}) + + +def test_select_docs_does_not_list_a_path_the_pattern_only_names(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"): + assert _names(root, ["docs/sub", "docs/top.md"]) == ["top.md"] + assert _names(root, ["docs/sub/a.md"]) == ["a.md"] + + +def test_select_docs_of_a_pattern_under_a_missing_directory_selects_nothing(tmp_path: Path): + assert _names(_docs(tmp_path), ["nothere/**/*.md"]) == [] + + +def test_select_docs_lists_a_linked_directory_that_stays_inside_the_root(tmp_path: Path): + root = _docs(tmp_path) + try: + (root / "alias").symlink_to(root / "docs", target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match="alias/sub"): + select_docs(root, {"include": ["alias/**/*.md"]}) + + +def test_select_docs_does_not_list_a_linked_directory_outside_the_root(tmp_path: Path): + root = _docs(tmp_path) + outside = tmp_path / "outside" + outside.mkdir() + (outside / "o.md").write_text("o", encoding="utf-8") + try: + (root / "link").symlink_to(outside, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + with unlistable(outside): + assert _names(root, ["docs/**/*.md", "link/*.md"]) == ["a.md", "top.md", "x.md"] + + +def test_select_docs_does_not_list_a_directory_a_dotdot_pattern_leaves_the_root_for(tmp_path: Path): + root = _docs(tmp_path) + outside = tmp_path / "outside" + outside.mkdir() + with unlistable(outside): + assert _names(root, ["docs/**/*.md", "../outside/**/*.md"]) == ["a.md", "top.md", "x.md"] + + +def test_select_docs_does_not_list_the_directory_an_exclude_drops_where_a_literal_path_starts(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"): + assert _names(root, ["docs/top.md", "docs/sub/**/*.md"], ["docs/sub/**"]) == ["top.md"] + + +def test_select_docs_ignores_an_unlistable_directory_below_one_the_exclude_list_names(tmp_path: Path): + root = _docs(tmp_path) + _link(root / "alias", root / "docs/sub/deep") + with unlistable(root / "docs/sub/deep"): + assert _names(root, ["alias/*.md"], ["docs/sub"]) == [] + with pytest.raises(DocSelectionError, match=r"cannot list .*/root/alias"): + select_docs(root, {"include": ["alias/*.md"], "exclude": ["docs/other"]}) + + +def test_select_docs_does_not_list_a_directory_a_literal_path_reaches_through_a_link(tmp_path: Path): + root = _docs(tmp_path) + _link(root / "alias", root / "docs/sub") + with unlistable(root / "docs/sub"): + assert _names(root, ["alias/a.md"]) == ["a.md"] + + +def test_select_docs_lists_a_directory_a_link_leads_to_through_a_wildcard_part(tmp_path: Path): + root = _docs(tmp_path) + (root / "shared/locked").mkdir(parents=True) + (root / "shared/locked/b.md").write_text("b", encoding="utf-8") + (root / "docs/ok").mkdir() + (root / "docs/ok/c.md").write_text("c", encoding="utf-8") + _link(root / "docs/alias", root / "shared/locked") + assert _names(root, ["docs/*/*.md"]) == ["a.md", "b.md", "c.md"] + with unlistable(root / "shared/locked"), pytest.raises(DocSelectionError, match="cannot list .*alias"): + select_docs(root, {"include": ["docs/*/*.md"], "min_docs": 1}) + + +def test_select_docs_lists_a_link_the_zero_directory_case_of_a_double_star_reaches(tmp_path: Path): + root = _docs(tmp_path) + (root / "shared/locked").mkdir(parents=True) + _link(root / "docs/alias", root / "shared/locked") + with unlistable(root / "shared/locked"), pytest.raises(DocSelectionError, match="cannot list .*alias"): + select_docs(root, {"include": ["docs/**/*/*.md"]}) + + +def test_select_docs_does_not_follow_a_link_through_a_double_star(tmp_path: Path): + root = _docs(tmp_path) + (root / "shared/locked").mkdir(parents=True) + _link(root / "docs/alias", root / "shared/locked") + with unlistable(root / "shared/locked"): + assert _names(root, ["docs/**/*.md"]) == ["a.md", "top.md", "x.md"] + + +def test_select_docs_lists_the_directory_a_pattern_ending_in_a_double_star_covers(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match="docs/sub"): + select_docs(root, {"include": ["docs/**"]}) + + +def test_select_docs_of_a_pattern_ending_in_a_double_star_over_a_listable_tree_raises_nothing(tmp_path: Path): + assert set(_names(_docs(tmp_path), ["docs/**"])) <= {"a.md", "top.md", "x.md"} # files too on 3.13+, none before + + +def test_select_docs_does_not_enter_a_directory_the_last_wildcard_part_matches(tmp_path: Path): + root = _docs(tmp_path) + (root / "docs/dir.md").mkdir() + with unlistable(root / "docs/dir.md"): + assert _names(root, ["docs/*.md"]) == ["top.md"] + + +def test_select_docs_enters_only_the_directories_a_wildcard_part_matches(tmp_path: Path): + root = _docs(tmp_path) + (root / "docs/other").mkdir() + with unlistable(root / "docs/other"): + assert _names(root, ["docs/s*/*.md"]) == ["a.md"] + + +def test_select_docs_walks_a_pattern_from_the_root_an_exclude_of_dot_names_does_not_drop(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match="docs/sub"): + select_docs(root, {"include": ["docs/**/*.md"], "exclude": [".*"]}) + + +def test_select_docs_leaves_out_a_link_whose_target_cannot_be_reached(tmp_path: Path): + root = _docs(tmp_path) + (root / "shared/locked/inner").mkdir(parents=True) + _link(root / "docs/alias", root / "shared/locked/inner") + with unlistable(root / "shared/locked", 0o000): + assert _names(root, ["docs/*/*.md"]) == ["a.md"] + + +def test_select_docs_ignores_an_unlistable_directory_a_wildcard_with_a_question_mark_exclude_drops(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"): + assert _names(root, ["docs/**/*.md"], ["docs/su?/*"]) == ["top.md"] + + +def test_select_docs_walks_on_through_a_dotdot_that_comes_back_into_the_root(tmp_path: Path): + root = _docs(tmp_path) + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub"): + select_docs(root, {"include": ["../root/docs/**/*.md"], "min_docs": 1}) + + +def test_select_docs_does_not_list_a_directory_outside_the_root_after_a_dotdot_that_comes_back(tmp_path: Path): + root = _docs(tmp_path) + (tmp_path / "outside").mkdir() + with unlistable(tmp_path / "outside"): + assert _names(root, ["../root/docs/top.md", "../outside/*.md"]) == ["top.md"] + + +def test_select_docs_does_not_list_the_root_an_exclude_drops_every_wildcard_match_of(tmp_path: Path): + root = _docs(tmp_path) + (root / "README.md").write_text("readme", encoding="utf-8") + with unlistable(root): + assert _names(root, ["README.md", "*.txt"], ["*.txt"]) == ["README.md"] + assert _names(root, ["README.md", "d*/*.md"], ["d*/*.md"]) == ["README.md"] + with unlistable(root), pytest.raises(DocSelectionError, match=r"cannot list .*root"): + select_docs(root, {"include": ["README.md", "*.txt"], "exclude": ["*.md"]}) + + +def test_select_docs_lists_the_directory_a_literal_link_in_an_excluded_one_leads_to(tmp_path: Path): + root = _docs(tmp_path) + (root / "shared/locked").mkdir(parents=True) + (root / "shared/locked/a.md").write_text("a", encoding="utf-8") + _link(root / "docs/sub/alias", root / "shared/locked") + include, exclude = ["docs/top.md", "docs/sub/alias/*.md"], ["docs/sub/**"] + assert _names(root, include, exclude) == ["a.md", "top.md"] + with unlistable(root / "shared/locked"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub/alias"): + select_docs(root, {"include": include, "exclude": exclude, "min_docs": 1}) + + +def test_select_docs_reads_a_bracket_class_that_starts_with_a_closing_bracket_as_fnmatch_does(tmp_path: Path): + root = _docs(tmp_path) + (root / "README.md").write_text("readme", encoding="utf-8") + include = ["README.md", "docs/[]x]*.md"] + (root / "docs/x.md").write_text("x", encoding="utf-8") + assert _names(root, include, ["docs/*x]*.md"]) == ["README.md", "x.md"] + with unlistable(root / "docs"), pytest.raises(DocSelectionError, match=r"cannot list .*docs"): + select_docs(root, {"include": include, "exclude": ["docs/*x]*.md"], "min_docs": 1}) + + +def test_select_docs_lists_a_directory_a_link_below_an_excluded_one_leads_to(tmp_path: Path): + root = _docs(tmp_path) + (root / "README.md").write_text("readme", encoding="utf-8") + (root / "shared/locked").mkdir(parents=True) + (root / "shared/locked/a.md").write_text("a", encoding="utf-8") + _link(root / "docs/sub/alias", root / "shared/locked") + include = ["README.md", "docs/*/alias/*.md"] + assert _names(root, include, ["docs/*.md"]) == ["README.md", "a.md"] + with unlistable(root / "shared/locked"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub/alias"): + select_docs(root, {"include": include, "exclude": ["docs/*.md"], "min_docs": 1}) + include = ["README.md", "docs/*/*/*.md"] + with unlistable(root / "shared/locked"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/sub/alias"): + select_docs(root, {"include": include, "exclude": ["docs/sub/**"], "min_docs": 1}) + + +def test_select_docs_lists_a_directory_a_dotdot_after_an_excluded_wildcard_branch_leads_to(tmp_path: Path): + root = _docs(tmp_path) + (root / "README.md").write_text("readme", encoding="utf-8") + (root / "shared").mkdir() + (root / "shared/a.md").write_text("a", encoding="utf-8") + include = ["README.md", "docs/*/../../shared/*.md"] + assert _names(root, include, ["docs/**"]) == ["README.md", "a.md"] + with unlistable(root / "shared"), pytest.raises(DocSelectionError, match=r"cannot list .*shared"): + select_docs(root, {"include": include, "exclude": ["docs/**"], "min_docs": 1}) + + +def test_select_docs_lists_the_target_of_a_link_that_stays_inside_an_excluded_directory(tmp_path: Path): + root = _docs(tmp_path) + (root / "README.md").write_text("readme", encoding="utf-8") + (root / "docs/real").mkdir() + (root / "docs/real/x.md").write_text("x", encoding="utf-8") + _link(root / "docs/alias", root / "docs/real") + include, exclude = ["README.md", "docs/a*/*.md"], ["docs/a*/*.md"] + assert _names(root, include, exclude) == ["README.md", "x.md"] + with unlistable(root / "docs/real"), pytest.raises(DocSelectionError, match=r"cannot list .*docs/alias"): + select_docs(root, {"include": include, "exclude": exclude, "min_docs": 1}) + + +def _link(path: Path, target: Path) -> None: + try: + path.symlink_to(target, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") diff --git a/dokimi/tests/test_skill_links_unlistable.py b/dokimi/tests/test_skill_links_unlistable.py new file mode 100644 index 000000000..ac2de4d50 --- /dev/null +++ b/dokimi/tests/test_skill_links_unlistable.py @@ -0,0 +1,88 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1479: the skill arm's link check refuses a folder it cannot list, where ``os.walk`` with no ``onerror`` skipped it +and ``build_plugin`` failed in the copy with a ``shutil.Error``. The folders have mode 111.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from dokimi.harnesses import skill_treatment +from dokimi.harnesses.skill_treatment import _check_link_loops, build_plugin, check_skill +from tests.test_unlistable_sites import FRONTMATTER, unlistable + + +def _skill(root: Path, files: dict[str, str]) -> Path: + for rel, text in {"SKILL.md": FRONTMATTER, **files}.items(): + (root / rel).parent.mkdir(parents=True, exist_ok=True) + (root / rel).write_text(text, encoding="utf-8") + return root + + +def _skill_with_link_out(tmp_path: Path, folder: str) -> Path: + outside = tmp_path / "outside.txt" + outside.write_text("x", encoding="utf-8") + skill = _skill(tmp_path / "skill", {}) + (skill / folder).mkdir(parents=True) + try: + (skill / folder / "link.txt").symlink_to(outside) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + return skill + + +@pytest.mark.parametrize("folder", [".h", "node_modules", "__pycache__"]) +def test_check_skill_refuses_a_hidden_or_vendored_folder_it_cannot_list(tmp_path: Path, folder: str): + skill = _skill_with_link_out(tmp_path, folder) + with unlistable(skill / folder), pytest.raises(ValueError, match=rf"skill folder .*{folder} cannot be listed \(\S.*\), so the links"): + check_skill(skill) + + +def test_check_skill_refuses_a_folder_below_pycache_it_cannot_list(tmp_path: Path): + skill = _skill_with_link_out(tmp_path, "__pycache__/sub") + with unlistable(skill / "__pycache__/sub"), pytest.raises(ValueError, match=r"skill folder .*sub cannot be listed"): + check_skill(skill) + + +def test_check_skill_leaves_a_folder_below_a_listable_hidden_one_to_load_skill(tmp_path: Path): + skill = _skill_with_link_out(tmp_path, ".h/sub") + with unlistable(skill / ".h/sub"), pytest.raises(ValueError, match="cannot load skill.*sub"): + check_skill(skill) + + +def test_build_plugin_refuses_before_the_copy_of_a_folder_it_cannot_list(tmp_path: Path): + skill = _skill_with_link_out(tmp_path, ".h") + dest = tmp_path / "plugin" + with unlistable(skill / ".h"), pytest.raises(ValueError, match=r"\.h cannot be listed"): + build_plugin(skill, dest) + assert not (dest / "skills").exists() + + +def test_check_skill_passes_a_listable_hidden_folder_with_a_harmless_file(tmp_path: Path): + assert check_skill(_skill(tmp_path / "skill", {".h/note.txt": "x"})) == "demo" + + +def test_check_skill_leaves_a_folder_load_skill_refuses_to_it(tmp_path: Path): + skill = _skill(tmp_path / "skill", {"references/a.md": "a"}) + with unlistable(skill / "references"), pytest.raises(ValueError, match="cannot load skill.*references"): + check_skill(skill) + + +def test_the_link_walk_refuses_a_hidden_folder_it_cannot_list_before_the_loop_check( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(skill_treatment, "_check_link_loops", lambda *_: None) + skill = _skill_with_link_out(tmp_path, ".h") + with unlistable(skill / ".h"), pytest.raises(ValueError, match=r"skill folder .*\.h cannot be listed"): + skill_treatment._check_links(skill) + + +def test_the_loop_check_refuses_a_hidden_folder_it_cannot_list(tmp_path: Path): + skill = _skill(tmp_path / "skill", {".h/note.txt": "x", "references/a.md": "a"}) + _check_link_loops(skill, skill.resolve()) + with unlistable(skill / ".h"), pytest.raises(ValueError, match=r"skill folder .*\.h cannot be listed"): + _check_link_loops(skill, skill.resolve()) + with unlistable(skill / "references"): + _check_link_loops(skill, skill.resolve()) # load_skill refuses it, naming it diff --git a/dokimi/tests/test_unlistable_sites.py b/dokimi/tests/test_unlistable_sites.py index 303c98fa5..62bb50ce1 100644 --- a/dokimi/tests/test_unlistable_sites.py +++ b/dokimi/tests/test_unlistable_sites.py @@ -32,9 +32,10 @@ @contextlib.contextmanager -def unlistable(directory: Path) -> Iterator[Path]: - """``directory`` with mode 111 (searchable, not listable); skips when the process can still list it.""" - directory.chmod(0o111) +def unlistable(directory: Path, mode: int = 0o111) -> Iterator[Path]: + """``directory`` with mode 111 (searchable, not listable; ``mode`` 0 is not even searchable); skips when the + process can still list it.""" + directory.chmod(mode) try: if os.access(directory, os.R_OK): pytest.skip("the process lists a mode 111 directory (root, or a file system with no modes)")