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,5 @@
### Fixed

- **`memory lint` refuses a memory directory it cannot list.** `read_claude_memory` found the topic files with a glob, which gives nothing for a directory without list permission, so the store linted as an empty one, with no topic files and no findings. It now exits 2 with `<dir>: cannot list the memory directory: <reason>`. A missing or non-directory path still gives `not a directory` ([#1506](https://github.com/intel/dokimi/issues/1506)).
- **`trace` names a session's `subagents` directory it cannot list.** `subagent_files` listed the transcripts with a glob, so such a directory read as no subagents and their tool calls were missing from the session. It now raises `SessionError` (`cannot read <dir>: <reason>`); `read_session_tree` keeps the parent session's events and records the error on the session, so `trace prefilter` warns on stderr and reports the status `partial`. A session with no `subagents` directory is unchanged ([#1508](https://github.com/intel/dokimi/issues/1508)).
- **The BenchFlow and Harbor result readers name a jobs or job directory they cannot list.** `rollout_dirs`, `rollout_results` and `read_harbor_job` found the rollouts with globs, which give nothing for such a directory, so the cell read as one that wrote no result (`harbor: no Harbor result.json`). The cell's `metrics.error` is now `benchflow: cannot list <dir>: <reason>` or `harbor: cannot list <dir>: <reason>`, with no reward (after a BenchFlow timeout it follows the timeout error, after `; `); a missing jobs directory still has no rollout. A command cell's output directory is read the same way: a directory under it that cannot be listed gives `solver_error: no verdict: cannot list <dir>: <reason>`, where a reward file in it was missed and the exit code read as the reward. A directory that disappears while the output directory is walked gives the same `cannot list <dir>` error instead of an output directory with no reward, and a reward file that is listed but cannot be read gives `solver_error: no verdict: cannot read <file>: <reason>`. After a BenchFlow timeout, the rollout containers under the job directories that can be listed are still removed when another job directory cannot be listed ([#1509](https://github.com/intel/dokimi/issues/1509)).
2 changes: 1 addition & 1 deletion dokimi/docs/memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ SPDX-License-Identifier: Apache-2.0
[#728](https://github.com/intel/dokimi/issues/728)). The first reader is Claude Code auto memory,
`~/.claude/projects/<project>/memory/`: a `MEMORY.md` index whose first 200 lines or 25KB load at
every session start, and one topic file per memory with YAML frontmatter (`name`, `description`,
`type`: user, feedback, project or reference). Files under `archive/` are read and counted, but not checked and never expected in the index. An `archive/` directory that cannot be listed is an input error (exit 2), not a smaller store.
`type`: user, feedback, project or reference). Files under `archive/` are read and counted, but not checked and never expected in the index. A memory directory, or its `archive/` directory, that cannot be listed is an input error (exit 2), not a smaller store.

## memory lint

Expand Down
2 changes: 1 addition & 1 deletion dokimi/docs/session-prefilter.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ This slice reads **Claude Code** session logs: JSON lines under
(`<session>/subagents/*.jsonl` next to `<session>.jsonl`) is read as part of that session, its
records merged in time order, so its tool calls count as the agent acting and `**/*.jsonl` still
gives one session per log; a subagent transcript named without its session log is skipped with a
warning. A resumed or forked session log repeats the records it continues, with the same
warning. A `subagents` directory that cannot be listed is a skipped part of its session in the same way (`cannot read <dir>: <reason>` on stderr, the session's own records kept, `status` `partial`, exit code 0). A resumed or forked session log repeats the records it continues, with the same
`uuid`: logs that share a record are read as one session, each record once. A file that cannot be read, is a
device (`/dev/zero`: "not a file") or holds no prompt and no tool call, is reported and the rest are still read; the exit
code is 1 when any of the files named on the command line failed. A failed subagent transcript is not such a file: it is a skipped part of its session, named on stderr as a warning, and the exit code stays 0 (`status` `partial`). When no session can be read at all, the command refuses the input: exit 2, and with `--json` a `failed` document with an `input` error `no session could be read`. A guidance file that is a device exits 2, `guidance <path>: not a file`; one that is missing, a directory or unreadable exits 2 too, `guidance <path>: <reason>`. A line that is valid JSON but not an object, or a
Expand Down
7 changes: 6 additions & 1 deletion dokimi/dokimi/commands/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,12 @@ def _read_sessions(names: list[str], dropped: list | None = None) -> tuple[list,
from dokimi.context.session_log import SessionError, merge_repeats, read_session_tree, subagent_files

paths = _session_paths(names)
folded = {os.path.realpath(sub) for path in paths for sub in subagent_files(Path(path))}
folded: set[str] = set()
for path in paths:
try:
folded.update(os.path.realpath(sub) for sub in subagent_files(Path(path)))
except SessionError: # read_session_tree below reports the directory
pass
loaded, failed = [], False
for path in paths:
if os.path.realpath(path) in folded: # read with its session
Expand Down
22 changes: 18 additions & 4 deletions dokimi/dokimi/context/session_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from pathlib import Path
from typing import Any

from dokimi.digest_entries import children_matching
from dokimi.text_spans import replace_pairs
from dokimi.files import InputError, refuse_device

Expand Down Expand Up @@ -85,14 +86,27 @@ def read_session(path: Path) -> Session:


def subagent_files(path: Path) -> list[Path]:
"""The subagent transcripts Claude Code wrote for the session log ``path``."""
return sorted((path.parent / path.stem / "subagents").glob("*.jsonl")) if path.suffix == ".jsonl" else []
"""The subagent transcripts Claude Code wrote for the session log ``path``: none when it has no ``subagents``
directory; a ``subagents`` directory that cannot be listed raises SessionError."""
if path.suffix != ".jsonl":
return []
directory = path.parent / path.stem / "subagents"
try:
return children_matching(directory, "*.jsonl")
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
except OSError as exc:
raise SessionError(f"cannot read {directory}: {exc}") from exc


def read_session_tree(path: Path) -> Session:
"""A session log with its subagents' transcripts folded in, in time order: their tool calls are the agent acting."""
"""A session log with its subagents' transcripts folded in, in time order: their tool calls are the agent acting.
A ``subagents`` directory that cannot be listed is an error of the session, as an unreadable transcript is."""
session = read_session(path)
for sub in subagent_files(path):
try:
subagents = subagent_files(path)
except SessionError as exc:
add_error(session, str(exc))
subagents = []
for sub in subagents:
try:
session.events.extend(read_session(sub).events)
except SessionError as exc:
Expand Down
33 changes: 10 additions & 23 deletions dokimi/dokimi/harnesses/benchflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from .command import clear_run_dir
from .harbor_export import harbor_view
from .models import HarnessResult, OperationRecord, PreflightError
from .rollouts import look_for_rollouts, rollout_dirs, rollout_results # noqa: F401 - rollout_results: re-exported
from .tasks import TaskSpec

SKILL_MODE_NO_SKILL = "no-skill"
Expand Down Expand Up @@ -190,8 +191,7 @@ def run(
elapsed = time.time() - start
(output_dir / "bench.log").write_text(stdout + stderr, encoding="utf-8")

results = rollout_results(jobs_dir)
n_attempts = len(rollout_dirs(jobs_dir))
results, n_attempts, list_error = look_for_rollouts(jobs_dir)
result_path = results[-1] if results else None
result = _load_json(result_path) if result_path else None
reward, metrics = parse_result(result)
Expand Down Expand Up @@ -222,7 +222,7 @@ def run(
# means bench wedged: no verdict, whatever an attempt left behind.
reward = None
metrics["timed_out"] = True
metrics["error"] = f"benchflow: bench killed after {timeout:.0f}s (outer budget)"
metrics["error"] = "; ".join(filter(None, (f"benchflow: bench killed after {timeout:.0f}s (outer budget)", list_error)))
elif n_attempts > 1:
# --retry-attempts 0 makes one cell one attempt; more means the
# flag stopped working, and the row would mix attempts.
Expand All @@ -236,8 +236,8 @@ def run(
else:
# bench failed before writing a rollout (a rubric it rejects, a
# bad task, its own hard deadline): its stderr says why.
metrics["error"] = (f"no BenchFlow result.json (exit {returncode})"
+ (f": {reason}" if reason else ""))
metrics["error"] = list_error or (f"no BenchFlow result.json (exit {returncode})"
+ (f": {reason}" if reason else ""))
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
if result:
operations.append(
OperationRecord(
Expand Down Expand Up @@ -633,9 +633,11 @@ def remove_rollout_containers(jobs_dir: Path, runner: process.Runner = process.r
run of the same task.
"""
removed: list[str] = []
if not jobs_dir.is_dir():
return removed
for rollout in rollout_dirs(jobs_dir):
try:
rollouts = rollout_dirs(jobs_dir)
except OSError: # a job dir that cannot be listed: glob skips it; look_for_rollouts names it in the cell's error
rollouts = sorted(p for p in jobs_dir.glob("*/*__*") if p.is_dir())
for rollout in rollouts:
project = _compose_project_name(rollout.name)
# Bounded like BenchFlow's own _force_kill_project: a wedged daemon
# must not hang the sweep after we already gave up on bench.
Expand Down Expand Up @@ -756,21 +758,6 @@ def skill_loads(rollout_dir: Path, reported: Optional[int], *,
return out


def rollout_dirs(jobs_dir: Path) -> list[Path]:
"""Every rollout dir (``<job>/<task>__<id>``) under a jobs dir, whether or not
it got as far as a ``result.json`` (a kill or a hard deadline leaves none)."""
if not jobs_dir.is_dir():
return []
return sorted(p for p in jobs_dir.glob("*/*__*") if p.is_dir())


def rollout_results(jobs_dir: Path) -> list[Path]:
"""Every rollout ``result.json`` under a BenchFlow jobs dir, oldest first."""
if not jobs_dir.is_dir():
return []
return sorted(jobs_dir.glob("*/*/result.json"), key=lambda p: p.stat().st_mtime)


def _subprocess_env(extra: dict[str, str], agent: Optional[str] = None,
runner: process.Runner = process.run) -> dict[str, str]:
"""The env for ``bench``: behind a proxy, both ``no_proxy`` spellings get one
Expand Down
67 changes: 53 additions & 14 deletions dokimi/dokimi/harnesses/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@

import json
import math
import os
import shlex
import shutil
import time
from dataclasses import dataclass, field
from os.path import normcase
from pathlib import Path
from typing import Any

Expand All @@ -20,6 +22,7 @@
from .models import HarnessResult, OperationRecord
from .operations import load_operations
from .harbor_export import harbor_view
from .rollouts import cannot_list, harbor_results
from .tasks import TaskSpec, harbor_task_problem
from .verifier_reward import _parse_reward_text, primary_reward, reward_in_file

Expand Down Expand Up @@ -154,12 +157,7 @@ def run(
given_dir / Path(harbor_metrics["result_json"]).relative_to(output_dir))
passed = reward is not None and reward >= 1.0
else:
# A printed reward is no verdict from a command that never ran or was killed.
printed = (stdout, stderr) if not _never_finished(returncode) else ("", "")
reward = _find_reward(output_dir, *printed)
if reward is None:
reward = _exit_code_reward(returncode, output_dir)
harbor_metrics = _no_verdict(reward, returncode, output_dir)
reward, harbor_metrics = _command_verdict(output_dir, returncode, stdout, stderr)
passed = reward is not None and reward >= 1.0

metrics: dict[str, Any] = {
Expand Down Expand Up @@ -255,11 +253,13 @@ def read_harbor_job(jobs_dir: Path | None, returncode: int) -> tuple[float | Non
"""
if jobs_dir is None:
return None, {"error": "harbor: no output dir, so no Harbor result.json to read"}
trials = sorted(jobs_dir.glob("*/*/result.json"))
try:
trials, has_job_result = harbor_results(jobs_dir)
except OSError as exc: # not "no result.json": the jobs could not be looked through
return None, {"n_trials": 0, "error": f"harbor: {cannot_list(exc, jobs_dir)}"}
metrics: dict[str, Any] = {"n_trials": len(trials)}
if not trials:
found = "a job result.json but no trial result.json" if any(jobs_dir.glob("*/result.json")) \
else "no Harbor result.json"
found = "a job result.json but no trial result.json" if has_job_result else "no Harbor result.json"
metrics["error"] = f"harbor: {found} (exit {returncode})"
return None, metrics
if len(trials) > 1:
Expand Down Expand Up @@ -472,22 +472,61 @@ def _no_verdict(reward: float | None, returncode: int, output_dir: Path | None)
return {"solver_error": f"no verdict: exit {returncode}{no_reward}"}


class _UnreadableReward(Exception):
"""A reward file that is listed but cannot be read, not one that cannot be listed."""


def _command_verdict(output_dir: Path | None, returncode: int, stdout: str, stderr: str) -> tuple[float | None, dict[str, Any]]:
"""``(reward, metrics)`` of a command cell. A directory of the output dir that cannot be listed is no verdict
that names it: a reward file in it would be missed, and the exit code read as the reward."""
# A printed reward is no verdict from a command that never ran or was killed.
printed = (stdout, stderr) if not _never_finished(returncode) else ("", "")
try:
reward = _find_reward(output_dir, *printed)
if reward is None:
reward = _exit_code_reward(returncode, output_dir)
return reward, _no_verdict(reward, returncode, output_dir)
except _UnreadableReward as exc:
return None, {"solver_error": f"no verdict: {exc}"}
except OSError as exc:
return None, {"solver_error": f"no verdict: {cannot_list(exc, output_dir)}"}
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
return reward, {}


def _reward_files(output_dir: Path) -> list[Path]:
"""The ``reward.txt`` files under ``output_dir``, then its ``reward.json`` files, each sorted: what ``rglob`` finds
(names compared as the platform's file system does, so ``REWARD.TXT`` counts on Windows), except that a
directory that cannot be listed, or sit behind one that cannot be searched, raises its OSError, and so does one
that vanishes mid-walk (an absent ``output_dir``, or one that is no directory, has no reward files)."""
from dokimi.digest_entries import listed_entries

try:
entries = listed_entries(output_dir)
except (FileNotFoundError, NotADirectoryError) as exc:
if os.fspath(exc.filename) != os.fspath(output_dir):
raise # a directory under it went away mid-walk: the walk is incomplete, not the output dir absent
entries = []
return [path for name in ("reward.txt", "reward.json") for path in sorted(e for e in entries if normcase(e.name) == name)]


def _has_reward_file(output_dir: Path | None) -> bool:
if not output_dir:
return False
return any(next(output_dir.rglob(name), None) for name in ("reward.txt", "reward.json"))
return bool(_reward_files(output_dir))


def _find_reward(output_dir: Path | None, stdout: str, stderr: str) -> float | None:
if output_dir:
candidates = sorted(output_dir.rglob("reward.txt")) + sorted(
output_dir.rglob("reward.json")
)
candidates = _reward_files(output_dir)
for path in candidates:
if not path.is_file(): # a directory of that name holds no reward, like an empty file
continue
try:
return reward_in_file(path.name, path.read_bytes())
data = path.read_bytes()
except OSError as exc:
raise _UnreadableReward(f"cannot read {path}: {exc.strerror or exc}") from exc
try:
return reward_in_file(normcase(path.name), data)
except ValueError: # no reward in this one: the next file may have it
continue
if candidates:
Expand Down
59 changes: 59 additions & 0 deletions dokimi/dokimi/harnesses/rollouts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Copyright (C) 2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

"""The rollout files of a BenchFlow or Harbor jobs dir (``<jobs>/<job>/<trial>/...``).

A missing jobs dir has no rollout. A jobs dir or a job dir that cannot be listed raises its OSError, which names it,
where a glob gave nothing and the cell read as one that wrote no result (#1509).
"""

from __future__ import annotations

from pathlib import Path

from dokimi.digest_entries import children_matching


def result_files(directory: Path) -> list[Path]:
"""``directory/<child>/result.json`` for each child that holds an entry of that name, as ``directory.glob("*/result.json")``
finds them, except that a directory that cannot be listed or a child that cannot be searched raises its OSError."""
found = []
for child in children_matching(directory, "*"):
try:
(child / "result.json").lstat()
except (FileNotFoundError, NotADirectoryError):
continue
found.append(child / "result.json")
return found


def rollout_dirs(jobs_dir: Path) -> list[Path]:
"""Every rollout dir (``<job>/<task>__<id>``) under a jobs dir, whether or not it got as far as a ``result.json``
(a kill or a hard deadline leaves none)."""
return sorted(p for job in children_matching(jobs_dir, "*") for p in children_matching(job, "*__*") if p.is_dir())


def rollout_results(jobs_dir: Path) -> list[Path]:
"""Every rollout ``result.json`` under a BenchFlow jobs dir, oldest first."""
found = [path for job in children_matching(jobs_dir, "*") for path in result_files(job)]
return sorted(found, key=lambda p: p.stat().st_mtime)


def harbor_results(jobs_dir: Path) -> tuple[list[Path], bool]:
"""``(<job>/<trial>/result.json files, whether a <job>/result.json exists)`` under a Harbor jobs dir."""
jobs = children_matching(jobs_dir, "*")
return sorted(path for job in jobs for path in result_files(job)), bool(result_files(jobs_dir))


def look_for_rollouts(jobs_dir: Path) -> tuple[list[Path], int, str | None]:
"""``(result.json files, rollout dir count, error)``: a jobs or job dir that cannot be listed is the cell's error
naming it, not a cell with no result.json."""
try:
return rollout_results(jobs_dir), len(rollout_dirs(jobs_dir)), None
except OSError as exc:
return [], 0, f"benchflow: {cannot_list(exc, jobs_dir)}"


def cannot_list(exc: OSError, fallback: Path | None) -> str:
"""``cannot list <dir>: <reason>`` for the OSError of a listing: the directory it names, else ``fallback``."""
return f"cannot list {exc.filename or fallback}: {exc.strerror or exc}"
Loading
Loading