canon-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
canon/scope.py ADDED
@@ -0,0 +1,589 @@
1
+ """Path scopes as regular languages, with *witnesses*.
2
+
3
+ A scope says which paths a rule governs. The whole design rests on one
4
+ choice: a scope is not a string to be matched, it is a **set**. Once scopes
5
+ are sets, the interesting questions are set questions, and all of them are
6
+ decidable by construction:
7
+
8
+ does rule A ever apply where B applies? A ∩ B ≠ ∅ -> witness path
9
+ is rule A redundant given rule B? A ⊆ B -> enumerated
10
+ do two rules contradict each other? A ∩ B ≠ ∅ and same key, different value
11
+ is this rule dead? A ∩ files(repo) ≠ ∅
12
+
13
+ We answer the first, third and fourth *exactly*, by building the product of two
14
+ epsilon-NFAs and searching it. A product search that reaches an accepting pair
15
+ does not merely say "yes": the path it walked is a concrete string both
16
+ patterns match. That witness is the difference between a linter that says
17
+ "possible conflict" and one that says "at `backend/ledger/money.py`, R3 says
18
+ integer minor units and R7 says float."
19
+
20
+ Grammar
21
+ -------
22
+ pattern := segment ('/' segment)*
23
+ segment := '**' | glob
24
+ glob := (literal | '?' | '*' | '[' class ']')*
25
+
26
+ `**` matches **zero or more** whole segments, so `a/**` also matches `a`.
27
+ Every other segment is a character-level glob. `*` does not cross `/`.
28
+
29
+ Everything here is exact for that grammar. There is no heuristic and no
30
+ "close enough" path.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ from collections import deque
36
+ from dataclasses import dataclass, field
37
+ from typing import Iterable, Iterator
38
+
39
+ __all__ = ["Pattern", "Scope", "compile_pattern", "compile_patterns",
40
+ "expand_braces", "path_matches", "product_witness"]
41
+
42
+ # Sentinel for "any character". frozenset = a concrete set of characters.
43
+ _ALL: None = None
44
+ _PRINTABLE = frozenset(chr(c) for c in range(32, 127))
45
+
46
+
47
+ # --------------------------------------------------------------------------
48
+ # character-level automata
49
+ # --------------------------------------------------------------------------
50
+
51
+
52
+ def _parse_class(body: str) -> frozenset[str]:
53
+ """`abc`, `a-z`, `!abc`, `^a-f` -> set of characters."""
54
+ negate = body[:1] in ("!", "^")
55
+ if negate:
56
+ body = body[1:]
57
+ chars: set[str] = set()
58
+ i = 0
59
+ while i < len(body):
60
+ if i + 2 < len(body) and body[i + 1] == "-":
61
+ lo, hi = ord(body[i]), ord(body[i + 2])
62
+ if lo <= hi:
63
+ chars.update(chr(c) for c in range(lo, hi + 1))
64
+ i += 3
65
+ else:
66
+ chars.add(body[i])
67
+ i += 1
68
+ if negate:
69
+ return frozenset(_PRINTABLE - chars)
70
+ return frozenset(chars)
71
+
72
+
73
+ def _tokenize(segment: str) -> list[tuple]:
74
+ out: list[tuple] = []
75
+ i = 0
76
+ while i < len(segment):
77
+ c = segment[i]
78
+ if c == "*":
79
+ if not out or out[-1][0] != "star":
80
+ out.append(("star",))
81
+ i += 1
82
+ elif c == "?":
83
+ out.append(("any",))
84
+ i += 1
85
+ elif c == "[":
86
+ j = segment.find("]", i + 1)
87
+ if j == -1:
88
+ out.append(("lit", "["))
89
+ i += 1
90
+ else:
91
+ out.append(("cls", _parse_class(segment[i + 1 : j])))
92
+ i = j + 1
93
+ else:
94
+ out.append(("lit", c))
95
+ i += 1
96
+ return out
97
+
98
+
99
+ class _SegNFA:
100
+ """Epsilon-NFA for a single path segment."""
101
+
102
+ __slots__ = ("n", "eps", "trans")
103
+
104
+ def __init__(self, segment: str) -> None:
105
+ toks = _tokenize(segment)
106
+ n = len(toks)
107
+ self.n = n
108
+ self.eps: list[list[int]] = [[] for _ in range(n + 1)]
109
+ self.trans: list[list[tuple[None | frozenset[str], int]]] = [
110
+ [] for _ in range(n + 1)
111
+ ]
112
+ for i, tok in enumerate(toks):
113
+ kind = tok[0]
114
+ if kind == "star":
115
+ self.trans[i].append((_ALL, i))
116
+ self.eps[i].append(i + 1)
117
+ elif kind == "any":
118
+ self.trans[i].append((_ALL, i + 1))
119
+ elif kind == "cls":
120
+ self.trans[i].append((tok[1], i + 1))
121
+ else:
122
+ self.trans[i].append((frozenset(tok[1]), i + 1))
123
+
124
+ def sample_char(self, state: int) -> str | None:
125
+ """Any character the automaton can consume at `state`, or None."""
126
+ best: str | None = None
127
+ for cs, _ in self.trans[state]:
128
+ if cs is None:
129
+ return "x"
130
+ if cs:
131
+ c = min(cs)
132
+ if best is None or c < best:
133
+ best = c
134
+ return best
135
+
136
+ def any_match(self) -> str:
137
+ """A shortest string accepted (reuses the product machinery)."""
138
+ w = _seg_witness(self, _ANY_SEG)
139
+ return w if w is not None else ""
140
+
141
+
142
+ _ANY_SEG = _SegNFA("?*") # non-empty: path segments are never empty
143
+
144
+
145
+ def _common(a: None | frozenset[str], b: None | frozenset[str]) -> str | None:
146
+ if a is None and b is None:
147
+ return "x"
148
+ if a is None:
149
+ return min(b) if b else None # type: ignore[arg-type]
150
+ if b is None:
151
+ return min(a) if a else None
152
+ both = a & b
153
+ return min(both) if both else None
154
+
155
+
156
+ def _seg_witness(a: _SegNFA, b: _SegNFA) -> str | None:
157
+ """Shortest string matched by both segment automata, or None.
158
+
159
+ Product BFS over (state_a, state_b). Epsilon moves belong to one side;
160
+ character moves are synchronised and must agree on a character.
161
+ """
162
+ start = (0, 0)
163
+ goal = (a.n, b.n)
164
+ if start == goal:
165
+ return ""
166
+ parent: dict[tuple[int, int], tuple[tuple[int, int], str]] = {}
167
+ seen = {start}
168
+ q: deque[tuple[int, int]] = deque([start])
169
+ while q:
170
+ si, sj = q.popleft()
171
+ if (si, sj) == goal:
172
+ # reconstruct
173
+ chars: list[str] = []
174
+ cur = (si, sj)
175
+ while cur in parent:
176
+ prev, ch = parent[cur]
177
+ if ch:
178
+ chars.append(ch)
179
+ cur = prev
180
+ return "".join(reversed(chars))
181
+ # epsilon (one side at a time)
182
+ for t in a.eps[si]:
183
+ nxt = (t, sj)
184
+ if nxt not in seen:
185
+ seen.add(nxt)
186
+ parent[nxt] = ((si, sj), "")
187
+ q.append(nxt)
188
+ for t in b.eps[sj]:
189
+ nxt = (si, t)
190
+ if nxt not in seen:
191
+ seen.add(nxt)
192
+ parent[nxt] = ((si, sj), "")
193
+ q.append(nxt)
194
+ # synchronised character consumption
195
+ for cs_a, ta in a.trans[si]:
196
+ for cs_b, tb in b.trans[sj]:
197
+ ch = _common(cs_a, cs_b)
198
+ if ch is None:
199
+ continue
200
+ nxt = (ta, tb)
201
+ if nxt not in seen:
202
+ seen.add(nxt)
203
+ parent[nxt] = ((si, sj), ch)
204
+ q.append(nxt)
205
+ return None
206
+
207
+
208
+ def _seg_fill(segment: str) -> str:
209
+ """A natural, non-degenerate string matched by a segment pattern.
210
+
211
+ `*.py` -> `x.py`, `foo*` -> `foox`, `*` -> `x`. A witness that reads like a
212
+ real path is worth more than one that is merely correct.
213
+ """
214
+ out: list[str] = []
215
+ i = 0
216
+ while i < len(segment):
217
+ c = segment[i]
218
+ if c in "*?":
219
+ out.append("x")
220
+ i += 1
221
+ elif c == "[":
222
+ j = segment.find("]", i + 1)
223
+ if j == -1:
224
+ out.append(c)
225
+ i += 1
226
+ else:
227
+ cs = _parse_class(segment[i + 1 : j])
228
+ out.append(min(cs, key=lambda ch: (not ch.isalnum(), ch)) if cs else "x")
229
+ i = j + 1
230
+ else:
231
+ out.append(c)
232
+ i += 1
233
+ return "".join(out) or "x"
234
+
235
+
236
+ def _seg_joint(a: _SegNFA, b: _SegNFA) -> str | None:
237
+ """Like `_seg_witness`, but repairs degenerate results (`*.py` -> `x.py`)."""
238
+ w = _seg_witness(a, b)
239
+ if w is None:
240
+ return None
241
+ if w and not w.startswith("."):
242
+ return w
243
+ for cand in ("x" + w, w + "x", "x" + w + "x", "x"):
244
+ if _seg_accepts(a, cand) and _seg_accepts(b, cand):
245
+ return cand
246
+ return w
247
+
248
+
249
+ # --------------------------------------------------------------------------
250
+ # whole-path automata
251
+ # --------------------------------------------------------------------------
252
+
253
+
254
+ @dataclass(frozen=True)
255
+ class Pattern:
256
+ """A compiled path pattern."""
257
+
258
+ raw: str
259
+ segments: tuple[str, ...]
260
+ _segs: tuple[_SegNFA | None, ...] = field(default=(), compare=False, repr=False)
261
+
262
+ def __post_init__(self) -> None:
263
+ compiled = tuple(None if s == "**" else _SegNFA(s) for s in self.segments)
264
+ object.__setattr__(self, "_segs", compiled)
265
+
266
+ @property
267
+ def depth(self) -> int:
268
+ """Non-`**` segment count: a crude but honest specificity measure."""
269
+ return sum(1 for s in self.segments if s != "**")
270
+
271
+ def __str__(self) -> str: # pragma: no cover - trivial
272
+ return self.raw
273
+
274
+
275
+ def _matching_brace(raw: str, start: int) -> int:
276
+ depth = 0
277
+ for i in range(start, len(raw)):
278
+ if raw[i] == "{":
279
+ depth += 1
280
+ elif raw[i] == "}":
281
+ depth -= 1
282
+ if depth == 0:
283
+ return i
284
+ return -1
285
+
286
+
287
+ def _split_top_level(body: str) -> list[str]:
288
+ parts: list[str] = []
289
+ depth = 0
290
+ current: list[str] = []
291
+ for ch in body:
292
+ if ch == "{":
293
+ depth += 1
294
+ elif ch == "}":
295
+ depth -= 1
296
+ if ch == "," and depth == 0:
297
+ parts.append("".join(current))
298
+ current = []
299
+ else:
300
+ current.append(ch)
301
+ parts.append("".join(current))
302
+ return parts
303
+
304
+
305
+ def expand_braces(raw: str) -> list[str]:
306
+ """`a/*.{tsx,css}` -> `a/*.tsx`, `a/*.css`. Handles nesting.
307
+
308
+ Brace groups are the one glob idiom every designer reaches for, and a
309
+ pattern that silently matches nothing is worse than one that errors.
310
+ """
311
+ start = raw.find("{")
312
+ if start == -1:
313
+ return [raw]
314
+ end = _matching_brace(raw, start)
315
+ if end == -1:
316
+ return [raw]
317
+ head, body, tail = raw[:start], raw[start + 1 : end], raw[end + 1 :]
318
+ out: list[str] = []
319
+ for alternative in _split_top_level(body):
320
+ out.extend(expand_braces(head + alternative + tail))
321
+ return out
322
+
323
+
324
+ def compile_patterns(raw: Iterable[str]) -> tuple[Pattern, ...]:
325
+ return tuple(
326
+ compile_pattern(part) for item in raw for part in expand_braces(str(item))
327
+ )
328
+
329
+
330
+ def compile_pattern(raw: str) -> Pattern:
331
+ raw = raw.strip().replace("\\", "/")
332
+ while raw.startswith("./"):
333
+ raw = raw[2:]
334
+ raw = raw.lstrip("/")
335
+ if not raw:
336
+ raw = "**"
337
+ parts = tuple(p for p in raw.split("/") if p not in ("", "."))
338
+ if not parts:
339
+ parts = ("**",)
340
+ return Pattern(raw="/".join(parts), segments=parts)
341
+
342
+
343
+ def _eclose(states: set[int], pat: Pattern) -> set[int]:
344
+ """Close a state set under `**` matching zero segments."""
345
+ out = set(states)
346
+ stack = list(out)
347
+ while stack:
348
+ i = stack.pop()
349
+ if i < len(pat._segs) and pat._segs[i] is None and (i + 1) not in out:
350
+ out.add(i + 1)
351
+ stack.append(i + 1)
352
+ return out
353
+
354
+
355
+ def _step(
356
+ states: set[int], pat: Pattern, segment: str
357
+ ) -> set[int]:
358
+ """Advance every live state by one concrete path segment (eps-closed)."""
359
+ out: set[int] = set()
360
+ segs = pat._segs
361
+ for i in _eclose(states, pat):
362
+ if i >= len(segs):
363
+ continue
364
+ sn = segs[i]
365
+ if sn is None: # '**': consume and stay
366
+ out.add(i)
367
+ elif _seg_accepts(sn, segment):
368
+ out.add(i + 1)
369
+ return _eclose(out, pat)
370
+
371
+
372
+ def _seg_accepts(sn: _SegNFA, segment: str) -> bool:
373
+ cur = {0}
374
+ # eps closure of start
375
+ stack = [0]
376
+ while stack:
377
+ s = stack.pop()
378
+ for t in sn.eps[s]:
379
+ if t not in cur:
380
+ cur.add(t)
381
+ stack.append(t)
382
+ for ch in segment:
383
+ nxt: set[int] = set()
384
+ for s in cur:
385
+ for cs, t in sn.trans[s]:
386
+ if cs is None or ch in cs:
387
+ nxt.add(t)
388
+ if not nxt:
389
+ return False
390
+ stack = list(nxt)
391
+ while stack:
392
+ s = stack.pop()
393
+ for t in sn.eps[s]:
394
+ if t not in nxt:
395
+ nxt.add(t)
396
+ stack.append(t)
397
+ cur = nxt
398
+ return sn.n in cur
399
+
400
+
401
+ def normalize_path(path: str) -> str:
402
+ path = path.replace("\\", "/").strip()
403
+ while path.startswith("./"):
404
+ path = path[2:]
405
+ return path.strip("/")
406
+
407
+
408
+ def path_matches(pat: Pattern, path: str) -> bool:
409
+ path = normalize_path(path)
410
+ if not path:
411
+ return False
412
+ parts = path.split("/")
413
+ states = _step({0}, pat, parts[0])
414
+ for seg in parts[1:]:
415
+ if not states:
416
+ return False
417
+ states = _step(states, pat, seg)
418
+ return len(pat.segments) in states
419
+
420
+
421
+ def product_witness(a: Pattern, b: Pattern) -> str | None:
422
+ """A concrete path matched by both patterns, or None if they are disjoint.
423
+
424
+ This is the product construction. Accepting the pair (len(a), len(b)) means
425
+ some path is in both languages; the BFS tree recovers that path, segment by
426
+ segment, which is what turns a boolean into evidence.
427
+ """
428
+ goal = (len(a.segments), len(b.segments))
429
+ start = (0, 0)
430
+ if start == goal:
431
+ return ""
432
+ parent: dict[tuple[int, int], tuple[tuple[int, int], str]] = {}
433
+ seen = {start}
434
+ q: deque[tuple[int, int]] = deque([start])
435
+ while q:
436
+ i, j = q.popleft()
437
+ if (i, j) == goal:
438
+ segs: list[str] = []
439
+ cur = (i, j)
440
+ while cur in parent:
441
+ prev, seg = parent[cur]
442
+ if seg:
443
+ segs.append(seg)
444
+ cur = prev
445
+ return "/".join(reversed(segs)) or "x"
446
+ a_star = i < len(a.segments) and a.segments[i] == "**"
447
+ b_star = j < len(b.segments) and b.segments[j] == "**"
448
+ if a_star:
449
+ nxt = (i + 1, j)
450
+ if nxt not in seen:
451
+ seen.add(nxt)
452
+ parent[nxt] = ((i, j), "")
453
+ q.append(nxt)
454
+ if b_star:
455
+ nxt = (i, j + 1)
456
+ if nxt not in seen:
457
+ seen.add(nxt)
458
+ parent[nxt] = ((i, j), "")
459
+ q.append(nxt)
460
+ if a_star and j < len(b.segments):
461
+ seg = _seg_fill(b.segments[j]) if b._segs[j] is not None else "x"
462
+ nxt = (i, j + 1)
463
+ if nxt not in seen:
464
+ seen.add(nxt)
465
+ parent[nxt] = ((i, j), seg)
466
+ q.append(nxt)
467
+ if b_star and i < len(a.segments):
468
+ seg = _seg_fill(a.segments[i]) if a._segs[i] is not None else "x"
469
+ nxt = (i + 1, j)
470
+ if nxt not in seen:
471
+ seen.add(nxt)
472
+ parent[nxt] = ((i, j), seg)
473
+ q.append(nxt)
474
+ if (
475
+ not a_star
476
+ and not b_star
477
+ and i < len(a.segments)
478
+ and j < len(b.segments)
479
+ ):
480
+ w = _seg_joint(a._segs[i], b._segs[j]) # type: ignore[arg-type]
481
+ if w is not None:
482
+ nxt = (i + 1, j + 1)
483
+ if nxt not in seen:
484
+ seen.add(nxt)
485
+ parent[nxt] = ((i, j), w)
486
+ q.append(nxt)
487
+ return None
488
+
489
+
490
+ # --------------------------------------------------------------------------
491
+ # scopes
492
+ # --------------------------------------------------------------------------
493
+
494
+
495
+ @dataclass(frozen=True)
496
+ class Scope:
497
+ """``include ∪ ...`` minus ``exclude ∪ ...``.
498
+
499
+ Empty `paths` means the universal scope (the rule is always in
500
+ jurisdiction), which is the common case for "always" rules.
501
+ """
502
+
503
+ paths: tuple[Pattern, ...] = ()
504
+ excludes: tuple[Pattern, ...] = ()
505
+ ops: tuple[str, ...] = ("write",)
506
+
507
+ def matches(self, path: str) -> bool:
508
+ if any(path_matches(e, path) for e in self.excludes):
509
+ return False
510
+ if not self.paths:
511
+ return True
512
+ return any(path_matches(p, path) for p in self.paths)
513
+
514
+ def covers_all(self) -> bool:
515
+ return not self.paths
516
+
517
+ @property
518
+ def specificity(self) -> int:
519
+ if not self.paths:
520
+ return 0
521
+ return max(p.depth for p in self.paths)
522
+
523
+ def witness_with(self, other: "Scope", *, attempts: int = 32) -> str | None:
524
+ """A path governed by both scopes, or None.
525
+
526
+ Exclusions are applied to candidate witnesses. Because a rule may
527
+ exclude the shortest witness while still intersecting elsewhere, we
528
+ enumerate candidates (bounded) before concluding disjointness. This is
529
+ sound when it returns a path, and conservative when it returns None.
530
+ """
531
+ if not set(self.ops) & set(other.ops):
532
+ return None
533
+ a_pats = self.paths or (compile_pattern("**"),)
534
+ b_pats = other.paths or (compile_pattern("**"),)
535
+ tried = 0
536
+ for pa in a_pats:
537
+ for pb in b_pats:
538
+ w = product_witness(pa, pb)
539
+ if w is None:
540
+ continue
541
+ if self.matches(w) and other.matches(w):
542
+ # A witness ending on a `**` boundary reads like a directory
543
+ # ("backend/ledger"); prefer a concrete file under it, since
544
+ # a path fragment is weaker evidence than a real path.
545
+ if "." not in w.rsplit("/", 1)[-1]:
546
+ for filler in ("/x.py", "/x"):
547
+ probe = w + filler if w else filler.lstrip("/")
548
+ if self.matches(probe) and other.matches(probe):
549
+ return probe
550
+ return w
551
+ tried += 1
552
+ if tried >= attempts:
553
+ return None
554
+ return None
555
+
556
+ def describe(self) -> str:
557
+ inc = ",".join(p.raw for p in self.paths) or "**"
558
+ exc = ",".join(p.raw for p in self.excludes)
559
+ ops = ",".join(self.ops)
560
+ base = f"{inc} [{ops}]" if inc != "**" else f"all [{ops}]"
561
+ if exc:
562
+ base += f" -({exc})"
563
+ return base
564
+
565
+
566
+ def coerce_scope(raw: object) -> Scope:
567
+ """Accept a string, a list, or a dict from the ledger."""
568
+ if raw is None:
569
+ return Scope()
570
+ if isinstance(raw, str):
571
+ return Scope(compile_patterns([raw]))
572
+ if isinstance(raw, list):
573
+ return Scope(compile_patterns([str(x) for x in raw]))
574
+ if isinstance(raw, dict):
575
+ paths = raw.get("paths", raw.get("path"))
576
+ exc = raw.get("not", raw.get("not_paths", raw.get("exclude")))
577
+ ops = raw.get("ops", ("write",))
578
+ if isinstance(paths, str):
579
+ paths = [paths]
580
+ if isinstance(exc, str):
581
+ exc = [exc]
582
+ if isinstance(ops, str):
583
+ ops = [ops]
584
+ return Scope(
585
+ compile_patterns([str(p) for p in (paths or [])]),
586
+ compile_patterns([str(p) for p in (exc or [])]),
587
+ tuple(str(o) for o in (ops or ["write"])),
588
+ )
589
+ raise TypeError(f"cannot interpret scope: {raw!r}")