diff --git a/dokimi/changelog.d/20261123_130000_catalog-scan-unlistable-subdir.md b/dokimi/changelog.d/20261123_130000_catalog-scan-unlistable-subdir.md new file mode 100644 index 000000000..48555d41d --- /dev/null +++ b/dokimi/changelog.d/20261123_130000_catalog-scan-unlistable-subdir.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A catalog scan row has no `skill_sha256` when a subdirectory of the skill cannot be listed** — `skill_dir_digest` walked with `Path.rglob`, which skips a subdirectory it cannot list (mode `0o111`) without an error, so the row carried a digest of a smaller tree. The walk is now strict: `skill_sha256` is `null`. The digest of a tree that can be listed is unchanged. diff --git a/dokimi/changelog.d/20261123_130100_arms-tree-sha256-unlistable-subdir.md b/dokimi/changelog.d/20261123_130100_arms-tree-sha256-unlistable-subdir.md new file mode 100644 index 000000000..696b7237d --- /dev/null +++ b/dokimi/changelog.d/20261123_130100_arms-tree-sha256-unlistable-subdir.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **The skill digests of a repo arms run raise when a subdirectory cannot be listed** — `tree_sha256` (the skill pins of a batch, the skill records of a run) walked with `Path.rglob`, which skips a subdirectory it cannot list (mode `0o111`) without an error, so it digested a smaller tree. It now raises `PermissionError` naming the directory. The digest of a tree that can be listed is unchanged. diff --git a/dokimi/changelog.d/20261123_130200_reach-fixtures-digest-unlistable-subdir.md b/dokimi/changelog.d/20261123_130200_reach-fixtures-digest-unlistable-subdir.md new file mode 100644 index 000000000..1955ac9d7 --- /dev/null +++ b/dokimi/changelog.d/20261123_130200_reach-fixtures-digest-unlistable-subdir.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **The reach matrix's `fixtures_digest` raises when a directory of the fixtures cannot be listed** — it walked with `Path.rglob`, which skips a directory it cannot list (mode `0o111`) without an error, so the matrix carried the digest of a smaller fixture tree. It now raises `PermissionError` naming the directory. The digest of a tree that can be listed is unchanged, and a link (to a directory too, or dangling) is still hashed by its target. diff --git a/dokimi/changelog.d/20261123_130300_novelty-bundle-unlistable-subdir.md b/dokimi/changelog.d/20261123_130300_novelty-bundle-unlistable-subdir.md new file mode 100644 index 000000000..ba1f9903a --- /dev/null +++ b/dokimi/changelog.d/20261123_130300_novelty-bundle-unlistable-subdir.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A novelty bundle raises when a subdirectory of the skill cannot be listed** — `load_bundle` listed the skill's files with `Path.rglob`, which skips a subdirectory it cannot list (mode `0o111`) without an error, so the bundle, its `measured_digest` and `resource_words_on_disk` described a smaller skill and the dropped files were not recorded as excluded. It now raises `PermissionError` naming the directory. A skill that can be listed loads as before. diff --git a/dokimi/changelog.d/20261123_140000_catalog-resume-null-digest.md b/dokimi/changelog.d/20261123_140000_catalog-resume-null-digest.md new file mode 100644 index 000000000..17bced499 --- /dev/null +++ b/dokimi/changelog.d/20261123_140000_catalog-resume-null-digest.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **`catalog scan --resume` rescans a skill whose digest is null** — a prior row with `skill_sha256: null` was kept when the skill's digest is null now too (`None == None`), so a skill with an unlistable subdirectory kept its old findings after `SKILL.md` changed. It is rescanned. diff --git a/dokimi/changelog.d/20261123_140100_novelty-bundle-skips-non-content-dirs.md b/dokimi/changelog.d/20261123_140100_novelty-bundle-skips-non-content-dirs.md new file mode 100644 index 000000000..178f8ad4b --- /dev/null +++ b/dokimi/changelog.d/20261123_140100_novelty-bundle-skips-non-content-dirs.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A novelty bundle does not list a directory that is not skill content** — `load_bundle` lists a skill's files strictly, and skips a dot-named directory or one named in `SKIP_DIR_NAMES` (`.git`, `venv`, ...) before it is listed, so one of those that cannot be listed does not stop the skill from loading. diff --git a/dokimi/docs/catalog-jsonl.md b/dokimi/docs/catalog-jsonl.md index 925a9be16..a814dddb7 100644 --- a/dokimi/docs/catalog-jsonl.md +++ b/dokimi/docs/catalog-jsonl.md @@ -40,7 +40,7 @@ The text on stdout is only the counts. A run killed midway keeps the whole lines | `error` | string or null | the load error, when the skill did not load | | `disable_model_invocation` | boolean | the skill sets `disable-model-invocation: true`, so the description-quality checks skip it; the frontmatter length limit still applies | | `content_sha256` | string or null | digest of the SKILL.md text; null when there is no review | -| `skill_sha256` | string or null | digest of every file in the skill's directory (the scan's own output files excluded); used by `--resume` | +| `skill_sha256` | string or null | digest of every file in the skill's directory (the scan's own output files excluded); null when the directory or a subdirectory cannot be read; used by `--resume` | | `dokimi_version` | string | the dokimi version that wrote the row; `--resume` redoes rows from another version | | `listing_chars` | integer or null | characters of the skill's entry in the routing field's listing (`name: description`, then ` - when_to_use` when it is not empty; the description and `when_to_use` count at most 1,536 characters); null when the skill is not listed (it does not load, has a spec error other than a long description, or sets `disable-model-invocation`). `--resume` redoes a row without it | | `listing_name` | string or null | the name the routing field knows the skill by: the loaded `SKILL.md` name, which can differ from `name` (a manifest alias); null when the skill did not load. The listing total groups copies by it. `--resume` redoes a row without it | diff --git a/dokimi/docs/reach-matrix.md b/dokimi/docs/reach-matrix.md index 5b1b5456c..2fb1e1c96 100644 --- a/dokimi/docs/reach-matrix.md +++ b/dokimi/docs/reach-matrix.md @@ -108,7 +108,7 @@ authenticates the run. For Bedrock, also set `CLAUDE_CODE_USE_BEDROCK=1` and same fixture, so a merge cannot double-count (failed and skipped runs hold no cells and are kept as they are). Each matrix carries `expectations_digest`, the sha256 of the expectations it was scored against; `merge` refuses matrices with different digests, and the `merge` command refuses ones whose digest is not that of its `--expectations` file. Each also carries -`fixtures_digest`, the sha256 of everything under the fixtures root its runs observed, and `merge` refuses matrices +`fixtures_digest`, the sha256 of everything under the fixtures root its runs observed (a directory that cannot be listed is an error, not a smaller tree), and `merge` refuses matrices with different ones: an edited fixture would otherwise read as a change between harness versions. The root also holds `guidance.yaml` and, by default, `expectations.yaml`, so an edit to either, even to a comment, changes the digest. diff --git a/dokimi/dokimi/commands/catalog_scan.py b/dokimi/dokimi/commands/catalog_scan.py index c3d6bee61..16dc4911e 100644 --- a/dokimi/dokimi/commands/catalog_scan.py +++ b/dokimi/dokimi/commands/catalog_scan.py @@ -97,7 +97,7 @@ def skill_dir_digest(entry, outputs: Iterable[Path] = ()) -> Optional[str]: try: base = path.resolve() skip = [out.relative_to(base).as_posix() for out in outputs if out.is_relative_to(base)] - return tree_digest(path, exclude=skip, tracked={}) + return tree_digest(path, exclude=skip, strict=True, tracked={}) except OSError: return None @@ -341,7 +341,7 @@ def _load_prior(path: Path, selected: dict[str, Optional[str]], ignore: frozense if row is None: continue key = _row_key(row) - if (key in selected and "skill_sha256" in row and "listing_chars" in row and "listing_name" in row and row["skill_sha256"] == selected[key] + if (key in selected and "skill_sha256" in row and "listing_chars" in row and "listing_name" in row and selected[key] is not None and row["skill_sha256"] == selected[key] and row.get("ignored", []) == sorted(ignore) and row.get("dokimi_version") == __version__): rows.append(row) else: diff --git a/dokimi/dokimi/digest_entries.py b/dokimi/dokimi/digest_entries.py index e777a6a59..50c8a5ae3 100644 --- a/dokimi/dokimi/digest_entries.py +++ b/dokimi/dokimi/digest_entries.py @@ -2,15 +2,23 @@ # SPDX-License-Identifier: Apache-2.0 """The digest of one entry a repo config subject walks: a file by its content and executable bit, a link by -its target text. ``repo_config._digest_files`` digests each entry with these.""" +its target text. ``repo_config._digest_files`` digests each entry with these. :func:`listed_entries` lists the entries +a digest of a tree walks.""" import hashlib import os import stat from pathlib import Path -from typing import Mapping +from typing import Callable, Mapping -from dokimi.utils import _tracked_modes, file_digest, link_text +from dokimi.utils import _entries, _tracked_modes, file_digest, link_text + + +def listed_entries(root: Path, drop: Callable[[Path], bool] | None = None) -> list[Path]: + """Every entry under ``root`` as ``root.rglob("*")`` lists them (directories included, a symlink as itself and not + followed), in no set order; a directory that cannot be listed raises its OSError where ``rglob`` skips it. An + entry ``drop`` names is left out and, when a directory, not listed, so it cannot raise.""" + return _entries(root, (), strict=True, drop=drop) def target_digest(target: Path, root_real: Path, modes: Mapping[str, bool] | None, holds: Mapping[Path, bytes]) -> str: diff --git a/dokimi/dokimi/novelty/bundle.py b/dokimi/dokimi/novelty/bundle.py index fbd656940..c0b2f992d 100644 --- a/dokimi/dokimi/novelty/bundle.py +++ b/dokimi/dokimi/novelty/bundle.py @@ -60,6 +60,7 @@ exclusion_kind, named_exclusions, ) +from dokimi.digest_entries import listed_entries from dokimi.utils import key_bytes from .answer_key import ABSENT, AnswerKeyRecord, parse_answer_key, shown @@ -107,6 +108,11 @@ SKIP_DIR_NAMES = frozenset({"__pycache__", "node_modules", "build", "dist", ".git", "venv", "env", "virtualenv", "site-packages"}) +def _not_content_dir(path: Path) -> bool: + """A dot-named entry, or a real directory named in :data:`SKIP_DIR_NAMES`: skipped before it is listed.""" + return path.name.startswith(".") or (path.name in SKIP_DIR_NAMES and path.is_dir() and not path.is_symlink()) + + #: Prefix of the heading `_stitch` injects before each bundled file. Those headings are #: scaffolding, not artifact text, so they are reported as pointer spans rather than #: counted as tokens that carry no knowledge. @@ -339,7 +345,7 @@ def load_bundle( if kind == "skill" and root.is_dir(): order = {"reference": 0, "pattern": 1, "eval": 2} entry_file = (entry if entry.is_file() else root / entry_name).resolve() - for path in sorted(root.rglob("*")): + for path in sorted(listed_entries(root, drop=_not_content_dir)): # A directory or dangling symlink is not a file, but it is still recorded below. if not path.is_file() and not path.is_symlink(): continue diff --git a/dokimi/dokimi/repos/arms.py b/dokimi/dokimi/repos/arms.py index 3e26ae63e..a192988d6 100644 --- a/dokimi/dokimi/repos/arms.py +++ b/dokimi/dokimi/repos/arms.py @@ -29,6 +29,7 @@ import yaml from dokimi.skills.formats import SPEC_NAME_MAX +from dokimi.digest_entries import listed_entries from dokimi import process @@ -298,9 +299,9 @@ def _check_expected_skills(arm: Any, tasks: list[Any], names: set[str], generate def tree_sha256(root: Path) -> str: - """sha256 over the relative paths and bytes of the files under ``root``.""" + """sha256 over the relative paths and bytes of the files under ``root``; a directory that cannot be listed raises.""" h = hashlib.sha256() - for path in sorted(p for p in root.rglob("*") if p.is_file()): + for path in sorted(p for p in listed_entries(root) if p.is_file()): h.update(os.fsencode(path.relative_to(root).as_posix()) + b"\0") h.update(hashlib.sha256(path.read_bytes()).digest()) return h.hexdigest() diff --git a/dokimi/dokimi/repos/conformance.py b/dokimi/dokimi/repos/conformance.py index 180181804..5cbf65141 100644 --- a/dokimi/dokimi/repos/conformance.py +++ b/dokimi/dokimi/repos/conformance.py @@ -27,6 +27,7 @@ from dokimi import process from dokimi.artifacts import load_artifact, save_artifact, schema_errors from dokimi.repos.reach import PROSE_LIMIT +from dokimi.digest_entries import listed_entries SCHEMA_EXPECTATIONS = "reach_conformance.v1" RECEIPT_NAME = "effective_instructions.json" @@ -110,9 +111,11 @@ def expectations_digest(expect: Mapping[str, Any]) -> str: def fixtures_digest(fixtures: Path) -> str: - """The sha256 of everything under the fixtures root (each file's path and bytes, a link's target), including its guidance file and, by default, its expectations file.""" + """The sha256 of everything under the fixtures root (each file's path and bytes, a link's target), including its guidance file and, by default, its expectations file. + + A directory that cannot be listed raises its OSError: the digest never describes a smaller tree.""" h = hashlib.sha256() - for p in sorted(fixtures.rglob("*"), key=lambda p: p.relative_to(fixtures).as_posix()): + for p in sorted(listed_entries(fixtures), key=lambda p: p.relative_to(fixtures).as_posix()): if not (p.is_symlink() or p.is_file()): continue data = b"L" + os.fsencode(os.readlink(p)) if p.is_symlink() else b"F" + p.read_bytes() diff --git a/dokimi/tests/test_catalog_scan_unlistable.py b/dokimi/tests/test_catalog_scan_unlistable.py new file mode 100644 index 000000000..02aa0633e --- /dev/null +++ b/dokimi/tests/test_catalog_scan_unlistable.py @@ -0,0 +1,65 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1103: ``skill_dir_digest`` is None for a skill directory with a subdirectory it cannot list, not a digest of a smaller tree. + +``skill_sha256`` of a catalog row is None then. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from dokimi import __version__ +from dokimi.commands.catalog_scan import _load_prior, skill_dir_digest +from dokimi.utils import tree_digest + + +def _skill(tmp_path: Path) -> Path: + skill = tmp_path / "skill" + (skill / "sub").mkdir(parents=True) + (skill / "SKILL.md").write_text("---\nname: skill\ndescription: d\n---\nbody\n", encoding="utf-8") + (skill / "sub" / "b.txt").write_text("b", encoding="utf-8") + return skill + + +def _entry(skill: Path) -> SimpleNamespace: + return SimpleNamespace(loaded=False, skill=None, path=skill) + + +@pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") +def test_a_skill_with_a_subdirectory_that_cannot_be_listed_has_no_digest(tmp_path: Path): + skill = _skill(tmp_path) + complete = skill_dir_digest(_entry(skill)) + assert complete is not None + (skill / "sub").chmod(0o111) + try: + assert skill_dir_digest(_entry(skill)) is None + finally: + (skill / "sub").chmod(0o700) + assert skill_dir_digest(_entry(skill)) == complete + + +@pytest.mark.parametrize(("digest", "kept"), [(None, False), ("abc", True)]) +def test_resume_keeps_a_prior_row_only_when_its_digest_is_a_digest(tmp_path: Path, digest: str | None, kept: bool): + row = {"name": "skill", "relpath": "skill", "state": "ok", "error": None, "findings": [], "content_sha256": None, + "skill_sha256": digest, "listing_chars": 1, "listing_name": "skill", "ignored": [], + "dokimi_version": __version__} + jsonl = tmp_path / "scan.jsonl" + jsonl.write_text(json.dumps(row) + "\n", encoding="utf-8") + rows, dirty = _load_prior(jsonl, {"skill": digest}, frozenset()) + assert (rows == [row], dirty) == (kept, not kept) + + +def test_a_listable_skill_digests_as_the_non_strict_walk_did(tmp_path: Path): + skill = _skill(tmp_path) + (skill / "eval").mkdir() + (skill / "eval" / "out.jsonl").write_text("{}", encoding="utf-8") + out = (skill / "eval" / "out.jsonl").resolve() + assert skill_dir_digest(_entry(skill), [out]) == tree_digest(skill, exclude=["eval/out.jsonl"], tracked={}) + assert skill_dir_digest(_entry(skill)) == tree_digest(skill, tracked={}) diff --git a/dokimi/tests/test_novelty_bundle_unlistable.py b/dokimi/tests/test_novelty_bundle_unlistable.py new file mode 100644 index 000000000..ab262947b --- /dev/null +++ b/dokimi/tests/test_novelty_bundle_unlistable.py @@ -0,0 +1,72 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1106: ``load_bundle`` raises for a skill subdirectory it cannot list, not a bundle of a smaller skill.""" + +from __future__ import annotations + +import os +from pathlib import Path + +import pytest + +from dokimi.novelty.bundle import load_bundle + + +def _skill(tmp_path: Path) -> Path: + skill = tmp_path / "skill" + (skill / "references").mkdir(parents=True) + (skill / "SKILL.md").write_text("---\nname: skill\ndescription: d\n---\nUse the references.\n", encoding="utf-8") + (skill / "references" / "a.md").write_text("alpha beta gamma\n", encoding="utf-8") + return skill + + +@pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") +@pytest.mark.parametrize("include_resources", [True, False]) +def test_a_subdirectory_that_cannot_be_listed_raises(tmp_path: Path, include_resources: bool): + skill = _skill(tmp_path) + (skill / "references").chmod(0o111) + try: + with pytest.raises(PermissionError, match="references"): + load_bundle(f"skill:{skill}", include_resources=include_resources) + finally: + (skill / "references").chmod(0o700) + assert [f.path for f in load_bundle(f"skill:{skill}", include_resources=True).files] == ["SKILL.md", "references/a.md"] + + +@pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") +@pytest.mark.parametrize("name", [".git", "venv", "node_modules"]) +@pytest.mark.parametrize("include_resources", [True, False]) +def test_a_directory_that_is_not_content_is_not_listed(tmp_path: Path, name: str, include_resources: bool): + skill = _skill(tmp_path) + (skill / name).mkdir() + (skill / name).chmod(0o111) + try: + bundle = load_bundle(f"skill:{skill}", include_resources=include_resources) + finally: + (skill / name).chmod(0o700) + assert [f.path for f in bundle.files] == (["SKILL.md", "references/a.md"] if include_resources else ["SKILL.md"]) + + +def test_a_file_named_like_a_skipped_directory_is_still_read(tmp_path: Path): + skill = _skill(tmp_path) + (skill / "references" / "build").write_text("one two\n", encoding="utf-8") + assert [f.path for f in load_bundle(f"skill:{skill}", include_resources=True).files] == [ + "SKILL.md", "references/a.md", "references/build"] + + +def test_a_listable_skill_keeps_its_files_digest_and_words_on_disk(tmp_path: Path): + skill = _skill(tmp_path) + (skill / "references" / "deeper").mkdir() + (skill / "references" / "deeper" / "b.md").write_text("delta\n", encoding="utf-8") + bundle = load_bundle(f"skill:{skill}", include_resources=True) + assert [(f.path, f.role) for f in bundle.files] == [ + ("SKILL.md", "entry_point"), ("references/a.md", "reference"), ("references/deeper/b.md", "reference")] + assert bundle.resource_words_on_disk == 4 + + +def test_a_symlink_named_like_a_skipped_directory_is_excluded_as_a_symlink(tmp_path: Path): + skill = _skill(tmp_path) + (skill / "venv").symlink_to("references") + bundle = load_bundle(f"skill:{skill}", include_resources=True) + assert [(row["path"], row["reason"]) for row in bundle.excluded] == [("venv", "symlink")] diff --git a/dokimi/tests/test_reach_conformance.py b/dokimi/tests/test_reach_conformance.py index e84060863..d1898d4b0 100644 --- a/dokimi/tests/test_reach_conformance.py +++ b/dokimi/tests/test_reach_conformance.py @@ -383,8 +383,8 @@ def test_fixtures_digest_does_not_depend_on_the_walk_order(tmp_path, monkeypatch (tree / name).write_text(name, encoding="utf-8") os.symlink("a.md", tree / "L.md") ordinary = cf.fixtures_digest(tree) - walk = type(tree).rglob - monkeypatch.setattr(type(tree), "rglob", lambda self, pattern: reversed(list(walk(self, pattern)))) + walk = cf.listed_entries + monkeypatch.setattr(cf, "listed_entries", lambda root: list(reversed(walk(root)))) assert cf.fixtures_digest(tree) == ordinary # the same tree, walked in the other order: one digest diff --git a/dokimi/tests/test_reach_fixtures_unlistable.py b/dokimi/tests/test_reach_fixtures_unlistable.py new file mode 100644 index 000000000..ff1c2601e --- /dev/null +++ b/dokimi/tests/test_reach_fixtures_unlistable.py @@ -0,0 +1,53 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1105: ``fixtures_digest`` raises for a directory it cannot list, not a digest of a smaller fixture tree. + +The digest is the matrix's ``fixtures_digest`` (docs/reach-matrix.md): matrices with different digests are not merged. +""" + +from __future__ import annotations + +import hashlib +import os +from pathlib import Path + +import pytest + +from dokimi.repos import conformance as cf + + +def _tree(tmp_path: Path) -> Path: + tree = tmp_path / "t" + (tree / "case" / "sub").mkdir(parents=True) + (tree / "case" / "AGENTS.md").write_bytes(b"x\n") + (tree / "case" / "sub" / "CLAUDE.md").write_bytes(b"y\n") + return tree + + +@pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") +@pytest.mark.parametrize("parts", [(), ("case",), ("case", "sub")]) # the fixtures root, a case, a directory below a listable one +def test_a_directory_that_cannot_be_listed_raises(tmp_path: Path, parts: tuple[str, ...]): + tree = _tree(tmp_path) + unlistable = tree.joinpath(*parts) + complete = cf.fixtures_digest(tree) + unlistable.chmod(0o111) + try: + with pytest.raises(PermissionError, match=unlistable.name): + cf.fixtures_digest(tree) + finally: + unlistable.chmod(0o700) + assert cf.fixtures_digest(tree) == complete + + +def test_a_link_to_a_directory_and_a_dangling_link_are_hashed_by_their_target(tmp_path: Path): + tree = _tree(tmp_path) + try: + os.symlink("case", tree / "dirlink", target_is_directory=True) + os.symlink("nowhere", tree / "dangling") + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + parts = (b"case/AGENTS.md", b"Fx\n", b"case/sub/CLAUDE.md", b"Fy\n", # sorted by relative path: the link to a directory is not entered + b"dangling", b"Lnowhere", b"dirlink", b"Lcase") + expected = hashlib.sha256(b"".join(len(part).to_bytes(8, "big") + part for part in parts)).hexdigest() + assert cf.fixtures_digest(tree) == expected diff --git a/dokimi/tests/test_repo_arms_unlistable.py b/dokimi/tests/test_repo_arms_unlistable.py new file mode 100644 index 000000000..9c9296668 --- /dev/null +++ b/dokimi/tests/test_repo_arms_unlistable.py @@ -0,0 +1,57 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1104: ``tree_sha256`` raises for a subdirectory it cannot list, not a digest of a smaller tree.""" + +from __future__ import annotations + +import hashlib +import os +from pathlib import Path + +import pytest + +from dokimi.digest_entries import listed_entries +from dokimi.repos.arms import tree_sha256 + + +def _skill(tmp_path: Path) -> Path: + skill = tmp_path / "skill" + (skill / "sub" / "deeper").mkdir(parents=True) + (skill / "SKILL.md").write_bytes(b"skill\n") + (skill / "sub" / "b.txt").write_text("b", encoding="utf-8") + (skill / "sub" / "deeper" / "c.txt").write_text("c", encoding="utf-8") + return skill + + +@pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") +@pytest.mark.parametrize("parts", [(), ("sub",), ("sub", "deeper")]) # the root itself, a subdirectory, one below a listable one +def test_a_skill_with_a_directory_that_cannot_be_listed_raises(tmp_path: Path, parts: tuple[str, ...]): + skill = _skill(tmp_path) + unlistable = skill.joinpath(*parts) + complete = tree_sha256(skill) + unlistable.chmod(0o111) + try: + with pytest.raises(PermissionError, match=unlistable.name): + tree_sha256(skill) + finally: + unlistable.chmod(0o700) + assert tree_sha256(skill) == complete + + +def test_a_listable_skill_digests_as_the_rglob_walk_did(tmp_path: Path): + skill = _skill(tmp_path) + expected = hashlib.sha256() + for rel, data in (("SKILL.md", b"skill\n"), ("sub/b.txt", b"b"), ("sub/deeper/c.txt", b"c")): + expected.update(rel.encode() + b"\0" + hashlib.sha256(data).digest()) + assert tree_sha256(skill) == expected.hexdigest() + + +def test_listed_entries_are_those_of_rglob_with_a_directory_link_not_followed(tmp_path: Path): + skill = _skill(tmp_path) + try: + (skill / "link").symlink_to(skill / "sub", target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("symlinks are not available") + (skill / "dangling").symlink_to(skill / "missing") + assert sorted(listed_entries(skill)) == sorted(skill.rglob("*"))