diff --git a/dokimi/changelog.d/20261204_100000_manifest-glob-braces.md b/dokimi/changelog.d/20261204_100000_manifest-glob-braces.md new file mode 100644 index 000000000..ca4fbdfee --- /dev/null +++ b/dokimi/changelog.d/20261204_100000_manifest-glob-braces.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A `{a,b}` brace in a manifest glob lists alternatives** — `guidance.globs`, `guidance.also_scan` and `useful.edit` read the `{`, `,` and `}` of `**/{AGENTS,CLAUDE}.md` or `src/{a,b}.h` as literal characters, so the glob matched no file and `repo scan` warned that it matched nothing. `dokimi.pattern_glob.match_posix_glob` now matches when any alternative does (nested braces and an empty alternative such as `a{,b}` too). A brace with no comma or no closing `}` stays literal, and a glob that would spell more than 16 alternatives reads each such brace as `*`, as the repository scan reads a code span; braces nested more than 32 deep are not expanded and match only their own literal text. The expansion moved from `dokimi.repos.l0.braces` to `dokimi.brace_alternatives`, which both use. diff --git a/dokimi/docs/architecture.md b/dokimi/docs/architecture.md index 066741f05..2220f0131 100644 --- a/dokimi/docs/architecture.md +++ b/dokimi/docs/architecture.md @@ -490,6 +490,9 @@ deterministic checks on it; `dokimi memory lint`. Guide: [memory.md](memory.md). consistency --arm`, the session paths of `trace prefilter`, `skill novelty ground --header` and `--shared-lib`). It matches as `glob.glob(pattern, recursive=True)` does, sorted, but a directory the pattern has to list and cannot raises its `OSError` where `glob` skips it; the commands turn that into an `InputError`. + `match_posix_glob(pattern, path)` is the match of a manifest glob, a `{a,b}` brace listing alternatives. +- `dokimi/brace_alternatives.py` — `expand(path)`, the alternatives a comma brace spells (at most 16), shared by + that match and by the repository scan's path claims (`dokimi/repos/l0/braces.py`). - `dokimi/llm.py` — the entry point for LLM calls. `LLM` (one model at one provider: `complete`/`ask`/`chat`, retry, the response cache, usage) sits on one adapter seam: `LiteLLMAdapter` in production, `FakeAdapter` in tests (the diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index b376635a7..367da0d47 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -257,6 +257,7 @@ label_host: false # optional: true runs a task the host Rules: - Every path is relative to the repository root. +- A glob of `guidance.globs`, `guidance.also_scan` and `useful.edit` is matched by `match_glob`: `*` and `?` stay inside one path segment, `**/` matches zero or more directories, and a `{a,b}` brace lists alternatives (`**/{AGENTS,CLAUDE}.md`, `src/a.{h,cpp}`; a nested brace and an empty alternative `a{,b}` too). A brace with no comma (`{b}`) or no closing `}` is literal. A glob that would spell more than 16 alternatives reads each such brace as `*`. - `eval_dir`, `tasks` and `entry_points` come together or not at all. Without them the manifest is *guidance-only*: `scan` and `reach` run on it and `validate` checks its globs, while `eval check` and `run` refuse it. `image` and `explore_tasks` need diff --git a/dokimi/dokimi/brace_alternatives.py b/dokimi/dokimi/brace_alternatives.py new file mode 100644 index 000000000..802373e69 --- /dev/null +++ b/dokimi/dokimi/brace_alternatives.py @@ -0,0 +1,110 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The alternatives a ``{a,b}`` brace spells in a path: ``src/a.{h,cpp}`` is ``src/a.h`` and ``src/a.cpp``.""" + +from __future__ import annotations + +import itertools + +MAX_ALTERNATIVES = 16 # in total; a path with more is not expanded +MAX_DEPTH = 32 # braces inside braces; a path nested deeper is not expanded + + +class _TooMany(Exception): + """More alternatives, or a deeper nesting, than a path is read with.""" + + +class _TooDeep(_TooMany): + """Braces nested deeper than :data:`MAX_DEPTH`.""" + + +def pairs(text: str) -> dict[int, int]: + """The index of each ``{`` that a ``}`` closes, to that ``}``; a brace with no partner is a plain character.""" + open_at: list[int] = [] + closed: dict[int, int] = {} + for i, c in enumerate(text): + if c == "{": + open_at.append(i) + elif c == "}" and open_at: + closed[open_at.pop()] = i + return closed + + +def expand(path: str) -> list[str] | None: + """The alternatives ``path`` spells with its comma braces (left to right, nested ones in place), or ``None``. + + ``None`` when ``path`` has no comma brace, or would have more than :data:`MAX_ALTERNATIVES` alternatives. + """ + closed = pairs(path) + try: + alts, has_comma = _sequence(path, closed, 0, len(path), 0) + except _TooMany: + return None + return list(dict.fromkeys(alts)) if has_comma else None + + +def over_cap(path: str) -> bool: + """Whether ``path`` has a comma brace that would spell more than :data:`MAX_ALTERNATIVES` alternatives.""" + try: + _sequence(path, pairs(path), 0, len(path), 0) + except _TooMany: + return True + return False + + +def too_deep(path: str) -> bool: + """Whether ``path`` nests matched braces deeper than :data:`MAX_DEPTH`, however many alternatives it spells.""" + depth = 0 + ends: list[int] = [] # the closing index of each brace open at this point + closed = pairs(path) + for i in range(len(path)): + while ends and ends[-1] < i: + ends.pop() + if i in closed: + ends.append(closed[i]) + depth = max(depth, len(ends)) + return depth > MAX_DEPTH + + +def _sequence(text: str, closed: dict[int, int], lo: int, hi: int, depth: int) -> tuple[list[str], bool]: + """The alternatives of ``text[lo:hi]``, and whether a brace in it has a comma; the count is checked before a string is built.""" + if depth > MAX_DEPTH: + raise _TooDeep + parts: list[list[str]] = [] # a literal run, or the options of a brace, in order; joined once at the end + count, has_comma, i, run = 1, False, lo, lo + while i < hi: + if i not in closed: + i += 1 + continue + end = closed[i] + options, comma = _group(text, closed, i + 1, end, depth) + count *= len(options) + if count > MAX_ALTERNATIVES: + raise _TooMany + parts += [[text[run:i]], options] + has_comma, i = has_comma or comma, end + 1 + run = i + parts.append([text[run:hi]]) + return ["".join(p) for p in itertools.product(*parts)], has_comma + + +def _group(text: str, closed: dict[int, int], lo: int, hi: int, depth: int) -> tuple[list[str], bool]: + """The options of the brace around ``text[lo:hi]``: one per top-level comma, or the braced text as it is with none.""" + cuts, i = [lo - 1], lo + while i < hi: + if text[i] == ",": + cuts.append(i) + if len(cuts) > MAX_ALTERNATIVES: + raise _TooMany + i = closed[i] + 1 if i in closed else i + 1 + if len(cuts) == 1: + inner, comma = _sequence(text, closed, lo, hi, depth + 1) + return [f"{{{x}}}" for x in inner], comma + cuts.append(hi) + options: list[str] = [] + for a, b in zip(cuts, cuts[1:], strict=False): + options += _sequence(text, closed, a + 1, b, depth + 1)[0] + if len(options) > MAX_ALTERNATIVES: + raise _TooMany + return options, True diff --git a/dokimi/dokimi/pattern_glob.py b/dokimi/dokimi/pattern_glob.py index 216e3d268..6bc884232 100644 --- a/dokimi/dokimi/pattern_glob.py +++ b/dokimi/dokimi/pattern_glob.py @@ -8,12 +8,16 @@ import errno import fnmatch +import functools import os import re import stat from collections.abc import Callable, Iterator +from dokimi.brace_alternatives import expand as expand_braces, pairs as brace_pairs, too_deep + _MAGIC = re.compile(r"[*?\[]") +_STAR = "\0" # a path holds no NUL: a brace past the cap becomes this, a single-segment wildcard #: Errors of a path that is not there (or not a directory, or a link that loops): ``glob`` lists nothing for it too. _ABSENT = frozenset({errno.ENOENT, errno.ENOTDIR, errno.ELOOP, errno.ENAMETOOLONG}) @@ -140,12 +144,39 @@ def match_posix_glob(pattern: str, path: str) -> bool: """Match a root-relative POSIX path against a ``**``-aware glob. ``*`` and ``?`` stay inside one path segment; ``**/`` matches zero or more - directories, so ``**/AGENTS.md`` also matches a root ``AGENTS.md``. + directories, so ``**/AGENTS.md`` also matches a root ``AGENTS.md``. A closed brace with a comma lists + alternatives (``src/{a,b}.h``, nested ones too, an empty one included); a brace with no comma, or no closing + ``}``, is literal. Past :data:`~dokimi.brace_alternatives.MAX_ALTERNATIVES` alternatives each outermost + comma brace is read as ``*``, as the repository scan reads a code span. Braces nested deeper than + :data:`~dokimi.brace_alternatives.MAX_DEPTH` are not expanded: the pattern is read with its braces literal. """ return _glob_regex(pattern).fullmatch(path) is not None +@functools.lru_cache(maxsize=1024) # mutation-ok[bump-int]: the size bounds the cache, it changes no match def _glob_regex(pattern: str) -> re.Pattern[str]: + alts = expand_braces(pattern) + if not alts: # no comma brace (nothing to star), nested past the depth cap (literal), or too many alternatives (starred) + alts = [pattern if too_deep(pattern) else _starred(pattern)] + return re.compile("|".join(f"(?:{_segment_regex(alt)})" for alt in alts)) + + +def _starred(pattern: str) -> str: + """``pattern`` with each outermost closed brace that holds a comma read as :data:`_STAR`, one segment's worth of + any characters, never joined with a neighbouring ``*`` or brace into ``**``.""" + closed = brace_pairs(pattern) + out, i = [], 0 + while i < len(pattern): + if i in closed and "," in pattern[i:closed[i]]: + out.append(_STAR) + i = closed[i] + 1 + else: + out.append(pattern[i]) + i += 1 + return "".join(out) + + +def _segment_regex(pattern: str) -> str: out, i = [], 0 while i < len(pattern): if pattern.startswith("**/", i): @@ -154,7 +185,7 @@ def _glob_regex(pattern: str) -> re.Pattern[str]: elif pattern.startswith("**", i): out.append(".*") i += 2 - elif pattern[i] == "*": + elif pattern[i] in ("*", _STAR): out.append("[^/]*") i += 1 elif pattern[i] == "?": @@ -163,4 +194,4 @@ def _glob_regex(pattern: str) -> re.Pattern[str]: else: out.append(re.escape(pattern[i])) i += 1 - return re.compile("".join(out)) + return "".join(out) diff --git a/dokimi/dokimi/repos/l0/braces.py b/dokimi/dokimi/repos/l0/braces.py index 2db1dacd5..0484628a8 100644 --- a/dokimi/dokimi/repos/l0/braces.py +++ b/dokimi/dokimi/repos/l0/braces.py @@ -6,11 +6,12 @@ from __future__ import annotations import ast -import itertools import re from collections.abc import Iterator, Sequence from typing import Callable +from dokimi.brace_alternatives import MAX_DEPTH, expand as expand, over_cap as over_cap, pairs as _pairs + _EXT = (r"h|hh|hpp|hxx|c|cc|cpp|cxx|cu|i|py|pyx|pxd|pyi|bzl|bazel|md|rst|txt|yml|yaml|json|toml|cfg|ini|" r"mk|cmake|in|sh|bat|ps1|ver|js|ts|go|rs|java") # A comma is a path character only inside a closed brace (`gone.{h,cpp}`; `a,b/c` is prose); the atomic group @@ -19,24 +20,7 @@ rf"^(?:\.{{0,2}}/)?(?:[\w.@\-*<>}}]|(?>\{{(?:[\w.@\-*,]*+\}})?))+(?:/[\w.@\-*<>{{}},]*)+$" rf"|^(?:[\w\-*.]|\{{[\w\-*.]*,[\w\-*.,]*\}})+\.(?:(?:{_EXT})|\{{(?:{_EXT})(?:,(?:{_EXT}))*\}})$" rf"|^\{{[\w\-*.]+\.(?:{_EXT})(?:,[\w\-*.]+\.(?:{_EXT}))+\}}$") # a brace of complete filenames: `{{a.h,b.h}}` -MAX_ALTERNATIVES = 16 # in total; a span with more is judged with each brace read as ``*`` -_MAX_DEPTH = 32 # braces inside braces; a span nested deeper is no brace expansion - - -class _TooMany(Exception): - """More alternatives, or a deeper nesting, than a path claim is read with.""" - - -def _pairs(text: str) -> dict[int, int]: - """The index of each ``{`` that a ``}`` closes, to that ``}``; a brace with no partner is a plain character.""" - open_at: list[int] = [] - pairs: dict[int, int] = {} - for i, c in enumerate(text): - if c == "{": - open_at.append(i) - elif c == "}" and open_at: - pairs[open_at.pop()] = i - return pairs +_MAX_DEPTH = MAX_DEPTH # a span nested deeper is no brace expansion; a span with more than MAX_ALTERNATIVES is judged with each brace read as ``*`` def pathlike(span: str) -> bool: @@ -92,71 +76,6 @@ def starred(path: str) -> str: return "".join(out) -def expand(path: str) -> list[str] | None: - """The alternatives ``path`` spells with its comma braces (left to right, nested ones in place), or ``None``. - - ``None`` when ``path`` has no comma brace, or would have more than :data:`MAX_ALTERNATIVES` alternatives. - """ - pairs = _pairs(path) - try: - alts, has_comma = _sequence(path, pairs, 0, len(path), 0) - except _TooMany: - return None - return list(dict.fromkeys(alts)) if has_comma else None - - -def over_cap(path: str) -> bool: - """Whether ``path`` has a comma brace that would spell more than :data:`MAX_ALTERNATIVES` alternatives.""" - try: - _sequence(path, _pairs(path), 0, len(path), 0) - except _TooMany: - return True - return False - - -def _sequence(text: str, pairs: dict[int, int], lo: int, hi: int, depth: int) -> tuple[list[str], bool]: - """The alternatives of ``text[lo:hi]``, and whether a brace in it has a comma; the count is checked before a string is built.""" - if depth > _MAX_DEPTH: - raise _TooMany - parts: list[list[str]] = [] # a literal run, or the options of a brace, in order; joined once at the end - count, has_comma, i, run = 1, False, lo, lo - while i < hi: - if i not in pairs: - i += 1 - continue - end = pairs[i] - options, comma = _group(text, pairs, i + 1, end, depth) - count *= len(options) - if count > MAX_ALTERNATIVES: - raise _TooMany - parts += [[text[run:i]], options] - has_comma, i = has_comma or comma, end + 1 - run = i - parts.append([text[run:hi]]) - return ["".join(p) for p in itertools.product(*parts)], has_comma - - -def _group(text: str, pairs: dict[int, int], lo: int, hi: int, depth: int) -> tuple[list[str], bool]: - """The options of the brace around ``text[lo:hi]``: one per top-level comma, or the braced text as it is with none.""" - cuts, i = [lo - 1], lo - while i < hi: - if text[i] == ",": - cuts.append(i) - if len(cuts) > MAX_ALTERNATIVES: - raise _TooMany - i = pairs[i] + 1 if i in pairs else i + 1 - if len(cuts) == 1: - inner, comma = _sequence(text, pairs, lo, hi, depth + 1) - return [f"{{{x}}}" for x in inner], comma - cuts.append(hi) - options: list[str] = [] - for a, b in zip(cuts, cuts[1:], strict=False): - options += _sequence(text, pairs, a + 1, b, depth + 1)[0] - if len(options) > MAX_ALTERNATIVES: - raise _TooMany - return options, True - - def judge(alts: list[str], resolve: Callable[[str], tuple[str, str] | None]) -> tuple[str, str] | None: """:func:`combine` of ``resolve`` on each alternative, or ``None`` when one is no path claim (then none is claimed ``ok``).""" got = [(a, resolve(a)) for a in alts] diff --git a/dokimi/tests/test_import_architecture.py b/dokimi/tests/test_import_architecture.py index 4b9438e11..6862945b8 100644 --- a/dokimi/tests/test_import_architecture.py +++ b/dokimi/tests/test_import_architecture.py @@ -82,7 +82,7 @@ "dokimi.llm_pricing", "dokimi.measure", "dokimi.process", "dokimi.process_hooks", "dokimi.process_io", "dokimi.atomic_write", "dokimi.digest", "dokimi.files", "dokimi.frontmatter", "dokimi.model_names", "dokimi.provenance", "dokimi.records", "dokimi.registry", "dokimi.utils", "dokimi.write_probe", - "dokimi.yaml_unique", "dokimi.pattern_glob", + "dokimi.yaml_unique", "dokimi.pattern_glob", "dokimi.brace_alternatives", "dokimi.judge_rule", "dokimi.spend", "dokimi.text_spans", "dokimi.code_spans", "dokimi.dokimi_commit", # Token/cost record the LLM chokepoint fills; it lives under metrics/ but diff --git a/dokimi/tests/test_pattern_glob_braces.py b/dokimi/tests/test_pattern_glob_braces.py new file mode 100644 index 000000000..defb8afe8 --- /dev/null +++ b/dokimi/tests/test_pattern_glob_braces.py @@ -0,0 +1,84 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""A ``{a,b}`` brace of a manifest glob lists alternatives (``dokimi/docs/repo-evaluation-contract.md``, guidance globs).""" + +from __future__ import annotations + +import pytest + +from dokimi.brace_alternatives import MAX_ALTERNATIVES, MAX_DEPTH +from dokimi.repos.manifest import match_glob + + +@pytest.mark.parametrize(("pattern", "path", "expected"), [ + ("src/{a,b}.h", "src/a.h", True), + ("src/{a,b}.h", "src/b.h", True), + ("src/{a,b}.h", "src/c.h", False), + ("src/{a,b}.h", "src/{a,b}.h", False), + ("**/{AGENTS,CLAUDE}.md", "AGENTS.md", True), + ("**/{AGENTS,CLAUDE}.md", "x/CLAUDE.md", True), + ("**/{AGENTS,CLAUDE}.md", "x/README.md", False), + ("src/{a,b}/*.h", "src/a/x.h", True), + ("src/{a,b}/*.h", "src/a/y/x.h", False), + ("a{,b}", "a", True), + ("a{,b}", "ab", True), + ("a{,b}", "abb", False), + ("{a,{b,c}}.md", "c.md", True), + ("{a,{b,c}}.md", "d.md", False), +], ids=lambda v: str(v)) +def test_a_comma_brace_lists_alternatives(pattern, path, expected): + assert match_glob(pattern, path) is expected + + +@pytest.mark.parametrize(("pattern", "path", "expected"), [ + ("a{b}c", "a{b}c", True), + ("a{b}c", "abc", False), + ("{}", "{}", True), + ("{}", "", False), + ("a{b,c", "a{b,c", True), + ("a{b,c", "ab", False), + ("a,b}", "a,b}", True), +]) +def test_a_brace_with_no_comma_or_no_partner_is_literal(pattern, path, expected): + assert match_glob(pattern, path) is expected + + +def test_a_comma_brace_past_the_cap_reads_as_a_star_within_one_segment(): + pattern = "src/{" + ",".join(f"f{i}" for i in range(MAX_ALTERNATIVES + 1)) + "}.h" + assert match_glob(pattern, "src/anything.h") is True + assert match_glob(pattern, "src/a/b.h") is False + assert match_glob(pattern, "src/anything.c") is False + assert match_glob(pattern, "src/anything_h") is False # the text after the brace is kept + assert match_glob("x{a}/" + pattern, "x{a}/src/q.h") is True + assert match_glob("x{a}/" + pattern, "xa/src/q.h") is False # a brace with no comma stays literal past the cap too + + +def test_braces_nested_past_the_depth_cap_stay_literal_not_a_star(): + pattern = "{" * (MAX_DEPTH + 1) + "a,b" + "}" * (MAX_DEPTH + 1) + assert match_glob(pattern, "unrelated.md") is False + assert match_glob(pattern, "a") is False + assert match_glob(pattern, pattern) is True + ok = "{" * MAX_DEPTH + "a,b" + "}" * MAX_DEPTH # a brace with no comma stays literal around each alternative + assert match_glob(ok, "{" * (MAX_DEPTH - 1) + "a" + "}" * (MAX_DEPTH - 1)) is True + assert match_glob(ok, "unrelated.md") is False + + +def test_braces_nested_past_the_depth_cap_stay_literal_also_past_the_alternative_cap(): + many = ",".join(f"f{i}" for i in range(MAX_ALTERNATIVES + 1)) + deep = "{" * (MAX_DEPTH + 1) + many + "}" * (MAX_DEPTH + 1) + assert match_glob(deep, "unrelated.md") is False + assert match_glob(deep, deep) is True + first = "{" + many + "}" + deep # an overflowing brace before the deep one + assert match_glob(first, "unrelated.md") is False + assert match_glob(first, first) is True + + +def test_a_brace_past_the_cap_next_to_a_brace_or_a_star_stays_within_one_segment(): + big = "{" + ",".join(f"f{i}" for i in range(MAX_ALTERNATIVES + 1)) + "}" + assert match_glob(f"src/{big}{big}.h", "src/x.h") is True + assert match_glob(f"src/{big}{big}.h", "src/deep/x.h") is False + assert match_glob(f"src/*{big}.h", "src/deep/x.h") is False + assert match_glob(f"src/{big}*.h", "src/deep/x.h") is False + assert match_glob(f"src/*{big}.h", "src/xy.h") is True + assert match_glob("src/{a,b,c,d,e}{f,g,h,i}.h", "src/deep/x.h") is False