diff --git a/dokimi/changelog.d/20261125_210000_napetrov_contract-modifies.md b/dokimi/changelog.d/20261125_210000_napetrov_contract-modifies.md new file mode 100644 index 000000000..9eecc1ed2 --- /dev/null +++ b/dokimi/changelog.d/20261125_210000_napetrov_contract-modifies.md @@ -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. diff --git a/dokimi/docs/quickstart.md b/dokimi/docs/quickstart.md index 507dbfacb..28f22ed59 100644 --- a/dokimi/docs/quickstart.md +++ b/dokimi/docs/quickstart.md @@ -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 (` : 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 : `), `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 | @@ -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 diff --git a/dokimi/docs/run-consistency.md b/dokimi/docs/run-consistency.md index fdb9a74f2..c3df6f782 100644 --- a/dokimi/docs/run-consistency.md +++ b/dokimi/docs/run-consistency.md @@ -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 &&` 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` diff --git a/dokimi/dokimi/commands/context.py b/dokimi/dokimi/commands/context.py index ec398d63e..3250a11cd 100644 --- a/dokimi/dokimi/commands/context.py +++ b/dokimi/dokimi/commands/context.py @@ -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 @@ -140,18 +141,25 @@ def _read_arms(arms: dict[str, list[str]], shell: str) -> tuple[dict[str, list], 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()): + _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 @@ -171,14 +179,26 @@ def cmd_context_consistency(args: argparse.Namespace) -> None: 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: + 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: @@ -316,15 +336,23 @@ def _consistency_text(report: dict) -> str: 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"]: + 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( diff --git a/dokimi/dokimi/context/consistency.py b/dokimi/dokimi/context/consistency.py index 4b1ccc69b..aec7d37cc 100644 --- a/dokimi/dokimi/context/consistency.py +++ b/dokimi/dokimi/context/consistency.py @@ -41,6 +41,7 @@ import json import math import os +import posixpath import re from dataclasses import dataclass, field from itertools import combinations @@ -48,14 +49,20 @@ from typing import Any from dokimi.context import shell +from dokimi.context.contract import Matcher as Matcher +from dokimi.context.contract import check_contract as check_contract +from dokimi.context.contract import contract_report +from dokimi.context.contract import load_contract as load_contract +from dokimi.context.contract import parse_contract as parse_contract +from dokimi.context.shell_directory import write_directories from dokimi.context.trace import TraceError from dokimi.eval.stats import _mean as stats_mean from dokimi.eval.stats import _pow2_scale as pow2_scale from dokimi.eval.stats import _sample_sd as sample_sd from dokimi.utils import InputError, refuse_device -_WRITE_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} -RULES = ("requires", "forbids", "before", "after_last", "last_ok") +#: How a write tool writes its file: "replace" the whole file, or "modify" what it holds. +_TOOL_WRITES = {"Write": "replace", "Edit": "modify", "MultiEdit": "modify", "NotebookEdit": "modify"} _TARGET_KEYS = ("file_path", "notebook_path", "path", "pattern", "url", "query", "subagent_type") @@ -68,6 +75,16 @@ class Event: failed: bool = False masked: bool = False # the call's status is another's: a pipe without pipefail, a later `;` / `||`, `&`, a loop call: int = -1 # the tool call this step came from; a chained command is one call and several steps + write: str = "" # "replace" or "modify" for a step that writes its file (see `write_mode`); "" for none + change: str = "" # "add" or "modify" for a write to a file the trace can place (see `label_changes`); "" for none + dynamic_path: bool = False # shell expansion may change the displayed file name + directory: str | None = None # shell directory for file identity; None when it cannot be placed + + def resolved_path(self, raw: str) -> str | None: + """Resolve a captured path against the trace directory when its spelling is known.""" + if self.dynamic_path or (self.directory is None and not posixpath.isabs(raw)): + return None + return posixpath.normpath(posixpath.join(self.directory or "", raw)) @dataclass @@ -138,6 +155,7 @@ def parse_run(raw: str, name: str = "", grain: str = "split") -> Run: run = Run(name) by_id: dict[str, list[Event]] = {} seen_messages: dict[str, int] = {} + directory: str | None = None stop_blocked = False # a Stop hook blocked since the last assistant message: its notification is its own for line in raw.split(chr(10)): rec = _record(line) @@ -151,9 +169,10 @@ def parse_run(raw: str, name: str = "", grain: str = "split") -> Run: content: list[Any] = raw_content if isinstance(raw_content, list) else [] main = rec.get("parent_tool_use_id") is None kind = rec.get("type") + directory = _trace_directory(rec, directory) if kind == "assistant": stop_blocked = stop_blocked and not main # a subagent's message does not end the stop - _assistant(run, rec, message, content, main, by_id, seen_messages, grain) + directory = _assistant(run, rec, message, content, main, by_id, seen_messages, grain, directory) elif kind == "user": if _user(run, content, main, by_id): stop_blocked = True @@ -172,6 +191,7 @@ def _finish(run: Run, seen_messages: dict[str, int]) -> None: run.output_tokens = sum(seen_messages.values()) if seen_messages else None if run.passed is None and run.events: run.passed = False + label_changes(run.events) def _record(line: str) -> dict[str, Any] | None: @@ -188,8 +208,17 @@ def _result(run: Run, rec: dict[str, Any]) -> None: run.passed = rec.get("subtype") == "success" and not rec.get("is_error") +def _trace_directory(record: dict[str, Any], current: str | None) -> str | None: + cwd = record.get("cwd") + if (record.get("type") == "system" and record.get("subtype") == "init" + and isinstance(cwd, str)): + return cwd if posixpath.isabs(cwd) else None + return current + + def _assistant(run: Run, rec: dict[str, Any], message: dict[str, Any], content: list[Any], main: bool, - by_id: dict[str, list[Event]], seen_messages: dict[str, int], grain: str) -> None: + by_id: dict[str, list[Event]], seen_messages: dict[str, int], grain: str, + directory: str | None) -> str | None: raw_usage = message.get("usage") usage: dict[str, Any] = raw_usage if isinstance(raw_usage, dict) else {} count = usage.get("output_tokens") @@ -197,15 +226,30 @@ def _assistant(run: Run, rec: dict[str, Any], message: dict[str, Any], content: mid = str(message.get("id") or id(rec)) # one call, many blocks seen_messages[mid] = max(seen_messages.get(mid, 0), int(count)) if not main: - return + return _subagent_directory(content, directory) for block in content: if isinstance(block, dict) and block.get("type") == "tool_use": - evs = _events(str(block.get("name") or ""), block.get("input"), grain) + evs, directory = _call_events(str(block.get("name") or ""), block.get("input"), grain, directory) for e in evs: e.call = run.calls_made run.calls_made += 1 run.events.extend(evs) by_id[str(block.get("id") or "")] = evs + return directory + + +def _subagent_directory(content: list[Any], current: str | None) -> str | None: + # Subagents may share the parent's shell, as in the normalized repo trace. + if current is None: + return None + for block in content: + if not isinstance(block, dict) or block.get("type") != "tool_use" or block.get("name") != "Bash": + continue + args = block.get("input") + command = args.get("command") if isinstance(args, dict) else None + if isinstance(command, str) and write_directories(shell.split_commands(command), current)[1] is None: + return None + return current def _user(run: Run, content: list[Any], main: bool, by_id: dict[str, list[Event]]) -> bool: @@ -226,7 +270,8 @@ def run_from_events(events: list[dict[str, Any]], name: str = "") -> Run: """A run from the normalized ``events.jsonl`` of ``repo run`` (any harness), main thread only. A command is split as a ``Bash`` call is; a read is ``Read``, an edit ``Edit``, another tool its - name. A command with a non-zero ``rc`` fails every command it chains, as a failed call does. + name. This format combines whole-file writes and edits; it supplies path steps, not change labels. + A command with a non-zero ``rc`` fails every command it chains, as a failed call does. """ run = Run(name) for ev in events: @@ -237,19 +282,51 @@ def run_from_events(events: list[dict[str, Any]], name: str = "") -> Run: evs = _events("Bash", {"command": str(ev.get("text") or "")}) for e in evs: e.failed = isinstance(ev.get("rc"), int) and ev["rc"] != 0 + e.write = "" e.call = len(run.events) run.events.extend(evs) elif kind in ("read", "edit"): tool = "Read" if kind == "read" else "Edit" path = str(ev.get("path") or "") + rc = ev.get("rc") + failed = bool(ev.get("denied")) or (isinstance(rc, int) and rc != 0) run.events.append(Event(tool, tool, f"{tool}({Path(path).name})" if path else tool, - {"file_path": path} if path else {})) + {"file_path": path} if path else {}, failed=failed)) elif kind == "tool" and ev.get("name"): tool = str(ev["name"]) run.events.append(Event(tool, tool, tool, {}, failed=bool(ev.get("denied")))) return run +def label_changes(events: list[Event]) -> None: + """Mark each write ``add`` or ``modify``, from the calls before it in the same trace. + + A whole-file write (``Write``, ``>``, ``tee``) to a file no earlier call read or wrote is an + ``add``: it is new if the harness refuses a ``Write`` over a file the session did not read (the + label is only as good as that rule; docs/run-consistency.md). Every other write is a ``modify``. + A refused tool write (``Write``, ``Edit``, ``MultiEdit``, ``NotebookEdit``) wrote nothing: it gets + no label and the file stays unseen. A failed shell call still opened its redirect target, so its + file counts as seen; a failed read leaves the file unseen. A file is one path after ``./`` and + ``..`` are resolved (not after symlinks or ``~``). + """ + seen: set[str] = set() + for ev in events: + raw = str(ev.input.get("file_path") or ev.input.get("notebook_path") or "") + if not raw: + continue + if ev.failed and ev.tool in _TOOL_WRITES: + continue + path = ev.resolved_path(raw) + if path is None: + ev.change = "modify" if ev.write == "modify" else "" + continue + if ev.write: + ev.change = "add" if ev.write == "replace" and path not in seen else "modify" + seen.add(path) + elif not ev.failed: + seen.add(path) + + def order_distance(runs: list[Run]) -> float | None: """Mean order distance of the kind sequences over every pair of runs; ``None`` under two runs.""" return _mean([seq_distance(a.kinds(), b.kinds()) for a, b in combinations(runs, 2)]) @@ -260,16 +337,31 @@ def _text(block: Any) -> str: def _events(tool: str, args: Any, grain: str = "split") -> list[Event]: + events, _ = _call_events(tool, args, grain, None) + return events + + +def _call_events(tool: str, args: Any, grain: str, + directory: str | None) -> tuple[list[Event], str | None]: args = args if isinstance(args, dict) else {} if tool == "Bash": - return _bash_events(tool, args, grain) + return _bash_events(tool, args, grain, directory) kind, target = tool, "" for key in _TARGET_KEYS: if args.get(key): value = str(args[key]) target = Path(value).name if key.endswith("path") else value break - return [Event(tool, kind, f"{kind}({target})" if target else kind, args)] + return [Event(tool, kind, f"{kind}({target})" if target else kind, args, + write=_tool_write(tool, args), directory=directory)], directory + + +def _tool_write(tool: str, args: dict[str, Any]) -> str: + """How ``tool`` writes its file; an empty first ``old_string`` creates a missing file.""" + edits = args.get("edits") if tool == "MultiEdit" else [args] if tool == "Edit" else None + if isinstance(edits, list) and edits and isinstance(edits[0], dict): + return "replace" if edits[0].get("old_string") == "" else "modify" + return _TOOL_WRITES.get(tool, "") def _hides_status(sep: str, errexit: bool) -> bool: @@ -315,34 +407,6 @@ def _set_options(seg: str, errexit: bool, pipefail: bool) -> tuple[bool, bool]: return errexit, pipefail -_GROUP_OPENS = ("if", "while", "until", "for", "select", "{") -_GROUP_CLOSES = ("fi", "done", "}") -_GROUP_BEFORE = ("then", "do", "else", "elif", "!", "{", "(") - - -def _group_balance(seg: str) -> int: - """Groups a segment closes (+1 each) less those it opens (-1 each): `fi`, `done`, `}` and an - unopened `)` close; `if`, `while`, `until`, `for`, `select`, `{` and `(` open. A keyword counts - where a command could start, so `echo fi` is no group.""" - words = shell.tokens(seg) - keywords = sum((w in _GROUP_CLOSES) - (w in _GROUP_OPENS) - for i, w in enumerate(words) if i == 0 or words[i - 1] in _GROUP_BEFORE) - opens, closes = shell.parens(seg) - return keywords + closes - opens - - -def _background_start(parts: list[tuple[str, str]], k: int) -> int: - """The first command a trailing `&` after part ``k`` backgrounds: the group it closes (`{ ... }`, - `( ... )`, `if ... fi`, `for ... done`) back to where it opens, and the `&&` / `||` list before - it.""" - depth = 0 - for j in range(k, -1, -1): - depth += _group_balance(parts[j][0]) - if depth <= 0 and (j == 0 or parts[j - 1][1] not in ("&&", "||")): - return j - return k - - def _masks(parts: list[tuple[str, str]]) -> list[bool]: """Per command of a line, whether the status the call reports may be another's: a pipe without `pipefail`; a later command after `||`, or after `;` or a newline (not under `set -e`); a @@ -352,8 +416,10 @@ def _masks(parts: list[tuple[str, str]]) -> list[bool]: errexit = pipefail = False out, loops = [], 0 outer: list[tuple[bool, bool]] = [] # the options each open subshell started from - backgrounded = {j for k, (_, sep) in enumerate(parts) if sep == "&" - for j in range(_background_start(parts, k), k + 1)} + background_ends: dict[int, int] = {} + for end, start in shell.background_starts(parts).items(): + background_ends[start] = end + last_background = -1 for i, (seg, sep) in enumerate(parts): opens, closes = shell.parens(seg) outer += [(errexit, pipefail)] * opens @@ -365,33 +431,39 @@ def _masks(parts: list[tuple[str, str]]) -> list[bool]: loops -= bool(loops and re.match(r"^done\b", seg)) # `done`, `fi` after the last command close it: its status is the call's sep = sep if sep == "&" or any(shell.clean(later) for later, _ in parts[i + 1:]) else "" + last_background = max(last_background, background_ends.get(i, -1)) out.append(piped or _hides_status(sep, errexit) - or _list_hides(parts, i) or i in backgrounded or (loops > 0 and not errexit)) + or _list_hides(parts, i) or i <= last_background or (loops > 0 and not errexit)) return out -def _bash_events(tool: str, args: dict[str, Any], grain: str) -> list[Event]: +def _bash_events(tool: str, args: dict[str, Any], grain: str, + directory: str | None) -> tuple[list[Event], str | None]: command = str(args.get("command") or "") parts = shell.split_commands(command) masks = _masks(parts) + directories, after = write_directories(parts, directory) if grain == "split": out = [] - for (seg, _), masked in zip(parts, masks, strict=True): + for (seg, _), masked, cwd in zip(parts, masks, directories, strict=True): prog = shell.program(seg) if not prog: continue text = shell.step_text(seg) # one step per file a command writes (`sed -i s/a/b/ a.py b.py` edits two files) - for written in shell.written_files(seg) or [""]: + writes = shell.write_targets(seg) + mode = shell.write_mode(seg) if writes else "" + for written, dynamic in writes or [("", False)]: ev_input = {**args, "command": text, **({"file_path": written} if written else {})} target = Path(written).name if written else text - out.append(Event(tool, f"Bash:{prog}", f"Bash:{prog}({target})", ev_input, masked=masked)) + out.append(Event(tool, f"Bash:{prog}", f"Bash:{prog}({target})", ev_input, masked=masked, + write=mode, directory=cwd, dynamic_path=dynamic)) if out: - return out + return out, after prog = shell.program(command) kind = f"Bash:{prog}" if prog else "Bash" masked = any(m for (seg, _), m in zip(parts, masks, strict=True) if shell.program(seg)) - return [Event(tool, kind, f"{kind}({command.strip()})" if command.strip() else kind, args, masked=masked)] + return [Event(tool, kind, f"{kind}({command.strip()})" if command.strip() else kind, args, masked=masked)], after def load_outcomes(path: Path) -> dict[str, bool]: @@ -458,111 +530,6 @@ def apply_outcomes(runs: list[Run], outcomes: dict[str, bool]) -> list[str]: return missing -# --- contract ---------------------------------------------------------------------------------- - -@dataclass -class Matcher: - tools: tuple[str, ...] = () - patterns: dict[str, re.Pattern[str]] = field(default_factory=dict) # input key -> regex - - def __call__(self, ev: Event) -> bool: - if self.tools and ev.tool not in self.tools and ev.kind not in self.tools: - # a shell write (`sed -i`, `echo > f`, `| tee`) is an edit for a matcher of edit tools; a - # program whose output is saved (`pytest > log`, `ls > f`) did not edit anything - if not (ev.tool == "Bash" and ev.input.get("file_path") and set(self.tools) & _WRITE_TOOLS - and shell.writes_file(ev.kind.removeprefix("Bash:"))): - return False - return all(p.search(str(ev.input.get(k, ""))) for k, p in self.patterns.items()) - - -def load_contract(path: Path) -> dict[str, Any]: - import yaml - - refuse_device(path, "--contract") - text = path.read_text(encoding="utf-8") # outside the try: bad UTF-8 is a ValueError, not a YAML error - try: - data = yaml.safe_load(text) or {} - except (yaml.YAMLError, ValueError, RecursionError) as exc: # ValueError: a bad date; RecursionError: deep nesting - raise ValueError(f"{path}: not valid YAML ({exc})") from exc - return parse_contract(data, str(path)) - - -def _names(value: Any, where: str) -> tuple[str, ...]: - """A string or a list of strings; anything else (a number, a nested list, a mapping) is refused.""" - if value is None: - return () - if isinstance(value, str): - return (value,) - if isinstance(value, list) and all(isinstance(v, str) for v in value): - return tuple(value) - raise ValueError(f"{where} wants a name or a list of names, got {value!r}") - - -def _pattern(value: Any, where: str) -> str: - """A regex, or a list of them as one alternation; anything else (a number, a mapping) is refused, - so that `[pytest, tox]` is not read as the character class `['pytest', 'tox']`.""" - if isinstance(value, list) and value: - return "|".join(f"(?:{p})" for p in _names(value, where)) - if isinstance(value, str): - return value - raise ValueError(f"{where} wants a regex or a list of regexes, got {value!r}") - - -def parse_contract(data: Any, where: str = "contract") -> dict[str, Any]: - if not isinstance(data, dict) or not isinstance(data.get("actions"), dict): - raise ValueError(f"{where}: want `actions:` (name -> matcher) and `rules:`") - actions: dict[str, Matcher] = {} - for name, spec in data["actions"].items(): - if not isinstance(spec, dict): - raise ValueError(f"{where}: action {name!r} is not a mapping") - tools = _names(spec.get("tool"), f"{where}: action {name!r}: `tool`") - try: - patterns = {str(k): re.compile(_pattern(v, f"{where}: action {name!r}: `{k}`")) - for k, v in spec.items() if k != "tool"} - except re.error as exc: - raise ValueError(f"{where}: action {name!r}: bad regex ({exc})") from exc - actions[str(name)] = Matcher(tools, patterns) - rules = [] - raw_rules = data.get("rules") or [] - if not isinstance(raw_rules, list): - raise ValueError(f"{where}: `rules:` wants a list") - for i, rule in enumerate(raw_rules): - if not isinstance(rule, dict) or len(rule) != 1 or next(iter(rule)) not in RULES: - raise ValueError(f"{where}: rule {i} must be one of {', '.join(RULES)}") - (kind, arg), = rule.items() - names = list(_names(arg, f"{where}: rule {i} `{kind}`")) - want = 2 if kind in ("before", "after_last") else 1 - if len(names) != want or any(n not in actions for n in names): - raise ValueError(f"{where}: rule {i} `{kind}` wants {want} defined action name(s), got {arg!r}") - rules.append((kind, names)) - return {"actions": actions, "rules": rules} - - -def check_contract(run: Run, contract: dict[str, Any]) -> list[str]: - """The rules this run broke, each as ``kind: args``.""" - hits = {name: [i for i, ev in enumerate(run.events) if m(ev)] for name, m in contract["actions"].items()} - broken = [] - for kind, names in contract["rules"]: - a = hits[names[0]] - b = hits[names[1]] if len(names) > 1 else [] - last = None - if kind == "requires": - ok = bool(a) - elif kind == "forbids": - ok = not a - elif kind == "before": # every b has an a earlier; vacuous with no b - ok = not b or (bool(a) and a[0] < b[0]) - elif kind == "after_last": # some b after the last a; vacuous with no a - ok = not a or any(j > a[-1] for j in b) - else: # last_ok: the last a did not fail, and its status was not hidden (a pipe, `;`, `&`, a loop) - last = run.events[a[-1]] if a else None - ok = last is None or not (last.failed or last.masked) - if not ok: - masked = kind == "last_ok" and last is not None and not last.failed - broken.append(f"{kind}: {' -> '.join(names)}" + (" (status hidden)" if masked else "")) - return broken - - # --- metrics ----------------------------------------------------------------------------------- def levenshtein(a: list[str], b: list[str]) -> int: @@ -696,20 +663,7 @@ def profile(runs: list[Run], contract: dict[str, Any] | None = None, threshold: out: dict[str, Any] = {"result": result, "path": path, "strategies": groups, "verdict": _summary_verdict(groups)} if contract is not None: - per_run = {r.name: check_contract(r, contract) for r in runs} - tally: dict[str, int] = {} - for broken in per_run.values(): - for rule in broken: - tally[rule] = tally.get(rule, 0) + 1 - conforming = sum(1 for b in per_run.values() if not b) - out["contract"] = { - "rules": len(contract["rules"]), "conforming_runs": conforming, - "conformance_rate": conforming / n if n else None, - "violations": dict(sorted(tally.items(), key=lambda kv: -kv[1])), - "per_run": per_run, - # a pass that broke a rule: the result alone would have hidden it - "passed_but_nonconforming": sum(1 for r in runs if r.passed and per_run[r.name]), - } + out["contract"] = contract_report(runs, contract) return out diff --git a/dokimi/dokimi/context/contract.py b/dokimi/dokimi/context/contract.py new file mode 100644 index 000000000..a86f13d8b --- /dev/null +++ b/dokimi/dokimi/context/contract.py @@ -0,0 +1,233 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Process contracts over the tool calls in a trace consistency run.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from dokimi.context import shell +from dokimi.utils import refuse_device + +if TYPE_CHECKING: + from dokimi.context.consistency import Event, Run + +_WRITE_TOOLS = {"Edit", "Write", "MultiEdit", "NotebookEdit"} +CHANGES = ("add", "modify") +RULES = ("requires", "forbids", "before", "after_last", "last_ok") + + +@dataclass +class Matcher: + tools: tuple[str, ...] = () + patterns: dict[str, re.Pattern[str]] = field(default_factory=dict) # input key -> regex + change: str = "" # "add" or "modify": only the writes labelled so; "" matches any call + + def __call__(self, ev: Event) -> bool: + return (not self.change or self.change == ev.change) and self.matches_input(ev) + + def matches_input(self, ev: Event, *, possible_write: bool = False) -> bool: + if self.tools and ev.tool not in self.tools and ev.kind not in self.tools: + # a shell write (`sed -i`, `echo > f`, `| tee`) is an edit for a matcher of edit tools; a + # program whose output is saved (`pytest > log`, `ls > f`) did not edit anything + if not (ev.tool == "Bash" and ev.input.get("file_path") and set(self.tools) & _WRITE_TOOLS + and shell.writes_file(ev.kind.removeprefix("Bash:"))): + return False + return all(self._matches_pattern(ev, key, pattern, possible_write) for key, pattern in self.patterns.items()) + + def _matches_pattern(self, ev: Event, key: str, pattern: re.Pattern[str], possible_write: bool) -> bool: + raw = str(ev.input.get(key, "")) + if pattern.search(raw): + return True + if not self.change or key not in ("file_path", "notebook_path") or not ev.input.get(key): + return False + resolved = ev.resolved_path(raw) + return possible_write if resolved is None else bool(pattern.search(resolved)) + + +def load_contract(path: Path) -> dict[str, Any]: + import yaml + + refuse_device(path, "--contract") + text = path.read_text(encoding="utf-8") # outside the try: bad UTF-8 is a ValueError, not a YAML error + try: + data = yaml.safe_load(text) or {} + except (yaml.YAMLError, ValueError, RecursionError) as exc: # ValueError: a bad date; RecursionError: deep nesting + raise ValueError(f"{path}: not valid YAML ({exc})") from exc + return parse_contract(data, str(path)) + + +def _names(value: Any, where: str) -> tuple[str, ...]: + """A string or a list of strings; anything else (a number, a nested list, a mapping) is refused.""" + if value is None: + return () + if isinstance(value, str): + return (value,) + if isinstance(value, list) and all(isinstance(v, str) for v in value): + return tuple(value) + raise ValueError(f"{where} wants a name or a list of names, got {value!r}") + + +def _pattern(value: Any, where: str) -> str: + """A regex, or a list of them as one alternation; anything else (a number, a mapping) is refused, + so that `[pytest, tox]` is not read as the character class `['pytest', 'tox']`.""" + if isinstance(value, list) and value: + return "|".join(f"(?:{p})" for p in _names(value, where)) + if isinstance(value, str): + return value + raise ValueError(f"{where} wants a regex or a list of regexes, got {value!r}") + + +def parse_contract(data: Any, where: str = "contract") -> dict[str, Any]: + if not isinstance(data, dict) or not isinstance(data.get("actions"), dict): + raise ValueError(f"{where}: want `actions:` (name -> matcher) and `rules:`") + actions: dict[str, Matcher] = {} + for name, spec in data["actions"].items(): + if not isinstance(spec, dict): + raise ValueError(f"{where}: action {name!r} is not a mapping") + tools = _names(spec.get("tool"), f"{where}: action {name!r}: `tool`") + change = spec.get("change", "") + if "change" in spec and change not in CHANGES: + raise ValueError(f"{where}: action {name!r}: `change` wants add or modify, got {change!r}") + try: + patterns = {str(k): re.compile(_pattern(v, f"{where}: action {name!r}: `{k}`")) + for k, v in spec.items() if k not in ("tool", "change")} + except re.error as exc: + raise ValueError(f"{where}: action {name!r}: bad regex ({exc})") from exc + actions[str(name)] = Matcher(tools, patterns, change) + rules = [] + raw_rules = data.get("rules") or [] + if not isinstance(raw_rules, list): + raise ValueError(f"{where}: `rules:` wants a list") + for i, rule in enumerate(raw_rules): + if not isinstance(rule, dict) or len(rule) != 1 or next(iter(rule)) not in RULES: + raise ValueError(f"{where}: rule {i} must be one of {', '.join(RULES)}") + (kind, arg), = rule.items() + names = list(_names(arg, f"{where}: rule {i} `{kind}`")) + want = 2 if kind in ("before", "after_last") else 1 + if len(names) != want or any(n not in actions for n in names): + raise ValueError(f"{where}: rule {i} `{kind}` wants {want} defined action name(s), got {arg!r}") + rules.append((kind, names)) + return {"actions": actions, "rules": rules} + + +def _unlabelled_write(event: Event) -> bool: + return (event.write == "replace" and not event.change and (event.directory is None or event.dynamic_path) + and (not event.failed or event.tool not in _WRITE_TOOLS) + and bool(event.input.get("file_path") or event.input.get("notebook_path"))) + + +def _unplaced_write(event: Event, change: str) -> bool: + """A write with the action's label whose path cannot be resolved may still be in its filter.""" + raw = event.input.get("file_path") or event.input.get("notebook_path") + return event.change == change and bool(raw) and event.resolved_path(str(raw)) is None + + +@dataclass +class _ActionHits: + known: list[int] = field(default_factory=list) + unlabelled: list[int] = field(default_factory=list) + + def possible(self) -> list[int]: + return sorted(self.known + self.unlabelled) + + +def _action_hits(run: Run, matcher: Matcher) -> _ActionHits: + hits = _ActionHits() + for index, event in enumerate(run.events): + if matcher(event): + hits.known.append(index) + elif matcher.change and (_unlabelled_write(event) or _unplaced_write(event, matcher.change)) \ + and matcher.matches_input(event, possible_write=True): + hits.unlabelled.append(index) + return hits + + +def _before(a: list[int], b: list[int]) -> bool: + return not b or (bool(a) and a[0] < b[0]) + + +def _after_last(a: list[int], b: list[int]) -> bool: + return not a or (bool(b) and b[-1] > a[-1]) + + +def _last_ok(run: Run, hits: _ActionHits) -> tuple[bool | None, bool]: + last = hits.known[-1] if hits.known else -1 + event = run.events[last] if last >= 0 else None + ok = event is None or not (event.failed or event.masked) + for index in hits.unlabelled: + candidate = run.events[index] + if index > last and ok == (candidate.failed or candidate.masked): + return None, False + return ok, bool(event and event.masked and not event.failed) + + +def _rule_verdict(kind: str, a: _ActionHits, b: _ActionHits) -> bool | None: + """Compare the rule's most and least favourable placements of the unlabelled writes.""" + if a is b: # an action cannot strictly precede or follow itself + return False if a.known else None if a.unlabelled else True + if kind == "requires": + lower, upper = bool(a.known), bool(a.possible()) + elif kind == "forbids": + lower, upper = not a.possible(), not a.known + elif kind == "before": + lower, upper = _before(a.known, b.possible()), _before(a.possible(), b.known) + else: # after_last + lower, upper = _after_last(a.possible(), b.known), _after_last(a.known, b.possible()) + return lower if lower == upper else None + + +def _check_contract(run: Run, contract: dict[str, Any]) -> tuple[list[str], list[str], dict[str, int]]: + used = dict.fromkeys(name for _, names in contract["rules"] for name in names) + actions = {name: _action_hits(run, contract["actions"][name]) for name in used} + broken, inconclusive = [], [] + for kind, names in contract["rules"]: + a = actions[names[0]] + masked = False + if kind == "last_ok": + ok, masked = _last_ok(run, a) + else: + b = actions[names[1]] if len(names) > 1 else _ActionHits() + ok = _rule_verdict(kind, a, b) + rule = f"{kind}: {' -> '.join(names)}" + if ok is None: + inconclusive.append(rule) + elif not ok: + broken.append(rule + (" (status hidden)" if masked else "")) + return broken, inconclusive, {name: len(hits.unlabelled) for name, hits in actions.items() if hits.unlabelled} + + +def check_contract(run: Run, contract: dict[str, Any]) -> list[str]: + """Confirmed violations, each as ``kind: args``.""" + return _check_contract(run, contract)[0] + + +def contract_report(runs: list[Run], contract: dict[str, Any]) -> dict[str, Any]: + per_run, uncertain, unlabelled = {}, {}, {} + for run in runs: + broken, inconclusive, counts = _check_contract(run, contract) + per_run[run.name] = broken + if inconclusive: + uncertain[run.name] = inconclusive + if counts: + unlabelled[run.name] = counts + tally: dict[str, int] = {} + for broken in per_run.values(): + for rule in broken: + tally[rule] = tally.get(rule, 0) + 1 + undetermined = sum(not per_run[name] for name in uncertain) + judged = len(runs) - undetermined + conforming = sum(not broken and name not in uncertain for name, broken in per_run.items()) + return { + "rules": len(contract["rules"]), "conforming_runs": conforming, + "conformance_rate": conforming / judged if judged else None, + "violations": dict(sorted(tally.items(), key=lambda kv: -kv[1])), + "per_run": per_run, + "inconclusive_rules": uncertain, "inconclusive_runs": undetermined, + "unlabelled_writes": unlabelled, + "passed_but_nonconforming": sum(1 for run in runs if run.passed and per_run[run.name]), + } diff --git a/dokimi/dokimi/context/shell.py b/dokimi/dokimi/context/shell.py index 2b1912912..f9227cf4f 100644 --- a/dokimi/dokimi/context/shell.py +++ b/dokimi/dokimi/context/shell.py @@ -16,8 +16,11 @@ import re import shlex +from bisect import bisect_right from pathlib import Path +from dokimi.context.shell_edit import OPERATORS, edited_files +from dokimi.repos.shell_redirects import without_redirects from dokimi.text_spans import HEREDOC_WORD, HeredocPattern #: Separators between commands, and what each says about the status a call reports: ``a && b`` fails @@ -26,7 +29,6 @@ _BLANKS = " \t\n(;&|" # what a ``#`` may follow to start a comment _TICK_COMMENT_END, _NEWLINE = re.compile(r"\\[`\\]|[\n`]"), re.compile(r"\n") # a backslash escapes a backtick and a backslash in backticks -_OPERATORS = {"|", "||", "&&", ";", "&", ">", ">>", ">|", ">&", "<", "<<", "&>", "&>>", "(", ")"} _SHELL_WRITERS = {"sed", "perl", "echo", "printf", "cat", "tee"} # their output written to a file is an edit _KEYWORDS = r"(?:if|then|else|elif|do|while|until|!|\{)" _NO_COMMAND = re.compile(r"^(?:(?:for|select|fi|done|esac|in|function)\b|\}(?=[\s<>|&]|$))") @@ -34,6 +36,7 @@ # `perl -Mstrict` is not an edit. _IN_PLACE = {"sed": re.compile(r"^(-[nEsrzu]*i[^-\s]*|--in-place(=.*)?)$"), "perl": re.compile(r"^-[pnalw0-9]*i[^-\s]*$")} +_BRACE_SEQUENCE = re.compile(r"(?:(?:[+-]?[0-9]+)\.\.(?:[+-]?[0-9]+)|[A-Za-z]\.\.[A-Za-z])(?:\.\.[+-]?[0-9]+)?") _CASE_HEADER = re.compile(rf"^(?:(?:\(|{_KEYWORDS}(?=\s))\s*)*case\b.*?\bin\b\s*") # `\(` not `\(+`: a run of `(` splits one way (#932) _HEREDOC_DELIMITER = r"(? int: return j -def _mask(text: str) -> str: +def _mask(text: str, *, mark_expansions: bool = False) -> str: """``text`` with each ``$(...)`` and backtick substitution replaced by one word, so its inner - spaces, ``;`` and ``&&`` are not read as this command's.""" - out, i, depth, quote = [], 0, 0, "" + spaces, ``;`` and ``&&`` are not read as this command's. When requested, mark expansions + without evaluating them.""" + out, i, quote = [], 0, "" + braces: list[tuple[int, bool]] = [] while i < len(text): ch = text[i] if ch == "\\" and quote != "'" and i + 1 < len(text): # an escaped `$` or quote opens nothing out.append(text[i:i + 2]) i += 2 continue + glob = not quote and (ch in "*?[" or ch == "~" and text[i - 1:i] in ("", *" \t=>:")) + if mark_expansions and (glob or quote != "'" and ch in "$`"): + out.append("EXPANSION") if quote: quote = "" if ch == quote else quote elif ch == "$" and text[i + 1:i + 2] == "'": @@ -321,23 +329,48 @@ def _mask(text: str) -> str: out.append(text[i:end]) i = end continue - elif ch in "'\"" and not depth: + elif ch in "'\"": quote = ch - if not quote and ch == "$" and text[i + 1:i + 2] == "(": - out.append("SUBST") - i = _substitution_end(text, i + 2) - continue - if not quote and ch == "`": - j = text.find("`", i + 1) - j = len(text) - 1 if j < 0 else j - out.append("SUBST") - i = j + 1 + if not quote and (substitution := _masked_substitution(text, i, mark_expansions)): + i, masked = substitution + out.append(masked) continue + if mark_expansions and not quote: + _mark_brace_expansion(text, i, braces, out) out.append(ch) i += 1 return "".join(out) +def _masked_substitution(text: str, i: int, mark_expansions: bool) -> tuple[int, str] | None: + """Skip constructs whose contents do not participate in the outer brace expansion.""" + if text[i:i + 2] == "$(": + return _substitution_end(text, i + 2), "SUBST" + if text[i] == "`": + end = text.find("`", i + 1) + return (len(text) if end < 0 else end + 1), "SUBST" + if mark_expansions and text[i:i + 2] == "${": + end = _param_end(text, i) + return end, text[i:end] + return None + + +def _mark_brace_expansion(text: str, i: int, braces: list[tuple[int, bool]], out: list[str]) -> None: + """Mark a matched, unquoted brace pair with an alternative or a sequence in the same word.""" + ch = text[i] + if ch == "{": + braces.append((i + 1, False)) + elif ch in " \t\r\n|&;<>()": + braces.clear() + elif braces and ch == ",": + start, _ = braces[-1] + braces[-1] = (start, True) + elif braces and ch == "}": + start, alternatives = braces.pop() + if alternatives or _BRACE_SEQUENCE.fullmatch(text, start, i): + out.append("EXPANSION") + + def parens(segment: str) -> tuple[int, int]: """How many ``(`` and ``)`` a segment has outside quotes, ``$(...)``, backticks and backslashes: the subshells it opens and closes (``(cd sub``, ``make)``).""" @@ -477,27 +510,114 @@ def step_text(segment: str) -> str: return clean(segment) or segment.strip() +_GROUP_OPENS = ("if", "while", "until", "for", "select", "{") +_GROUP_CLOSES = ("fi", "done", "}") +_GROUP_BEFORE = ("then", "do", "else", "elif", "!", "{", "(") + + +def _group_balance(seg: str) -> int: + """Groups a segment closes (+1 each) less those it opens (-1 each): `fi`, `done`, `}` and an + unopened `)` close; `if`, `while`, `until`, `for`, `select`, `{` and `(` open. A keyword counts + where a command could start, so `echo fi` is no group.""" + words = tokens(seg) + keywords = sum((w in _GROUP_CLOSES) - (w in _GROUP_OPENS) + for i, w in enumerate(words) if i == 0 or words[i - 1] in _GROUP_BEFORE) + opens, closes = parens(seg) + return keywords + closes - opens + + +def background_starts(parts: list[tuple[str, str]]) -> dict[int, int]: + """Map each `&` to the beginning of its group or and/or list.""" + if not any(separator == "&" for _, separator in parts): + return {} + # A start must precede the same or a shallower group depth. Keep the latest + # start at each increasing depth, discarding older, deeper candidates. + depths: list[int] = [] + indices: list[int] = [] + depth = 0 + starts = {} + for index, (segment, separator) in enumerate(parts): + if index == 0 or parts[index - 1][1] not in ("&&", "||"): + while depths and depths[-1] >= depth: + depths.pop() + indices.pop() + depths.append(depth) + indices.append(index) + depth -= _group_balance(segment) + if separator == "&": + count = bisect_right(depths, depth) + starts[index] = indices[count - 1] if count else index + return starts + + def written(segment: str) -> str: """The first file a shell command writes ("" for none); see `written_files`.""" return next(iter(written_files(segment)), "") -def written_files(segment: str) -> list[str]: - """The files a shell command writes, if it is one of the plain ways to write one.""" +def write_mode(segment: str) -> str: + """How a shell command writes the file `written_files` names: ``"modify"`` changes what the file + holds (`sed -i`, `perl -i`, `>>`, `tee -a`); ``"replace"`` writes the whole file (`>`, `tee`). + The mode is read from the write that names the file, not from the whole command.""" words = tokens(clean(segment)) + for stage in _stages(_write_words(segment, words)): + stage = strip_wrappers(stage) + if not _stage_writes(stage): + continue + in_place = _IN_PLACE.get(Path(stage[0]).name) + if in_place and any(in_place.match(w) for w in stage[1:]): + return "modify" + return "modify" if stage[0] == "tee" and _tee_appends(stage[1:]) else "replace" + redirects = _redirects(segment, words) + return "modify" if redirects and redirects[0][1] in (">>", "&>>") else "replace" + + +def _tee_appends(args: list[str]) -> bool: + for word in args: + if word == "--": + break + if word == "--append" or (re.fullmatch(r"-[aip]+", word) and "a" in word): + return True + return False + + +def _stages(words: list[str]) -> list[list[str]]: + """The words of each pipeline stage (`a | b` is two stages).""" stages: list[list[str]] = [[]] for w in words: stages.append([]) if w == "|" else stages[-1].append(w) - for stage in stages: + return stages + + +def write_targets(segment: str) -> list[tuple[str, bool]]: + """Pair each displayed path with whether shell expansion can change its identity.""" + paths = written_files(segment) + if not any(ch in segment for ch in "$`*?[~{"): + return [(path, False) for path in paths] + marked = written_files(_mask(segment, mark_expansions=True)) + return [(path, i >= len(marked) or path != marked[i]) for i, path in enumerate(paths)] + + +def written_files(segment: str) -> list[str]: + """The files a shell command writes, if it is one of the plain ways to write one.""" + words = tokens(clean(segment)) + for stage in _stages(_write_words(segment, words)): if files := _stage_writes(strip_wrappers(stage)): return files + return [target for target, _ in _redirects(segment, words)][:1] + + +def _redirects(segment: str, words: list[str]) -> list[tuple[str, str]]: + """The (target, operator) of each redirect that writes a file: not `/dev/null`, a fd duplicate, or + a stream redirect such as `2>>err.log`.""" + found = [] for i, w in enumerate(words[:-1]): if w in (">", ">>", ">|", "&>", "&>>", ">&") and not (i and _fd_redirect(segment, words[i - 1])): target = words[i + 1] - if target in _OPERATORS or target == "/dev/null" or (w == ">&" and (target == "-" or target.isdigit())): + if target in OPERATORS or target == "/dev/null" or (w == ">&" and (target == "-" or target.isdigit())): continue - return [target] - return [] + found.append((target, w)) + return found def _stage_writes(stage: list[str]) -> list[str]: @@ -506,38 +626,30 @@ def _stage_writes(stage: list[str]) -> list[str]: return [] in_place = _IN_PLACE.get(Path(stage[0]).name) if in_place and any(in_place.match(w) for w in stage[1:]): - return _edited_files(stage[1:]) + return edited_files(stage[1:]) if stage[0] == "tee": - rest = [x for x in stage[1:] if not x.startswith("-")] - if rest and rest[0] not in _OPERATORS: - return [rest[0]] + return _tee_files(stage[1:]) return [] -_SCRIPT_OPTIONS = {"-e", "-f", "--expression", "--file"} -#: A script given in the same word as its option: `-es/a/b/`, `-fa.sed`, `--expression=s/a/b/`. -_SCRIPT_ATTACHED = re.compile(r"^(?:--expression=|--file=|-[nEsrzu]*[ef]\S)") +def _write_words(segment: str, words: list[str]) -> list[str]: + # A tee operand may follow a redirect. Its target and descriptor are not tee files. + if "tee" in words and any(word in OPERATORS - {"|"} for word in words): + return tokens(without_redirects(clean(segment))) + return words -def _edited_files(args: list[str]) -> list[str]: - """The files named after an in-place edit's options. Its script is the first word unless `-e` / `-f` - gives one, and is not a file; a digit before a redirect is a stream number, not a file. An empty - word is the BSD `sed -i ''` suffix.""" - files, script_given, i = [], False, 0 - while i < len(args) and args[i] not in _OPERATORS: - w = args[i] - if w in _SCRIPT_OPTIONS: - script_given, i = True, i + 2 - continue - if _SCRIPT_ATTACHED.match(w): - script_given, i = True, i + 1 - continue - if not w or w.startswith("-") or (w.isdigit() and i + 1 < len(args) and args[i + 1] in _OPERATORS): - i += 1 - continue - files.append(w) - i += 1 - return files if script_given else files[1:] +def _tee_files(args: list[str]) -> list[str]: + files = [] + options = True + for word in args: + if word in OPERATORS or re.fullmatch(r"[<>|&();]+", word): + break + if options and word == "--": + options = False + elif not options or not word.startswith("-"): + files.append(word) + return files def _fd_redirect(segment: str, prev: str) -> bool: diff --git a/dokimi/dokimi/context/shell_directory.py b/dokimi/dokimi/context/shell_directory.py new file mode 100644 index 000000000..6d97dadb2 --- /dev/null +++ b/dokimi/dokimi/context/shell_directory.py @@ -0,0 +1,193 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Track the shell directory of each write in a split trace command.""" + +from __future__ import annotations + +import posixpath +import re + +from dokimi.context.shell import background_starts, clean, parens, tokens +from dokimi.repos.shell_functions import FunctionDefinition, define, track_bodies +from dokimi.repos.shell_redirects import bare, may_fail_redirect, without_redirects +from dokimi.repos.shell_words import activates_virtualenv +from dokimi.text_spans import quote_after + + +def write_directories(parts: list[tuple[str, str]], initial: str | None) -> tuple[list[str | None], str | None]: + """Directories for file identity in a split call. A literal ``cd &&`` anchors + the remaining commands in its list. The ending directory is unknown if the call may have moved it. + """ + functions: dict[str, frozenset[str]] = {} + script = "\n".join(f"{segment}{separator}" for segment, separator in parts) + dirs = _WriteDirectories(initial, functions, define(functions, script)) + backgrounds = background_starts(parts) + starts = set(backgrounds.values()) + snapshots = {} + out = [] + for index, (segment, separator) in enumerate(parts): + if index in starts: + snapshots[index] = dirs.snapshot() + out.append(dirs.directory) + dirs.step(segment, separator) + if index in backgrounds: + dirs.restore(snapshots[backgrounds[index]]) + return out, dirs.after() + + +class _WriteDirectories: + def __init__(self, initial: str | None, functions: dict[str, frozenset[str]], movers: frozenset[str]) -> None: + self.directory = initial + self.moved = False + self.cdpath = False + self.previous = "" + self.outer: list[tuple[str | None, bool, bool]] = [] + self.bodies: list[bool] = [] + self.definition = FunctionDefinition() + self.functions = functions + self.movers = movers + + def snapshot(self) -> tuple[str | None, bool, bool]: + return self.directory, self.moved, self.cdpath + + def restore(self, state: tuple[str | None, bool, bool]) -> None: + self.directory, self.moved, self.cdpath = state + + def step(self, segment: str, separator: str) -> None: + syntax = bare(segment) + opens, closes = parens(segment) + in_definition = self.definition.contains(syntax, opens - closes) + if not in_definition: + track_bodies(self.bodies, syntax) + self.outer.extend([self.snapshot()] * opens) + self.move(segment, separator) + for _ in range(min(closes, len(self.outer))): + self.restore(self.outer.pop()) + if not (self.definition.depth or self.definition.head or self.definition.subshell): + if self.moved and separator != "&&": + self.directory = None + self.previous = separator + + def move(self, segment: str, separator: str) -> None: + words, prefix = _directory_words(segment, self.functions, self.movers) + if words and separator != "&": + anchors = separator == "&&" and self.previous != "||" and not self.bodies + self.directory = _literal_cd(self.directory, words, segment, + self.cdpath if prefix is None else prefix) if anchors else None + self.moved = True + elif separator != "&": + self.track_cdpath(segment) + + def track_cdpath(self, segment: str) -> None: + text = clean(segment) + setting = _cdpath_setting(without_redirects(text).strip()) + if setting is None: + return + gated = self.previous in ("&&", "||") or bool(self.bodies) or may_fail_redirect(text) + self.cdpath = setting or (gated and self.cdpath) + + def after(self) -> str | None: + return None if self.moved else self.directory + + +_DIRECTORY_COMMANDS = {"cd", "pushd", "popd", "source", ".", "eval"} +_ASSIGNMENT = re.compile(r"(?P[A-Za-z_][A-Za-z_0-9]*)(?P\+)?=") +_LOCAL_CDPATH = re.compile(r"""(?::|':*'|":*")*+""") +_WORD_END = re.compile(r"[\s|&;<>()]") +_TIMED = re.compile(r"^time(?=\s|$)(?:\s+-p(?=\s|$))?(?:\s+--(?=\s|$))?\s*") + + +def _after_assignment_prefix(text: str) -> tuple[str, bool | None]: + """Read the unquoted name and operator, then skip the value with shell quote scopes.""" + start = 0 + cdpath = None + while assignment := _ASSIGNMENT.match(text, start): + start = _assignment_value_end(text, assignment.end()) + if assignment.group("name") == "CDPATH": + local = _LOCAL_CDPATH.fullmatch(text, assignment.end(), start) is not None + cdpath = bool(assignment.group("append")) or not local + while start < len(text) and text[start].isspace(): + start += 1 + return text[start:], cdpath + + +def _assignment_value_end(text: str, start: int) -> int: + scope = "" + while end := _WORD_END.search(text, start): + scope, start = quote_after(text, start, end.start(), scope) + if start > end.start(): + continue + if not scope and start == end.start(): + return start + scope, start = quote_after(text, start, end.end(), scope) + return len(text) + + +def _directory_words(segment: str, functions: dict[str, frozenset[str]], + movers: frozenset[str]) -> tuple[list[str], bool | None]: + text = clean(segment) + timed = _TIMED.match(text) + suffix = text[timed.end():] if timed else text + command, cdpath = _after_assignment_prefix(suffix) + words = tokens(command) + if "|" in words: + return [], None + if words and words[0] in functions: + return (["function"] if words[0] in movers or words[0] in _DIRECTORY_COMMANDS else []), cdpath + if words[:1] in (["builtin"], ["command"]): + offset = 2 if words[1:2] in (["--"], ["-p"]) else 1 + words = words[offset:] + if words and words[0] in _DIRECTORY_COMMANDS and not activates_virtualenv(words[0], words[1:], literal=True): + return words, cdpath + return [], cdpath + + + +def _cdpath_setting(text: str) -> bool | None: + """Whether a standalone assignment, export or unset leaves a directory search.""" + rest, prefix = _after_assignment_prefix(text) + if not rest: + return prefix + if match := re.match(r"^export[ \t]+", rest): + return _exported_cdpath(rest[match.end():]) + words = tokens(rest) + if words[:1] == ["unset"] and "CDPATH" in words[1:] and not any(word.startswith("-") for word in words[1:]): + return False + return None + + +def _exported_cdpath(operands: str) -> bool | None: + # Each operand is one shell word, even when its value holds quoted or substituted spaces. + setting = None + while operands: + end = _assignment_value_end(operands, 0) + if not end: + break + word, operands = operands[:end], operands[end:].lstrip() + if value := _exported_assignment(word): + _, setting = _after_assignment_prefix(value) + return setting + + +def _exported_assignment(word: str) -> str: + # Export accepts a NAME=value argument after quote removal, even when its name was quoted. + if word.startswith(("CDPATH=", "CDPATH+=")): + return word + words = tokens(word) + if words and words[0].startswith(("CDPATH=", "CDPATH+=")): + return words[0].split("=", 1)[0] + "=nonliteral" + return "" + +def _literal_cd(directory: str | None, words: list[str], segment: str, cdpath: bool) -> str | None: + if words[:1] != ["cd"] or re.match(r"^\s*!\s", segment): + return None + args = words[2:] if words[1:2] == ["--"] else words[1:] + if len(args) != 1 or not args[0] or args[0].startswith(("-", "~")): + return None + target = args[0] + if cdpath and not posixpath.isabs(target) and target.split("/", 1)[0] not in (".", ".."): + return None + if any(char in segment for char in "$`*?[]{}<>") or (directory is None and not posixpath.isabs(target)): + return None + return posixpath.normpath(posixpath.join(directory or "", target)) diff --git a/dokimi/dokimi/context/shell_edit.py b/dokimi/dokimi/context/shell_edit.py new file mode 100644 index 000000000..3012c6a60 --- /dev/null +++ b/dokimi/dokimi/context/shell_edit.py @@ -0,0 +1,32 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Identify the file operands of in-place sed and perl commands.""" + +import re + +OPERATORS = {"|", "||", "&&", ";", "&", ">", ">>", ">|", ">&", "<", "<<", "&>", "&>>", "(", ")"} +_SCRIPT_OPTIONS = {"-e", "-f", "--expression", "--file"} +#: A script given in the same word as its option: `-es/a/b/`, `-fa.sed`, `--expression=s/a/b/`. +_SCRIPT_ATTACHED = re.compile(r"^(?:--expression=|--file=|-[nEsrzu]*[ef]\S)") + + +def edited_files(args: list[str]) -> list[str]: + """The files named after an in-place edit's options. Its script is the first word unless `-e` / `-f` + gives one, and is not a file; a digit before a redirect is a stream number, not a file. An empty + word is the BSD `sed -i ''` suffix.""" + files, script_given, i = [], False, 0 + while i < len(args) and args[i] not in OPERATORS: + w = args[i] + if w in _SCRIPT_OPTIONS: + script_given, i = True, i + 2 + continue + if _SCRIPT_ATTACHED.match(w): + script_given, i = True, i + 1 + continue + if not w or w.startswith("-") or (w.isdigit() and i + 1 < len(args) and args[i + 1] in OPERATORS): + i += 1 + continue + files.append(w) + i += 1 + return files if script_given else files[1:] diff --git a/dokimi/dokimi/repos/shell_functions.py b/dokimi/dokimi/repos/shell_functions.py index d803cff7f..27a2f77fb 100644 --- a/dokimi/dokimi/repos/shell_functions.py +++ b/dokimi/dokimi/repos/shell_functions.py @@ -31,6 +31,46 @@ _SOURCES = frozenset({"source", "."}) # named by a body only as a command's word +GROUP_OPEN = re.compile(r"(?:^|[\s;&|(])\{(?=\s|$)") # a brace group opens: ``{`` as a word +GROUP_CLOSE = re.compile(r"(?:^|\s)\}(?=\s|$|[;&|])") +_FUNCTION_HEAD = re.compile(r"\s*(?:function\s+[^\s(){}]+(?:\s*\(\s*\))?|[^\s(){}=$`]+\s*\(\s*\))\s*") # ``f()``, ``function f`` +_FUNCTION_DEF = re.compile(_FUNCTION_HEAD.pattern + r"\{(?=\s|$)") # a definition opening its body: ``f() {``, ``function f {`` +# ``f() (`` or ``function f (`` (no ``()``: bash takes the ``(`` as the body's), a definition whose body is a subshell +_SUBSHELL_HEAD = re.compile(r"\s*(?:function\s+)?[^\s(){}=$`]+\s*\(\s*\)\s*\(|\s*function\s+[^\s(){}]+\s*\((?!\s*\))") + + +class FunctionDefinition: + """Tracks shell parts inside a function definition, which runs no commands.""" + + def __init__(self) -> None: + self.depth = 0 + self.head = False + self.subshell = 0 + + def contains(self, text: str, paren_balance: int = 0) -> bool: + head, self.head = self.head, False + if self.subshell or (not self.depth and _SUBSHELL_HEAD.match(text)): + self.subshell = max(0, self.subshell + paren_balance) + return True + if not self.depth and not _FUNCTION_DEF.match(text) and not (head and GROUP_OPEN.match(text)): + self.head = bool(_FUNCTION_HEAD.fullmatch(text)) + return self.head + self.depth = max(self.depth + len(GROUP_OPEN.findall(text)) - len(GROUP_CLOSE.findall(text)), 0) + return True + + +def track_bodies(bodies: list[bool], part: str) -> None: + """Track open if/loop constructs. True means its conditional body has begun.""" + for word in part.split(): + if word in ("if", "while", "until", "for", "select"): + bodies.append(False) + elif word in ("then", "do") and bodies: + bodies[-1] = True + elif word in ("fi", "done") and bodies: + bodies.pop() + elif word not in ("else", "elif", "!", "{", "time"): + break + def define(known: Functions, script: str) -> frozenset[str]: """Add the functions ``script`` defines (``f() { ...; }``, ``function f { ...; }``) to ``known``, and return the names in ``known`` whose call may move the shell: the body names a directory builtin, or a function that does diff --git a/dokimi/dokimi/repos/shell_walk.py b/dokimi/dokimi/repos/shell_walk.py index 9f31c380a..4850d0236 100644 --- a/dokimi/dokimi/repos/shell_walk.py +++ b/dokimi/dokimi/repos/shell_walk.py @@ -23,7 +23,7 @@ from dokimi.text_spans import HEREDOC_WORD, HeredocPattern from .event_format import plain_path -from .shell_functions import Functions, define, may_change_posix +from .shell_functions import GROUP_CLOSE, GROUP_OPEN, FunctionDefinition, Functions, define, may_change_posix, track_bodies from .shell_redirects import ( bare, closed_fds, copied_fds, masked, may_fail_redirect, reopened_fds, without_redirects, without_stderr, ) @@ -42,12 +42,6 @@ before=" \t", after=" \t\r", quote=1, empty=re.compile(_HEREDOC_DELIMITER + r"([^\n]*)\n(?:[^\n]*\n)*?^[\t\r]*$", re.M)) _GLOB = re.compile(r"[*?\[]|\{[^\s{}]*(?:,|\.\.)[^\s{}]*\}") # a pathname or brace expansion, unquoted _PIPE = re.compile(r"(?>?|(?])1?>>?(?!&)|(?])1?>&(?!\d)") # a group's stdout to a file: not the agent's # the values of long options that take a separate word (``head --lines 5``), by command _LONG_VALUE = { @@ -205,8 +199,7 @@ def __init__(self, here: str | None, movers: frozenset[str] = frozenset(), funct self.groups: list[tuple[_Spot, bool, tuple[int, int, bool], tuple[_Spot, bool]]] = [] self.list_start: _Spot = (here, False, False, _POSIX_OFF) # the spot where the && / || list began self.listed = False # that list has more than one command - self.function = 0 # the brace depth inside a function definition - self.head = False # the last part was a function's name alone (``f()``): its body's ``{`` comes next + self.definition = FunctionDefinition() self.def_ran: bool | None = True # whether the function definition being walked runs, as :attr:`ran` at its start self.case = 0 # the depth inside ``case ... esac`` self.operands: int | None = None # how many files the last printing command named @@ -239,15 +232,7 @@ def runs(self, op: str) -> bool | None: def track_bodies(self, part: str) -> None: """The ``if`` / ``while`` / ``until`` / ``for`` / ``select`` that ``part`` opens and the ``fi`` / ``done`` that closes one; after its ``then`` or ``do`` a construct's body is every command up to its end, each of which may not run (:attr:`bodies`).""" - for word in part.split(): - if word in ("if", "while", "until", "for", "select"): - self.bodies.append(False) - elif word in ("then", "do") and self.bodies: - self.bodies[-1] = True - elif word in ("fi", "done") and self.bodies: - self.bodies.pop() - elif word not in ("else", "elif", "!", "{", "time"): - break + track_bodies(self.bodies, part) def track_state(self, part: str, words: list[str], after: str) -> None: """The state a command of ``part`` sets (:meth:`track_posix`), also when a redirect leaves it no ``words`` @@ -313,19 +298,12 @@ def in_function(self, bare: str) -> bool: comments are no parts, so the part after a name alone opens the body. A body in parentheses (``cd() ( ... )``, ``function cd ( ... )``) is a subshell's, so its parts record nothing; the head is skipped, so a name ``cd`` there moves nothing, and a ``{`` word in it (``f() ( echo { ); cd sub``) opens no body that would hide the ``cd``.""" - head, self.head = self.head, False - if not self.function and not head: + if not self.definition.depth and not self.definition.head: self.def_ran = self.ran - if not self.function and _SUBSHELL_DEF.match(bare): + defining = self.definition.contains(bare) + if defining and not self.definition.depth and not self.definition.head: self.defined() - return True - if not self.function and not _FUNCTION_DEF.match(bare) and not (head and _GROUP_OPEN.match(bare)): - self.head = bool(_FUNCTION_HEAD.fullmatch(bare)) - return self.head - self.function = max(self.function + len(_GROUP_OPEN.findall(bare)) - len(_GROUP_CLOSE.findall(bare)), 0) - if not self.function: - self.defined() - return True + return defining def defined(self) -> None: """A function definition that ran exits 0 (``f() { :; } || export P=1`` skips the export); a skipped one keeps @@ -360,9 +338,9 @@ def track_groups(self, bare: str, after: str, out: list[str]) -> None: whose output feeds a pipe after it, or a file, are dropped from ``out``, and so are those it counted in ``unknown`` and the ``passthru`` it set: its output is not the agent's. Each brace of ``bare`` counts, in order (``{ { cd x``, ``} | { cat a``).""" - braces = [(m.end() - 1, m) for m in _GROUP_OPEN.finditer(bare)] + [(m.end(), m) for m in _GROUP_CLOSE.finditer(bare)] + braces = [(m.end() - 1, m) for m in GROUP_OPEN.finditer(bare)] + [(m.end(), m) for m in GROUP_CLOSE.finditer(bare)] for _, m in sorted(braces, key=lambda b: b[0]): - if m.re is _GROUP_OPEN: + if m.re is GROUP_OPEN: self.open_group(bare[:m.end() - 1], len(out)) elif self.groups: self.close_group(bare[m.start():], bare[m.end():], after, out) @@ -721,4 +699,4 @@ def _search_stage(part: str, functions: Functions) -> str | None: def _ungrouped(text: str) -> str: """A part's ``text`` past the ``{`` that open brace groups in it; ``""`` for the ``}`` that closes one.""" - return "" if _GROUP_CLOSE.match(text) else re.sub(r"^(?:\{\s+)+", "", text) + return "" if GROUP_CLOSE.match(text) else re.sub(r"^(?:\{\s+)+", "", text) diff --git a/dokimi/dokimi/repos/shell_words.py b/dokimi/dokimi/repos/shell_words.py index 9225c61b8..87c599047 100644 --- a/dokimi/dokimi/repos/shell_words.py +++ b/dokimi/dokimi/repos/shell_words.py @@ -126,7 +126,7 @@ def _walk(lead: str, base: list[str], lock: int, target: str, physical: bool) -> def _runs_dir(outer: str, dirs: Collection[str] = _DIRS, functions: Collection[str] = ()) -> bool: """Whether a part's text, or its outer text (:class:`~dokimi.repos.shell_split.Part`), runs a directory builtin, as ``cd $(...)`` and ``X="a b" cd "$D"`` do, or may (:func:`_may_run_dir`), but for a virtualenv's activate - (``source .venv/bin/activate > /dev/null``: :func:`_activates`); a subshell ``(cd x; ...)`` has no such + (``source .venv/bin/activate > /dev/null``: :func:`activates_virtualenv`); a subshell ``(cd x; ...)`` has no such text, so it changes nothing outside itself. Text shlex cannot split is read word by word (:func:`_unquoted`): its command word counts, and when a quote up to it does not close (``X="a b c" cd``), any builtin's name in it counts. ``dirs`` are those names: ``_DIRS``, and the script's functions that name one (``f > log`` of ``f() { cd x; }``); @@ -147,7 +147,7 @@ def _runs_dir(outer: str, dirs: Collection[str] = _DIRS, functions: Collection[s return False if told is not None and not all(told[:len(words) - len(rest) + at + 1]): return any(w in dirs for w in words) - return not via_env and rest[at] in dirs and not _activates(rest[at], rest[at + 1:], literal=True) + return not via_env and rest[at] in dirs and not activates_virtualenv(rest[at], rest[at + 1:], literal=True) def _may_run_dir(words: list[str], timed: bool) -> bool: @@ -319,7 +319,7 @@ def _past_time(words: list[str]) -> int: return 0 if any(i is not None and i < len(words) and words[i] in _DIRS for i in (at, loose)) else at -def _activates(name: str, args: list[str], literal: bool = False) -> bool: +def activates_virtualenv(name: str, args: list[str], literal: bool = False) -> bool: """Whether ``name`` and its unquoted ``args`` are ``source`` or ``.`` of a virtualenv's activate script and nothing more but redirections (``> /dev/null``): one operand whose last two components are ``bin/activate`` (``.venv/bin/activate``, ``"/opt/v/bin/activate"``); ``literal``: one with no expansion (not ``$V/bin/activate``), for @@ -347,10 +347,10 @@ def _is_cd(part: str) -> bool: def _is_activate(part: str) -> bool: - """Whether ``part`` sources a virtualenv's activate script (:func:`_activates`), past what the walker skips; a + """Whether ``part`` sources a virtualenv's activate script (:func:`activates_virtualenv`), past what the walker skips; a quoted operand is one word (``source 'my env/bin/activate'``), as the walker reads it.""" words, via_env, _, _ = _command_words(_split(part), _time_keyword(part)) - return not via_env and bool(words) and _activates(words[0], words[1:]) + return not via_env and bool(words) and activates_virtualenv(words[0], words[1:]) def _split(part: str) -> list[str]: @@ -364,11 +364,11 @@ def _split(part: str) -> list[str]: def _loses(name: str, words: list[str], conditional: bool, timed: bool, via_env: bool = False) -> bool: """Whether the followed command ``words``, run as ``name``, leaves the directory not known: a ``pushd``, ``popd``, - ``eval``, ``source`` or ``.`` (not of an activate script, :func:`_activates`), a ``cd`` that may not run + ``eval``, ``source`` or ``.`` (not of an activate script, :func:`activates_virtualenv`), a ``cd`` that may not run (``conditional``), or a part not fully followed (:func:`_may_run_dir`), but for one a child runs (``via_env``: ``env command -p cd sub`` runs a program, so it moves no shell).""" if name in _DIR_LOST: - return not _activates(name, words[1:]) + return not activates_virtualenv(name, words[1:]) return (conditional and name == "cd") or (not via_env and _may_run_dir(words, timed)) diff --git a/dokimi/tests/test_context_change_review.py b/dokimi/tests/test_context_change_review.py new file mode 100644 index 000000000..8cc708a3b --- /dev/null +++ b/dokimi/tests/test_context_change_review.py @@ -0,0 +1,631 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Trace consistency write labels and contracts when a trace cannot identify a write.""" + +import json +import sys + +import pytest +from test_context_consistency import _run, _trace + +from dokimi.cli import build_parser, main +from dokimi.context.consistency import check_contract, parse_contract, parse_run, profile, run_from_events + + +def _trace_in_workspace(*steps): + init, calls = _trace(*steps).split("\n", 1) + return json.dumps({**json.loads(init), "cwd": "/w"}) + "\n" + calls + + +@pytest.mark.parametrize("command", [ + "cd a || cd /b && echo x > f.py", + "test -d build || cd sub && echo x > f.py", + "cd a && true || echo x > f.py", +]) +def test_cd_in_an_or_list_does_not_assume_which_path_ran(command): + run = parse_run(_trace_in_workspace(("Read", {"file_path": "/w/a/f.py"}), + ("Bash", {"command": command}))) + assert [(ev.change, ev.input["file_path"]) for ev in run.events if ev.write] == [("", "f.py")] + + +@pytest.mark.parametrize("rule, labelled, inconclusive, violations", [ + ({"forbids": "new_test"}, False, 1, []), + ({"requires": "new_test"}, False, 1, []), + ({"forbids": "new_test"}, True, 0, ["forbids: new_test"]), + ({"requires": "new_test"}, True, 0, []), + ({"requires": "test"}, False, 0, ["requires: test"]), +]) +def test_contract_distinguishes_unlabelled_writes_from_verdicts(rule, labelled, inconclusive, violations): + contract = parse_contract({"actions": { + "new_test": {"change": "add", "file_path": "tests/"}, + "test": {"tool": "Bash:pytest"}, + "doc": {"change": "add", "file_path": "docs/"}, + }, "rules": [rule]}) + steps = [("Bash", {"command": 'cd "$DIR" && echo > tests/a.py; echo > docs/a.md'}), + ("Write", {"file_path": "/w/tests/refused.py"}, True), + ("Read", {"file_path": "/w/tests/seen.py"})] + if labelled: + steps.append(("Bash", {"command": "echo > /w/tests/b.py"})) + run = parse_run(_trace_in_workspace(*steps), "r") + result = profile([run], contract)["contract"] + assert result["unlabelled_writes"] == ({"r": {"new_test": 2}} if "test" not in rule.values() else {}) + assert result["inconclusive_runs"] == inconclusive + assert result["per_run"] == {"r": violations} + assert result["conformance_rate"] == (None if inconclusive else float(not violations)) + + +@pytest.mark.parametrize("as_json", [False, True]) +@pytest.mark.parametrize("steps", [ + [("Bash", {"command": "cd elsewhere"}), ("Bash", {"command": "echo > tests/new.py"})], + [("Bash", {"command": 'name=test_new; echo > "tests/$name.py"'})], +]) +def test_cli_reports_a_contract_it_could_not_check(tmp_path, capsys, monkeypatch, as_json, steps): + trace = tmp_path / "run.jsonl" + trace.write_text(_trace_in_workspace(*steps)) + contract = tmp_path / "contract.yaml" + contract.write_text("actions:\n new_test: {change: add, file_path: 'tests/'}\nrules:\n - forbids: new_test\n") + monkeypatch.setattr(sys, "argv", ["dokimi", "trace", "consistency", str(trace), "--contract", str(contract), + *(["--json"] if as_json else [])]) + with pytest.raises(SystemExit) as error: + main() + assert error.value.code == 3 + out = capsys.readouterr().out + if as_json: + doc = json.loads(out) + assert doc["status"] == "partial" + assert doc["data"]["runs"]["contract"]["inconclusive_rules"] == {str(trace): ["forbids: new_test"]} + else: + assert "contract inconclusive" in out and "new_test: 1 unlabelled write" in out + + +@pytest.mark.parametrize("rule, command, failed, expected", [ + ({"before": ["write", "test"]}, 'cd "$DIR" && echo > tests/a.py && pytest', False, + {"r": ["before: write -> test"]}), + ({"after_last": ["write", "test"]}, 'pytest && cd "$DIR" && echo > tests/a.py', False, + {"r": ["after_last: write -> test"]}), + ({"last_ok": "write"}, 'cd "$DIR" && echo > tests/a.py', True, {"r": ["last_ok: write"]}), + ({"last_ok": "write"}, 'cd "$DIR" && echo > tests/a.py', False, {}), + ({"before": ["write", "write"]}, 'cd "$DIR" && echo > tests/a.py', False, {}), + ({"after_last": ["write", "write"]}, 'cd "$DIR" && echo > tests/a.py', False, {}), +]) +def test_contract_order_and_status_with_an_unlabelled_write(rule, command, failed, expected): + contract = parse_contract({"actions": {"write": {"change": "add"}, "test": {"tool": "Bash:pytest"}}, + "rules": [rule]}) + steps = [("Bash", {"command": command}, failed)] + if rule in ({"before": ["write", "write"]}, {"after_last": ["write", "write"]}): + steps.append(("Bash", {"command": "echo > /w/tests/b.py"})) + result = profile([parse_run(_trace_in_workspace(*steps), "r")], contract)["contract"] + assert result["inconclusive_rules"] == expected + if isinstance(args := next(iter(rule.values())), list) and args[0] == args[1]: + assert result["per_run"]["r"] == [f"{next(iter(rule))}: write -> write"] + + +@pytest.mark.parametrize("source, label", [ + ("source .venv/bin/activate", "modify"), + (". '/opt/my env/bin/activate' >/dev/null", "modify"), + ("source ./environment.sh", ""), + ('source "$ENV/bin/activate"', ""), +]) +def test_literal_virtualenv_activation_does_not_lose_the_directory(source, label): + run = parse_run(_trace_in_workspace(("Read", {"file_path": "/w/tests/a.py"}), + ("Bash", {"command": source}), + ("Bash", {"command": "echo > tests/a.py"}))) + assert run.events[-1].change == label + + +@pytest.mark.parametrize("command, label", [("cd tests", ""), ("pytest", "modify"), ("(cd tests)", "modify")]) +def test_a_subagent_that_may_move_the_shell_changes_parent_cwd_confidence(command, label): + lines = [json.loads(line) for line in _trace_in_workspace(("Read", {"file_path": "/w/a.py"}), + ("Bash", {"command": "echo > a.py"})).splitlines()] + subagent = {"type": "assistant", "parent_tool_use_id": "task", "message": {"content": [ + {"type": "tool_use", "id": "sub", "name": "Bash", "input": {"command": command}}, + ]}} + lines.insert(3, subagent) + run = parse_run("\n".join(json.dumps(line) for line in lines)) + assert run.kinds() == ["Read", "Bash:echo"] + assert run.events[-1].change == label + + +def test_normalized_edit_cannot_distinguish_a_write_from_an_edit(): + run = run_from_events([{"kind": "edit", "path": "tests/new.py"}]) + assert run.actions() == ["Edit(new.py)"] and run.events[0].change == "" + + +@pytest.mark.parametrize("setting, target, label", [ + ("CDPATH=/elsewhere;", "tests", ""), + ("export CDPATH=/elsewhere &&", "tests", ""), + ("export 'CDPATH=/elsewhere' &&", "tests", ""), + ("CDPATH=/elsewhere >/dev/null;", "tests", ""), + ("CDPATH=/elsewhere; CDPATH= >/dev/null;", "tests", "modify"), + ("CDPATH=/elsewhere; if true; then CDPATH=; fi;", "tests", ""), + ("CDPATH=/elsewhere; CDPATH=;", "tests", "modify"), + ("CDPATH=/elsewhere; unset CDPATH;", "tests", "modify"), + ("CDPATH=/elsewhere;", "./tests", "modify"), + ("CDPATH=/elsewhere;", "/w/tests", "modify"), + ("CDPATH=:;", "tests", "modify"), + ("CDPATH=/elsewhere env true;", "tests", "modify"), + ("(CDPATH=/elsewhere);", "tests", "modify"), + ("CDPATH=/elsewhere; false && CDPATH=;", "tests", ""), + ("CDPATH=/elsewhere; false && unset CDPATH;", "tests", ""), +]) +def test_an_explicit_shell_cdpath_can_affect_later_cd_in_that_call(setting, target, label): + run = parse_run(_trace_in_workspace(("Read", {"file_path": "/w/tests/a.py"}), + ("Bash", {"command": f"{setting} cd {target} && echo > a.py"}))) + assert run.events[-1].change == label + + +@pytest.mark.parametrize("command, label", [ + ("f() { cd sub; }; f; echo > a.py", ""), + ("f() { cd sub; }; echo > a.py", "modify"), + ("f()\n{ cd sub; }\nf && echo > a.py", ""), + ("f() ( cd sub ); f; echo > a.py", "modify"), + ("f() ( :; cd sub; ); f; echo > a.py", "modify"), + ("for i in 1 2; do cd sub && echo > a.py; done", ""), + ("if true; then cd sub && echo > a.py; fi", ""), + ("while cd sub && echo > a.py; do :; done", ""), + ("cd sub && echo > a.py & echo > a.py", "modify"), +]) +def test_shell_control_flow_does_not_prove_a_move_from_literal_cd(command, label): + run = parse_run(_trace_in_workspace(("Read", {"file_path": "/w/a.py"}), + ("Bash", {"command": command}))) + assert run.events[-1].change == label + + +NEW_TEST = ("Write", {"file_path": "/w/tests/test_new.py", "content": "x"}) +OLD_TEST = ("Edit", {"file_path": "/w/tests/test_old.py", "old_string": "a", "new_string": "b"}) + + +def _changes(*steps): + """The ``change`` label of each write, in order (reads and other steps have none).""" + return [e.change for e in parse_run(_trace_in_workspace(*steps)).events if e.change] + + +def test_a_write_to_an_unseen_file_is_an_add_and_to_a_seen_one_a_modify(): + assert _changes(NEW_TEST) == ["add"] + assert _changes(NEW_TEST, NEW_TEST) == ["add", "modify"] + assert _changes(("Read", {"file_path": "/w/a.py"}), ("Write", {"file_path": "/w/a.py", "content": "x"})) == ["modify"] + assert _changes(OLD_TEST) == ["modify"] + assert _changes(("NotebookEdit", {"notebook_path": "/w/n.ipynb"})) == ["modify"] + + +def test_a_read_that_failed_leaves_the_file_unseen(): + gone = ("Read", {"file_path": "/w/tests/test_new.py"}, True) + assert _changes(gone, NEW_TEST) == ["add"] + + +def test_the_same_file_under_two_spellings_is_one_file(): + assert _changes(("Read", {"file_path": "./tests/a.py"}), ("Write", {"file_path": "tests/a.py", "content": "x"})) == ["modify"] + + +@pytest.mark.parametrize("cmd, want", [ + ("echo x > tests/test_new.py", ["add"]), + ("cat > tests/test_new.py <<'EOF'\nx\nEOF", ["add"]), + ("printf x | tee tests/test_new.py", ["add"]), + ("echo x >> tests/test_old.py", ["modify"]), + ("printf x | tee -a tests/test_old.py", ["modify"]), + ("sed -i s/a/b/ tests/test_old.py", ["modify"]), +]) +def test_a_shell_write_is_an_add_or_a_modify(cmd, want): + assert _changes(("Bash", {"command": cmd})) == want + + +@pytest.mark.parametrize("separate_calls", [False, True]) +def test_shell_write_identity_uses_the_directory_without_changing_matcher_input(separate_calls): + commands = ["cd /w/one && echo x > tests/a.py", "cd /w/two && echo y > tests/a.py"] + if not separate_calls: + commands = ["; ".join(commands)] + run = _run("r", *(("Bash", {"command": command}) for command in commands)) + assert [(event.change, event.input["file_path"]) for event in run.events] == [ + ("add", "tests/a.py"), ("add", "tests/a.py"), + ] + contract = parse_contract({"actions": {"edit_test": {"change": "modify", "file_path": r"^tests/"}}, + "rules": [{"forbids": "edit_test"}]}) + assert check_contract(run, contract) == [] + + +def test_relative_shell_write_can_match_an_earlier_absolute_path_in_a_known_directory(): + read = ("Read", {"file_path": "/w/one/tests/a.py"}) + write = ("Bash", {"command": "cd /w && cd one && echo x > tests/./a.py"}) + assert _changes(read, write) == ["modify"] + + +def test_unknown_shell_directory_leaves_relative_replacement_unlabelled(): + write = ("Bash", {"command": 'cd "$D" && echo x > tests/a.py'}) + assert _changes(write) == [] + + +def test_the_trace_start_directory_resolves_relative_shell_changes(): + trace = _trace( + ("Read", {"file_path": "/w/sub/tests/a.py"}), + ("Bash", {"command": "cd sub && echo x > tests/a.py"}), + ) + init, calls = trace.split("\n", 1) + raw = json.dumps({**json.loads(init), "cwd": "/w"}) + "\n" + calls + assert [event.change for event in parse_run(raw).events] == ["", "modify"] + + +@pytest.mark.parametrize("cd", [ + "cd /w 2>&1", "cd /w &>/dev/null", 'X="$VALUE" cd /w', +]) +def test_cd_variants_do_not_leave_the_original_write_directory_known(cd): + run = _run("r", ("Read", {"file_path": "a.py"}), + ("Bash", {"command": f"{cd} && echo x > a.py"}), + ("Bash", {"command": "echo y > a.py"})) + assert [(event.change, event.input.get("file_path")) for event in run.events if event.write] == [ + ("", "a.py"), ("", "a.py"), + ] + + +@pytest.mark.parametrize("cd", ["builtin cd", "command cd", "X=1 cd", "X+=1 cd", "time cd", + "time -p X=1 command cd", "X='two words' cd", + 'X="two words" Y=a" b" cd', "time -- X='' cd", + 'X="a' + "\\\n" + 'b" cd', "X=a" + "\\\n" + "b cd"]) +def test_simple_cd_prefixes_resolve_relative_writes_in_their_target_directory(cd): + read = ("Read", {"file_path": "/w/one/tests/a.py"}) + write = ("Bash", {"command": f"{cd} /w/one && echo x > tests/a.py"}) + assert _changes(read, write) == ["modify"] + + +@pytest.mark.parametrize("command", ["env X=1 cd /w", "command -v cd", "/usr/bin/time cd /w"]) +def test_an_external_command_or_lookup_does_not_move_the_shell(command): + write = ("Bash", {"command": f"{command}; echo x > a.py"}) + read = ("Read", {"file_path": "a.py"}) + assert _changes(read, write) == ["modify"] + + +@pytest.mark.parametrize("prefix", [ + "'X=1'", "'X'=1", r"X\=1", r"\X=1", "Y=2 'X=1'", "time 'X=1'", "$'X'=1", "$'X=1'", +]) +def test_quoted_or_escaped_assignment_spelling_does_not_hide_a_modification(prefix): + run = parse_run(_trace_in_workspace(("Read", {"file_path": "tests/a.py"}), + ("Bash", {"command": f"{prefix} cd /w/two; echo x > tests/a.py"}))) + contract = parse_contract({"actions": {"edit": {"change": "modify", "file_path": r"^tests/"}}, + "rules": [{"forbids": "edit"}]}) + assert check_contract(run, contract) == ["forbids: edit"] + + +@pytest.mark.parametrize("assignment", [ + r"X=$'it\'s'", r"X=pre$'it\'s'post", r"X=1 Y=$'it\'s'", r"time -p X=$'it\'s'", + 'X=$(printf "a b")', 'X=$(printf "a b"; printf "c")', + 'X=${UNSET:-a b}', 'X="$(printf "a b")"', +]) +def test_shell_assignment_expansions_do_not_keep_the_old_directory(assignment): + read = ("Read", {"file_path": "/w/one/tests/a.py"}) + write = ("Bash", {"command": f"cd /w/one && {assignment} cd /w/two && echo x > tests/a.py"}) + assert _changes(read, write) == [] + + +@pytest.mark.parametrize("assignment, target, label", [ + ("CDPATH=/w/two", "sub", ""), + ('CDPATH="/w/two"', "sub", ""), + ("X=1 CDPATH=/w/two:", "sub", ""), + ("time -p CDPATH+=/w/two", "sub", ""), + ("CDPATH+=", "sub", ""), + ("CDPATH=", "sub", "modify"), + ('CDPATH=":"', "sub", "modify"), + ("CDPATH=/w/two", "./sub", "modify"), + ("CDPATH=/w/two", "../one/sub", "modify"), + ("CDPATH=/w/two", "/w/one/sub", "modify"), + ("CDPATH=/w/two CDPATH=", "sub", "modify"), + ("CDPATH= CDPATH=/w/two", "sub", ""), +]) +def test_explicit_cdpath_only_affects_eligible_relative_targets(assignment, target, label): + read = ("Read", {"file_path": "/w/one/sub/tests/a.py"}) + command = f"cd /w/one && {assignment} cd {target} && echo x > tests/a.py" + write = _run("r", read, ("Bash", {"command": command})).events[-1] + assert (write.change, write.input["file_path"]) == (label, "tests/a.py") + + +def test_negated_cd_does_not_set_the_directory_of_a_following_write(): + read = ("Read", {"file_path": "/w/tests/a.py"}) + write = ("Bash", {"command": "! cd /w && echo x > tests/a.py"}) + assert _changes(read, write) == [] + + +def test_a_later_bash_call_does_not_assume_the_original_directory_after_cd(): + run = _run("r", ("Read", {"file_path": "tests/a.py"}), + ("Bash", {"command": "cd /w/one && true"}), + ("Bash", {"command": "echo x > tests/a.py"}), + ("Bash", {"command": "cd /w/two && echo y > tests/a.py"})) + assert [event.change for event in run.events] == ["", "", "", "add"] + + +def test_shell_write_identity_restores_the_parent_after_a_subshell(): + command = "cd /w && (cd /w/one && echo x > tests/a.py) && echo y > tests/a.py" + assert _changes(("Bash", {"command": command})) == ["add", "add"] + + +def test_a_shell_redirect_to_a_file_the_trace_saw_is_a_modify(): + seen = ("Read", {"file_path": "tests/test_new.py"}) + assert _changes(seen, ("Bash", {"command": "echo x > tests/test_new.py"})) == ["modify"] + + +def test_a_contract_can_forbid_new_tests_and_allow_editing_old_ones(): + add = parse_contract({"actions": {"new_test": {"change": "add", "file_path": r"tests/"}}, + "rules": [{"forbids": "new_test"}]}) + assert check_contract(_run("n", NEW_TEST, ("Bash", {"command": "pytest -q"})), add) == ["forbids: new_test"] + assert check_contract(_run("o", ("Read", {"file_path": "/w/tests/test_old.py"}), OLD_TEST), add) == [] + modify = parse_contract({"actions": {"edit_test": {"change": "modify", "file_path": r"tests/"}}, + "rules": [{"forbids": "edit_test"}]}) + assert check_contract(_run("o", ("Read", {"file_path": "/w/tests/test_old.py"}), OLD_TEST), modify) == ["forbids: edit_test"] + assert check_contract(_run("n", NEW_TEST), modify) == [] + + +def test_cli_refuses_change_contract_at_call_grain(tmp_path, capsys, monkeypatch): + trace = tmp_path / "run.jsonl" + trace.write_text(_trace_in_workspace(("Bash", {"command": "echo x > tests/a.py"})), encoding="utf-8") + contract = tmp_path / "contract.yaml" + argv = ["trace", "consistency", str(trace), "--contract", str(contract), "--json"] + contract.write_text("actions: {test: {change: add, file_path: 'tests/'}}\nrules: [{forbids: test}]\n", + encoding="utf-8") + monkeypatch.setattr(sys, "argv", ["dokimi", *argv, "--shell", "call"]) + with pytest.raises(SystemExit) as stopped: + main() + assert stopped.value.code == 2 + refused = capsys.readouterr() + assert "requires --shell split" in refused.out or "requires --shell split" in refused.err + + parser = build_parser() + args = parser.parse_args(argv) + args.func(args) + assert json.loads(capsys.readouterr().out)["data"]["runs"]["contract"]["violations"] == {"forbids: test": 1} + + contract.write_text("actions: {test: {tool: 'Bash:echo'}}\nrules: [{requires: test}]\n", encoding="utf-8") + args = parser.parse_args([*argv, "--shell", "call"]) + args.func(args) + assert json.loads(capsys.readouterr().out)["data"]["runs"]["contract"]["conformance_rate"] == 1.0 + + +def test_a_change_action_with_a_tool_matches_a_shell_edit_of_an_existing_file(): + c = parse_contract({"actions": {"edit": {"tool": "Edit", "change": "modify"}}, + "rules": [{"requires": "edit"}]}) + assert check_contract(_run("r", ("Bash", {"command": "sed -i s/a/b/ tests/test_old.py"})), c) == [] + assert check_contract(_run("r", NEW_TEST), c) == ["requires: edit"] + + +@pytest.mark.parametrize("value", ["", "create", "Add", ["add"], 1, None]) +def test_contract_change_is_add_or_modify(value): + with pytest.raises(ValueError): + parse_contract({"actions": {"a": {"change": value}}, "rules": []}) + + +@pytest.mark.parametrize("kind", ["read", "edit"]) +@pytest.mark.parametrize("failure", [{"denied": True}, {"rc": 1}]) +# Test-narrowed: normalized events no longer infer changes because edit combines Write and Edit. +def test_a_failed_normalized_access_is_marked_failed(kind, failure): + run = run_from_events([ + {"kind": kind, "path": "tests/a.py", **failure}, + {"kind": "command", "text": "echo x > tests/a.py", "rc": 0}, + ]) + failed, write = run.events + assert failed.failed and not failed.change + assert not write.failed and not write.change + + +def test_a_refused_write_creates_nothing_so_it_is_no_add_and_leaves_the_file_unseen(): + refused = ("Write", {"file_path": "/w/tests/test_old.py", "content": "x"}, True) + assert _changes(refused) == [] + assert _changes(refused, ("Write", {"file_path": "/w/tests/test_old.py", "content": "y"})) == ["add"] + + +def test_a_failed_shell_call_still_opened_its_redirect_target(): + chain = ("Bash", {"command": "echo x > tests/test_new.py && pytest -q"}, True) + assert _changes(chain, ("Write", {"file_path": "tests/test_new.py", "content": "y"})) == ["add", "modify"] + + +@pytest.mark.parametrize("options", ["-ai", "-ia", "-ap", "-pa", "--append -i"]) +def test_tee_append_with_other_options_modifies_its_target(options): + assert _changes(("Bash", {"command": f"printf x | tee {options} tests/a.py"})) == ["modify"] + + +def test_tee_append_like_path_after_end_of_options_is_not_a_flag(): + assert _changes(("Bash", {"command": "printf x | tee -- tests/a.py -a"})) == ["add", "add"] + + +def test_a_tee_to_a_new_file_after_an_append_elsewhere_is_an_add(): + assert _changes(("Bash", {"command": "echo x >> log.txt | tee tests/test_new.py"})) == ["add"] + + +def test_a_quoted_append_marker_is_an_argument_not_a_redirect(): + assert _changes(("Bash", {"command": 'echo ">>" > tests/test_new.py'})) == ["add"] + + +def test_a_stderr_append_is_not_the_file_written(): + assert _changes(("Bash", {"command": "pytest 2>>err.log > tests/test_new.py"})) == ["add"] + + +def test_windows_init_leaves_relative_redirect_identity_unknown(): + trace = _trace_in_workspace(("Read", {"file_path": r"C:\w\tests\a.py"}), + ("Bash", {"command": "echo x > tests/a.py"})) + trace = trace.replace('"/w"', json.dumps(r"C:\w"), 1) + assert [event.change for event in parse_run(trace).events if event.write] == [""] + + +@pytest.mark.parametrize("command, broke", [("echo > tests/new.py", True), ("true", False)]) +def test_text_report_names_a_passing_run_that_broke_the_contract(tmp_path, capsys, command, broke): + trace = tmp_path / "run.jsonl" + trace.write_text(_trace_in_workspace(("Bash", {"command": command}))) + contract = tmp_path / "contract.yaml" + contract.write_text("actions:\n new_test: {change: add, file_path: 'tests/'}\nrules:\n - forbids: new_test\n") + args = build_parser().parse_args(["trace", "consistency", "--arm", f"run={trace}", "--contract", str(contract)]) + args.func(args) + out = capsys.readouterr().out + assert ("broke the contract" in out) == broke + assert ("1 passing run(s) broke the contract" in out) == broke + + +def test_cli_json_is_partial_and_exits_1_when_a_trace_cannot_be_read(tmp_path, capsys, monkeypatch): + good = tmp_path / "good.jsonl" + good.write_text(_trace_in_workspace(("Read", {"file_path": "/w/a.py"}))) + missing = tmp_path / "missing.jsonl" + monkeypatch.setattr(sys, "argv", ["dokimi", "trace", "consistency", str(good), str(missing), "--json"]) + with pytest.raises(SystemExit) as error: + main() + assert error.value.code == 1 + doc = json.loads(capsys.readouterr().out) + assert doc["status"] == "partial" + assert doc["reason"] == "one or more traces could not be read (see stderr)" + + +def test_an_edit_after_an_unknown_directory_is_a_modify_that_meets_the_contract(): + contract = parse_contract({"actions": {"edit_test": {"change": "modify", "file_path": "tests/"}}, + "rules": [{"requires": "edit_test"}]}) + run = parse_run(_trace(("Bash", {"command": "cd /w; sed -i s/a/b/ tests/x.py"})), "r") + assert [e.change for e in run.events if e.write] == ["modify"] + assert profile([run], contract)["contract"]["per_run"] == {"r": []} + + +@pytest.mark.parametrize("target, expected", [('"tests/$name.py"', ""), ("'tests/$name.py'", "add")]) +def test_redirect_identity_respects_shell_variable_expansion(target, expected): + trace = _trace_in_workspace(("Read", {"file_path": "/w/tests/test_old.py"}), + ("Bash", {"command": f"name=test_old; printf x > {target}"})) + assert [event.change for event in parse_run(trace).events if event.write] == [expected] + + +def test_relative_replacement_without_an_init_cwd_is_inconclusive(): + run = parse_run(_trace(("Read", {"file_path": "/w/tests/x.py"}), + ("Bash", {"command": "echo > tests/x.py"})), "run") + assert run.events[-1].change == "" + contract = parse_contract({"actions": {"added": {"change": "add", "file_path": "tests/"}}, + "rules": [{"forbids": "added"}]}) + assert profile([run], contract)["contract"]["inconclusive_runs"] == 1 + + +def test_nested_background_groups_scan_each_segment_once(monkeypatch): + from dokimi.context import shell + from dokimi.context.shell_directory import write_directories + + parts = shell.split_commands("{ " * 40 + "true; " + "} & " * 40 + "echo end") + calls = 0 + balance = shell._group_balance + + def counted(segment): + nonlocal calls + calls += 1 + return balance(segment) + + monkeypatch.setattr(shell, "_group_balance", counted) + write_directories(parts, "/w") + assert calls <= len(parts) + + +@pytest.mark.parametrize("step", [ + ("Edit", {"file_path": "/w/tests/test_new.py", "old_string": "", "new_string": "x"}), + ("MultiEdit", {"file_path": "/w/tests/test_new.py", "edits": [{"old_string": "", "new_string": "x"}]}), +]) +def test_an_edit_with_an_empty_old_string_creates_the_file_so_it_is_an_add(step): + add = parse_contract({"actions": {"new_test": {"change": "add", "file_path": "tests/"}}, + "rules": [{"forbids": "new_test"}]}) + assert check_contract(_run("n", step), add) == ["forbids: new_test"] + assert _changes(("Read", {"file_path": "/w/tests/test_new.py"}), step) == ["modify"] + + +@pytest.mark.parametrize("command, expected", [ + ("echo x > tests/test_ol?.py", ""), ("echo x > tests/test_o*.py", ""), ("echo x > tests/test_ol[d].py", ""), + ("echo x | tee tests/test_ol?.py", ""), ("echo x > ~/tests/test_old.py", ""), + ("echo x > 'tests/test_ol?.py'", "add"), ('echo x > "tests/test_o*.py"', "add"), + ("ls *.py ~ > tests/test_old.py", "modify"), +]) +def test_a_glob_or_tilde_target_is_an_expanded_path_with_no_label(command, expected): + trace = _trace_in_workspace(("Read", {"file_path": "/w/tests/test_old.py"}), ("Bash", {"command": command})) + assert [event.change for event in parse_run(trace).events if event.write] == [expected] + + +@pytest.mark.parametrize("target", ["tests/{a,b}.py", "tests/{1..3}.py", "tests/{d..a..-2}.py", + "tests/{prefix{a,b}}.py", """tests/{'a b',c}.py"""]) +def test_a_brace_expanded_replacement_makes_change_rules_inconclusive(target): + contract = parse_contract({"actions": {"new": {"change": "add", "file_path": "tests/"}, + "edit": {"change": "modify", "file_path": "tests/"}}, + "rules": [{"forbids": "new"}, {"forbids": "edit"}]}) + run = parse_run(_trace_in_workspace(("Read", {"file_path": "/w/tests/a.py"}), + ("Read", {"file_path": "/w/tests/b.py"}), + ("Bash", {"command": f"echo x | tee {target}"})), "r") + [write] = [event for event in run.events if event.write] + assert write.dynamic_path and write.change == "" + result = profile([run], contract)["contract"] + assert result["per_run"] == {"r": []} + assert result["inconclusive_rules"] == {"r": ["forbids: new", "forbids: edit"]} + + +@pytest.mark.parametrize("target, literal", [ + ("'tests/{a,b}.py'", "tests/{a,b}.py"), ('"tests/{1..3}.py"', "tests/{1..3}.py"), + (r"tests/\{a,b\}.py", "tests/{a,b}.py"), (r"tests/{a\,b}.py", "tests/{a,b}.py"), + ('tests/{a","b}.py', "tests/{a,b}.py"), ("tests/{foo..bar}.py", "tests/{foo..bar}.py"), + ("tests/{'1'..3}.py", "tests/{1..3}.py"), + ("tests/{a,b.py", "tests/{a,b.py"), +]) +def test_a_literal_braced_path_keeps_its_change_label(target, literal): + trace = _trace_in_workspace(("Read", {"file_path": f"/w/{literal}"}), + ("Bash", {"command": f"echo x | tee {target}"})) + [write] = [event for event in parse_run(trace).events if event.write] + assert write.input["file_path"] == literal + assert not write.dynamic_path and write.change == "modify" + + +def test_braces_in_another_word_do_not_hide_a_literal_target(): + from dokimi.context import shell + + assert shell.write_targets("printf '%s' {a,b} > tests/literal.py") == [("tests/literal.py", False)] + assert shell.write_targets("tee tests/{a, b}.py") == [("tests/{a,", False), ("b}.py", False)] + assert shell.write_targets("tee tests/{a,b}.py 'tests/{a,b}.py' tests/c.py") == [ + ("tests/{a,b}.py", True), ("tests/{a,b}.py", False), ("tests/c.py", False)] + + +def test_a_brace_expanded_in_place_edit_keeps_its_known_modify_intent(): + run = parse_run(_trace_in_workspace(("Bash", {"command": "sed -i 's/a/b/' tests/{a,b}.py"})), "r") + [write] = [event for event in run.events if event.write] + assert write.input["file_path"] == "tests/{a,b}.py" + assert write.dynamic_path and write.change == "modify" + + +@pytest.mark.parametrize("option, label", [("", "add"), ("-a", "modify")]) +def test_tee_reports_each_file_to_change_contracts(option, label): + run = parse_run(_trace_in_workspace(("Read", {"file_path": "/w/tests/old.py"}), + ("Bash", {"command": f"printf x | tee {option} tests/old.py 2>/dev/null tests/new.py"}))) + assert [(e.input["file_path"], e.change) for e in run.events if e.write] == [ + ("tests/old.py", "modify"), ("tests/new.py", label)] + contract = parse_contract({"actions": {"new": {"change": "add", "file_path": "tests/"}}, + "rules": [{"forbids": "new"}]}) + assert check_contract(run, contract) == (["forbids: new"] if label == "add" else []) + + +@pytest.mark.parametrize("suffix", ["<<< word", ">(cat)", "|& cat"]) +def test_tee_does_not_treat_shell_syntax_as_extra_output_paths(suffix): + from dokimi.context import shell + + assert shell.written_files(f"tee tests/existing.py {suffix}") == ["tests/existing.py"] + + +@pytest.mark.parametrize("steps, violations, uncertain", [ + (["cd tests", "echo x > test_new.py"], [], 1), + (["cd /w/tests && echo x > test_new.py"], ["forbids: new_test"], 0), +]) +def test_a_contract_uses_known_write_directories_and_counts_unknown_ones(steps, violations, uncertain): + contract = parse_contract({"actions": {"new_test": {"change": "add", "file_path": "tests/"}}, + "rules": [{"forbids": "new_test"}]}) + run = parse_run(_trace_in_workspace(*(("Bash", {"command": step}) for step in steps)), "r") + result = profile([run], contract)["contract"] + assert result["per_run"] == {"r": violations} + assert result["inconclusive_runs"] == uncertain + + +@pytest.mark.parametrize("separator, directory, change", [("||", None, ""), (";", None, ""), ("&&", "/w/sub", "add")]) +def test_function_definition_only_carries_cd_into_an_and_branch(separator, directory, change): + steps = (("Read", {"file_path": "/w/tests/a.py"}), + ("Bash", {"command": f"cd sub && f() {{ :; }} {separator} echo x > tests/a.py"})) + run = parse_run(_trace_in_workspace(*steps)) + assert [(event.directory, event.change) for event in run.events if event.write] == [(directory, change)] + + +@pytest.mark.parametrize("rule", ["forbids", "requires"]) +def test_an_in_place_edit_in_an_unknown_directory_makes_a_modify_rule_inconclusive(rule): + contract = parse_contract({"actions": {"edit": {"change": "modify", "file_path": "tests/"}}, + "rules": [{rule: "edit"}]}) + run = parse_run(_trace_in_workspace(("Bash", {"command": "cd tests"}), + ("Bash", {"command": "sed -i s/a/b/ test_x.py"})), "r") + [write] = [event for event in run.events if event.write] + assert write.change == "modify" and write.directory is None + result = profile([run], contract)["contract"] + assert result["per_run"] == {"r": []} + assert result["inconclusive_rules"] == {"r": [f"{rule}: edit"]}