From 7caa69fa5eb608e0155051f946b02f3b5b50a159 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 15:49:03 +0000 Subject: [PATCH 01/14] fix(runner): select_docs raises for a directory its pattern cannot list (#1383) select_docs expanded each include pattern with Path.glob, which skips a directory it cannot list (mode 0o111, non-root) without an error. With docs/top.md and docs/sub/a.md, include docs/**/*.md and docs/sub unlistable, it returned top.md alone, and min_docs and max_docs were checked against that smaller count. Each include pattern's walk is now checked for a directory it has to list: an unlistable one raises DocSelectionError naming it. A directory the exclude list drops, one no match can lie under, a path the pattern only names, a path that is not there and a link that leaves the root are not listed by the pattern and stay no error. The check is a new helper, apart from _outside_links. Signed-off-by: Anton Volkov --- dokimi/README.md | 2 +- .../20261204_100000_select-docs-unlistable.md | 8 ++ dokimi/dokimi/runner/spec.py | 29 ++++++ dokimi/tests/test_select_docs_unlistable.py | 97 +++++++++++++++++++ 4 files changed, 135 insertions(+), 1 deletion(-) create mode 100644 dokimi/changelog.d/20261204_100000_select-docs-unlistable.md create mode 100644 dokimi/tests/test_select_docs_unlistable.py diff --git a/dokimi/README.md b/dokimi/README.md index 415209c0c7..8985530f97 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 0000000000..0b7c79f044 --- /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). A directory the pattern never lists (outside it, under an `exclude` entry, or on a branch no match can lie under) is still not an error (#1383). diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index ae5b7898d2..4b9618879e 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -11,6 +11,7 @@ from __future__ import annotations +import errno import fnmatch import itertools import os @@ -181,6 +182,33 @@ 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``. A directory the exclude list drops, one no match can lie under, and a path that is + not there are not listed by the pattern, so they are not errors. + """ + pattern_parts = Path(pattern).parts + base = _literal_prefix(root, pattern) + if len(base.parts) >= len(pattern_parts): # no wildcard left: the pattern names a path and lists nothing + return + top = root / base + # mutation-ok[drop-clause]: a base that is no link stays inside the root, as _literal_prefix stops at the first link + if top.is_symlink() and not top.resolve().is_relative_to(root.resolve()): + return # never selected: _outside_links names it + + def unlistable(exc: OSError) -> None: + if exc.errno not in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP): # a path that is not there lists nothing + raise DocSelectionError(f"cannot list {exc.filename}: {exc.strerror}") from exc + + for here, dirs, _files in os.walk(top, onerror=unlistable): + for d in list(dirs): + rel = (Path(here) / d).relative_to(root) + if _is_excluded(rel.as_posix(), exclude) or not _could_match(rel.parts, pattern_parts): + dirs.remove(d) + + def select_docs(root: Path, manifest: dict) -> list[Path]: """Resolve and bound the document set from a ``golden_manifest``. @@ -200,6 +228,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_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py new file mode 100644 index 0000000000..ef566728c7 --- /dev/null +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -0,0 +1,97 @@ +# 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"] + with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match="docs/sub"): + select_docs(root, {"include": ["docs/*/a.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"] + + +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"] From 858b6352be418d3569b76534f22e86447d200aa1 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 15:49:06 +0000 Subject: [PATCH 02/14] fix(harnesses): the skill link check refuses a folder it cannot list (#1479) _check_links walked the skill with os.walk and no onerror, so a link out of the skill inside a hidden or vendored folder that cannot be listed (mode 0o111, non-root) was never checked. check_skill returned the name, and build_plugin then failed in the copy with a shutil.Error instead of the ValueError the other refusals raise. _check_link_loops returned on the same OSError, leaving it to the copy. Both now raise a ValueError naming the folder, before the copy. A folder load_skill already refuses (any but a dot-named, vendored or __pycache__ one) is left to it, so its error is unchanged. Signed-off-by: Anton Volkov --- .../20261204_100100_skill-links-unlistable.md | 8 ++ dokimi/docs/coding-harnesses.md | 4 +- dokimi/dokimi/harnesses/skill_treatment.py | 20 ++++- dokimi/tests/test_skill_links_unlistable.py | 76 +++++++++++++++++++ 4 files changed, 104 insertions(+), 4 deletions(-) create mode 100644 dokimi/changelog.d/20261204_100100_skill-links-unlistable.md create mode 100644 dokimi/tests/test_skill_links_unlistable.py 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 0000000000..d7e1728009 --- /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 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/docs/coding-harnesses.md b/dokimi/docs/coding-harnesses.md index fe4f517812..cce0d04fb1 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, + 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/dokimi/harnesses/skill_treatment.py b/dokimi/dokimi/harnesses/skill_treatment.py index a54bb886db..ab8d2b18ae 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,18 @@ def check_skill(skill_dir: Path) -> str: return skill.name +def _refuse_unlisted(exc: OSError) -> 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 (any but a dot-named, vendored or ``__pycache__`` one) is left to it, which names it. + """ + folder = Path(str(exc.filename)) + if _not_listed_as_resource(folder): + 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 +161,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=_refuse_unlisted): # 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 +196,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) + 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/tests/test_skill_links_unlistable.py b/dokimi/tests/test_skill_links_unlistable.py new file mode 100644 index 0000000000..38df20dbb1 --- /dev/null +++ b/dokimi/tests/test_skill_links_unlistable.py @@ -0,0 +1,76 @@ +# 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() + 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_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 From d812ec82faa49d1b180eeb58169a987bdaf65dc7 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 15:49:09 +0000 Subject: [PATCH 03/14] fix(catalog): provenance exits 2 for a directory the scan could not list (#1480) Since the scan gives an error row for a directory above the skills that cannot be listed, catalog provenance dropped it at the _skill_file(...) is None branch: the skills under that directory were missing from the table and its summary, with no note. Such a row (unlisted, with an error, its path a directory with no SKILL.md) now raises an InputError naming the directory, before any row is printed, with or without a skills.yaml. A manifest entry with no file, and a skill whose own folder cannot be listed, keep their behaviour. Signed-off-by: Anton Volkov --- .../20261204_100200_provenance-unlistable.md | 8 +++ dokimi/docs/external-content.md | 1 + dokimi/dokimi/commands/catalog_provenance.py | 18 ++++- dokimi/tests/test_provenance_unlistable.py | 66 +++++++++++++++++++ 4 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 dokimi/changelog.d/20261204_100200_provenance-unlistable.md create mode 100644 dokimi/tests/test_provenance_unlistable.py 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 0000000000..c7b70ff94e --- /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 manifest entry with no file is still skipped, as `catalog check` reports it (#1480). diff --git a/dokimi/docs/external-content.md b/dokimi/docs/external-content.md index 0a90501a60..d2d89364c5 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, 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 46c79c4f7c..793114b57f 100644 --- a/dokimi/dokimi/commands/catalog_provenance.py +++ b/dokimi/dokimi/commands/catalog_provenance.py @@ -82,6 +82,19 @@ def _skill_file(entry, root: Path) -> Path | None: return path +def _refuse_unlisted(entries: list) -> 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 (folder / "SKILL.md").exists() and not (folder / "SKILL.md").is_symlink(): + 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 +111,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) 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) + 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/tests/test_provenance_unlistable.py b/dokimi/tests/test_provenance_unlistable.py new file mode 100644 index 0000000000..feeea1e386 --- /dev/null +++ b/dokimi/tests/test_provenance_unlistable.py @@ -0,0 +1,66 @@ +# 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("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): + 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"), pytest.raises(InputError, match=r"--root: .*root/sub cannot be listed"): + _provenance(tmp_path, root, capsys) + assert capsys.readouterr().out == "" + + +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"] From aa75ca1844bdc71a190dc12f649ba2b086903c5c Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 20:49:24 +0000 Subject: [PATCH 04/14] fix(runner): select_docs leaves a looping docs link to the min_docs error (#1383) The unlistable-directory check resolved the include pattern's base link with no guard, so a link that loops, where resolve raises RuntimeError (Python before 3.13) or OSError, escaped select_docs instead of giving the min_docs error. A link that resolve cannot follow leads nowhere, so the check now treats it as not walked and goes on. Tests cover the resolve failure and a loop below the pattern's base. Signed-off-by: Anton Volkov --- dokimi/dokimi/runner/spec.py | 9 ++-- dokimi/tests/test_select_docs_link_loops.py | 55 +++++++++++++++++++++ 2 files changed, 61 insertions(+), 3 deletions(-) create mode 100644 dokimi/tests/test_select_docs_link_loops.py diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index 4b9618879e..ea8cf22d34 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -194,9 +194,12 @@ def _refuse_unlistable(root: Path, pattern: str, exclude: list[str]) -> None: if len(base.parts) >= len(pattern_parts): # no wildcard left: the pattern names a path and lists nothing return top = root / base - # mutation-ok[drop-clause]: a base that is no link stays inside the root, as _literal_prefix stops at the first link - if top.is_symlink() and not top.resolve().is_relative_to(root.resolve()): - return # never selected: _outside_links names it + if top.is_symlink(): + try: + if not top.resolve().is_relative_to(root.resolve()): + return # never selected: _outside_links names it + except (RuntimeError, OSError): # a loop of links: it leads nowhere, so nothing is walked + return def unlistable(exc: OSError) -> None: if exc.errno not in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP): # a path that is not there lists nothing 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 0000000000..a2b36303e5 --- /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"] From 622bcdd102b180e33fe9863bd6ffd75fbda1b525 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 5 Dec 2026 00:40:14 +0000 Subject: [PATCH 05/14] fix(runner): the unlistable-directory checks list what Path.glob lists and no more select_docs now walks an include pattern as Path.glob does: a literal part is entered (through a link too) and the last literal name is looked up, not listed, a wildcard part lists and follows a link to a directory, `**` lists and skips links. A directory outside the root or dropped by the exclude list is not listed, at the start of the walk as below it. So `alias/a.md`, `docs/*/a.md`, `../outside/**/*.md` and an include whose base the exclude list drops no longer raise, and a directory reached through a link by `docs/*/*.md` is listed (review threads on spec.py). The skill link check leaves to load_skill only a folder it names: one under a `__pycache__` it leaves out is refused by the link check, as the copy would fail on it (skill_treatment.py thread). catalog provenance treats a folder it cannot even search (mode 000) as holding no SKILL.md instead of raising PermissionError from the probe (catalog_provenance.py thread). Signed-off-by: Anton Volkov --- .../20261204_100000_select-docs-unlistable.md | 2 +- .../20261204_100100_skill-links-unlistable.md | 2 +- dokimi/docs/coding-harnesses.md | 2 +- dokimi/dokimi/commands/catalog_provenance.py | 12 +- dokimi/dokimi/harnesses/skill_treatment.py | 11 +- dokimi/dokimi/runner/spec.py | 72 ++++++++---- dokimi/tests/test_provenance_unlistable.py | 5 +- dokimi/tests/test_select_docs_unlistable.py | 104 +++++++++++++++++- dokimi/tests/test_skill_links_unlistable.py | 14 ++- dokimi/tests/test_unlistable_sites.py | 7 +- 10 files changed, 194 insertions(+), 37 deletions(-) diff --git a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md index 0b7c79f044..493b52c8ce 100644 --- a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md +++ b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### 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). A directory the pattern never lists (outside it, under an `exclude` entry, or on a branch no match can lie under) is still not an error (#1383). +- **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, 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 (#1383). diff --git a/dokimi/changelog.d/20261204_100100_skill-links-unlistable.md b/dokimi/changelog.d/20261204_100100_skill-links-unlistable.md index d7e1728009..7e057dcd6b 100644 --- a/dokimi/changelog.d/20261204_100100_skill-links-unlistable.md +++ b/dokimi/changelog.d/20261204_100100_skill-links-unlistable.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### 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 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). +- **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/docs/coding-harnesses.md b/dokimi/docs/coding-harnesses.md index cce0d04fb1..38ba45f6f0 100644 --- a/dokimi/docs/coding-harnesses.md +++ b/dokimi/docs/coding-harnesses.md @@ -1003,7 +1003,7 @@ The arms differ by the skill and one notice, and by nothing else: 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, and so does one with a folder that cannot be listed (a hidden or vendored one, - where a link would go unchecked and the copy would fail on it). + 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/dokimi/commands/catalog_provenance.py b/dokimi/dokimi/commands/catalog_provenance.py index 793114b57f..5e397b4967 100644 --- a/dokimi/dokimi/commands/catalog_provenance.py +++ b/dokimi/dokimi/commands/catalog_provenance.py @@ -82,6 +82,15 @@ def _skill_file(entry, root: Path) -> Path | None: return path +def _holds_skill_file(folder: Path) -> bool: + """Whether ``folder/SKILL.md`` is there; a folder that cannot even be searched (mode 000) holds none we can load.""" + skill_file = folder / "SKILL.md" + try: + return skill_file.exists() or skill_file.is_symlink() + except OSError: + return False + + def _refuse_unlisted(entries: list) -> None: """Refuse the scan's error row of a directory above the skills that cannot be listed (#1480). @@ -90,8 +99,7 @@ def _refuse_unlisted(entries: list) -> None: """ for entry in entries: folder = entry.path - if entry.unlisted and entry.error and folder is not None and folder.is_dir() \ - and not (folder / "SKILL.md").exists() and not (folder / "SKILL.md").is_symlink(): + if entry.unlisted and entry.error and folder is not None and folder.is_dir() and not _holds_skill_file(folder): raise InputError(f"--root: {entry.error}") diff --git a/dokimi/dokimi/harnesses/skill_treatment.py b/dokimi/dokimi/harnesses/skill_treatment.py index ab8d2b18ae..c4e7fcc349 100644 --- a/dokimi/dokimi/harnesses/skill_treatment.py +++ b/dokimi/dokimi/harnesses/skill_treatment.py @@ -140,14 +140,15 @@ def check_skill(skill_dir: Path) -> str: return skill.name -def _refuse_unlisted(exc: OSError) -> None: +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 (any but a dot-named, vendored or ``__pycache__`` one) is left to it, which names it. + :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)) - if _not_listed_as_resource(folder): + 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") @@ -161,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, onerror=_refuse_unlisted): # 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"] @@ -197,7 +198,7 @@ def visit(directory: Path, real: Path, stack: tuple[Path, ...]) -> None: children = [Path(e.path) for e in entries if e.is_dir() and not (directory == skill_dir and e.name == "evals")] except OSError as exc: - _refuse_unlisted(exc) + _refuse_unlisted(exc, skill_dir) return # one load_skill refuses next, naming it for child in children: target = child.resolve() diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index ea8cf22d34..7f9e1e3142 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -186,30 +186,64 @@ 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``. A directory the exclude list drops, one no match can lie under, and a path that is - not there are not listed by the pattern, so they are not errors. + counted against ``min_docs``. Only a directory a wildcard part lists is an error: one the exclude list drops, one + outside ``root``, one only named (a literal part, however it is reached) and a path that is not there are not. """ - pattern_parts = Path(pattern).parts - base = _literal_prefix(root, pattern) - if len(base.parts) >= len(pattern_parts): # no wildcard left: the pattern names a path and lists nothing - return - top = root / base - if top.is_symlink(): + root_resolved = root.resolve() + seen: set[tuple[Path, tuple[str, ...]]] = set() + + def walk(directory: Path, parts: tuple[str, ...]) -> None: try: - if not top.resolve().is_relative_to(root.resolve()): - return # never selected: _outside_links names it - except (RuntimeError, OSError): # a loop of links: it leads nowhere, so nothing is walked + real = directory.resolve() + except (RuntimeError, OSError): # a loop of links leads nowhere + return + # mutation-ok[drop-clause]: ``seen`` only keeps ``**/**`` from walking a directory twice + if 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 real != root_resolved and _is_excluded(real.relative_to(root_resolved).as_posix(), exclude): 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 unlistable(exc: OSError) -> None: - if exc.errno not in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP): # a path that is not there lists nothing - raise DocSelectionError(f"cannot list {exc.filename}: {exc.strerror}") from exc - for here, dirs, _files in os.walk(top, onerror=unlistable): - for d in list(dirs): - rel = (Path(here) / d).relative_to(root) - if _is_excluded(rel.as_posix(), exclude) or not _could_match(rel.parts, pattern_parts): - dirs.remove(d) +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]: diff --git a/dokimi/tests/test_provenance_unlistable.py b/dokimi/tests/test_provenance_unlistable.py index feeea1e386..abf9fcc1e5 100644 --- a/dokimi/tests/test_provenance_unlistable.py +++ b/dokimi/tests/test_provenance_unlistable.py @@ -42,13 +42,14 @@ def test_provenance_of_a_listable_root_gives_one_row_per_skill(tmp_path: Path, c 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): + 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"), pytest.raises(InputError, match=r"--root: .*root/sub cannot be listed"): + 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 == "" diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index ef566728c7..e8eda2d365 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -53,8 +53,14 @@ def test_select_docs_ignores_an_unlistable_directory_no_match_can_lie_under(tmp_ root = _docs(tmp_path) with unlistable(root / "docs/sub/deep"): assert _names(root, ["docs/*/a.md"]) == ["a.md"] - with unlistable(root / "docs/sub"), pytest.raises(DocSelectionError, match="docs/sub"): - select_docs(root, {"include": ["docs/*/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): @@ -95,3 +101,97 @@ def test_select_docs_does_not_list_a_linked_directory_outside_the_root(tmp_path: 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_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 _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 index 38df20dbb1..ac2de4d50a 100644 --- a/dokimi/tests/test_skill_links_unlistable.py +++ b/dokimi/tests/test_skill_links_unlistable.py @@ -26,7 +26,7 @@ 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() + (skill / folder).mkdir(parents=True) try: (skill / folder / "link.txt").symlink_to(outside) except (OSError, NotImplementedError): @@ -41,6 +41,18 @@ def test_check_skill_refuses_a_hidden_or_vendored_folder_it_cannot_list(tmp_path 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" diff --git a/dokimi/tests/test_unlistable_sites.py b/dokimi/tests/test_unlistable_sites.py index 303c98fa5b..62bb50ce16 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)") From 4d8fc2fa2d960508c666d1654e87abc48274f5fd Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 5 Dec 2026 01:56:59 +0000 Subject: [PATCH 06/14] fix(runner): unlistable folder checks refuse two more layouts provenance: a folder that cannot be listed and holds a directory or a dangling link named SKILL.md passed the exists() check of _holds_skill_file, so _skill_file dropped its row and the skills beside it went unseen; the check is now is_file(), the test _skill_file applies. select_docs: an unlistable directory the exclude list matches itself but not the files below it (docs/[s]ub) was pruned before listing, while its files stay selected on a listable tree; it is pruned only when the exclusion also covers a file below it, and otherwise raises. Signed-off-by: Anton Volkov --- dokimi/dokimi/commands/catalog_provenance.py | 7 +++++-- dokimi/dokimi/runner/spec.py | 9 ++++++--- dokimi/tests/test_provenance_unlistable.py | 16 ++++++++++++++++ dokimi/tests/test_select_docs_unlistable.py | 7 +++++++ 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/dokimi/dokimi/commands/catalog_provenance.py b/dokimi/dokimi/commands/catalog_provenance.py index 5e397b4967..8bc8fcb5aa 100644 --- a/dokimi/dokimi/commands/catalog_provenance.py +++ b/dokimi/dokimi/commands/catalog_provenance.py @@ -83,10 +83,13 @@ def _skill_file(entry, root: Path) -> Path | None: def _holds_skill_file(folder: Path) -> bool: - """Whether ``folder/SKILL.md`` is there; a folder that cannot even be searched (mode 000) holds none we can load.""" + """Whether ``folder/SKILL.md`` is a file; a folder that cannot even be searched (mode 000) holds none we can load. + + A directory or a dangling link 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.exists() or skill_file.is_symlink() + return skill_file.is_file() except OSError: return False diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index 7f9e1e3142..c9f6fb51a2 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -186,7 +186,8 @@ 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, one + 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 only named (a literal part, however it is reached) and a path that is not there are not. """ root_resolved = root.resolve() @@ -201,8 +202,10 @@ def walk(directory: Path, parts: tuple[str, ...]) -> None: if 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 real != root_resolved and _is_excluded(real.relative_to(root_resolved).as_posix(), exclude): - return + if real != root_resolved: + rel = real.relative_to(root_resolved).as_posix() + if _is_excluded(rel + "/x", exclude): # a file below goes: the exclude covers the directory's files + return for child, remaining in _next_steps(directory, parts): walk(child, remaining) diff --git a/dokimi/tests/test_provenance_unlistable.py b/dokimi/tests/test_provenance_unlistable.py index abf9fcc1e5..1b57b38e6a 100644 --- a/dokimi/tests/test_provenance_unlistable.py +++ b/dokimi/tests/test_provenance_unlistable.py @@ -54,6 +54,22 @@ def test_provenance_refuses_a_directory_above_the_skills_that_cannot_be_listed( 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 == "" + + 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"): diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index e8eda2d365..e3d198cc13 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -69,6 +69,13 @@ def test_select_docs_ignores_an_unlistable_directory_the_exclude_list_drops(tmp_ 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_does_not_list_a_path_the_pattern_only_names(tmp_path: Path): root = _docs(tmp_path) with unlistable(root / "docs/sub"): From a76fe5c720c8f30900ad515967b79b40c243113e Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 5 Dec 2026 02:51:42 +0000 Subject: [PATCH 07/14] fix(runner): select_docs drops an unlistable directory only when the exclude list covers its whole subtree An exclude such as `docs/*/x` matched the synthetic name `docs/sub/x`, so an unlistable `docs/sub` holding `a.md` was pruned and `select_docs` returned `top.md` alone with no error, while the listable tree selected both. The walk now prunes a directory only when an exclude entry names it or a parent (`docs/sub`, `docs/sub/**`) or ends in `*` and matches it (`docs/s*`). catalog provenance: cover the `OSError` branch of the SKILL.md lookup, which Python 3.11 and 3.12 raise for a folder with mode 000, with a test that makes `is_file` raise it. Signed-off-by: Anton Volkov --- .../20261204_100000_select-docs-unlistable.md | 2 +- dokimi/dokimi/runner/spec.py | 17 +++++++++++++- dokimi/tests/test_provenance_unlistable.py | 16 +++++++++++++ dokimi/tests/test_select_docs_unlistable.py | 23 +++++++++++++++++++ 4 files changed, 56 insertions(+), 2 deletions(-) diff --git a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md index 493b52c8ce..0fa1988130 100644 --- a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md +++ b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### 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, 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 (#1383). +- **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/**`, 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 (#1383). diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index c9f6fb51a2..41db8b0157 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -118,6 +118,21 @@ 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 ends in ``*``, which + crosses ``/`` in fnmatch, and matches the directory (``docs/s*``). ``docs/*/x`` drops one file name below it, not the subtree. + """ + for pattern in patterns: + prefix = pattern.rstrip("/").removesuffix("/**").rstrip("/") + if rel_dir == prefix or rel_dir.startswith(prefix + "/"): + return True + if pattern.endswith("*") and any(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 + + 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() @@ -204,7 +219,7 @@ def walk(directory: Path, parts: tuple[str, ...]) -> None: seen.add((real, parts)) # mutation-ok[delete-statement]: see above if real != root_resolved: rel = real.relative_to(root_resolved).as_posix() - if _is_excluded(rel + "/x", exclude): # a file below goes: the exclude covers the directory's files + if _excludes_subtree(rel, exclude): return for child, remaining in _next_steps(directory, parts): walk(child, remaining) diff --git a/dokimi/tests/test_provenance_unlistable.py b/dokimi/tests/test_provenance_unlistable.py index 1b57b38e6a..2add0bd466 100644 --- a/dokimi/tests/test_provenance_unlistable.py +++ b/dokimi/tests/test_provenance_unlistable.py @@ -70,6 +70,22 @@ def test_provenance_refuses_an_unlistable_folder_whose_skill_md_is_no_file( 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"): diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index e3d198cc13..1f41e874b0 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -67,6 +67,7 @@ def test_select_docs_ignores_an_unlistable_directory_the_exclude_list_drops(tmp_ 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): @@ -76,6 +77,19 @@ def test_select_docs_refuses_a_directory_the_exclude_list_drops_without_the_file 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_does_not_list_a_path_the_pattern_only_names(tmp_path: Path): root = _docs(tmp_path) with unlistable(root / "docs/sub"): @@ -124,6 +138,15 @@ def test_select_docs_does_not_list_the_directory_an_exclude_drops_where_a_litera 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") From 3489a1d020f1ee9bde11f7e7f99b476998bcf049 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 5 Dec 2026 03:58:01 +0000 Subject: [PATCH 08/14] fix(runner): select_docs drops an unlistable directory that an exclude ending in /* covers Review point: `exclude=["docs/sub/*"]` drops every file below `docs/sub`, but `_excludes_subtree` matched the directory name `docs/sub` against the pattern, which fnmatch refuses, so an unlistable `docs/sub` raised DocSelectionError. A pattern that ends in `*` is now matched against the directory plus a `/`, so `docs/sub/*` and `docs/*/*` count as covering the subtree; `docs/sub/a*` still does not. Signed-off-by: Anton Volkov --- dokimi/dokimi/runner/spec.py | 5 +++-- dokimi/tests/test_select_docs_unlistable.py | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index 41db8b0157..cd1e2b0d0b 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -122,13 +122,14 @@ 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 ends in ``*``, which - crosses ``/`` in fnmatch, and matches the directory (``docs/s*``). ``docs/*/x`` drops one file name below it, not the subtree. + 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. """ for pattern in patterns: prefix = pattern.rstrip("/").removesuffix("/**").rstrip("/") if rel_dir == prefix or rel_dir.startswith(prefix + "/"): return True - if pattern.endswith("*") and any(fnmatch.fnmatch(rel_dir, form) for form in _zero_dir_forms(pattern)): + if pattern.endswith("*") and any(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 diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index 1f41e874b0..f4ce79f2ee 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -90,6 +90,15 @@ def test_select_docs_ignores_an_unlistable_directory_a_trailing_wildcard_exclude 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_does_not_list_a_path_the_pattern_only_names(tmp_path: Path): root = _docs(tmp_path) with unlistable(root / "docs/sub"): From 1aea8f5c73649a22045b4da0c964282c2af28b75 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 5 Dec 2026 09:51:41 +0000 Subject: [PATCH 09/14] fix(runner): select_docs refuses a directory only a non-wildcard form of an exclude matches An exclude such as docs/sub?/** has the forms docs/sub?/* and docs/sub?. The second matches docs/sub/ through the ? but no file below it, so _excludes_subtree dropped an unlistable docs/sub while _is_excluded kept docs/sub/a.md selected, and the result lost a document without an error. The matching form must itself end in *. This settles the review thread on spec.py:132. Signed-off-by: Anton Volkov --- dokimi/dokimi/runner/spec.py | 9 +++++---- dokimi/tests/test_select_docs_unlistable.py | 7 +++++++ 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index cd1e2b0d0b..7f552f2c92 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -121,15 +121,16 @@ def _is_excluded(rel_path: str, patterns: list[str]) -> bool: 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 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. + 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 pattern.endswith("*") and any(fnmatch.fnmatch(rel_dir + "/", form) for form in _zero_dir_forms(pattern)): + 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 diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index f4ce79f2ee..eeff9ab994 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -99,6 +99,13 @@ def test_select_docs_ignores_an_unlistable_directory_an_exclude_of_everything_in 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_does_not_list_a_path_the_pattern_only_names(tmp_path: Path): root = _docs(tmp_path) with unlistable(root / "docs/sub"): From 3684f1aabdc34def93d2d9efae0769ec5d0a4940 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sun, 6 Dec 2026 12:23:41 +0000 Subject: [PATCH 10/14] fix(runner): select_docs skips an unlistable dir whose documents an exclude drops An include of `README.md` and `docs/**/*.md` with the exclude `docs/*.md` selects `README.md` on main, but with `docs/restricted` unlistable the walk refused it: only an exclude that drops the whole subtree counted, and `docs/*.md` names the Markdown below `docs/restricted`, not the directory. The walk now also skips a directory when an exclude pattern made of literals and `*` matches every path the rest of the include can select below it. A pattern with `?` or `[` is still never taken to cover, so the directory is refused as before. Settles the thread on spec.py:224. Signed-off-by: Anton Volkov --- .../20261204_100000_select-docs-unlistable.md | 2 +- dokimi/dokimi/runner/spec.py | 20 +++++++++++++++++-- dokimi/tests/test_select_docs_unlistable.py | 12 +++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md index 0fa1988130..4cdc36f7ab 100644 --- a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md +++ b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### 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/**`, 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 (#1383). +- **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 (#1383). diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index 7f552f2c92..85fa3d7b46 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -15,6 +15,7 @@ import fnmatch import itertools import os +import re from pathlib import Path import yaml @@ -135,6 +136,20 @@ def _excludes_subtree(rel_dir: str, patterns: list[str]) -> bool: return False # mutation-ok[return-none]: None is as false as False +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}" for form in _zero_dir_forms("/".join(parts))} + samples = {re.sub(r"\[[^\]]*\]|[*?]", "\0", form) 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() @@ -205,7 +220,8 @@ def _refuse_unlistable(root: Path, pattern: str, exclude: list[str]) -> None: ``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 only named (a literal part, however it is reached) and a path that is not there are not. + 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. """ root_resolved = root.resolve() seen: set[tuple[Path, tuple[str, ...]]] = set() @@ -221,7 +237,7 @@ def walk(directory: Path, parts: tuple[str, ...]) -> None: seen.add((real, parts)) # mutation-ok[delete-statement]: see above if real != root_resolved: rel = real.relative_to(root_resolved).as_posix() - if _excludes_subtree(rel, exclude): + if _excludes_subtree(rel, exclude) or _excludes_selection(rel, parts, exclude): return for child, remaining in _next_steps(directory, parts): walk(child, remaining) diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index eeff9ab994..461ec5fcef 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -106,6 +106,18 @@ def test_select_docs_refuses_a_directory_only_a_non_wildcard_form_of_an_exclude_ 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"): From 147e840310ea5a25823bd11b6bcbc44e21d7382f Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sun, 6 Dec 2026 12:23:41 +0000 Subject: [PATCH 11/14] docs(catalog): the unlistable-directory sentence of catalog provenance covers a directory with no SKILL.md A directory above the skills that cannot be listed but holds a readable `SKILL.md` is listed with no error; the sentence in external-content.md said any such directory exits 2. It now says a directory that holds no `SKILL.md`, as the code (`_refuse_unlisted`) and the PR description do. Settles the thread on external-content.md:607. Signed-off-by: Anton Volkov --- dokimi/docs/external-content.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dokimi/docs/external-content.md b/dokimi/docs/external-content.md index d2d89364c5..37f7e41128 100644 --- a/dokimi/docs/external-content.md +++ b/dokimi/docs/external-content.md @@ -604,7 +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, 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. +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`) From d9c823f895437dffa159cb734fd9ce2c1c1f6f76 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sun, 6 Dec 2026 13:16:02 +0000 Subject: [PATCH 12/14] fix(runner): select_docs walks literal parts on and prunes the root Answers the three open threads on the unlistable-directory walk (4816870922, 4816870930, 4816870931). A literal part of an include pattern is only looked up, so it is now followed whatever the directory it leaves: a `..` that comes back into the root (`../root/docs/**/*.md`) and a link inside an excluded directory that leads to an unlistable target (`docs/sub/alias/*.md` with `docs/sub/**` excluded) no longer end the walk early. Exclude pruning and the outside-the-root cut apply only where a wildcard part lists the directory. The root is pruned by the exclude list too: a root that cannot be listed no longer fails `README.md` plus a `*.txt` the exclude list drops entirely. A test for the `?` form of a subtree exclude (`docs/su?/*`) kills the `_excludes_subtree` mutants. Signed-off-by: Anton Volkov --- dokimi/dokimi/runner/spec.py | 13 ++++--- dokimi/tests/test_select_docs_unlistable.py | 40 +++++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index 85fa3d7b46..2869390d7b 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -144,7 +144,7 @@ def _excludes_selection(rel_dir: str, parts: tuple[str, ...], patterns: list[str 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}" for form in _zero_dir_forms("/".join(parts))} + include_forms = {f"{rel_dir}/{form}" if rel_dir else form for form in _zero_dir_forms("/".join(parts))} samples = {re.sub(r"\[[^\]]*\]|[*?]", "\0", form) 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) @@ -222,6 +222,8 @@ def _refuse_unlistable(root: Path, pattern: str, exclude: list[str]) -> None: 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. """ root_resolved = root.resolve() seen: set[tuple[Path, tuple[str, ...]]] = set() @@ -231,13 +233,14 @@ def walk(directory: Path, parts: tuple[str, ...]) -> None: 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 not real.is_relative_to(root_resolved) or (real, parts) in seen: # outside: never selected + 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 real != root_resolved: - rel = real.relative_to(root_resolved).as_posix() - if _excludes_subtree(rel, exclude) or _excludes_selection(rel, parts, exclude): + if lists: + rel = "" if real == root_resolved else real.relative_to(root_resolved).as_posix() + if (rel and _excludes_subtree(rel, exclude)) or _excludes_selection(rel, parts, exclude): return for child, remaining in _next_steps(directory, parts): walk(child, remaining) diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index 461ec5fcef..f4cb5ec8eb 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -248,6 +248,46 @@ def test_select_docs_leaves_out_a_link_whose_target_cannot_be_reached(tmp_path: 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 _link(path: Path, target: Path) -> None: try: path.symlink_to(target, target_is_directory=True) From 551aa5f53813f567e1871af5344b213f40f931a9 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sun, 6 Dec 2026 13:58:06 +0000 Subject: [PATCH 13/14] fix(runner): select_docs reads a bracket class as fnmatch does and keeps a directory with a link out Answers two review points on the exclude pruning of the unlistable-directory check. The sample of an include form read `[]a]` as the empty class `[]` followed by `a]`, so `docs/[]a]*.md` looked covered by the exclude `docs/*a]*.md`; the class now takes fnmatch's reading (a `]` first is a member), per path part. And an exclude is judged on the name of a path while the final filter judges the resolved one, so a directory whose subtree holds a link out of it (`docs/sub/alias` to `shared/locked`) is no longer dropped unlisted: the walk goes on and refuses the unlistable target. Signed-off-by: Anton Volkov --- .../20261204_100000_select-docs-unlistable.md | 2 +- dokimi/dokimi/runner/spec.py | 20 +++++++++++++-- dokimi/tests/test_select_docs_unlistable.py | 25 +++++++++++++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md index 4cdc36f7ab..401b2c42bf 100644 --- a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md +++ b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### 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 (#1383). +- **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 below it that leads out of it is not left out for an `exclude` entry, since the entry is judged on the name of the path and the selection on where the link leads (#1383). diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index 2869390d7b..cb7bfe7a43 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -136,6 +136,21 @@ def _excludes_subtree(rel_dir: str, patterns: list[str]) -> bool: 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 _links_leave(directory: Path) -> bool: + """Whether a link to a directory below ``directory`` leads out of it, where an exclude is judged on the resolved path.""" + real = directory.resolve() + for here, dirs, _files in os.walk(directory): # a directory it cannot list is skipped: it shows no link + for name in dirs: + link = Path(here) / name + if link.is_symlink() and not link.resolve().is_relative_to(real): + return True + return False + + 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``. @@ -145,7 +160,7 @@ def _excludes_selection(rel_dir: str, parts: tuple[str, ...], patterns: list[str 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 = {re.sub(r"\[[^\]]*\]|[*?]", "\0", form) for form in include_forms} + 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) @@ -240,7 +255,8 @@ def walk(directory: Path, parts: tuple[str, ...]) -> None: 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() - if (rel and _excludes_subtree(rel, exclude)) or _excludes_selection(rel, parts, exclude): + dropped = (rel and _excludes_subtree(rel, exclude)) or _excludes_selection(rel, parts, exclude) + if dropped and not _links_leave(real): # a link out is judged by where it leads, not by its name here return for child, remaining in _next_steps(directory, parts): walk(child, remaining) diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index f4cb5ec8eb..7be3bd8666 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -288,6 +288,31 @@ def test_select_docs_lists_the_directory_a_literal_link_in_an_excluded_one_leads 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 _link(path: Path, target: Path) -> None: try: path.symlink_to(target, target_is_directory=True) From 386fd4c739abe9d2177198714a98f836030eaf01 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sun, 6 Dec 2026 14:42:47 +0000 Subject: [PATCH 14/14] fix(runner): select_docs and catalog provenance no longer hide an unlistable directory behind a link or a `..` select_docs pruned a directory an exclude drops by the name the walk reaches it by, while the final filter judges the resolved name, so a `..` part after a wildcard and a link to a directory inside the pruned directory each let an unlistable target go unseen. A directory is now pruned only when nothing below it can change a resolved name: no link to a directory below it and no `..` part of the include left. This replaces the link-leaves-the-directory check, which covered only one of the cases. catalog provenance exempted the error row of an unlistable folder whose SKILL.md is a file, but a SKILL.md that is a link out of --root is not read, so the row and the skills below it were dropped. The exemption now needs the file to be under --root, as _skill_file does. Settles the three exai-bot threads on spec.py:260 (two) and catalog_provenance.py:92 and the mutation rows for _links_leave. Signed-off-by: Anton Volkov --- .../20261204_100000_select-docs-unlistable.md | 2 +- .../20261204_100200_provenance-unlistable.md | 2 +- dokimi/dokimi/commands/catalog_provenance.py | 16 ++++++------- dokimi/dokimi/runner/spec.py | 24 ++++++++++--------- dokimi/tests/test_provenance_unlistable.py | 14 +++++++++++ dokimi/tests/test_select_docs_unlistable.py | 23 ++++++++++++++++++ 6 files changed, 60 insertions(+), 21 deletions(-) diff --git a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md index 401b2c42bf..3d731b0651 100644 --- a/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md +++ b/dokimi/changelog.d/20261204_100000_select-docs-unlistable.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### 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 below it that leads out of it is not left out for an `exclude` entry, since the entry is judged on the name of the path and the selection on where the link leads (#1383). +- **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_100200_provenance-unlistable.md b/dokimi/changelog.d/20261204_100200_provenance-unlistable.md index c7b70ff94e..013a6d3d84 100644 --- a/dokimi/changelog.d/20261204_100200_provenance-unlistable.md +++ b/dokimi/changelog.d/20261204_100200_provenance-unlistable.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### 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 manifest entry with no file is still skipped, as `catalog check` reports it (#1480). +- **`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/dokimi/commands/catalog_provenance.py b/dokimi/dokimi/commands/catalog_provenance.py index 8bc8fcb5aa..e82d334c7b 100644 --- a/dokimi/dokimi/commands/catalog_provenance.py +++ b/dokimi/dokimi/commands/catalog_provenance.py @@ -82,19 +82,19 @@ def _skill_file(entry, root: Path) -> Path | None: return path -def _holds_skill_file(folder: Path) -> bool: - """Whether ``folder/SKILL.md`` is a file; a folder that cannot even be searched (mode 000) holds none we can load. +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 or a dangling link named ``SKILL.md`` is no file for :func:`_skill_file`, so it hides the skills beside it. + 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() + return skill_file.is_file() and skill_file.resolve().is_relative_to(root.resolve()) except OSError: return False -def _refuse_unlisted(entries: list) -> None: +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 @@ -102,7 +102,7 @@ def _refuse_unlisted(entries: list) -> None: """ 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): + 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}") @@ -122,12 +122,12 @@ 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) + _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} scanned = _scan_skill_files(root) - _refuse_unlisted(scanned) + _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 = [] diff --git a/dokimi/dokimi/runner/spec.py b/dokimi/dokimi/runner/spec.py index cb7bfe7a43..023d604890 100644 --- a/dokimi/dokimi/runner/spec.py +++ b/dokimi/dokimi/runner/spec.py @@ -140,15 +140,16 @@ def _excludes_subtree(rel_dir: str, patterns: list[str]) -> bool: _BRACKET_OR_WILDCARD = re.compile(r"\[!?\]?[^\]]*\]|[*?]") -def _links_leave(directory: Path) -> bool: - """Whether a link to a directory below ``directory`` leads out of it, where an exclude is judged on the resolved path.""" - real = directory.resolve() - for here, dirs, _files in os.walk(directory): # a directory it cannot list is skipped: it shows no link - for name in dirs: - link = Path(here) / name - if link.is_symlink() and not link.resolve().is_relative_to(real): - return True - return False +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: @@ -238,7 +239,8 @@ def _refuse_unlistable(root: Path, pattern: str, exclude: list[str]) -> None: 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. + 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() @@ -256,7 +258,7 @@ def walk(directory: Path, parts: tuple[str, ...]) -> None: 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 _links_leave(real): # a link out is judged by where it leads, not by its name here + 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) diff --git a/dokimi/tests/test_provenance_unlistable.py b/dokimi/tests/test_provenance_unlistable.py index 2add0bd466..4320a427fc 100644 --- a/dokimi/tests/test_provenance_unlistable.py +++ b/dokimi/tests/test_provenance_unlistable.py @@ -70,6 +70,20 @@ def test_provenance_refuses_an_unlistable_folder_whose_skill_md_is_no_file( 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.""" diff --git a/dokimi/tests/test_select_docs_unlistable.py b/dokimi/tests/test_select_docs_unlistable.py index 7be3bd8666..c9f1a6b5ce 100644 --- a/dokimi/tests/test_select_docs_unlistable.py +++ b/dokimi/tests/test_select_docs_unlistable.py @@ -313,6 +313,29 @@ def test_select_docs_lists_a_directory_a_link_below_an_excluded_one_leads_to(tmp 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)