Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
### Fixed

- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. Those patterns now refuse as bad input (exit 2, `Error: ...`) instead of crashing: a `process_metrics` counter in the repo manifest and a `trace consistency --contract` pattern.
- **A regex a user writes that Python cannot compile is refused, not a traceback.** `re.compile` raises `OverflowError` for a repeat count that does not fit (`a{999999999999}`) and `RecursionError` for groups nested too deep, not the `re.error` the `process_metrics` and contract loaders caught. A `trace consistency --contract` pattern that triggers either error is refused with exit 2 and `Error: ...`. If a `process_metrics` counter in a repo manifest triggers either error, `eval check` and `repo run` report a manifest error with `✗` and exit 1.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!--
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: Apache-2.0
-->

### Fixed

- **A list of regexes in a `trace consistency --contract` action is checked one element at a time.** The list was joined with `|`, each element wrapped in `(?:...)`, and only the joined pattern was compiled, so `["a)|(?:b"]` was accepted (it joins to two groups) though `a)|(?:b` is not a regex. Each element is now compiled on its own, and a bad one is refused by name as `bad regex`. A list whose elements are each a regex compiles to the same pattern as before. The behaviour change: a list in which one element refers to a group of another (`["(a)", "\1"]`, `["(?P<x>a)", "(?P=x)"]`) is now refused, since that element is not a regex on its own; it was accepted before.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- **A list-valued contract pattern refuses a backreference** — a list such as `command: ['(x)', '(a)\1']` joins its elements into one alternation, and a group number shifts when they are joined, so `\1` then named the `(x)` group and the action missed a call it should have matched. `contract` now refuses a `\1`-`\99`, a `(?P=name)` or a `(?(1)...)` in a list element with `a backreference is refused in a list pattern`. A single-string pattern keeps its backreferences and matches as before.
6 changes: 5 additions & 1 deletion dokimi/docs/run-consistency.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,11 @@ file: a contract that wants an edit reports it missing, so name `Bash:find` /
`Bash:xargs` in the edit action if agents edit that way.

A regex value may be a list (`command: [pytest, tox]`), read as one alternation;
a number or a mapping is refused.
a number or a mapping is refused. Each element must be a regex on its own, so a
list element cannot refer to a group of another element. A list element also cannot
carry a backreference (`\1`-`\99`, `(?P=name)` or `(?(1)...)`): joined, the group numbers shift,
so `(a)\1` after `(x)` would refer to `(x)`, and the contract refuses it. A single
string keeps its backreferences.

### Added files and changed files

Expand Down
45 changes: 43 additions & 2 deletions dokimi/dokimi/context/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,52 @@ def _names(value: Any, where: str) -> tuple[str, ...]:
raise ValueError(f"{where} wants a name or a list of names, got {value!r}")


def _has_backreference(source: str) -> bool:
"""A group reference by number or name: `\\1`-`\\99`, `(?P=name)` or a conditional `(?(1)...)`. An escaped
backslash (`\\\\1`) is not one, and neither is anything in a character class, where `\\1` is an octal escape."""
i, in_class = 0, False
while i < len(source):
c = source[i]
if c == "\\":
if not in_class and i + 1 < len(source) and source[i + 1] in "123456789":
return True
i += 2
elif in_class:
in_class = c != "]"
i += 1
elif c == "[":
in_class = True
i += 1
if source.startswith("^", i):
i += 1
if source.startswith("]", i): # a `]` first in the class is a literal
i += 1
elif source.startswith("(?P=", i) or (source.startswith("(?(", i) and source[i + 3:i + 4].isdigit()):
return True
else:
i += 1
return False


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']`."""
so that `[pytest, tox]` is not read as the character class `['pytest', 'tox']`. Each element must be a regex
on its own: joined, `a)|(?:b` would compile as two groups and pass. So a list element cannot refer to a group
of another element (`["(a)", "\\1"]`), though the joined pattern compiled before. Nor can it carry a
backreference of its own: joined after another element, group numbers shift, so `(a)\\1` after `(x)` refers
to `(x)` (a `(?P=name)` is refused for the same reason). A single string keeps its backreferences."""
if isinstance(value, list) and value:
return "|".join(f"(?:{p})" for p in _names(value, where))
parts = []
for p in _names(value, where):
try:
compile_user_regex(p)
except ValueError as exc:
raise ValueError(f"{where}: element {p!r}: bad regex ({exc})") from exc
if _has_backreference(p):
raise ValueError(f"{where}: element {p!r}: a backreference is refused in a list pattern, "
"since the group numbers shift when the elements are joined")
parts.append(f"(?:{p})")
return "|".join(parts)
if isinstance(value, str):
return value
raise ValueError(f"{where} wants a regex or a list of regexes, got {value!r}")
Expand Down
36 changes: 36 additions & 0 deletions dokimi/tests/test_context_consistency.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,42 @@ def test_a_pattern_that_is_not_a_regex_is_refused(value):
parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []})


@pytest.mark.parametrize("value", [
["a)|(?:b"], [r"\bpytest\b", "a)|(?:b"], ["(", "x"],
["(a)", "\\1"], ["(?P<x>a)", "(?P=x)"], # each joins to a pattern that compiled before; alone, neither element does
])
def test_each_element_of_a_list_pattern_must_be_a_valid_regex_on_its_own(value):
"""Joined with `|` and each wrapped in `(?:...)`, `a)|(?:b` compiles; it is not a regex on its own. The
backreference cases are refused on the same rule: `\\1` alone is not a regex."""
with pytest.raises(ValueError, match="bad regex"):
parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []})


@pytest.mark.parametrize("value", [
[r"(x)", r"(a)\1"], [r"(a)\1", "b"], [r"(?P<n>a)(?P=n)", "b"], [r"(a)(b)\2"], [r"(a)\1"],
[r"(x)", r"(a)(?(1)b|c)"],
])
def test_a_backreference_in_a_list_pattern_is_refused(value):
"""Joined, the elements get new group numbers: `(a)\\1` after `(x)` refers to `(x)`, so the alternation
does not match `aa`, though `(a)\\1` alone does. A single string keeps its backreferences."""
with pytest.raises(ValueError, match="backreference"):
parse_contract({"actions": {"test": {"tool": "Bash", "command": value}}, "rules": []})


@pytest.mark.parametrize("element, text", [(r"a\\1", "a\\1"), (r"[\1]x", "\x01x"), (r"[]\1]", "]")])
def test_a_digit_that_is_not_a_backreference_is_allowed_in_a_list(element, text):
"""`\\\\1` is a backslash and a 1; `[\\1]` is an octal escape in a character class, not a group."""
c = parse_contract({"actions": {"test": {"tool": "Bash", "command": [element, "b"]}},
"rules": [{"requires": "test"}]})
assert check_contract(_run("r", ("Bash", {"command": text})), c) == []


def test_a_backreference_in_a_single_string_pattern_still_matches():
c = parse_contract({"actions": {"test": {"tool": "Bash", "command": r"(a)\1"}}, "rules": [{"requires": "test"}]})
assert check_contract(_run("r", ("Bash", {"command": "aa"})), c) == []
assert check_contract(_run("r", ("Bash", {"command": "ab"})), c) == ["requires: test"]


@pytest.mark.parametrize("value", ["a{999999999999}", "(" * 2000 + ")" * 2000])
def test_a_regex_that_overflows_or_nests_too_deep_is_refused(value):
"""re.compile raises OverflowError or RecursionError for these; the contract refuses them as bad input."""
Expand Down
Loading