Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dokimi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!--
Copyright (C) 2026 Intel Corporation
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 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).
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!--
Copyright (C) 2026 Intel Corporation
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, 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).
8 changes: 8 additions & 0 deletions dokimi/changelog.d/20261204_100200_provenance-unlistable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!--
Copyright (C) 2026 Intel Corporation
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 `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).
4 changes: 3 additions & 1 deletion dokimi/docs/coding-harnesses.md
Original file line number Diff line number Diff line change
Expand Up @@ -1001,7 +1001,9 @@ The arms differ by the skill and one notice, and by nothing else:
copied as the files they point to, and only when they point inside the
skill directory and outside its `evals/`: a link out of the skill could
ship a task's `solution/` and `tests/`, and a link to an ancestor would copy
the checkout into itself. Such a skill fails the cell before the image build.
the checkout into itself. Such a skill fails the cell before the image build,
and so does one with a folder that cannot be listed (a hidden or vendored one,
or one under `__pycache__`, where a link would go unchecked and the copy would fail on it).
- `$CLAUDE_CONFIG_DIR/skills` does not work here: it is not loaded under
`--setting-sources ""` (measured, Claude Code 2.1.286).
- `--setting-sources project` would also read the task tree's own
Expand Down
1 change: 1 addition & 0 deletions dokimi/docs/external-content.md
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,7 @@ directory name, is the name for a `similar` match. A checkout that lacks blobs o
partial clone) reports `history: partial` with `missing_blobs`; fetch them for an exact count.
When a manifest leaves the head of the matched path unspecified, the behind column reads
`unknown`. Its JSON fields `at_head`, `behind_commits`, and `behind_months` are null. `--format json` adds the upstreams, one row per skill and a `summary`.
A directory under `--root` that cannot be listed and holds no `SKILL.md`, above the skills, exits 2 and names the directory (`--root: <dir> 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`)

Expand Down
29 changes: 28 additions & 1 deletion dokimi/dokimi/commands/catalog_provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,30 @@ def _skill_file(entry, root: Path) -> Path | None:
return path


def _holds_skill_file(folder: Path, root: Path) -> bool:
"""Whether ``folder/SKILL.md`` is a file under *root*; a folder that cannot even be searched (mode 000) holds none we can load.

A directory, a dangling link or a link out of *root* named ``SKILL.md`` is no file for :func:`_skill_file`, so it hides the skills beside it.
"""
skill_file = folder / "SKILL.md"
try:
return skill_file.is_file() and skill_file.resolve().is_relative_to(root.resolve())
except OSError:
return False


def _refuse_unlisted(entries: list, root: Path) -> None:
"""Refuse the scan's error row of a directory above the skills that cannot be listed (#1480).

The row has no ``SKILL.md`` under its path, so :func:`_skill_file` gives None for it; the table would describe a
smaller tree than ``--root``. A row of a skill that does load or fails its own load is not one.
"""
for entry in entries:
folder = entry.path
if entry.unlisted and entry.error and folder is not None and folder.is_dir() and not _holds_skill_file(folder, root):
raise InputError(f"--root: {entry.error}")


def cmd_catalog_provenance(args: argparse.Namespace) -> None:
from dokimi.external import read_skill_manifest
from dokimi.external import upstream
Expand All @@ -98,10 +122,13 @@ def cmd_catalog_provenance(args: argparse.Namespace) -> None:
entries = read_skill_manifest(root)
except ValueError as exc:
raise InputError(f"skills.yaml: {exc}") from exc
_refuse_unlisted(entries, root)
if (root / "skills.yaml").is_file():
# The manifest lists some skills; every other SKILL.md under --root is still a copy to report.
listed = {f.resolve() for f in (_skill_file(e, root) for e in entries) if f is not None}
entries = [*entries, *(e for e in _scan_skill_files(root)
scanned = _scan_skill_files(root)
_refuse_unlisted(scanned, root)
entries = [*entries, *(e for e in scanned
if (f := _skill_file(e, root)) is not None and f.resolve() not in listed)]
rows = []
for entry in entries:
Expand Down
21 changes: 18 additions & 3 deletions dokimi/dokimi/harnesses/skill_treatment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -139,6 +140,19 @@ def check_skill(skill_dir: Path) -> str:
return skill.name


def _refuse_unlisted(exc: OSError, skill_dir: Path) -> None:
"""``os.walk``'s ``onerror`` and the loop check's: a folder that cannot be listed is a ``ValueError`` (#1479).

A link in it would go unchecked, and the copy would then fail on it with a ``shutil.Error``. A folder
:func:`load_skill` refuses (not under a dot-named, vendored or ``__pycache__`` one it leaves out) is left to it.
"""
folder = Path(str(exc.filename))
inside = [folder, *folder.parents][:len(folder.relative_to(skill_dir).parts)] # up to the skill, not above it
if any(_not_listed_as_resource(p) for p in inside):
raise ValueError(f"skill folder {folder} cannot be listed ({exc.strerror}), "
"so the links in it are not checked and the copy would fail")


def _check_links(skill_dir: Path) -> None:
"""Refuse a link that leaves the skill, points into its ``evals/``, loops, or dangles.

Expand All @@ -148,7 +162,7 @@ def _check_links(skill_dir: Path) -> None:
the checkout into itself until ``ELOOP``.
"""
root = skill_dir.resolve()
for dirpath, dirnames, filenames in os.walk(skill_dir): # does not descend into links
for dirpath, dirnames, filenames in os.walk(skill_dir, onerror=lambda exc: _refuse_unlisted(exc, skill_dir)): # does not descend into links
here = Path(dirpath)
if here == skill_dir: # the top-level evals/ is not copied, see build_plugin
dirnames[:] = [d for d in dirnames if d != "evals"]
Expand Down Expand Up @@ -183,8 +197,9 @@ def visit(directory: Path, real: Path, stack: tuple[Path, ...]) -> None:
with os.scandir(directory) as entries:
children = [Path(e.path) for e in entries if e.is_dir()
and not (directory == skill_dir and e.name == "evals")]
except OSError:
return # unreadable, as os.walk would have skipped it: the copy reports it
except OSError as exc:
_refuse_unlisted(exc, skill_dir)
return # one load_skill refuses next, naming it
for child in children:
target = child.resolve()
if not target.is_relative_to(root) or target in done:
Expand Down
123 changes: 123 additions & 0 deletions dokimi/dokimi/runner/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@

from __future__ import annotations

import errno
import fnmatch
import itertools
import os
import re
from pathlib import Path

import yaml
Expand Down Expand Up @@ -117,6 +119,53 @@ def _is_excluded(rel_path: str, patterns: list[str]) -> bool:
return False


def _excludes_subtree(rel_dir: str, patterns: list[str]) -> bool:
"""Whether the exclude ``patterns`` drop every file below the directory ``rel_dir``, not only one name in it.

A pattern does when it names the directory or a parent (``docs/sub``, ``docs/sub/**``), or one of its forms ends in
``*``, which crosses ``/`` in fnmatch, and matches the directory (``docs/s*``) or the directory and a ``/``
(``docs/sub/*``). ``docs/*/x`` drops one file name below it, not the subtree; nor does ``docs/sub?/**``, whose
form ``docs/sub?`` matches ``docs/sub/`` through the ``?`` but no file below it.
"""
for pattern in patterns:
prefix = pattern.rstrip("/").removesuffix("/**").rstrip("/")
if rel_dir == prefix or rel_dir.startswith(prefix + "/"):
return True
if any(form.endswith("*") and fnmatch.fnmatch(rel_dir + "/", form) for form in _zero_dir_forms(pattern)):
return True
return False # mutation-ok[return-none]: None is as false as False


# fnmatch's class: ``[``, an optional ``!``, an optional ``]`` that is a member, the rest up to the closing ``]``
_BRACKET_OR_WILDCARD = re.compile(r"\[!?\]?[^\]]*\]|[*?]")


def _can_rename(directory: Path, parts: tuple[str, ...]) -> bool:
"""Whether a path below ``directory`` can resolve to another name than the one the walk reaches it by.

An exclude is judged on the resolved name of a document, so it drops a directory's documents by that directory's
name only when no link to a directory (it may lead out or to a sibling) and no ``..`` part of the include is left.
"""
if ".." in parts:
return True
# a directory it cannot list is skipped: it shows no link
return any((Path(here) / name).is_symlink() for here, dirs, _files in os.walk(directory) for name in dirs)


def _excludes_selection(rel_dir: str, parts: tuple[str, ...], patterns: list[str]) -> bool:
"""Whether the exclude ``patterns`` drop every file the include ``parts`` can still select below ``rel_dir``.

A form of an exclude pattern made of literals and ``*`` covers a form of the include when it matches that form with
each of the include's wildcards replaced by a character no literal of the exclude has: the ``*`` of the exclude
take the place of whatever the wildcards match. ``docs/*.md`` covers ``docs/restricted/**/*.md``. A form with ``?``
or ``[`` is never taken to cover, so that the directory is refused as before.
"""
include_forms = {f"{rel_dir}/{form}" if rel_dir else form for form in _zero_dir_forms("/".join(parts))}
samples = {"/".join(_BRACKET_OR_WILDCARD.sub("\0", seg) for seg in form.split("/")) for form in include_forms}
forms = {form for pattern in patterns for form in _zero_dir_forms(pattern) if not any(c in form for c in "?[")}
return any(all(fnmatch.fnmatchcase(sample, form) for sample in samples) for form in forms)


def _literal_prefix(root: Path, pattern: str) -> Path:
"""The leading path of ``pattern`` without wildcards, cut at the first part that is a symlink."""
base = Path()
Expand Down Expand Up @@ -181,6 +230,79 @@ def _symlink_note(root: Path, include: list[str], exclude: list[str], escaped: l
return (" " + "; ".join(notes) + ".") if notes else ""


def _refuse_unlistable(root: Path, pattern: str, exclude: list[str]) -> None:
"""Raise :class:`DocSelectionError` for a directory the include ``pattern`` has to list and cannot (#1383).

``Path.glob`` skips such a directory, so the documents under it would be missing from a set that is then
counted against ``min_docs``. Only a directory a wildcard part lists is an error: one the exclude list drops with
everything below it (``docs/sub`` or ``docs/sub/**``, not ``docs/[s]ub``, which drops the directory and no file), one
outside ``root``, one whose every document the include can still select an exclude pattern drops (``docs/*.md``
for the ``docs/**/*.md`` below ``docs/sub``), one only named (a literal part, however it is reached) and a path that is not there are not.
A literal part is followed also outside ``root`` and through an excluded directory, since ``..`` or a link can lead
back in; only a directory a wildcard lists is pruned, and not one with a link to a directory below it or a ``..``
part of the include left (:func:`_can_rename`).
"""
root_resolved = root.resolve()
seen: set[tuple[Path, tuple[str, ...]]] = set()

def walk(directory: Path, parts: tuple[str, ...]) -> None:
try:
real = directory.resolve()
except (RuntimeError, OSError): # a loop of links leads nowhere
return
lists = any(c in parts[0] for c in "*?[") # a name is only looked up, so it needs no pruning
# mutation-ok[drop-clause]: ``seen`` only keeps ``**/**`` from walking a directory twice
if (lists and not real.is_relative_to(root_resolved)) or (real, parts) in seen: # outside: never selected
return
seen.add((real, parts)) # mutation-ok[delete-statement]: see above
if lists:
rel = "" if real == root_resolved else real.relative_to(root_resolved).as_posix()
dropped = (rel and _excludes_subtree(rel, exclude)) or _excludes_selection(rel, parts, exclude)
if dropped and not _can_rename(real, parts): # a link or a ``..`` below is judged by where it leads
return
for child, remaining in _next_steps(directory, parts):
walk(child, remaining)

walk(root, Path(pattern).parts)


def _next_steps(directory: Path, parts: tuple[str, ...]) -> list[tuple[Path, tuple[str, ...]]]:
"""Where ``Path.glob`` goes from ``directory`` with ``parts``: a name is entered, a wildcard lists, ``**`` skips links."""
head, rest = parts[0], parts[1:]
recursive = head == "**"
if not any(c in head for c in "*?["): # ``**`` has a ``*``
return [(directory / head, rest)] if rest else [] # the last name is looked up, not listed
steps = []
for entry in _scan(directory):
if recursive and _is_dir(entry, follow_symlinks=False):
steps.append((Path(entry.path), parts))
elif not recursive and rest and fnmatch.fnmatch(entry.name, head) and _is_dir(entry):
steps.append((Path(entry.path), rest))
# mutation-ok[drop-clause]: a wildcard part walking its own directory again lists only what it listed already
if recursive and rest: # ``**`` also matches no directory
steps.append((directory, rest))
return steps


def _scan(directory: Path) -> list[os.DirEntry[str]]:
"""The entries of ``directory``; none for a path that is not there, :class:`DocSelectionError` if it cannot be listed."""
try:
with os.scandir(directory) as entries:
return list(entries)
except OSError as exc:
if exc.errno in (errno.ENOENT, errno.ENOTDIR, errno.ELOOP):
return []
raise DocSelectionError(f"cannot list {exc.filename}: {exc.strerror}") from exc


def _is_dir(entry: os.DirEntry[str], follow_symlinks: bool = True) -> bool:
"""``entry.is_dir``, false for a link whose target cannot be reached (``Path.glob`` leaves it out too)."""
try:
return entry.is_dir(follow_symlinks=follow_symlinks)
except OSError:
return False # mutation-ok[return-none]: None is as false as False


def select_docs(root: Path, manifest: dict) -> list[Path]:
"""Resolve and bound the document set from a ``golden_manifest``.

Expand All @@ -200,6 +322,7 @@ def select_docs(root: Path, manifest: dict) -> list[Path]:
matches = list(root.glob(pattern))
except (ValueError, NotImplementedError) as exc: # an empty or absolute pattern
raise DocSelectionError(f"golden_manifest include pattern {pattern!r}: {exc}") from exc
_refuse_unlistable(root, pattern, exclude)
for p in matches:
# Reject matches that escape root (e.g. via ".." in a pattern).
if not p.is_file():
Expand Down
Loading
Loading