Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
a385c9e
feat(trace): a contract action can match writes that add a file or mo…
napetrov Nov 29, 2026
f48cbdc
fix(trace): a refused write gets no label, a failed shell redirect co…
napetrov Nov 29, 2026
f948133
Merge branch 'main' of https://github.com/intel/dokimi into HEAD
napetrov Nov 29, 2026
f6e3502
Preserve normalized read and edit failures
napetrov Nov 29, 2026
a0f4b3c
Identify shell writes by their known directory
napetrov Nov 29, 2026
cc34513
Reject explicit empty contract change filters
napetrov Nov 29, 2026
96d34ae
Recognize grouped tee append options
napetrov Nov 29, 2026
fba2384
Keep directory uncertainty across trace forms
napetrov Nov 29, 2026
1c0e8a6
Merge branch 'main' of https://github.com/intel/dokimi into HEAD
napetrov Nov 29, 2026
6e82b79
Type the optional trace directory
napetrov Nov 29, 2026
48d5578
Require split traces for write change contracts
napetrov Nov 29, 2026
18f02f0
Detect shell directory changes past prefixes
napetrov Nov 29, 2026
82e79fd
Check assignment prefixes before removing quotes
napetrov Nov 29, 2026
ba0ab66
Track shell quoting inside assignment values
napetrov Nov 29, 2026
02db372
Respect explicit CDPATH in write directory tracing
napetrov Nov 29, 2026
3746c00
Merge branch 'main' of https://github.com/intel/dokimi into HEAD
napetrov Nov 30, 2026
af0ecdf
Keep fallback cd from anchoring shell writes
napetrov Nov 30, 2026
0eae906
Report inconclusive write contracts
napetrov Nov 30, 2026
7b1b792
Preserve cwd during literal virtualenv activation
napetrov Nov 30, 2026
7aa6eed
Account for subagents that may change cwd
napetrov Nov 30, 2026
8933b9b
Leave normalized repo write type unlabelled
napetrov Nov 30, 2026
6484896
Carry explicit CDPATH through a Bash call
napetrov Nov 30, 2026
7fd1b6d
Share shell movement classification for functions and loops
napetrov Nov 30, 2026
68fa485
Record resolution of review summary
napetrov Nov 30, 2026
2619d0b
Handle quoted and redirected CDPATH assignments
napetrov Nov 30, 2026
2c3c6a5
Merge branch 'main' of https://github.com/intel/dokimi into HEAD
napetrov Nov 30, 2026
b757ff6
Preserve cwd across a subshell function definition
napetrov Nov 30, 2026
e89f27d
Merge branch 'main' of https://github.com/intel/dokimi into HEAD
napetrov Nov 30, 2026
850d928
Merge branch 'main' of https://github.com/intel/dokimi into HEAD
napetrov Nov 30, 2026
ef220ef
Merge commit '35dfeb87aced4e5998ddb7ff0c1ed9eac1b9ca97' into HEAD
napetrov Nov 30, 2026
e10e570
Merge branch 'main' of https://github.com/intel/dokimi into HEAD
napetrov Nov 30, 2026
cd77c26
Merge commit 'e1f774049b300d23ef0565f625248076c301e47b' into HEAD
napetrov Nov 30, 2026
fabd7fd
Keep write-contract tests together after main sync
napetrov Nov 30, 2026
68c624e
Merge commit 'bcb1f9f0927b5cea32d6b08797ac8e58142c4cf6' into HEAD
napetrov Dec 1, 2026
ce74fb3
Treat unsupported trace working directories as unknown
napetrov Dec 1, 2026
d3002b1
Check the count of passing runs that broke a contract
napetrov Dec 1, 2026
3664a14
Check partial JSON status for unreadable traces
napetrov Dec 1, 2026
d3034e9
Cover in-place edits with an unknown directory
napetrov Dec 1, 2026
571aa24
Leave variable-expanded shell write identities unknown
napetrov Dec 1, 2026
be10b63
Report expanded replacement targets as inconclusive
napetrov Dec 1, 2026
4b8ec94
refactor: split in-place edit operand parsing
napetrov Dec 1, 2026
2bd133d
Merge remote-tracking branch 'intel/main' into HEAD
napetrov Dec 1, 2026
716c3f9
fix: leave relative trace paths unresolved without a cwd
napetrov Dec 1, 2026
0dd320b
perf: locate background shell groups in one scan
napetrov Dec 1, 2026
1b07588
fix(trace): an Edit with an empty old_string that creates a file is a…
xaleryb Dec 2, 2026
2a91623
fix(trace): a glob or ~ write target is an expanded path with no label
xaleryb Dec 2, 2026
7f94cae
Merge remote-tracking branch 'intel/main' into HEAD
napetrov Dec 2, 2026
cb3e7aa
fix: account for every tee output in change contracts
napetrov Dec 2, 2026
3401d0a
fix: stop reading tee operands at shell syntax
napetrov Dec 2, 2026
a66c18d
Merge commit 'refs/pr-address/base/main' into HEAD
napetrov Dec 2, 2026
8fd8902
fix(trace): account for unresolved write paths
napetrov Dec 2, 2026
18ff6c4
fix(trace): reset cwd after function definitions
napetrov Dec 2, 2026
7c04d42
Merge commit 'refs/pr-address/fallback-a/main' into HEAD
napetrov Dec 2, 2026
c8e0279
test(cli): supply an agent run fault fixture
napetrov Dec 2, 2026
315970b
Merge commit 'refs/pr-address/followup/1408-main' into HEAD
napetrov Dec 2, 2026
9f317b3
Treat shell brace expansions as unknown write paths
napetrov Dec 2, 2026
21bb79b
fix(trace): treat a labelled write with an unknown path as a possible…
vlad-perevezentsev Dec 3, 2026
f06a42c
docs(changelog): note labelled writes with unknown paths
vlad-perevezentsev Dec 3, 2026
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 @@
### Added

- **A contract action can say a write added a file or modified one**: `trace consistency --contract` takes `change: add` or `change: modify` on an action, so `forbids: new_test` (`change: add`, `file_path: 'tests/'`) flags new test files and leaves edits to existing ones alone. The trace labels each write from the calls before it: `Write`, `>` and `tee` to a file no earlier call read or wrote are `add`, `Edit`, `MultiEdit`, `sed -i`, `>>` and `tee -a` are `modify` (an `Edit` with an empty `old_string` creates the file and is labelled like `Write`). The label is read from the trace only, so a file that existed and was never read in it can be labelled `add`; see the limits in `docs/run-consistency.md`. A run is reported as inconclusive when an unlabelled replacement, or a labelled write whose path is unknown, could change its contract verdict.
4 changes: 2 additions & 2 deletions dokimi/docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ failed check.
| 0 | The command ran and, if it checks something, the check passed. | |
| 1 | A verdict or a gate that ran and failed, or a runtime failure the command reports (a model call, a run, a clone or fetch); a crash that escapes is 5. `eval judge validate --strict` and `eval leak`/`eval redteam` that fail as blocked. | `baseline compare --max-context-drop 0` over a regression, `repo reach` with a harness binary that cannot run, `eval triggers generate --fail-on warn` over a lint finding |
| 2 | A bad invocation: a missing, unreadable or malformed input file, a configuration the agent's CLI rejects (`repo run --tools all` with a `.mcp.json` the CLI does not accept: refused before any cell runs), a device given as one (`<flag> <path>: not a file`), a flag combination the command refuses, an output file that cannot be written, a missing provider credential, a source string that is malformed, unpinned or not a repository root. | `baseline save` on a bad eval file, `evaluate --questions` on an empty or non-JSON file (`--questions <path>: <reason>`), `benchmark preflight` with no golden set, `repo scan --manifest ../x.yaml` |
| 3 | Inconclusive: the run stopped short because a budget ran out (`--max-usd`, or a call with no price) and kept the partial output (`tools preference`, `skill novelty atoms`, `probe` and `analyze`, `skill routing` and `catalog routing`, `repo run` when the batch budget is the only reason a cell was not started (with a cell error or a failed probe too it exits 1, 5 for a cell that crashed of the machinery; a batch that started no cell exits 1), and `repo hits judge`; a stop on a permanent provider error, on 3 judge calls in a row failing with one error, or a `catalog routing` run with a failed model call, exits 1; `eval personas discover` refuses its one call before it runs, so nothing is written), or the result is undecided (`eval judge validate`: a pass whose interval straddles the gate, or a variant no pair was built for, with `--strict` making it 1; `eval leak`: an item that could not be checked, or none could; `eval redteam`: a graded question not measured, or nothing graded; `eval judge agreement --strict`: an arm NOT MEASURED, or no arm to compare; `repo security --fail-on`: an unfinished cell or an arm with no measured cell, when no arm failed and every model has a baseline cell). | `tools preference --max-usd 5` with calls not run; `eval judge validate` with too few bases |
| 3 | Inconclusive: the run stopped short because a budget ran out (`--max-usd`, or a call with no price) and kept the partial output (`tools preference`, `skill novelty atoms`, `probe` and `analyze`, `skill routing` and `catalog routing`, `repo run` when the batch budget is the only reason a cell was not started (with a cell error or a failed probe too it exits 1, 5 for a cell that crashed of the machinery; a batch that started no cell exits 1), and `repo hits judge`; a stop on a permanent provider error, on 3 judge calls in a row failing with one error, or a `catalog routing` run with a failed model call, exits 1; `eval personas discover` refuses its one call before it runs, so nothing is written), or the result is undecided (`trace consistency --contract`: a rule depends on an unlabelled write; `eval judge validate`: a pass whose interval straddles the gate, or a variant no pair was built for, with `--strict` making it 1; `eval leak`: an item that could not be checked, or none could; `eval redteam`: a graded question not measured, or nothing graded; `eval judge agreement --strict`: an arm NOT MEASURED, or no arm to compare; `repo security --fail-on`: an unfinished cell or an arm with no measured cell, when no arm failed and every model has a baseline cell). | `tools preference --max-usd 5` with calls not run; `eval judge validate` with too few bases |
| 4 | Invalid: the result is not comparable or not trustworthy: a model that differs from the baseline's, or one that cannot be verified, under `baseline compare --strict` or the regression gate (`--max-context-drop` or `--max-lift-drop`); under `repo security --fail-on`, a model with no baseline cell when no arm failed; under `eval judge agreement --strict`, an arm JUDGE-DEPENDENT; under `runs baseline save --expect-previous`, a baseline that no longer points to the run expected (a stale baseline, the pointer left as it was). | `baseline compare --strict` over a baseline scored with another judge |
| 5 | Infrastructure failure: a crash (an uncaught exception) in any command, with its traceback on stderr. For a command that emits the cli_output document, `--json` prints its `infra` document on stdout first. Also a `repo run` cell that crashes (a harness that exits nonzero before its first trace line, unless the cap killed it, a docker daemon or CLI failure that stops the agent, a scratch directory that vanished): the batch keeps the other cells and exits 5. | `backends --json` when `detect` raises; `repo run` with the docker daemon down |

Expand All @@ -282,7 +282,7 @@ its rows, when any skill it took on is `partial`, `error` or not run).
`eval judge agreement` with a repeated `--judge` and `eval score pairwise` exit 1, not 2, when
every judge call fails, a missing provider credential included.

`trace inspect`, `trace consistency` and `trace prefilter` exit 2 when no trace or session reads.
`trace inspect`, `trace consistency` and `trace prefilter` exit 2 when no trace or session reads. `trace consistency --contract` exits 3 when a rule remains inconclusive.

## Troubleshooting

Expand Down
81 changes: 81 additions & 0 deletions dokimi/docs/run-consistency.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,87 @@ file: a contract that wants an edit reports it missing, so name `Bash:find` /
A regex value may be a list (`command: [pytest, tox]`), read as one alternation;
a number or a mapping is refused.

### Added files and changed files

`change: add` or `change: modify` narrows an action to the writes the trace
labels that way. Without it, `forbids: edit` cannot tell a new test file from
an edit of an old one, and a contract that forbids edits forbids both.

```yaml
actions:
new_test: {change: add, file_path: 'tests/'}
edit_test: {change: modify, file_path: 'tests/'}
rules:
- forbids: new_test # no new test files; editing the existing ones is fine
```

The label is made from the trace alone, in the order its calls were made:

* `Edit`, `MultiEdit` and `NotebookEdit` are `modify`. An `Edit` or a first `MultiEdit`
edit with an empty `old_string` creates a missing file, so it is labelled like `Write`.
* `Write`, a `>` redirect and `tee` without `-a` are `add` when no earlier call in the
trace read or wrote the file, and `modify` when one did.
* `>>`, `tee -a`, `sed -i` and `perl -i` are `modify`.
* A failed `Read` leaves its file unseen, so a later `Write` to it is an `add`. A refused
`Write`, `Edit`, `MultiEdit` or `NotebookEdit` wrote nothing: it gets no label and leaves
the file unseen. A failed shell call still opened its redirect target (the redirect runs
before the command), so that file counts as seen; the trace does not say whether an
earlier command in a chain stopped the redirect from running.
* A path is compared after `./` and `..` are resolved. Symlinks, `~`, and an absolute
and a relative spelling of one file are not matched up unless the trace gives a directory
for the relative path. A recorded starting directory or a literal `cd <path> &&` can
identify Bash writes. Actions with `change` match either the captured or the resolved
spelling of a known path. A relative replacement without a recorded starting directory or after
an unresolved directory change receives no label. A later Bash call starts at an
unknown directory if an earlier call may have moved its shell. An explicit `CDPATH`
that may search other directories makes a bare relative `cd` target unknown.
This includes temporary assignments before `cd`, standalone assignments and
exports earlier in the same Bash call.
A fallback `cd` after `||`, a `cd` in a loop or conditional block, or a shell
function that may move the shell leaves the directory unknown. Subagents may
share the parent's shell, so their directory changes also make it unknown.
Sourcing a literal virtualenv `bin/activate` script preserves it.

`change` is a reserved key: it is not an input regex, and a value other than `add`
or `modify` is refused. A matcher with `change` and no `tool` matches any write
with that label, shell writes included. Contracts using `change` require `--shell split`
(the default).

Shell variable, glob (`*`, `?`, `[...]`), brace (`{a,b}`, `{1..3}`) and leading `~` expansion
can leave the target of a replacement unknown, even in a known directory.
The trace retains the captured path for input filters. When a replacement has no label,
its unknown path could match any path filter. Its tool and other input filters still
have to match the action. A labelled write whose path is unknown, such as `sed -i` on a
relative path in an unknown directory, could likewise match any path filter of an action
with its label, and is counted with the unlabelled writes. A rule is inconclusive if assigning
labels or paths to those writes could change its verdict. The JSON reports
`unlabelled_writes` by run and action and lists `inconclusive_rules` by run.
A confirmed violation makes its run nonconforming. Runs with an inconclusive
rule and no confirmed violation do not enter `conformance_rate`. The command
exits 3 when any run's contract result is inconclusive and 1 when any trace
could not be read.

What the trace cannot tell:

* **The starting tree is not read.** A file that existed before the run and that
the trace never read is `add` when it is written with `Write` or `>`. The label is
right only where the harness refuses a `Write` over a file the session did not read.
As we understand Claude Code's `Write` tool it does; no trace in this repo confirms
it. A harness that allows the unread write can get a changed file labelled `add`.
* **Shell reads do not count.** `cat f`, `grep f` or `sed -n p f` leave `f` unseen, so
`echo x > f` after them is `add`.
* **Only plain writes are seen.** A file made by `touch`, `cp`, `mv`, `git apply`, or a
generator script (`python gen.py`) has no label, so neither `add` nor `modify` matches
it. Name those commands in an action of their own if they matter.
* **A refused shell write is labelled as if it ran.** A permission denial comes back as an
error result, the same as a command that ran and failed, and the trace does not tell the two
apart. A denied `echo x > tests/new.py` is an `add` and its file is seen.
* **Subagent writes are not labelled**, as they are not in the path at all.

So a `forbids` on `add` misses a file made with `touch`, and flags a file
rewritten with `>` after only a `cat`. Read the violations next to their paths
before reading them as a count.

`last_ok` also fails when the status the call reported may be another
command's: a pipe without `pipefail`, a later command after `||`, or after `;`
or a newline (not under `set -e`), a trailing `&` (the list or `{ }` / `if ... fi`
Expand Down
58 changes: 43 additions & 15 deletions dokimi/dokimi/commands/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from typing import NoReturn

from dokimi.cli_types import non_negative_int, unit_interval
from dokimi.exit_codes import EXIT_INCONCLUSIVE
from dokimi.utils import InputError, refuse_device


Expand Down Expand Up @@ -140,18 +141,25 @@
return loaded, failed


def cmd_context_consistency(args: argparse.Namespace) -> None:
"""Result stability, path stability and contract conformance of repeated runs of one task."""
from dokimi import cli_output
from dokimi.context.consistency import apply_outcomes, load_contract, load_outcomes, profile
def _consistency_inputs(args: argparse.Namespace) -> tuple[dict | None, dict | None]:
from dokimi.context.consistency import load_contract, load_outcomes

arms = _trace_arms(args)
try:
contract = load_contract(Path(args.contract)) if args.contract else None
outcomes = load_outcomes(Path(args.outcomes)) if args.outcomes else None
except (OSError, ValueError) as exc:
_refuse(str(exc))
if args.shell == "call" and contract and any(action.change for action in contract["actions"].values()):

Check warning on line 152 in dokimi/dokimi/commands/context.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `args.shell == "call" and contract and any(action.change for action in contract["actions"].values())` -> `(args.shell == 'call' and any((action.change for action in contract['actions'].values())))`
_refuse("a contract with a change filter requires --shell split")
return contract, outcomes


def cmd_context_consistency(args: argparse.Namespace) -> None:
"""Result stability, path stability and contract conformance of repeated runs of one task."""
from dokimi.context.consistency import apply_outcomes, profile

arms = _trace_arms(args)
contract, outcomes = _consistency_inputs(args)
loaded, failed = _read_arms(arms, args.shell)
missing: set[str] = set()
if outcomes is not None: # over every arm at once: a key that two arms share is caught
Expand All @@ -171,14 +179,26 @@
report[label]["outcome_source"] = "outcomes file" if outcomes is not None else "harness result event"
report[label]["shell"] = args.shell # the grain the step counts were taken at

if args.json:
status = "partial" if failed else "complete"
cli_output.emit_leaf("trace consistency", report, status=status,
reason="one or more traces could not be read (see stderr)" if failed else None)
_emit_consistency(report, as_json=args.json, failed=failed)


def _emit_consistency(report: dict, *, as_json: bool, failed: bool) -> None:
from dokimi import cli_output

inconclusive = any(p.get("contract", {}).get("inconclusive_runs") for p in report.values())
reason = None
if failed:
Comment thread
napetrov marked this conversation as resolved.
Resolved
reason = "one or more traces could not be read (see stderr)"
elif inconclusive:
reason = "a contract could not be checked because writes could not be labelled"
if as_json:
cli_output.emit_leaf("trace consistency", report, status="partial" if reason else "complete", reason=reason)
else:
print(_consistency_text(report))
if failed:
sys.exit(1)
if inconclusive:
sys.exit(EXIT_INCONCLUSIVE)


def cmd_context_prefilter(args: argparse.Namespace) -> None:
Expand Down Expand Up @@ -316,15 +336,23 @@
for i, g in enumerate(p["strategies"], 1):
shown = " → ".join(g["path"][:12]) + (" …" if len(g["path"]) > 12 else "")
lines.append(f" S{i} ×{len(g['runs'])} {g['verdict']} ({g['passed']}/{g['judged']}): {shown}")
c = p.get("contract")
if c:
for rule, count in c["violations"].items():
lines.append(f" ✗ {rule}: {count}/{p['result']['runs']} runs")
if c["passed_but_nonconforming"]:
lines.append(f" ! {c['passed_but_nonconforming']} passing run(s) broke the contract")
if c := p.get("contract"):
lines.extend(_contract_text(c, p["result"]["runs"]))
return "\n".join(lines)


def _contract_text(contract: dict, runs: int) -> list[str]:
lines = [f" ✗ {rule}: {count}/{runs} runs" for rule, count in contract["violations"].items()]
if count := contract["passed_but_nonconforming"]:
Comment thread
napetrov marked this conversation as resolved.
Resolved
lines.append(f" ! {count} passing run(s) broke the contract")
if count := contract["inconclusive_runs"]:
lines.append(f" ? {count}/{runs} runs: contract inconclusive")
for run, actions in contract["unlabelled_writes"].items():
details = ", ".join(f"{action}: {count} unlabelled write(s)" for action, count in actions.items())
lines.append(f" ? {run}: {details}")
return lines


def register(sub, positive_int) -> None:
"""Add the `trace` group (#94 M2: it was `context`): what a run's trace and sessions show."""
trace_p = sub.add_parser(
Expand Down
Loading
Loading