tessera-skill 1.0.0__tar.gz
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.
- tessera_skill-1.0.0/LICENSE +21 -0
- tessera_skill-1.0.0/PKG-INFO +26 -0
- tessera_skill-1.0.0/README.md +9 -0
- tessera_skill-1.0.0/pyproject.toml +30 -0
- tessera_skill-1.0.0/setup.cfg +4 -0
- tessera_skill-1.0.0/src/tessera_skill/__init__.py +2 -0
- tessera_skill-1.0.0/src/tessera_skill/__main__.py +27 -0
- tessera_skill-1.0.0/src/tessera_skill/scripts/_core.py +457 -0
- tessera_skill-1.0.0/src/tessera_skill/scripts/_index.py +621 -0
- tessera_skill-1.0.0/src/tessera_skill/scripts/_rank.py +1003 -0
- tessera_skill-1.0.0/src/tessera_skill/scripts/deps.py +50 -0
- tessera_skill-1.0.0/src/tessera_skill/scripts/find.py +46 -0
- tessera_skill-1.0.0/src/tessera_skill/scripts/map.py +51 -0
- tessera_skill-1.0.0/src/tessera_skill/scripts/pack.py +53 -0
- tessera_skill-1.0.0/src/tessera_skill/scripts/slice.py +48 -0
- tessera_skill-1.0.0/src/tessera_skill.egg-info/PKG-INFO +26 -0
- tessera_skill-1.0.0/src/tessera_skill.egg-info/SOURCES.txt +18 -0
- tessera_skill-1.0.0/src/tessera_skill.egg-info/dependency_links.txt +1 -0
- tessera_skill-1.0.0/src/tessera_skill.egg-info/entry_points.txt +2 -0
- tessera_skill-1.0.0/src/tessera_skill.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sahil
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tessera-skill
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Tessera: token-budgeted code context for AI coding agents exploring Python repositories (standard library only).
|
|
5
|
+
Author: Sahil
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: ai-agents,code-search,context,tokens,skill
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Software Development
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# tessera-skill
|
|
19
|
+
|
|
20
|
+
Command line behind the Tessera skill: finds the relevant functions and classes in a Python
|
|
21
|
+
repository and prints one token-budgeted bundle (exact code, outlines, and a list of what did not fit).
|
|
22
|
+
Python 3.10+, standard library only, read-only.
|
|
23
|
+
|
|
24
|
+
uvx tessera-skill@1.0.0 pack "retry session cookie" --root <repo> --task bug
|
|
25
|
+
|
|
26
|
+
Commands: `pack`, `find`, `map`, `slice`, `deps`. Add `--help` to any of them.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# tessera-skill
|
|
2
|
+
|
|
3
|
+
Command line behind the Tessera skill: finds the relevant functions and classes in a Python
|
|
4
|
+
repository and prints one token-budgeted bundle (exact code, outlines, and a list of what did not fit).
|
|
5
|
+
Python 3.10+, standard library only, read-only.
|
|
6
|
+
|
|
7
|
+
uvx tessera-skill@1.0.0 pack "retry session cookie" --root <repo> --task bug
|
|
8
|
+
|
|
9
|
+
Commands: `pack`, `find`, `map`, `slice`, `deps`. Add `--help` to any of them.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tessera-skill"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Tessera: token-budgeted code context for AI coding agents exploring Python repositories (standard library only)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Sahil" }]
|
|
14
|
+
keywords = ["ai-agents", "code-search", "context", "tokens", "skill"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.13",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Topic :: Software Development",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
tessera-skill = "tessera_skill.__main__:main"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools.packages.find]
|
|
27
|
+
where = ["src"]
|
|
28
|
+
|
|
29
|
+
[tool.setuptools.package-data]
|
|
30
|
+
tessera_skill = ["scripts/*.py"]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Dispatcher: `tessera-skill <pack|find|map|slice|deps> [arguments]` runs the matching script unchanged."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import runpy
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Optional, Sequence
|
|
8
|
+
|
|
9
|
+
COMMANDS = ("pack", "find", "map", "slice", "deps")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
13
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
14
|
+
if not args or args[0] not in COMMANDS:
|
|
15
|
+
print("usage: tessera-skill {%s} [arguments] (add --help after a command)" % "|".join(COMMANDS))
|
|
16
|
+
return 0 if not args or args[0] in ("-h", "--help") else 2
|
|
17
|
+
script = Path(__file__).resolve().parent / "scripts" / (args[0] + ".py")
|
|
18
|
+
sys.argv = [str(script)] + args[1:]
|
|
19
|
+
try:
|
|
20
|
+
runpy.run_path(str(script), run_name="__main__")
|
|
21
|
+
except SystemExit as stop:
|
|
22
|
+
return stop.code if isinstance(stop.code, int) else (0 if stop.code is None else 1)
|
|
23
|
+
return 0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
if __name__ == "__main__":
|
|
27
|
+
sys.exit(main())
|
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
"""File walking, ignore rules, safe paths, token estimate and output helpers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import fnmatch
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Callable, List, Optional, Sequence, Tuple
|
|
13
|
+
|
|
14
|
+
MAX_FILE_BYTES = 1_000_000
|
|
15
|
+
BINARY_SNIFF_BYTES = 8192
|
|
16
|
+
SAFETY_PERCENT = 110
|
|
17
|
+
UNITS_PER_TOKEN = 2
|
|
18
|
+
ALPHA_CHARS = 6
|
|
19
|
+
DIGIT_CHARS = 3
|
|
20
|
+
MAX_OMITTED_ITEMS = 15
|
|
21
|
+
MAX_WARNINGS = 5
|
|
22
|
+
|
|
23
|
+
TASK_BUDGETS = {"lookup": 1500, "test": 2000, "bug": 2500, "explore": 3000, "feature": 3500}
|
|
24
|
+
DEFAULT_BUDGET = 2000
|
|
25
|
+
HARD_CAP = 8000
|
|
26
|
+
MIN_BUDGET = 200
|
|
27
|
+
BUDGET_TOO_SMALL = "BUDGET TOO SMALL (minimum 200)"
|
|
28
|
+
NO_PYTHON_FILES = "NO PYTHON FILES: tessera v1 supports Python only"
|
|
29
|
+
DEFAULT_MAX_SECONDS = 20.0
|
|
30
|
+
|
|
31
|
+
DEFAULT_DIR_NAMES = frozenset({
|
|
32
|
+
".git", ".hg", ".svn", ".venv", "node_modules", "__pycache__", ".mypy_cache",
|
|
33
|
+
".pytest_cache", ".ruff_cache", ".tox", ".nox", ".eggs", "site-packages",
|
|
34
|
+
".idea", ".vscode", "htmlcov",
|
|
35
|
+
})
|
|
36
|
+
DEFAULT_DIR_GLOBS = ("*.egg-info",)
|
|
37
|
+
ROOT_ONLY_DIRS = frozenset({"build", "dist"})
|
|
38
|
+
SECRET_FILE_GLOBS = (
|
|
39
|
+
".env*", "*.pem", "*.key", "*.p12", "id_rsa*", "credentials.json", "secrets.*",
|
|
40
|
+
)
|
|
41
|
+
DEFAULT_FILE_GLOBS = (
|
|
42
|
+
"*.lock", "poetry.lock", "pipfile.lock", "*.pyc", "*.pyo", "*.so", "*.dll",
|
|
43
|
+
"*.png", "*.jpg", "*.jpeg", "*.gif", "*.ico", "*.zip", "*.tar", "*.gz", "*.whl",
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PathError(Exception):
|
|
48
|
+
"""A path is outside the root, ignored, secret or missing (CLI exit code 3)."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class UsageError(Exception):
|
|
52
|
+
"""Invalid command-line input (CLI exit code 2)."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def setup_stdout() -> None:
|
|
56
|
+
"""Make stdout UTF-8 so unicode names never crash a Windows console."""
|
|
57
|
+
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
|
58
|
+
if reconfigure is not None:
|
|
59
|
+
reconfigure(encoding="utf-8", errors="replace")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
# ---------------------------------------------------------------- ignore rules
|
|
63
|
+
|
|
64
|
+
class _Rule:
|
|
65
|
+
"""One compiled .gitignore line."""
|
|
66
|
+
|
|
67
|
+
__slots__ = ("regex", "negated", "dir_only")
|
|
68
|
+
|
|
69
|
+
def __init__(self, regex: "re.Pattern[str]", negated: bool, dir_only: bool) -> None:
|
|
70
|
+
self.regex = regex
|
|
71
|
+
self.negated = negated
|
|
72
|
+
self.dir_only = dir_only
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _glob_to_regex(glob: str) -> str:
|
|
76
|
+
"""Translate gitignore glob syntax (`*`, `?`, `**`, `[...]`) to a regex body."""
|
|
77
|
+
out: List[str] = []
|
|
78
|
+
i, n = 0, len(glob)
|
|
79
|
+
while i < n:
|
|
80
|
+
c = glob[i]
|
|
81
|
+
if c == "*":
|
|
82
|
+
if glob.startswith("**", i):
|
|
83
|
+
at_start = i == 0 or glob[i - 1] == "/"
|
|
84
|
+
if at_start and glob.startswith("**/", i):
|
|
85
|
+
out.append("(?:.*/)?")
|
|
86
|
+
i += 3
|
|
87
|
+
continue
|
|
88
|
+
if at_start and i + 2 == n:
|
|
89
|
+
out.append(".*")
|
|
90
|
+
i += 2
|
|
91
|
+
continue
|
|
92
|
+
out.append("[^/]*")
|
|
93
|
+
elif c == "?":
|
|
94
|
+
out.append("[^/]")
|
|
95
|
+
elif c == "[":
|
|
96
|
+
end = glob.find("]", i + 2)
|
|
97
|
+
if end == -1:
|
|
98
|
+
out.append(re.escape(c))
|
|
99
|
+
else:
|
|
100
|
+
body = glob[i + 1:end].replace("\\", "\\\\")
|
|
101
|
+
if body.startswith("!"):
|
|
102
|
+
body = "^" + body[1:]
|
|
103
|
+
out.append("[" + body + "]")
|
|
104
|
+
i = end
|
|
105
|
+
elif c == "\\" and i + 1 < n:
|
|
106
|
+
i += 1
|
|
107
|
+
out.append(re.escape(glob[i]))
|
|
108
|
+
else:
|
|
109
|
+
out.append(re.escape(c))
|
|
110
|
+
i += 1
|
|
111
|
+
return "".join(out)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _parse_rule(line: str) -> Optional[_Rule]:
|
|
115
|
+
"""Compile one ignore-file line; comments and blanks give None."""
|
|
116
|
+
if line.endswith(" ") and not line.endswith("\\ "):
|
|
117
|
+
line = line.rstrip(" ")
|
|
118
|
+
if not line or line.startswith("#"):
|
|
119
|
+
return None
|
|
120
|
+
negated = line.startswith("!")
|
|
121
|
+
if negated:
|
|
122
|
+
line = line[1:]
|
|
123
|
+
elif line.startswith("\\#"):
|
|
124
|
+
line = line[1:]
|
|
125
|
+
dir_only = line.endswith("/")
|
|
126
|
+
line = line.rstrip("/")
|
|
127
|
+
if not line:
|
|
128
|
+
return None
|
|
129
|
+
anchored = line.startswith("/") or "/" in line
|
|
130
|
+
body = _glob_to_regex(line.lstrip("/"))
|
|
131
|
+
pattern = "^" + body + "$" if anchored else "^(?:.*/)?" + body + "$"
|
|
132
|
+
return _Rule(re.compile(pattern), negated, dir_only)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _match_any(name: str, globs: Tuple[str, ...]) -> bool:
|
|
136
|
+
lowered = name.lower()
|
|
137
|
+
return any(fnmatch.fnmatchcase(lowered, g) for g in globs)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class IgnoreRules:
|
|
141
|
+
"""Built-in defaults plus root-level .gitignore and .prunerignore rules."""
|
|
142
|
+
|
|
143
|
+
def __init__(self, lines: Optional[List[str]] = None, root: Optional[str] = None) -> None:
|
|
144
|
+
self.root = root
|
|
145
|
+
self._rules: List[_Rule] = []
|
|
146
|
+
for line in lines or []:
|
|
147
|
+
rule = _parse_rule(line.rstrip("\r\n"))
|
|
148
|
+
if rule is not None:
|
|
149
|
+
self._rules.append(rule)
|
|
150
|
+
|
|
151
|
+
@classmethod
|
|
152
|
+
def from_root(cls, root: str) -> "IgnoreRules":
|
|
153
|
+
"""Load `<root>/.gitignore` then `<root>/.prunerignore` (later lines win)."""
|
|
154
|
+
lines: List[str] = []
|
|
155
|
+
for name in (".gitignore", ".prunerignore"):
|
|
156
|
+
path = os.path.join(root, name)
|
|
157
|
+
if os.path.isfile(path):
|
|
158
|
+
lines.extend(read_text(Path(path)).split("\n"))
|
|
159
|
+
return cls(lines, root)
|
|
160
|
+
|
|
161
|
+
def _user_ignored(self, rel: str, is_dir: bool) -> bool:
|
|
162
|
+
ignored = False
|
|
163
|
+
for rule in self._rules:
|
|
164
|
+
if rule.dir_only and not is_dir:
|
|
165
|
+
continue
|
|
166
|
+
if rule.regex.match(rel):
|
|
167
|
+
ignored = not rule.negated
|
|
168
|
+
return ignored
|
|
169
|
+
|
|
170
|
+
def dir_reason(self, rel: str, name: str) -> Optional[str]:
|
|
171
|
+
"""Why a directory is skipped (None if it is walked). `rel` is POSIX, no slash."""
|
|
172
|
+
if name in DEFAULT_DIR_NAMES or _match_any(name, DEFAULT_DIR_GLOBS):
|
|
173
|
+
return "default ignore"
|
|
174
|
+
if "/" not in rel and name in ROOT_ONLY_DIRS:
|
|
175
|
+
return "build output"
|
|
176
|
+
if self.root is not None and os.path.isfile(os.path.join(self.root, rel, "pyvenv.cfg")):
|
|
177
|
+
return "virtualenv"
|
|
178
|
+
if self._user_ignored(rel, True):
|
|
179
|
+
return "ignore rule"
|
|
180
|
+
return None
|
|
181
|
+
|
|
182
|
+
def file_reason(self, rel: str) -> Optional[str]:
|
|
183
|
+
"""Why a file is skipped (None if it is readable)."""
|
|
184
|
+
name = rel.rsplit("/", 1)[-1]
|
|
185
|
+
if _match_any(name, SECRET_FILE_GLOBS):
|
|
186
|
+
return "secret"
|
|
187
|
+
if _match_any(name, DEFAULT_FILE_GLOBS):
|
|
188
|
+
return "default ignore"
|
|
189
|
+
if self._user_ignored(rel, False):
|
|
190
|
+
return "ignore rule"
|
|
191
|
+
return None
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _rel_posix(root: str, path: str) -> str:
|
|
195
|
+
rel = os.path.relpath(path, root)
|
|
196
|
+
return "" if rel == "." else rel.replace(os.sep, "/")
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _is_binary(path: str) -> bool:
|
|
200
|
+
with open(path, "rb") as handle:
|
|
201
|
+
return b"\x00" in handle.read(BINARY_SNIFF_BYTES)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _dir_warnings(skipped: List[Tuple[str, str, str]]) -> List[str]:
|
|
205
|
+
"""One warning per skipped directory; default-ignored names are counted per name."""
|
|
206
|
+
by_name: dict = {}
|
|
207
|
+
out: List[str] = []
|
|
208
|
+
for rel, name, reason in skipped:
|
|
209
|
+
if reason == "default ignore":
|
|
210
|
+
by_name.setdefault(name, []).append(rel)
|
|
211
|
+
else:
|
|
212
|
+
out.append("skipped dir: %s/ (%s)" % (rel, reason))
|
|
213
|
+
for name, rels in by_name.items():
|
|
214
|
+
if len(rels) == 1:
|
|
215
|
+
out.append("skipped dir: %s/ (default ignore)" % rels[0])
|
|
216
|
+
else:
|
|
217
|
+
out.append("skipped %d dirs named %s (default ignore)" % (len(rels), name))
|
|
218
|
+
return sorted(out)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def find_repo_files(
|
|
222
|
+
root: str, rules: Optional[IgnoreRules] = None, warnings: Optional[List[str]] = None
|
|
223
|
+
) -> List[str]:
|
|
224
|
+
"""Sorted POSIX relative paths of readable `.py` files; skips are added to `warnings`."""
|
|
225
|
+
root = os.path.abspath(str(root))
|
|
226
|
+
if rules is None:
|
|
227
|
+
rules = IgnoreRules.from_root(root)
|
|
228
|
+
files: List[str] = []
|
|
229
|
+
skipped_dirs: List[Tuple[str, str, str]] = []
|
|
230
|
+
notes: List[str] = []
|
|
231
|
+
rule_ignored = 0
|
|
232
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
233
|
+
rel_dir = _rel_posix(root, dirpath)
|
|
234
|
+
kept = []
|
|
235
|
+
for name in sorted(dirnames):
|
|
236
|
+
rel = rel_dir + "/" + name if rel_dir else name
|
|
237
|
+
if os.path.islink(os.path.join(dirpath, name)):
|
|
238
|
+
skipped_dirs.append((rel, name, "symlink"))
|
|
239
|
+
continue
|
|
240
|
+
reason = rules.dir_reason(rel, name)
|
|
241
|
+
if reason:
|
|
242
|
+
skipped_dirs.append((rel, name, reason))
|
|
243
|
+
else:
|
|
244
|
+
kept.append(name)
|
|
245
|
+
dirnames[:] = kept
|
|
246
|
+
for name in sorted(filenames):
|
|
247
|
+
if not name.endswith(".py"):
|
|
248
|
+
continue
|
|
249
|
+
rel = rel_dir + "/" + name if rel_dir else name
|
|
250
|
+
full = os.path.join(dirpath, name)
|
|
251
|
+
if rules.file_reason(rel):
|
|
252
|
+
rule_ignored += 1
|
|
253
|
+
elif os.path.islink(full) and not _inside(root, os.path.realpath(full)):
|
|
254
|
+
notes.append("skipped file: %s (symlink outside root)" % rel)
|
|
255
|
+
elif os.path.getsize(full) > MAX_FILE_BYTES:
|
|
256
|
+
notes.append("skipped file: %s (over 1 MB)" % rel)
|
|
257
|
+
elif _is_binary(full):
|
|
258
|
+
notes.append("skipped file: %s (binary)" % rel)
|
|
259
|
+
else:
|
|
260
|
+
files.append(rel)
|
|
261
|
+
if warnings is not None:
|
|
262
|
+
warnings.extend(_dir_warnings(skipped_dirs))
|
|
263
|
+
warnings.extend(sorted(notes))
|
|
264
|
+
if rule_ignored:
|
|
265
|
+
warnings.append("skipped %d .py files by ignore rules" % rule_ignored)
|
|
266
|
+
return sorted(files)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# ----------------------------------------------------------------- safe paths
|
|
270
|
+
|
|
271
|
+
def _inside(root: str, path: str) -> bool:
|
|
272
|
+
try:
|
|
273
|
+
Path(path).relative_to(Path(root))
|
|
274
|
+
except ValueError:
|
|
275
|
+
return False
|
|
276
|
+
return True
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def safe_resolve(root: str, user_path: str, rules: Optional[IgnoreRules] = None) -> Path:
|
|
280
|
+
"""Resolve `user_path` under `root`; raise PathError if outside, ignored, secret or missing."""
|
|
281
|
+
root_path = Path(root).resolve()
|
|
282
|
+
candidate = Path(user_path)
|
|
283
|
+
if not candidate.is_absolute():
|
|
284
|
+
candidate = root_path / candidate
|
|
285
|
+
resolved = candidate.resolve()
|
|
286
|
+
if not _inside(str(root_path), str(resolved)):
|
|
287
|
+
raise PathError("path is outside the root: %s" % user_path)
|
|
288
|
+
if rules is None:
|
|
289
|
+
rules = IgnoreRules.from_root(str(root_path))
|
|
290
|
+
rel = _rel_posix(str(root_path), str(resolved))
|
|
291
|
+
parts = rel.split("/") if rel else []
|
|
292
|
+
for depth in range(1, len(parts)):
|
|
293
|
+
sub = "/".join(parts[:depth])
|
|
294
|
+
if rules.dir_reason(sub, parts[depth - 1]):
|
|
295
|
+
raise PathError("path is in an ignored directory: %s" % rel)
|
|
296
|
+
if parts:
|
|
297
|
+
if resolved.is_dir():
|
|
298
|
+
if rules.dir_reason(rel, parts[-1]):
|
|
299
|
+
raise PathError("path is an ignored directory: %s" % rel)
|
|
300
|
+
elif rules.file_reason(rel):
|
|
301
|
+
raise PathError("path is ignored or secret: %s" % rel)
|
|
302
|
+
if not resolved.exists():
|
|
303
|
+
raise PathError("not found: %s" % user_path)
|
|
304
|
+
return resolved
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def read_text(path: Path) -> str:
|
|
308
|
+
"""Decode UTF-8 (replacing bad bytes), strip a BOM, normalize newlines to `\\n`.
|
|
309
|
+
|
|
310
|
+
Always split the result with `text.split("\\n")`, never `splitlines()`: the latter
|
|
311
|
+
also splits on form feed and breaks agreement with `ast` line numbers.
|
|
312
|
+
"""
|
|
313
|
+
text = Path(path).read_bytes().decode("utf-8", errors="replace")
|
|
314
|
+
if text.startswith(""):
|
|
315
|
+
text = text[1:]
|
|
316
|
+
return text.replace("\r\n", "\n").replace("\r", "\n")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# ------------------------------------------------------------ token estimates
|
|
320
|
+
|
|
321
|
+
_TOKEN_RE = re.compile(
|
|
322
|
+
r"(?P<a>[A-Za-z]+)|(?P<d>[0-9]+)|(?P<w>[ \t\r\n\f\v]+)|(?P<u>[^\x00-\x7f])|(?P<p>.)",
|
|
323
|
+
re.DOTALL,
|
|
324
|
+
)
|
|
325
|
+
_CAMEL_RE = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+")
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def estimate_tokens(text: str) -> int:
|
|
329
|
+
"""Rough token ESTIMATE (each model tokenizes differently); non-zero for non-empty text."""
|
|
330
|
+
return max(1, units_to_tokens(raw_units(text))) if text else 0
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def raw_units(text: str) -> int:
|
|
334
|
+
"""Estimate in half-tokens; additive over parts joined by one newline (1 unit) each."""
|
|
335
|
+
total = 0
|
|
336
|
+
for match in _TOKEN_RE.finditer(text):
|
|
337
|
+
kind, token = match.lastgroup, match.group()
|
|
338
|
+
if kind == "a":
|
|
339
|
+
total += UNITS_PER_TOKEN * sum(math.ceil(len(w) / ALPHA_CHARS) for w in _CAMEL_RE.findall(token))
|
|
340
|
+
elif kind == "d":
|
|
341
|
+
total += UNITS_PER_TOKEN * math.ceil(len(token) / DIGIT_CHARS)
|
|
342
|
+
elif kind == "w":
|
|
343
|
+
total += token.count("\n")
|
|
344
|
+
elif kind == "u":
|
|
345
|
+
total += 2 * UNITS_PER_TOKEN
|
|
346
|
+
else:
|
|
347
|
+
total += 1
|
|
348
|
+
return total
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def units_to_tokens(units: int) -> int:
|
|
352
|
+
return -(-units // UNITS_PER_TOKEN)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def padded(tokens: int) -> int:
|
|
356
|
+
"""Apply the budget safety margin to an estimated token total."""
|
|
357
|
+
return (tokens * SAFETY_PERCENT + 99) // 100
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def printed_cost(text: str) -> int:
|
|
361
|
+
"""Padded token cost of `text` as printed (print adds a trailing newline)."""
|
|
362
|
+
return padded(estimate_tokens(text + "\n"))
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
class Deadline:
|
|
366
|
+
"""Wall-clock limit checked between files; `None` means no limit."""
|
|
367
|
+
|
|
368
|
+
def __init__(self, max_seconds: Optional[float]) -> None:
|
|
369
|
+
self._end = None if max_seconds is None else time.monotonic() + max_seconds
|
|
370
|
+
|
|
371
|
+
def expired(self) -> bool:
|
|
372
|
+
return self._end is not None and time.monotonic() >= self._end
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
# -------------------------------------------------------------------- budgets
|
|
376
|
+
|
|
377
|
+
def resolve_budget(explicit: Optional[int], task: Optional[str]) -> Tuple[int, str, List[str]]:
|
|
378
|
+
"""Explicit budget beats task profile beats default; returns (budget, source, warnings)."""
|
|
379
|
+
if task is not None and task not in TASK_BUDGETS:
|
|
380
|
+
raise UsageError("unknown --task '%s' (use %s)" % (task, ", ".join(TASK_BUDGETS)))
|
|
381
|
+
if explicit is not None:
|
|
382
|
+
if explicit < 1:
|
|
383
|
+
raise UsageError("--budget must be a positive number")
|
|
384
|
+
if explicit > HARD_CAP:
|
|
385
|
+
return HARD_CAP, "clamped", ["budget %d clamped to %d (hard cap)" % (explicit, HARD_CAP)]
|
|
386
|
+
return explicit, "explicit", []
|
|
387
|
+
if task is not None:
|
|
388
|
+
return TASK_BUDGETS[task], "task", []
|
|
389
|
+
return DEFAULT_BUDGET, "default", []
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def next_budget(current: int) -> Optional[int]:
|
|
393
|
+
"""Next larger budget on the ladder, 1.5x steps above `feature`, None at the hard cap."""
|
|
394
|
+
if current >= HARD_CAP:
|
|
395
|
+
return None
|
|
396
|
+
for value in sorted(TASK_BUDGETS.values()):
|
|
397
|
+
if value > current:
|
|
398
|
+
return value
|
|
399
|
+
return min(math.ceil(current * 1.5 / 500) * 500, HARD_CAP)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
# ------------------------------------------------------------- output helpers
|
|
403
|
+
|
|
404
|
+
def _capped(items: List[str], limit: int) -> List[str]:
|
|
405
|
+
if len(items) <= limit:
|
|
406
|
+
return list(items)
|
|
407
|
+
return items[:limit] + ["+%d more" % (len(items) - limit)]
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def footer(omitted: List[str], warnings: List[str],
|
|
411
|
+
max_omitted: int = MAX_OMITTED_ITEMS, max_warnings: int = MAX_WARNINGS) -> str:
|
|
412
|
+
"""OMITTED (max 15 items) and WARNINGS (max 5) lines; an empty line is left out."""
|
|
413
|
+
lines = []
|
|
414
|
+
if omitted:
|
|
415
|
+
lines.append("OMITTED: " + "; ".join(_capped(omitted, max_omitted)))
|
|
416
|
+
if warnings:
|
|
417
|
+
lines.append("WARNINGS: " + "; ".join(_capped(warnings, max_warnings)))
|
|
418
|
+
return "\n".join(lines)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
# ------------------------------------------------------------------------ CLI
|
|
422
|
+
|
|
423
|
+
class CliParser(argparse.ArgumentParser):
|
|
424
|
+
"""argparse that raises UsageError instead of printing usage and exiting."""
|
|
425
|
+
|
|
426
|
+
def error(self, message: str): # type: ignore[override]
|
|
427
|
+
raise UsageError(message)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def make_parser(prog: str, description: str) -> CliParser:
|
|
431
|
+
"""Parser with the flags shared by every tool: --root and --max-seconds."""
|
|
432
|
+
parser = CliParser(prog=prog, description=description)
|
|
433
|
+
parser.add_argument("--root", default=".", help="repository root (default .)")
|
|
434
|
+
parser.add_argument("--max-seconds", type=float, default=DEFAULT_MAX_SECONDS,
|
|
435
|
+
help="stop indexing after N seconds (default 20)")
|
|
436
|
+
return parser
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def require_root(root: str) -> str:
|
|
440
|
+
"""Absolute root path, or PathError if it is not a directory."""
|
|
441
|
+
path = os.path.abspath(root)
|
|
442
|
+
if not os.path.isdir(path):
|
|
443
|
+
raise PathError("root is not a directory: %s" % root)
|
|
444
|
+
return path
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def run_guarded(fn: Callable[[Optional[Sequence[str]]], int], argv: Optional[Sequence[str]]) -> int:
|
|
448
|
+
"""Run a CLI body with UTF-8 stdout; map UsageError to exit 2 and PathError to exit 3."""
|
|
449
|
+
setup_stdout()
|
|
450
|
+
try:
|
|
451
|
+
return fn(argv)
|
|
452
|
+
except UsageError as exc:
|
|
453
|
+
print("ERROR: %s" % exc)
|
|
454
|
+
return 2
|
|
455
|
+
except PathError as exc:
|
|
456
|
+
print("ERROR: %s" % exc)
|
|
457
|
+
return 3
|