testscope 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.
testscope/__init__.py ADDED
File without changes
@@ -0,0 +1,61 @@
1
+ """Loaded in child Python processes started by a recorded test (via PYTHONPATH).
2
+
3
+ Records the child's deps and writes them to $TESTSCOPE_OUT at exit, then chains
4
+ to any real sitecustomize this one shadows.
5
+ """
6
+ import os
7
+ import sys
8
+
9
+ _here = os.path.dirname(os.path.abspath(__file__))
10
+
11
+
12
+ def _start():
13
+ out, root = os.environ.get("TESTSCOPE_OUT"), os.environ.get("TESTSCOPE_ROOT")
14
+ if not out or not root or sys.version_info < (3, 12):
15
+ return
16
+ import atexit, json
17
+ try:
18
+ from testscope.recorder import Recorder
19
+ except ImportError: # child runs an interpreter without testscope installed
20
+ return
21
+
22
+ rec = Recorder(root)
23
+ try:
24
+ rec.install()
25
+ except Exception:
26
+ return
27
+ rec.start()
28
+
29
+ def flush():
30
+ if not rec.active:
31
+ return
32
+ funcs, files, dirs = rec.stop()
33
+ try:
34
+ with open(os.path.join(out, f"{os.getpid()}-{id(rec)}.json"), "w") as fh:
35
+ json.dump({"funcs": sorted(funcs), "files": sorted(files), "dirs": sorted(dirs)}, fh)
36
+ except OSError:
37
+ pass
38
+
39
+ atexit.register(flush)
40
+ real_exit = os._exit
41
+
42
+ def _exit(code): # os._exit skips atexit
43
+ flush()
44
+ real_exit(code)
45
+
46
+ os._exit = _exit
47
+
48
+
49
+ _start()
50
+
51
+ # Chain to the sitecustomize we shadow, if any.
52
+ _mod = sys.modules.pop("sitecustomize", None)
53
+ _saved = list(sys.path)
54
+ sys.path[:] = [p for p in sys.path if os.path.abspath(p or ".") != _here]
55
+ try:
56
+ import sitecustomize # noqa: F401
57
+ except ImportError:
58
+ if _mod is not None:
59
+ sys.modules["sitecustomize"] = _mod
60
+ finally:
61
+ sys.path[:] = _saved
@@ -0,0 +1,210 @@
1
+ """Content fingerprints and the static import graph.
2
+
3
+ A .py file is split into functions (by qualname, hashed by token stream, so moving
4
+ code or editing comments does not count as a change) and module/class-level statements
5
+ keyed by the names they bind, so a changed constant maps to the code that reads it.
6
+ Other files get a sha1.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import hashlib
12
+ import io
13
+ import os
14
+ import subprocess
15
+ import textwrap
16
+ import tokenize
17
+
18
+ def _h(s: str | bytes) -> str:
19
+ return hashlib.sha1(s if isinstance(s, bytes) else s.encode()).hexdigest()[:16]
20
+
21
+
22
+ _SKIP_TOK = {tokenize.COMMENT, tokenize.NL, tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT,
23
+ tokenize.ENCODING, tokenize.ENDMARKER}
24
+
25
+
26
+ def _tok_hash(text: str) -> str:
27
+ """Hash of the token stream: ignores comments, blank lines and indentation, and
28
+ unlike ast.dump() it is stable across Python versions (map from CI 3.12, run on 3.14)."""
29
+ try:
30
+ toks = tokenize.generate_tokens(io.StringIO(textwrap.dedent(text)).readline)
31
+ return _h(" ".join(t.string for t in toks if t.type not in _SKIP_TOK))
32
+ except (tokenize.TokenError, IndentationError, SyntaxError):
33
+ return _h(text)
34
+
35
+
36
+ def bound_names(node) -> list[str]:
37
+ """Names a module- or class-level statement binds."""
38
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
39
+ return [node.name]
40
+ if isinstance(node, ast.Import):
41
+ return [a.asname or a.name.split(".")[0] for a in node.names]
42
+ if isinstance(node, ast.ImportFrom):
43
+ return [a.asname or a.name for a in node.names]
44
+ if isinstance(node, ast.Expr):
45
+ return [] # bare call / docstring: binds nothing
46
+ out = []
47
+ for n in ast.walk(node):
48
+ if isinstance(n, ast.Name) and isinstance(n.ctx, (ast.Store, ast.Del)):
49
+ out.append(n.id)
50
+ elif isinstance(n, ast.Attribute) and isinstance(n.ctx, (ast.Store, ast.Del)):
51
+ out.append(n.attr)
52
+ elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
53
+ out.append(n.name)
54
+ elif isinstance(n, (ast.Import, ast.ImportFrom)):
55
+ out += bound_names(n)
56
+ return out
57
+
58
+
59
+ def referenced_names(node) -> tuple[set[str], set[str]]:
60
+ """(bare names, attribute names) a node reads. Function parameters count as bare
61
+ names so a pytest fixture maps to the tests that request it."""
62
+ bare, attr = set(), set()
63
+ for n in ast.walk(node):
64
+ if isinstance(n, ast.Name):
65
+ bare.add(n.id)
66
+ elif isinstance(n, ast.Attribute):
67
+ attr.add(n.attr)
68
+ elif isinstance(n, ast.arg):
69
+ bare.add(n.arg)
70
+ elif isinstance(n, ast.alias):
71
+ bare.add(n.name.split(".")[-1])
72
+ return bare, attr
73
+
74
+
75
+ def module_statements(tree, lines):
76
+ """Yield (key, node, text) for each module- and class-level statement that is not a def.
77
+
78
+ key is "n:<scope><names>" for statements that bind names, "x:<scope>#<i>" otherwise.
79
+ A def contributes "n:<scope><name>" with no text, so adding or removing one is a change."""
80
+ def seg(a, b):
81
+ return "".join(lines[a - 1:b])
82
+
83
+ def walk(body, scope):
84
+ anon = 0
85
+ for node in body:
86
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
87
+ yield f"n:{scope}{node.name}", node, "def"
88
+ elif isinstance(node, ast.ClassDef):
89
+ first = min([node.lineno] + [d.lineno for d in node.decorator_list])
90
+ yield f"n:{scope}{node.name}", node, seg(first, node.body[0].lineno - 1) or node.name
91
+ yield from walk(node.body, f"{scope}{node.name}.")
92
+ else:
93
+ names = bound_names(node)
94
+ if names:
95
+ key = f"n:{scope}" + ",".join(sorted(set(names)))
96
+ else:
97
+ anon += 1
98
+ key = f"x:{scope}#{anon}"
99
+ yield key, node, seg(node.lineno, node.end_lineno)
100
+
101
+ yield from walk(tree.body, "")
102
+
103
+
104
+ def py_fingerprint(src: str) -> dict:
105
+ try:
106
+ tree = ast.parse(src)
107
+ except SyntaxError:
108
+ return {"funcs": {}, "stmts": {"x:#syntax": _h(src)}}
109
+ lines = src.splitlines(keepends=True)
110
+ funcs: dict[str, str] = {}
111
+ stmts: dict[str, str] = {}
112
+
113
+ def walk(body, prefix):
114
+ for node in body:
115
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
116
+ first = min([node.lineno] + [d.lineno for d in node.decorator_list])
117
+ funcs[prefix + node.name] = _tok_hash("".join(lines[first - 1:node.end_lineno]))
118
+ elif isinstance(node, ast.ClassDef):
119
+ walk(node.body, prefix + node.name + ".")
120
+
121
+ walk(tree.body, "")
122
+ for key, _node, text in module_statements(tree, lines):
123
+ h = _tok_hash(text)
124
+ # Same names bound twice (try/except import, redefinition): fold into one entry.
125
+ stmts[key] = _h(stmts[key] + h) if key in stmts else h
126
+ return {"funcs": funcs, "stmts": stmts}
127
+
128
+
129
+ def repo_files(root: str) -> list[str]:
130
+ try:
131
+ out = subprocess.run(["git", "ls-files", "-co", "--exclude-standard", "-z"], cwd=root,
132
+ capture_output=True, check=True).stdout
133
+ return sorted(p for p in os.fsdecode(out).split("\0")
134
+ if p and not p.startswith(".testscope/") and os.path.isfile(os.path.join(root, p)))
135
+ except (OSError, subprocess.CalledProcessError):
136
+ files = []
137
+ for d, dirs, names in os.walk(root):
138
+ dirs[:] = [x for x in dirs if not x.startswith(".") and x not in ("venv", "node_modules", "__pycache__")]
139
+ files += [os.path.relpath(os.path.join(d, n), root) for n in names]
140
+ return sorted(files)
141
+
142
+
143
+ def snapshot(root: str, base: dict | None = None) -> dict:
144
+ """Fingerprint every repo file. Files whose bytes match `base` reuse its entry, so
145
+ only changed files are parsed (selection on a big repo stays well under a second)."""
146
+ snap = {}
147
+ base = base or {}
148
+ for rel in repo_files(root):
149
+ try:
150
+ data = open(os.path.join(root, rel), "rb").read()
151
+ except OSError:
152
+ continue
153
+ sha = _h(data)
154
+ if base.get(rel, {}).get("sha") == sha:
155
+ snap[rel] = base[rel]
156
+ elif rel.endswith(".py"):
157
+ fp = py_fingerprint(data.decode("utf-8", "replace"))
158
+ fp["sha"] = sha
159
+ snap[rel] = fp
160
+ else:
161
+ snap[rel] = {"sha": sha}
162
+ return snap
163
+
164
+
165
+ def module_index(snap: dict) -> dict[str, str]:
166
+ """dotted module name -> repo file. Every dotted suffix is a name ("src/pkg/mod.py" ->
167
+ src.pkg.mod, pkg.mod, mod), longest first, so a full path beats a shorter suffix."""
168
+ mods: dict[str, str] = {}
169
+ paths = []
170
+ for rel in snap:
171
+ if rel.endswith(".py"):
172
+ parts = rel[:-3].split("/")
173
+ paths.append((parts[:-1] if parts[-1] == "__init__" else parts, rel))
174
+ for depth in range(max((len(p) for p, _ in paths), default=0), 0, -1):
175
+ for parts, rel in paths:
176
+ if len(parts) >= depth:
177
+ mods.setdefault(".".join(parts[len(parts) - depth:]), rel)
178
+ return mods
179
+
180
+
181
+ def file_imports(rel: str, tree, mods: dict[str, str]) -> dict[str, set[str]]:
182
+ """repo files this file imports -> names taken with `from x import ...` ("*" for a
183
+ star import, empty for `import x` where only attribute access can reach names)."""
184
+ pkg = rel.split("/")[:-1]
185
+ out: dict[str, set[str]] = {}
186
+
187
+ def hit(mod, names=()):
188
+ bits = mod.split(".")
189
+ for i in range(1, len(bits) + 1): # importing a.b.c also runs a/__init__, a/b/__init__
190
+ f = mods.get(".".join(bits[:i]))
191
+ if f and f != rel:
192
+ out.setdefault(f, set())
193
+ f = mods.get(mod)
194
+ if f and f != rel:
195
+ out.setdefault(f, set()).update(names)
196
+
197
+ for node in ast.walk(tree):
198
+ if isinstance(node, ast.Import):
199
+ for a in node.names:
200
+ hit(a.name)
201
+ elif isinstance(node, ast.ImportFrom):
202
+ base = node.module or ""
203
+ if node.level:
204
+ up = pkg[: len(pkg) - node.level + 1] if node.level > 1 else pkg
205
+ base = ".".join(up + ([base] if base else []))
206
+ hit(base, [a.name for a in node.names])
207
+ for a in node.names: # `from pkg import mod` imports a module
208
+ if base and mods.get(f"{base}.{a.name}"):
209
+ hit(f"{base}.{a.name}")
210
+ return out
testscope/plugin.py ADDED
@@ -0,0 +1,268 @@
1
+ """pytest plugin.
2
+
3
+ pytest --testscope-record full run; writes .testscope/map.json (baseline)
4
+ pytest --testscope run only tests the change since the baseline can affect
5
+ TESTSCOPE=on|off|auto auto (default) selects when an AI agent runs pytest
6
+ (CLAUDECODE / CODEX_* in env) and a map exists
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import time
16
+
17
+ import pytest
18
+
19
+ from . import selection as _sel
20
+ from .fingerprint import snapshot
21
+
22
+ BOOT = os.path.join(os.path.dirname(__file__), "_boot")
23
+ AGENT_ENV = ("CLAUDECODE", "CODEX_SANDBOX", "CODEX_THREAD_ID", "CURSOR_AGENT", "GEMINI_CLI")
24
+
25
+
26
+ def pytest_addoption(parser):
27
+ g = parser.getgroup("testscope")
28
+ g.addoption("--testscope", action="store_true", help="run only tests affected by changes since the map")
29
+ g.addoption("--testscope-record", action="store_true", help="run tests and record the dependency map")
30
+ g.addoption("--testscope-off", action="store_true", help="disable testscope selection")
31
+
32
+
33
+ def _mode(config) -> str | None:
34
+ if config.getoption("testscope_off") or os.environ.get("TESTSCOPE") == "off":
35
+ return None
36
+ if config.getoption("testscope_record"):
37
+ return "record"
38
+ if config.getoption("testscope") or os.environ.get("TESTSCOPE") == "on":
39
+ return "select"
40
+ if any(os.environ.get(k) for k in AGENT_ENV):
41
+ # Agent asked for specific files/ids: respect that, do not narrow further.
42
+ for a in config.args:
43
+ if "::" in a or os.path.isfile(a):
44
+ return None
45
+ return "select"
46
+ return None
47
+
48
+
49
+ @pytest.hookimpl(trylast=True)
50
+ def pytest_configure(config):
51
+ mode = _mode(config)
52
+ if mode is None:
53
+ return
54
+ root = str(config.rootpath)
55
+ if mode == "record":
56
+ if sys.version_info < (3, 12):
57
+ raise pytest.UsageError("testscope --testscope-record needs Python 3.12+ (sys.monitoring)")
58
+ config.pluginmanager.register(_Record(config, root), "testscope-record")
59
+ return
60
+ m = _sel.load_map(root)
61
+ if m is None:
62
+ if config.getoption("testscope") or os.environ.get("TESTSCOPE") == "on":
63
+ raise pytest.UsageError("testscope: no map for this version. Run `pytest --testscope-record` "
64
+ "first (or fetch it from CI).")
65
+ return
66
+ config.pluginmanager.register(_Select(config, root, m), "testscope-select")
67
+
68
+
69
+ def _lastfailed(root):
70
+ try:
71
+ return set(json.load(open(os.path.join(root, _sel.MAP_DIR, "lastfailed.json"))))
72
+ except (OSError, ValueError):
73
+ return set()
74
+
75
+
76
+ class _Select:
77
+ def __init__(self, config, root, m):
78
+ self.config, self.root, self.map = config, root, m
79
+ self.sel = _sel.compute(root, m)
80
+ self.failed_before = _lastfailed(root)
81
+ self.ran, self.failed, self.passed = 0, set(), set()
82
+ self.why: dict[str, str] = {}
83
+ # Test files with nothing selected are never imported (collection is most of the
84
+ # cost on a big suite). New files, unknown to the map, are always collected.
85
+ self.known_files = {n.split("::", 1)[0] for n in m["tests"]}
86
+ self.keep_files = {n.split("::", 1)[0] for n in list(self.sel.tests) + list(self.failed_before)}
87
+
88
+ def pytest_ignore_collect(self, collection_path, config):
89
+ if self.sel.full or not collection_path.is_file():
90
+ return None
91
+ rel = os.path.relpath(str(collection_path), self.root)
92
+ if rel not in self.known_files or rel in self.keep_files:
93
+ return None
94
+ if any(rel == p or rel.startswith(p.rstrip("/") + "/") or p == "." for p in self.sel.paths):
95
+ return None
96
+ return True
97
+
98
+ def pytest_report_header(self, config):
99
+ s = self.sel
100
+ if s.full:
101
+ return f"testscope: full run — {s.full}"
102
+ return (f"testscope: {len(s.changed)} changed file(s) since map {self.map.get('commit', '')[:10]}; "
103
+ f"running affected tests only (TESTSCOPE=off for all)")
104
+
105
+ def pytest_collection_modifyitems(self, config, items):
106
+ keep, drop = [], []
107
+ known = self.map["tests"]
108
+ for it in items:
109
+ why = self.sel.wants(it.nodeid, it.nodeid in known)
110
+ if why is None and it.nodeid in self.failed_before:
111
+ why = "failed last run"
112
+ if why is None:
113
+ drop.append(it)
114
+ else:
115
+ keep.append(it)
116
+ self.why[it.nodeid] = why
117
+ if drop:
118
+ config.hook.pytest_deselected(items=drop)
119
+ items[:] = keep
120
+ self._write_why()
121
+
122
+ def _write_why(self):
123
+ d = os.path.join(self.root, _sel.MAP_DIR)
124
+ os.makedirs(d, exist_ok=True)
125
+ with open(os.path.join(d, "last-selection.json"), "w") as fh:
126
+ json.dump({"changed": self.sel.changed, "unobserved": self.sel.unobserved,
127
+ "full": self.sel.full, "selected": self.why}, fh, indent=1)
128
+
129
+ def pytest_runtest_logreport(self, report):
130
+ if report.when == "call" or report.outcome == "failed":
131
+ if report.failed:
132
+ self.failed.add(report.nodeid)
133
+ elif report.when == "call":
134
+ self.passed.add(report.nodeid)
135
+
136
+ def pytest_sessionfinish(self, session):
137
+ if hasattr(self.config, "workerinput"):
138
+ return
139
+ lf = (self.failed_before - self.passed) | self.failed
140
+ with open(os.path.join(self.root, _sel.MAP_DIR, "lastfailed.json"), "w") as fh:
141
+ json.dump(sorted(lf), fh)
142
+ if session.exitstatus == pytest.ExitCode.NO_TESTS_COLLECTED and not self.sel.full:
143
+ session.exitstatus = pytest.ExitCode.OK # nothing affected is a pass, not an error
144
+
145
+ def pytest_terminal_summary(self, terminalreporter):
146
+ s = self.sel
147
+ total = len(self.map["tests"])
148
+ n = len(self.passed | self.failed)
149
+ tr = terminalreporter
150
+ tr.write_sep("-", "testscope")
151
+ if s.full:
152
+ tr.write_line(f"full run: {s.full}")
153
+ elif not s.changed:
154
+ tr.write_line(f"no changes since the map; ran {n} test(s) that failed last time")
155
+ else:
156
+ tr.write_line(f"ran {n} of ~{total} tests affected by: {', '.join(s.changed[:8])}"
157
+ + (" ..." if len(s.changed) > 8 else ""))
158
+ if s.unobserved:
159
+ tr.write_line(f"no recorded test touches: {', '.join(s.unobserved[:8])} "
160
+ f"(run the full suite if these matter)")
161
+ tr.write_line("why each test ran: .testscope/last-selection.json · full suite: TESTSCOPE=off pytest")
162
+
163
+
164
+ class _Record:
165
+ def __init__(self, config, root):
166
+ from .recorder import Recorder
167
+
168
+ self.config, self.root = config, root
169
+ self.rec = Recorder(root)
170
+ self.rec.install()
171
+ self.deps: dict[str, int] = {}
172
+ self.tests: dict[str, set[int]] = {}
173
+ self.module_deps: dict[str, set[int]] = {}
174
+ self.tmp = os.path.join(root, _sel.MAP_DIR, "tmp", os.environ.get("PYTEST_XDIST_WORKER", "main"))
175
+ shutil.rmtree(self.tmp, ignore_errors=True)
176
+ os.makedirs(self.tmp, exist_ok=True)
177
+ self.n = 0
178
+ self.failed: set[str] = set()
179
+
180
+ def _ids(self, funcs, files, dirs):
181
+ out = set()
182
+ for f, q in funcs:
183
+ out.add(self.deps.setdefault(f"f:{f}::{q}", len(self.deps)))
184
+ for f in files:
185
+ out.add(self.deps.setdefault(f"r:{f}", len(self.deps)))
186
+ for d in dirs:
187
+ out.add(self.deps.setdefault(f"d:{d}", len(self.deps)))
188
+ return out
189
+
190
+ # Import-time code of a test module runs during collection: charge it to the file.
191
+ @pytest.hookimpl(hookwrapper=True)
192
+ def pytest_make_collect_report(self, collector):
193
+ is_mod = isinstance(collector, pytest.Module)
194
+ if is_mod:
195
+ self.rec.start()
196
+ yield
197
+ if is_mod:
198
+ path = os.path.relpath(str(collector.path), self.root)
199
+ self.module_deps[path] = self._ids(*self.rec.stop())
200
+
201
+ @pytest.hookimpl(hookwrapper=True)
202
+ def pytest_runtest_protocol(self, item, nextitem):
203
+ self.n += 1
204
+ out = os.path.join(self.tmp, str(self.n))
205
+ os.makedirs(out, exist_ok=True)
206
+ saved = {k: os.environ.get(k) for k in ("TESTSCOPE_OUT", "TESTSCOPE_ROOT", "PYTHONPATH")}
207
+ os.environ["TESTSCOPE_OUT"], os.environ["TESTSCOPE_ROOT"] = out, self.root
208
+ os.environ["PYTHONPATH"] = os.pathsep.join([BOOT] + ([saved["PYTHONPATH"]] if saved["PYTHONPATH"] else []))
209
+ self.rec.start()
210
+ try:
211
+ yield
212
+ finally:
213
+ ids = self._ids(*self.rec.stop())
214
+ for k, v in saved.items():
215
+ if v is None:
216
+ os.environ.pop(k, None)
217
+ else:
218
+ os.environ[k] = v
219
+ for name in os.listdir(out):
220
+ try:
221
+ d = json.load(open(os.path.join(out, name)))
222
+ ids |= self._ids([tuple(x) for x in d["funcs"]], d["files"], d["dirs"])
223
+ except (OSError, ValueError, KeyError):
224
+ pass
225
+ shutil.rmtree(out, ignore_errors=True)
226
+ path = item.nodeid.split("::", 1)[0]
227
+ self.tests[item.nodeid] = ids | self.module_deps.get(path, set())
228
+
229
+ def pytest_runtest_logreport(self, report):
230
+ if report.failed:
231
+ self.failed.add(report.nodeid)
232
+
233
+ def _shard(self):
234
+ names = sorted(self.deps, key=self.deps.get)
235
+ return {"deps": names, "tests": {k: sorted(v) for k, v in self.tests.items()}}
236
+
237
+ def pytest_sessionfinish(self, session):
238
+ d = os.path.join(self.root, _sel.MAP_DIR)
239
+ wid = getattr(self.config, "workerinput", {}).get("workerid")
240
+ if wid:
241
+ with open(os.path.join(d, f"shard-{wid}.json"), "w") as fh:
242
+ json.dump(self._shard(), fh)
243
+ return
244
+ shards = [self._shard()] if self.tests else []
245
+ for name in sorted(os.listdir(d)):
246
+ if name.startswith("shard-"):
247
+ shards.append(json.load(open(os.path.join(d, name))))
248
+ os.remove(os.path.join(d, name))
249
+ deps: dict[str, int] = {}
250
+ tests: dict[str, list[int]] = {}
251
+ for sh in shards:
252
+ for nid, ids in sh["tests"].items():
253
+ tests[nid] = sorted({deps.setdefault(sh["deps"][i], len(deps)) for i in ids})
254
+ try:
255
+ commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=self.root, capture_output=True,
256
+ text=True).stdout.strip()
257
+ except OSError:
258
+ commit = ""
259
+ m = {"version": _sel.MAP_VERSION, "created": int(time.time()), "commit": commit,
260
+ "python": sys.version.split()[0], "snap": snapshot(self.root),
261
+ "deps": sorted(deps, key=deps.get), "tests": tests}
262
+ with open(os.path.join(d, "map.json"), "w") as fh:
263
+ json.dump(m, fh, separators=(",", ":"))
264
+ shutil.rmtree(os.path.join(d, "tmp"), ignore_errors=True)
265
+ with open(os.path.join(d, "lastfailed.json"), "w") as fh:
266
+ json.dump(sorted(self.failed), fh)
267
+ session.config.pluginmanager.get_plugin("terminalreporter").write_line(
268
+ f"testscope: recorded {len(tests)} tests, {len(deps)} deps -> {_sel.MAP_DIR}/map.json")
testscope/recorder.py ADDED
@@ -0,0 +1,86 @@
1
+ """Records what a test touches: Python functions it runs, repo files it opens/lists/execs.
2
+
3
+ Function deps use sys.monitoring PY_START and return DISABLE, so each code object
4
+ costs one callback per test (restart_events re-arms them), not one per line.
5
+ Imported by the pytest plugin and, in child Python processes, by _boot/sitecustomize.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import sys
11
+
12
+ TOOL_ID = 4 # 0-2 and 5 are named (debugger, coverage, profiler, optimizer)
13
+ _SKIP_PARTS = (os.sep + ".git" + os.sep, os.sep + ".testscope" + os.sep, os.sep + "__pycache__" + os.sep,
14
+ os.sep + "site-packages" + os.sep, os.sep + ".venv" + os.sep, os.sep + "venv" + os.sep)
15
+
16
+
17
+ class Recorder:
18
+ def __init__(self, root: str):
19
+ self.root = os.path.realpath(root) + os.sep
20
+ self.funcs: set[tuple[str, str]] = set() # (relpath, qualname)
21
+ self.files: set[str] = set() # data files read or executed
22
+ self.dirs: set[str] = set() # directories listed
23
+ self.active = False
24
+ self._rel: dict[str, str | None] = {}
25
+
26
+ def rel(self, path) -> str | None:
27
+ if isinstance(path, bytes):
28
+ path = os.fsdecode(path)
29
+ if not isinstance(path, str):
30
+ return None
31
+ r = self._rel.get(path, "")
32
+ if r != "":
33
+ return r
34
+ full = os.path.realpath(path)
35
+ r = None
36
+ if full.startswith(self.root) and not any(p in full + os.sep for p in _SKIP_PARTS):
37
+ r = full[len(self.root):]
38
+ self._rel[path] = r
39
+ return r
40
+
41
+ # -- sys.monitoring -------------------------------------------------
42
+ def _on_start(self, code, offset):
43
+ if self.active:
44
+ r = self.rel(code.co_filename)
45
+ if r is not None and r.endswith(".py"):
46
+ self.funcs.add((r, code.co_qualname))
47
+ return sys.monitoring.DISABLE
48
+ # Not recording right now: keep the event armed so the next test sees it.
49
+ return None
50
+
51
+ # -- audit events ---------------------------------------------------
52
+ def _on_audit(self, event, args):
53
+ if not self.active:
54
+ return
55
+ if event == "open":
56
+ r = self.rel(args[0])
57
+ if r is not None and not r.endswith((".py", ".pyc")):
58
+ self.files.add(r)
59
+ elif event in ("os.listdir", "os.scandir"):
60
+ r = self.rel(args[0] if args and args[0] is not None else ".")
61
+ if r is not None:
62
+ self.dirs.add(r.rstrip(os.sep))
63
+ elif event == "subprocess.Popen":
64
+ argv = args[1]
65
+ if isinstance(argv, (str, bytes)):
66
+ argv = [argv]
67
+ for a in argv or ():
68
+ r = self.rel(a)
69
+ if r is not None and os.path.isfile(self.root + r):
70
+ self.files.add(r)
71
+
72
+ def install(self):
73
+ mon = sys.monitoring
74
+ mon.use_tool_id(TOOL_ID, "testscope")
75
+ mon.register_callback(TOOL_ID, mon.events.PY_START, self._on_start)
76
+ mon.set_events(TOOL_ID, mon.events.PY_START)
77
+ sys.addaudithook(self._on_audit) # cannot be removed; gated by self.active
78
+
79
+ def start(self):
80
+ self.funcs, self.files, self.dirs = set(), set(), set()
81
+ sys.monitoring.restart_events()
82
+ self.active = True
83
+
84
+ def stop(self):
85
+ self.active = False
86
+ return self.funcs, self.files, self.dirs
testscope/selection.py ADDED
@@ -0,0 +1,267 @@
1
+ """Map a change (current tree vs the recorded baseline) to the tests it can affect."""
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ import fnmatch
6
+ import json
7
+ import os
8
+ from collections import defaultdict
9
+
10
+ from .fingerprint import file_imports, module_index, module_statements, referenced_names, snapshot
11
+
12
+ # A change to any of these can change every test's behavior: run everything.
13
+ FULL_RUN = ["pyproject.toml", "setup.py", "setup.cfg", "tox.ini", "pytest.ini", "noxfile.py",
14
+ "requirements*.txt", "*.lock", "Pipfile", ".python-version", "constraints*.txt"]
15
+ # Changes here cannot affect a test run.
16
+ IGNORE = ["*.md", "*.rst", "docs/*", "LICENSE*", "CHANGELOG*", ".github/*", "*.png", "*.jpg", "*.svg", "*.gif"]
17
+
18
+ MAP_DIR = ".testscope"
19
+ MAP_VERSION = 2
20
+ CANARIES = 5
21
+ SCRIPTS = (".sh", ".bash", ".zsh")
22
+
23
+
24
+ def load_map(root: str) -> dict | None:
25
+ try:
26
+ with open(os.path.join(root, MAP_DIR, "map.json")) as fh:
27
+ m = json.load(fh)
28
+ except (OSError, ValueError):
29
+ return None
30
+ return m if m.get("version") == MAP_VERSION else None
31
+
32
+
33
+ def _match(rel: str, pats) -> bool:
34
+ return any(fnmatch.fnmatch(rel, p) or fnmatch.fnmatch(os.path.basename(rel), p) for p in pats)
35
+
36
+
37
+ class Selection:
38
+ def __init__(self):
39
+ self.full: str | None = None # reason to run everything
40
+ self.tests: dict[str, str] = {} # nodeid -> reason
41
+ self.paths: dict[str, str] = {} # path prefix -> reason (whole file / dir)
42
+ self.changed: list[str] = []
43
+ self.unobserved: list[str] = [] # changed, but no recorded test touched it
44
+
45
+ def wants(self, nodeid: str, known: bool) -> str | None:
46
+ if self.full:
47
+ return self.full
48
+ if not known:
49
+ return "new test (not in map)"
50
+ if nodeid in self.tests:
51
+ return self.tests[nodeid]
52
+ path = nodeid.split("::", 1)[0]
53
+ for pre, why in self.paths.items():
54
+ if path == pre or path.startswith(pre.rstrip("/") + "/"):
55
+ return why
56
+ return None
57
+
58
+
59
+ class _Src:
60
+ """Lazily parsed current sources, plus who imports whom."""
61
+
62
+ def __init__(self, root, snap):
63
+ self.root, self.snap = root, snap
64
+ self.mods = module_index(snap)
65
+ self._trees: dict[str, tuple] = {}
66
+ self._importers: dict[str, dict[str, set[str]]] | None = None
67
+
68
+ def tree(self, rel):
69
+ if rel not in self._trees:
70
+ try:
71
+ src = open(os.path.join(self.root, rel), encoding="utf-8", errors="replace").read()
72
+ self._trees[rel] = (ast.parse(src), src.splitlines(keepends=True))
73
+ except (OSError, SyntaxError, ValueError):
74
+ self._trees[rel] = (None, [])
75
+ return self._trees[rel]
76
+
77
+ def importers(self, rel) -> dict[str, set[str]]:
78
+ """files that import rel directly -> names they take from it."""
79
+ if self._importers is None:
80
+ self._importers = defaultdict(dict)
81
+ for g in self.snap:
82
+ if g.endswith(".py"):
83
+ t, _ = self.tree(g)
84
+ if t is not None:
85
+ for f, names in file_imports(g, t, self.mods).items():
86
+ self._importers[f][g] = names
87
+ return self._importers.get(rel, {})
88
+
89
+
90
+ def _split_key(key):
91
+ """'n:C.a,b' -> ('C.', {'a','b'})"""
92
+ rest = key[2:]
93
+ scope, _, names = rest.rpartition(".")
94
+ return (scope + "." if scope else ""), set(names.split(","))
95
+
96
+
97
+ def compute(root: str, m: dict, snap: dict | None = None) -> Selection:
98
+ sel = Selection()
99
+ base = m["snap"]
100
+ snap = snapshot(root, base) if snap is None else snap
101
+ changed = sorted(f for f in set(base) | set(snap)
102
+ if base.get(f, {}).get("sha") != snap.get(f, {}).get("sha"))
103
+ sel.changed = changed
104
+ if not sel.changed:
105
+ return sel
106
+ for f in sel.changed:
107
+ if _match(f, FULL_RUN):
108
+ sel.full = f"{f} changed (environment/config)"
109
+ return sel
110
+
111
+ deps, tests = m["deps"], m["tests"]
112
+ users: dict[int, list[str]] = defaultdict(list) # dep id -> tests holding it
113
+ for nid, ids in tests.items():
114
+ for i in ids:
115
+ users[i].append(nid)
116
+ by_file: dict[str, list[tuple[str, int]]] = defaultdict(list) # py file -> [(qualname, dep id)]
117
+ reads: dict[str, int] = {}
118
+ lists: dict[str, int] = {}
119
+ for i, d in enumerate(deps):
120
+ kind, _, rest = d.partition(":")
121
+ if kind == "f":
122
+ f, _, q = rest.partition("::")
123
+ by_file[f].append((q, i))
124
+ elif kind == "r":
125
+ reads[rest] = i
126
+ elif kind == "d":
127
+ lists[rest] = i
128
+ test_files = {nid.split("::", 1)[0] for nid in tests}
129
+ src = _Src(root, snap)
130
+
131
+ def add(nids, why):
132
+ for n in nids:
133
+ sel.tests.setdefault(n, why)
134
+
135
+ def code_users(f, pred, why):
136
+ for q, i in by_file.get(f, ()):
137
+ if pred(q):
138
+ add(users[i], why)
139
+
140
+ def func_changed(f, qual, why): # recorded qualname q ran inside qual (nested, lambdas)
141
+ code_users(f, lambda q: q == qual or q.startswith(qual + "."), why)
142
+
143
+ names_todo: list[tuple[str, set[str], str]] = [] # (file, changed names, why)
144
+ canaries: list[str] = []
145
+
146
+ for f in sel.changed:
147
+ old, new = base.get(f) or {}, snap.get(f) or {}
148
+ hit_before = len(sel.tests) + len(sel.paths)
149
+ if f.endswith(".py"):
150
+ ofn, nfn = old.get("funcs", {}), new.get("funcs", {})
151
+ for q in set(ofn) | set(nfn):
152
+ if ofn.get(q) != nfn.get(q):
153
+ func_changed(f, q, f"{f}::{q} changed")
154
+ ost, nst = old.get("stmts", {}), new.get("stmts", {})
155
+ if ost != nst:
156
+ # Any module-level edit can make the import itself raise, which breaks every
157
+ # importer whether or not it reads the changed name. A few tests that ran this
158
+ # module's import code surface that. ponytail: 5 canaries; raise if needed.
159
+ canaries.append(f)
160
+ for key in set(ost) | set(nst):
161
+ if ost.get(key) == nst.get(key):
162
+ continue
163
+ if key.startswith("x:"): # binds nothing (bare call, docstring): anything in f
164
+ why = f"{f}: module-level code changed"
165
+ code_users(f, lambda q: True, why)
166
+ if f in test_files:
167
+ sel.paths[f] = why
168
+ if os.path.basename(f) == "conftest.py":
169
+ sel.paths[os.path.dirname(f) or "."] = why
170
+ continue
171
+ scope, names = _split_key(key)
172
+ why = f"{f}: {scope}{','.join(sorted(names))} changed"
173
+ if scope: # class attribute: tests that used the class
174
+ code_users(f, lambda q, c=scope: q.startswith(c), why)
175
+ names_todo.append((f, names, why))
176
+ if f in reads:
177
+ add(users[reads[f]], f"{f} read by test")
178
+ if (not old or not new) and os.path.dirname(f) in lists:
179
+ add(users[lists[os.path.dirname(f)]], f"{f} added/removed in a listed dir")
180
+ if len(sel.tests) + len(sel.paths) == hit_before and not f.endswith(".py") and not _match(f, IGNORE):
181
+ sel.unobserved.append(f)
182
+
183
+ _propagate(names_todo, src, test_files, func_changed, code_users)
184
+ _referenced_data(root, [f for f in sel.changed if not f.endswith(".py")], reads, users, add)
185
+ for f in canaries: # after real reasons, so those win in the report
186
+ ran_import = sorted({n for q, i in by_file.get(f, ()) if q == "<module>" for n in users[i]})
187
+ add(ran_import[:CANARIES], f"{f}: import canary (module-level change)")
188
+ return sel
189
+
190
+
191
+ def _referenced_data(root, changed, reads, users, add):
192
+ """Files no test opens directly (a script `source`d by another script, a config included
193
+ by another config) are reached through a file tests did read that names them."""
194
+ texts: dict[str, str] = {}
195
+
196
+ def text(rel):
197
+ if rel not in texts:
198
+ try:
199
+ with open(os.path.join(root, rel), "rb") as fh:
200
+ b = fh.read(1 << 20)
201
+ texts[rel] = "" if b"\0" in b else b.decode("utf-8", "replace")
202
+ except OSError:
203
+ texts[rel] = ""
204
+ return texts[rel]
205
+
206
+ seen, todo = set(changed), list(changed)
207
+ while todo:
208
+ f = todo.pop()
209
+ name = os.path.basename(f)
210
+ for x, i in reads.items():
211
+ if x in seen or _match(x, IGNORE) or name not in text(x):
212
+ continue # docs name files without loading them
213
+ add(users[i], f"{x} references {f}")
214
+ seen.add(x)
215
+ if x.endswith(SCRIPTS): # a script sourcing a script sourcing ...; data stops at one hop
216
+ todo.append(x)
217
+
218
+
219
+ def _propagate(todo, src, test_files, func_changed, code_users):
220
+ """A changed name selects code that reads it: in its own file, and in files that
221
+ import it. Module-level statements that read it make their own names changed too."""
222
+ seen: set[tuple[str, str]] = set()
223
+ while todo:
224
+ f, names, why = todo.pop()
225
+ names = {n for n in names if (f, n) not in seen}
226
+ if not names:
227
+ continue
228
+ seen |= {(f, n) for n in names}
229
+ cands = {f: None, **src.importers(f)} # None: same file, every reference counts
230
+ if os.path.basename(f) == "conftest.py": # fixtures reach tests by parameter name
231
+ d = os.path.dirname(f)
232
+ cands.update({t: None for t in test_files if not d or t.startswith(d + "/")})
233
+ for g, taken in cands.items():
234
+ tree, lines = src.tree(g)
235
+ if tree is None:
236
+ continue
237
+ via_from = names if taken is None or "*" in taken else names & taken
238
+
239
+ def reads(node):
240
+ bare, attr = referenced_names(node)
241
+ return (bare & via_from) | (attr & names)
242
+
243
+ for qual, node in _functions(tree):
244
+ if reads(node):
245
+ func_changed(g, qual, why)
246
+ for key, node, _text in module_statements(tree, lines):
247
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
248
+ continue
249
+ target = ast.Module(body=node.bases + node.keywords + node.decorator_list, type_ignores=[]) \
250
+ if isinstance(node, ast.ClassDef) else node
251
+ if not reads(target):
252
+ continue
253
+ if isinstance(node, ast.ClassDef): # base class / decorator changed
254
+ code_users(g, lambda q, c=node.name + ".": q.startswith(c), why)
255
+ continue
256
+ if key.startswith("x:"):
257
+ code_users(g, lambda q: True, why)
258
+ continue
259
+ todo.append((g, _split_key(key)[1], why))
260
+
261
+
262
+ def _functions(tree, prefix=""):
263
+ for node in tree.body if isinstance(tree, ast.Module) else tree:
264
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
265
+ yield prefix + node.name, node
266
+ elif isinstance(node, ast.ClassDef):
267
+ yield from _functions(node.body, prefix + node.name + ".")
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.5
2
+ Name: testscope
3
+ Version: 0.1.0
4
+ Summary: Run only the tests a change can affect. Built for AI coding agents and CI.
5
+ Project-URL: Homepage, https://github.com/Ar9av/testscope
6
+ Project-URL: Issues, https://github.com/Ar9av/testscope/issues
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: ai agents,ci,claude code,pytest,regression test selection,test impact analysis
10
+ Classifier: Framework :: Pytest
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Testing
13
+ Requires-Python: >=3.9
14
+ Requires-Dist: pytest>=7
15
+ Description-Content-Type: text/markdown
16
+
17
+ # testscope
18
+
19
+ Run only the tests your change can affect. Built for AI coding agents and CI.
20
+
21
+ Coding agents run `pytest` after every edit. On a 6,000-test suite that is minutes per
22
+ run. It goes past Claude Code's ~2-minute foreground limit, so the run moves to the
23
+ background and the agent stops reading its output. testscope records which code and
24
+ files each test really touches. After that, plain `pytest` runs only the tests your
25
+ change can reach.
26
+
27
+ ![testscope picks 71 of 6,162 tests for a one-file change](https://raw.githubusercontent.com/Ar9av/testscope/master/assets/demo.gif)
28
+
29
+ On a real 6,195-test project, over its last 30 commits:
30
+
31
+ ![Median tests run per change: full suite 6,195, testmon 584, testscope 353](https://raw.githubusercontent.com/Ar9av/testscope/master/assets/selection.svg)
32
+
33
+ | | testscope | pytest-testmon | import graph |
34
+ |---|---|---|---|
35
+ | Median tests run per real commit (of 6,195) | **353** | 584 | 352 files of 378 |
36
+ | Injected faults caught (34 that break a test) | **33** | 22 | 22 |
37
+ | Faults in data files caught (YAML, JSON, shell) | **10 / 10** | 0 / 10 | 0 / 10 |
38
+ | Recording overhead on a 3m36s suite | none measured | +23 s | - |
39
+
40
+ Method, caveats and raw data: [`bench/RESULTS.md`](bench/RESULTS.md).
41
+
42
+ ```bash
43
+ pip install testscope
44
+ pytest --testscope-record # once (or in CI on main): full run + dependency map
45
+ # ... edit code ...
46
+ pytest --testscope # only affected tests
47
+ ```
48
+
49
+ When Claude Code runs pytest (it sets `CLAUDECODE=1`) and a map exists, selection turns
50
+ on automatically. The agent needs no new command and no hook. For other agents, export
51
+ `TESTSCOPE=on` in their environment.
52
+ `TESTSCOPE=off pytest` always runs everything. Explicit targets
53
+ (`pytest tests/test_x.py::test_y`) are never narrowed.
54
+
55
+ ## What it tracks
56
+
57
+ | Dependency | How | testmon | import graph |
58
+ |---|---|---|---|
59
+ | Functions a test runs | `sys.monitoring` PY_START, disabled after the first hit, re-armed per test | yes (coverage) | no |
60
+ | Code run in child Python processes | `sitecustomize` on `PYTHONPATH`, tagged with the running test | no | no |
61
+ | Data files read (YAML, JSON, fixtures, shell scripts run) | audit hooks: `open`, `subprocess.Popen` | no | no |
62
+ | Files added to / removed from a listed directory | audit hooks: `os.listdir`, `os.scandir` | no | no |
63
+ | Module-level code (constants, decorators, class bodies) | by name: tests that ran code reading the changed name, in this module or its importers; plus up to 5 tests that import the module, to catch import crashes | yes | yes |
64
+ | Data files named by other files (a script that sources `_lib.sh`, a config that names a fixture) | one hop from files tests read; chains only through shell scripts | no | no |
65
+ | Config / lockfile change (`pyproject.toml`, `*.lock`, `requirements*.txt`, …) | full run | full run | no |
66
+ | Tests that failed last run | always rerun | yes | no |
67
+
68
+ Fingerprints are token-stream hashes without line numbers or comments, so moving code or
69
+ changing a comment selects nothing. The map is a *baseline*. Selection compares
70
+ the working tree with it by content, so it works on uncommitted edits and on
71
+ branches built from an older main. As you edit, the selection can only grow.
72
+ Re-record to reset it.
73
+
74
+ ## CI
75
+
76
+ [`examples/github-actions.yml`](examples/github-actions.yml):
77
+
78
+ - **push to main:** `pytest --testscope-record`; the map goes into the Actions cache.
79
+ - **pull requests:** restore the newest map; `pytest --testscope`.
80
+ - **merge queue + nightly:** plain full run. This is the safety net for what any selector can miss.
81
+
82
+ ## Limits
83
+
84
+ - Recording needs Python 3.12+ (`sys.monitoring`). Selection works on any 3.9+.
85
+ - A test that starts a child process with a scrubbed environment (`env={}`), or with
86
+ `python -I` / `-E`, hides that child's deps. Shell scripts that read files themselves
87
+ are seen only as "script ran".
88
+ - Network services, databases and time are not dependencies. A flaky test stays flaky.
89
+ - Installing or upgrading a package is not detected. Re-record after dependency changes
90
+ (a lockfile or `requirements*.txt` edit already triggers a full run).
91
+ - A module-level edit runs at most 5 "import canary" tests for crashes at import time.
92
+ - `eval`/`exec` strings and other dynamic code that no recorded test reached cannot be mapped.
93
+
94
+ ## Evidence
95
+
96
+ [`bench/RESULTS.md`](bench/RESULTS.md): real commits and fault injection on one 6,195-test
97
+ project. For each injected fault, a full-suite run gives the ground truth. Missed files are
98
+ rerun to rule out flaky tests. The harness is in [`bench/`](bench/), so you can run it on
99
+ your own suite.
@@ -0,0 +1,11 @@
1
+ testscope/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ testscope/fingerprint.py,sha256=8Ow3zTF12J89n_E353l3805JX_pQ76qc8O7Hn3T595A,8504
3
+ testscope/plugin.py,sha256=jnji6hxmXO1ypPVb-Uh3pycSOlzZcR93RhCibLpfa1E,11373
4
+ testscope/recorder.py,sha256=48x94kUds2MJmU6BjXoUU3vEPrapBrGLE3dMcSec0y0,3407
5
+ testscope/selection.py,sha256=inmV5Y3tJj5zO6VbvjgWwBw_jcjdDzTd-sWbgr0Bi-0,11248
6
+ testscope/_boot/sitecustomize.py,sha256=aHh-Ll4jcQNu98xto0WZPwDsCbS489xqo1o-uAC6q3U,1620
7
+ testscope-0.1.0.dist-info/METADATA,sha256=pBAE6JXKKdvES8dMOzdAcebdrFw_V5TiD4jnrOofOwA,5202
8
+ testscope-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ testscope-0.1.0.dist-info/entry_points.txt,sha256=nQeRfwKQMbtAUpF8_k-CvynLTSPaahV9Soa5BtpZNR8,40
10
+ testscope-0.1.0.dist-info/licenses/LICENSE,sha256=h_lhleogl0kIcvBYU4xbXxcTG4yuEIpqx_1R4dtXEMs,11337
11
+ testscope-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [pytest11]
2
+ testscope = testscope.plugin
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Prismor
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.