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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions dokimi/changelog.d/20261204_100000_manifest-glob-braces.md
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 `{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.
3 changes: 3 additions & 0 deletions dokimi/docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions dokimi/docs/repo-evaluation-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
110 changes: 110 additions & 0 deletions dokimi/dokimi/brace_alternatives.py
Original file line number Diff line number Diff line change
@@ -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

Check warning on line 10 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `16` -> `17`
MAX_DEPTH = 32 # braces inside braces; a path nested deeper is not expanded

Check warning on line 11 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `32` -> `33`


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

Check warning on line 58 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `0` -> `1`
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

Check warning on line 75 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: flip-bool `False` -> `True`

Check warning on line 75 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `1` -> `2`
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)

Check warning on line 82 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `count *= len(options)` -> `pass`
if count > MAX_ALTERNATIVES:
raise _TooMany

Check warning on line 84 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `raise _TooMany` -> `pass`
parts += [[text[run:i]], options]
has_comma, i = has_comma or comma, end + 1

Check warning on line 86 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `has_comma or comma` -> `(comma)`
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

Check warning on line 99 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: delete-statement `raise _TooMany` -> `pass`
i = closed[i] + 1 if i in closed else i + 1

Check warning on line 100 in dokimi/dokimi/brace_alternatives.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: swap-addsub `closed[i] + 1` -> `closed[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
37 changes: 34 additions & 3 deletions dokimi/dokimi/pattern_glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})

Expand Down Expand Up @@ -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):
Expand All @@ -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] == "?":
Expand All @@ -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)
87 changes: 3 additions & 84 deletions dokimi/dokimi/repos/l0/braces.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion dokimi/tests/test_import_architecture.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading