Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- **Four repo-eval readers refuse a directory they cannot list instead of reading it as empty** — an eval `tasks` directory at mode `0o111` gave `no task under eval/tasks`, `repo report` and `repo compare` of a batch directory reported no missing cell and no unsupported one, the check of a batch against another execution found none and let `repo run` resume or report with the cells of two executions mixed, and `eval tasks generate --from prs` or `--from history` did not see the tasks already in `--out-dir` and authored the pull request again. Each now stops with `cannot list <directory>: Permission denied`: `repo report` and `repo compare` exit 2, `repo run` and `eval tasks generate` refuse and exit 1 as they do for their other unusable inputs. A missing directory still has no entries.
8 changes: 6 additions & 2 deletions dokimi/docs/repo-evaluation-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,8 @@ malformed source, an unpinned remote, a local source that is not a directory, a
a repository that is not its root (`<repo>/sub@<sha>`: give the root), or a `--cache-dir` that is not a usable directory. It exits 1 when the pull request file cannot be read or
holds no pull request, when no pull request gave a task (written, or kept from before), and on
an error that is not one pull request's own: a malformed pull request (a `number` that is not
an integer), a source it cannot open, a manifest that is missing or malformed, the prompt file (unreadable or empty), or a task it
an integer), a source it cannot open, a manifest that is missing or malformed, the prompt file (unreadable or empty), an `--out-dir` that cannot be listed (its tasks cannot be told from none, so a pull request
would be authored again), or a task it
cannot write. Each prints `✗` and the reason; a `--manifest` path that leaves the source tree exits 2 instead, pinned or not. Grading a task needs the manifest's
`entry_points.test` (§2).

Expand Down Expand Up @@ -2618,7 +2619,10 @@ python cli.py repo compare repo-runs/authoring --baseline guidance:none --metric
- Each cell holds the §4 inputs plus `agent.stdout` (the raw trace) and
`result.json`, the framework's verdict. A cell with `result.json` is skipped
on a rerun unless `--force`; a cell without one is reported as missing, not
failed, and the next run of the batch fills it. `meta.json` and
failed, and the next run of the batch fills it. A batch directory that cannot be listed is refused
(`repo run`: it cannot tell whether the cells of another execution are in it; `repo report`,
`repo compare`: exit 2), not read as one with no cell; so is an eval `tasks` directory that cannot be listed
(`no task under ...` would blame a missing task). `meta.json` and
`result.json` record `execution`: the tool mode, the delegation mode (the one
whose arguments ran; a skill with `context: fork` can still start a subagent
under `none`) and an
Expand Down
20 changes: 19 additions & 1 deletion dokimi/dokimi/digest_entries.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

"""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. :func:`listed_entries` lists the entries
a digest of a tree walks; :func:`children_matching` and :func:`pack_files` list one directory."""
a digest of a tree walks; :func:`children_matching`, :func:`children_holding` and :func:`pack_files` list one directory."""

import errno
import fnmatch
Expand Down Expand Up @@ -43,6 +43,24 @@ def pack_files(directory: Path, filename: str) -> list[Path]:
return [path for path in (child / filename for child in children_matching(directory, "*")) if _is_regular(path)]


def children_holding(directory: Path, pattern: str, filename: str) -> list[Path]:
"""``directory/<child>/filename`` for each child whose name ``pattern`` matches and that holds ``filename`` as any
kind of entry, sorted: ``directory.glob(pattern + "/" + filename)`` where a directory that cannot be listed, or a
child that cannot be searched, raises its OSError. An absent ``filename`` or a child that is no directory is no hit."""
hits = []
for path in (child / filename for child in children_matching(directory, pattern)):
try:
path.lstat()
except (FileNotFoundError, NotADirectoryError):
continue
except OSError as exc:
if exc.errno == errno.ELOOP:
continue
raise
hits.append(path)
return hits


def _is_regular(path: Path) -> bool:
"""True when ``path`` is a regular file (a link is followed); an absent path, a parent that is no directory or a
link loop is not, and any other OSError (a parent that cannot be searched) is raised."""
Expand Down
8 changes: 7 additions & 1 deletion dokimi/dokimi/repos/batch_ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from typing import Any

from dokimi.atomic_write import write_text_atomic
from dokimi.digest_entries import children_holding
from .arms import resolve_skills, slug, tree_sha256
from .bases import NOT_UTF8
from .errors import PrepError
Expand Down Expand Up @@ -164,14 +165,19 @@
which would stay in the report next to the new ones. A cell whose result cannot be read has no execution
to compare; a cell of this run's plan reports it when it runs, so it is not an error here."""
found: set[str] = set()
for path in sorted(batch_dir.glob("*/result.json")):
try:
results = children_holding(batch_dir, "*", "result.json")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: A cell due for replacement can fail the identity check

dokimi/dokimi/repos/batch_ledger.py:169 The replacing filter runs after the new helper has probed all result paths.

How to check: With a mode-000 cell in replacing, base permits the identity check and head raises ExecutionMismatch before it checks replacing.
Expected: Apply the replacing filter before probing a cell’s result.json, so the identity check covers cells the run will keep.

except OSError as exc: # its cells cannot be told from none: the batch could be resumed with another execution's
raise ExecutionMismatch(f"cannot list {batch_dir}: {exc.strerror or exc}; its cells cannot be checked "
"against this run's execution") from exc
for path in results:
if replacing is not None and path.parent.name in replacing:
continue
try:
ran = recorded_execution(finished_result(path))
except (OSError, UnreadableResult):
# No execution to compare. A cell of this run's plan reports it when it runs; one outside the plan
# is not read again.

Check warning on line 180 in dokimi/dokimi/repos/batch_ledger.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
continue
found.add(ran["id"] if isinstance(ran.get("id"), str) else "unrecorded")
other = found - wanted
Expand Down
8 changes: 7 additions & 1 deletion dokimi/dokimi/repos/replay/authoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
from typing import Any

from dokimi.atomic_write import write_json_atomic
from dokimi.digest_entries import children_holding
from ...provenance import generated_by
from ..errors import PrepError
from ..graders.hidden_tests import HIDDEN_DIR
from ..graders.typecheck import REFERENCE_DIR
from ..manifest import RepoManifest
Expand Down Expand Up @@ -103,7 +105,11 @@
def tasks_by_pr(out: Path) -> dict[int, str]:
"""Index existing authoring tasks once per batch, by their source pull request."""
found: dict[int, str] = {}
for path in sorted(out.glob("authoring_*/task.json")):
try:
paths = children_holding(out, "authoring_*", "task.json")
except OSError as exc: # its tasks cannot be told from none: a pull request would be authored again
raise PrepError(f"cannot list {out}: {exc.strerror or exc}") from exc

Check warning on line 111 in dokimi/dokimi/repos/replay/authoring.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `exc.strerror or exc` -> `(exc.strerror)`
for path in paths:
suffix = path.parent.name.removeprefix("authoring_pr")
if suffix.isascii() and suffix.isdecimal():
found[int(suffix)] = path.parent.name # the direct PR task takes precedence
Expand Down
18 changes: 14 additions & 4 deletions dokimi/dokimi/repos/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
from pathlib import Path
from typing import Any

from dokimi.digest_entries import children_holding
from dokimi.eval.sign_flip import round_off_zero
from dokimi.measure import as_float, is_number
from dokimi.provenance import STATUSES, UNKNOWN
Expand Down Expand Up @@ -201,13 +202,22 @@
raise CellFileError(f"{path} has no usable `batch`")


def _cell_files(batch_dir: Path, name: str) -> list[Path]:
"""``batch_dir/<cell>/name`` for each cell that has it, sorted; a :class:`CellFileError` naming ``batch_dir`` when
it cannot be listed (a missing one has no cell)."""
try:
return children_holding(batch_dir, "*", name)
except OSError as exc:
raise CellFileError(f"cannot list {batch_dir}: {exc.strerror or exc}") from exc

Check warning on line 211 in dokimi/dokimi/repos/report.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
Comment on lines +210 to +211

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix (blocking): A cell at mode 0o000 in a batch that lists fine makes load_cells report cannot list <batch dir>, which names the wrong directory.
Input: a batch directory that lists fine, with cell1/meta.json and cell2 at mode 0o000.
Got: The latest commit raises cannot list <batch>: Permission denied, because _cell_files gives the batch directory's name to the OSError of cell2.

Also at: dokimi/dokimi/repos/batch_ledger.py:171, dokimi/dokimi/repos/workspace.py:271, dokimi/dokimi/repos/replay/authoring.py:111.

I tested this suggestion: it fixes the problem, and the tests still pass.

Suggested change
except OSError as exc:
raise CellFileError(f"cannot list {batch_dir}: {exc.strerror or exc}") from exc
except OSError as exc:
named = batch_dir if Path(exc.filename) == batch_dir else Path(exc.filename).parent
raise CellFileError(f"cannot list {named}: {exc.strerror or exc}") from exc
Details

Main returns ([], ["cell1"]). I'd expect the message to name the entry that could not be searched, and to keep cannot list <batch dir> for a batch that cannot be listed.



def load_cells(batch_dir: Path) -> tuple[list[dict[str, Any]], list[str]]:
"""Finished cells (their ``result.json``) and the names of missing ones."""
started = {p.parent.name for p in _cell_files(batch_dir, "meta.json")} # first: it names a directory that cannot be listed
plan_path = batch_dir / "_eval" / "plan.json"
planned = _planned_cells(plan_path) if plan_path.is_file() else set()
started = {p.parent.name for p in batch_dir.glob("*/meta.json")}
finished = []
for path in sorted(batch_dir.glob("*/result.json")):
for path in _cell_files(batch_dir, "result.json"):
rec = _read_object(path)
_fail_unmeasurable_score(rec)
_check_cell(path, rec)
Expand All @@ -218,7 +228,7 @@
rec["score_task"] = bool(rec["score_task"] if "score_task" in rec else rec["grade"]["score_only"])
finished.append(rec)
done = {r["cell"] for r in finished}
unsupported = {p.parent.name for p in batch_dir.glob(f"*/{UNSUPPORTED_FILE}")}
unsupported = {p.parent.name for p in _cell_files(batch_dir, UNSUPPORTED_FILE)}
return finished, sorted((planned | started) - done - unsupported)


Expand Down Expand Up @@ -252,7 +262,7 @@
def load_unsupported(batch_dir: Path) -> list[dict[str, Any]]:
"""Cells the runner did not run on a host that missed their task's ``host`` requirements."""
out = []
for path in sorted(batch_dir.glob(f"*/{UNSUPPORTED_FILE}")):
for path in _cell_files(batch_dir, UNSUPPORTED_FILE):
if (path.parent / "result.json").is_file():
continue
rec = _read_object(path)
Expand Down
6 changes: 5 additions & 1 deletion dokimi/dokimi/repos/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
from typing import Any

from dokimi import process
from dokimi.digest_entries import children_holding
from dokimi.process_io import exact_path_text

from .arms import ArmError, Skill, resolve_skills, tree_sha256
Expand Down Expand Up @@ -264,7 +265,10 @@
No task at all is refused: a check or run over none would report 0/0 as a pass."""
eval_dir, tasks = manifest.run_paths()
tasks_dir = content_dir / PurePosixPath(tasks).relative_to(eval_dir)
found = {p.parent.name: p for p in sorted(tasks_dir.glob("*/task.json"))}
try:
found = {p.parent.name: p for p in children_holding(tasks_dir, "*", "task.json")}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocking: An inaccessible sibling blocks an explicitly selected task

dokimi/dokimi/repos/workspace.py:269 children_holding stats every task candidate before ids is applied.

How to check: With one valid selected task and a sibling directory at mode 000, base loads the selected task and head refuses the tasks directory with PrepError.
Expected: Preserve explicit selection by checking only the selected task entries after listing the tasks root.

except OSError as exc: # a directory that cannot be listed is not one with no task
raise PrepError(f"cannot list {tasks_dir}: {exc.strerror or exc}") from exc

Check warning on line 271 in dokimi/dokimi/repos/workspace.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant inconclusive: a candidate test file for it did not run
if not found:
raise PrepError(f"no task under {manifest.tasks} (no */task.json): nothing to check or run")
wanted = ids or sorted(found)
Expand Down
4 changes: 2 additions & 2 deletions dokimi/tests/cli_faults.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@
}

# The allowlist only shrinks: any row added, deleted or swapped changes this count or digest (#1294), so review sees it.
ALLOWLIST_ROWS = 48
ALLOWLIST_DIGEST = "98d781d77eb6"
ALLOWLIST_ROWS = 45
ALLOWLIST_DIGEST = "17c76f7f9a04"

# Commands whose input refusals are not all exit 2 (docs/quickstart.md, "Exit codes"): they may also exit 1.
OWN_CODES: dict[str, frozenset[int]] = {
Expand Down
3 changes: 0 additions & 3 deletions dokimi/tests/data/cli_fault_allowlist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,13 @@ eval native-import | log | dangling-link | exit 5 with a traceback (FileNotFound
eval tasks list | --tasks-root | unreadable | exit 5 with a traceback (PermissionError)
explore run | --out-md | directory | exit 2 but leaves a results directory behind in the working directory
explore run | --out-md | unwritable-parent | exit 2 but leaves a results directory behind in the working directory
repo compare | batch_dirs | unreadable | python <3.14: exit 5 with a traceback (PermissionError)
repo hits judge | --labels | missing | exit 2 but leaves the batch's _eval directory behind
repo hits judge | --labels | directory | exit 2 but leaves the batch's _eval directory behind
repo hits judge | --labels | unreadable | exit 2 but leaves the batch's _eval directory behind
repo hits judge | --labels | dangling-link | exit 2 but leaves the batch's _eval directory behind
repo hits judge | --labels | link-out-of-root | exit 2 but leaves the batch's _eval directory behind
repo hits judge | --labels | dotdot | exit 2 but leaves the batch's _eval directory behind
repo hits judge | --labels | absolute | exit 2 but leaves the batch's _eval directory behind
repo hits sheet | batch_dir | unreadable | python <3.14: exit 5 with a traceback (PermissionError)
repo report | batch_dir | unreadable | exit 5 with a traceback (PermissionError)
repo skill-reach | --work-dir | unreadable | exit 5 with a traceback (PermissionError)
report opportunities | inputs | empty | exit 0, nothing on stderr
report summary | inputs | unreadable | exit 0, nothing on stderr
Expand Down
91 changes: 91 additions & 0 deletions dokimi/tests/test_children_holding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Copyright (C) 2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

"""#1507: ``children_holding`` lists ``<child>/<name>`` as ``glob`` did, a link included, and raises what it cannot look up."""

from __future__ import annotations

import os

import pytest

from dokimi.cli import build_parser
from dokimi.digest_entries import children_holding
from tests.cli_refusal import refusal


def _names(root, hits):
return [str(p.relative_to(root)) for p in hits]


def test_a_dangling_or_looping_leaf_link_is_a_hit_like_the_glob_found_it(tmp_path):
for child in ("dangling", "loop", "file", "dir"):
(tmp_path / child).mkdir()
os.symlink("nowhere", tmp_path / "dangling" / "result.json")
os.symlink("result.json", tmp_path / "loop" / "result.json")
(tmp_path / "file" / "result.json").write_text("{}")
(tmp_path / "dir" / "result.json").mkdir()
assert _names(tmp_path, children_holding(tmp_path, "*", "result.json")) == [
"dangling/result.json", "dir/result.json", "file/result.json", "loop/result.json"]
assert _names(tmp_path, children_holding(tmp_path, "*", "result.json")) == sorted(
str(p.relative_to(tmp_path)) for p in tmp_path.glob("*/result.json"))


def test_an_absent_name_a_child_that_is_no_directory_and_a_missing_root_are_no_hit(tmp_path):
(tmp_path / "empty").mkdir()
(tmp_path / "plain").write_text("not a directory")
assert children_holding(tmp_path, "*", "result.json") == []
assert children_holding(tmp_path / "missing", "*", "result.json") == []


def test_a_child_that_is_a_link_loop_is_no_hit_as_for_the_glob(tmp_path):
os.symlink("loop", tmp_path / "loop")
assert children_holding(tmp_path, "*", "result.json") == []
assert list(tmp_path.glob("*/result.json")) == []


def test_a_child_that_cannot_be_searched_raises(tmp_path):
child = tmp_path / "cell1"
child.mkdir()
(child / "result.json").write_text("{}")
child.chmod(0)
try:
try:
os.stat(child / "result.json")
except PermissionError:
with pytest.raises(PermissionError):
children_holding(tmp_path, "*", "result.json")
else:
pytest.skip("this process searches a mode 0 directory (root)")
finally:
child.chmod(0o700)


def test_a_batch_directory_that_cannot_be_searched_is_refused_naming_it_on_every_python(tmp_path):
from dokimi.repos.report import CellFileError, load_cells

batch = tmp_path / "b1"
batch.mkdir()
batch.chmod(0)
try:
try:
os.stat(batch / "_eval")
except PermissionError:
with pytest.raises(CellFileError, match=f"cannot list {batch}: Permission denied"):
load_cells(batch)
else:
pytest.skip("this process searches a mode 0 directory (root)")
finally:
batch.chmod(0o700)


@pytest.mark.parametrize("link",["nowhere", "result.json"], ids=["dangling", "looping"])
def test_report_reads_a_leaf_link_it_cannot_follow_and_refuses_it_naming_the_file(tmp_path, capsys, link):
cell = tmp_path / "b1" / "t__a__m__r1"
cell.mkdir(parents=True)
os.symlink(link, cell / "result.json")
with refusal() as exc:
args = build_parser().parse_args(["repo", "report", str(tmp_path / "b1")])
args.func(args)
assert exc.code == 2
assert f"cannot read {cell / 'result.json'}" in capsys.readouterr().err
22 changes: 22 additions & 0 deletions dokimi/tests/test_repo_authoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,28 @@ def test_an_existing_task_is_kept_unless_forced(toy, tmp_path, capsys):
assert _task(out, 1)["family"] == "feature" and not (out / "authoring_pr1/reference/stale.txt").exists()


def test_an_out_directory_that_cannot_be_listed_exits_1_naming_it_and_authors_nothing_again(toy, tmp_path, capsys):
"""#1507: the tasks index of `--out` at mode 111 is a refusal, not `{}` (which authors PR 1 a second time)."""
from dokimi.repos.errors import PrepError
from dokimi.repos.replay.authoring import task_of_pr, tasks_by_pr
from tests.unlistable_dir import unlistable

out = tmp_path / "tasks"
_authoring(toy["root"], [_pr1(toy)], out)
capsys.readouterr()
(out / "notes").mkdir()
(out / "notes" / "task.json").write_text(json.dumps({"source_pr": 9}), encoding="utf-8") # not an authoring_ directory
assert tasks_by_pr(out) == {1: "authoring_pr1"} and task_of_pr(out, 1) == "authoring_pr1"
assert tasks_by_pr(tmp_path / "missing") == {}
with unlistable(out):
with pytest.raises(PrepError, match=f"cannot list {out}: Permission denied"):
task_of_pr(out, 1)
with pytest.raises(SystemExit) as exc:
_authoring(toy["root"], [_pr1(toy)], out)
err = capsys.readouterr().err
assert exc.value.code == 1 and err.startswith("✗ ") and f"cannot list {out}: Permission denied" in err


@pytest.mark.parametrize(("raw", "message"), [
(None, "cannot read the pull request file"),
("", "cannot read the pull request file"),
Expand Down
16 changes: 16 additions & 0 deletions dokimi/tests/test_repo_overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -896,6 +896,22 @@ def cell_id(profile, arm):
check_batch_executions(batch, [options(claude)]) # a plain cell beside an overlay cell of one profile


def test_a_batch_directory_that_cannot_be_listed_is_refused_not_read_as_holding_no_cell(tmp_path):
"""#1507: the cells of another execution are not hidden by a batch directory at mode 111."""
from dokimi.repos.batch_ledger import ExecutionMismatch, check_batch_executions
from tests.unlistable_dir import unlistable

batch = tmp_path / "batch"
(batch / "cell1").mkdir(parents=True)
(batch / "cell1" / "result.json").write_text(json.dumps({"execution": {"id": "other"}}), encoding="utf-8")
with pytest.raises(ExecutionMismatch, match="holds cells of another execution"):
check_batch_executions(batch, {"mine"})
with unlistable(batch), pytest.raises(ExecutionMismatch) as err:
check_batch_executions(batch, {"mine"})
assert f"cannot list {batch}: Permission denied" in str(err.value) and "holds cells" not in str(err.value)
check_batch_executions(tmp_path / "missing", {"mine"}) # no directory, no cell


def test_overlay_report_leaves_a_load_of_a_foreign_target_with_an_own_alias_unattributed():
records = [{"file": "AGENTS.codex.md", "scenario": "cwd=.", "class": "loaded"}]
report = overlay_report(records, "claude", {"AGENTS.codex.md": ("AGENTS.claude.md",)})
Expand Down
Loading
Loading