systemap 1.0.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.
systemap/__init__.py ADDED
@@ -0,0 +1,48 @@
1
+ """systemap: the map your coding agent draws of your system.
2
+
3
+ Facts are read out of the code with `ast`; the meaning is authored by a
4
+ coding agent following the shipped skill and reviewed by a person; the map
5
+ draws what exists today; the checker refuses an incomplete or stale map;
6
+ and one generator draws every picture so nothing drifts.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from systemap.model import (
12
+ AGENT_KINDS,
13
+ KINDS,
14
+ STANDARD_KINDS,
15
+ Component,
16
+ Container,
17
+ Flow,
18
+ Invariant,
19
+ Journey,
20
+ Layer,
21
+ Meaning,
22
+ Model,
23
+ Region,
24
+ Step,
25
+ all_layers,
26
+ build_state,
27
+ )
28
+
29
+ __version__ = "1.0.0"
30
+
31
+ __all__ = [
32
+ "AGENT_KINDS",
33
+ "KINDS",
34
+ "STANDARD_KINDS",
35
+ "Component",
36
+ "Container",
37
+ "Flow",
38
+ "Invariant",
39
+ "Journey",
40
+ "Layer",
41
+ "Meaning",
42
+ "Model",
43
+ "Region",
44
+ "Step",
45
+ "__version__",
46
+ "all_layers",
47
+ "build_state",
48
+ ]
systemap/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ from __future__ import annotations
2
+
3
+ from systemap.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
systemap/change.py ADDED
@@ -0,0 +1,328 @@
1
+ """Work out what a branch changes about the system, in logical terms.
2
+
3
+ A change view needs more than "these files differ". It needs to know which
4
+ components moved, what each one gained or lost, which exported names were
5
+ redefined on the wire, and how far the change reaches. Reach is computed here
6
+ rather than left to the reader, because "what does this affect" is the
7
+ question a change view exists to answer.
8
+
9
+ Everything is derived from the same primitives the map itself uses: the
10
+ public surface of a module is `extract.parse_surface` applied to the git
11
+ blob on each side of the diff, and reach follows the name-level imports the
12
+ facts record. Two answers about the same module can therefore never disagree,
13
+ because there is only one definition of what the module exports.
14
+
15
+ Reach and redefinition answer different questions on purpose. Reach is
16
+ behavioral: any edit to a module can change the behavior of everything that
17
+ imports it, so every direct importer is reached. Redefinition is interface:
18
+ only an exported name whose definition changed, and that some other module
19
+ imports by name, counts as redefined on the wire. A whole-module import
20
+ (`import m`) hides which names are used, so it contributes reach but never a
21
+ named artifact; that blind spot is accepted rather than guessed at.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import subprocess
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ from systemap.config import Config
32
+ from systemap.extract import (
33
+ WHOLE_MODULE,
34
+ internal_uses,
35
+ module_of,
36
+ parse_surface,
37
+ test_names,
38
+ )
39
+ from systemap.model import Model, module_matches
40
+
41
+ # `gained` carries only the buckets the schematic's segmented bar draws
42
+ # (operations, types, refusals, tests), so its +N badge always equals the sum
43
+ # of the segments; constants stay in the surface detail.
44
+ BUCKETS = ("operations", "types", "refusals", "constants")
45
+
46
+
47
+ def _run(args: list[str], cwd: Path) -> str:
48
+ proc = subprocess.run(args, cwd=cwd, capture_output=True, text=True, timeout=90)
49
+ return proc.stdout if proc.returncode == 0 else ""
50
+
51
+
52
+ def _show(repo: Path, ref: str, path: str) -> str:
53
+ """The file's content at a ref, or empty where it does not exist there."""
54
+ return _run(["git", "show", f"{ref}:{path}"], repo)
55
+
56
+
57
+ def pr_meta(repo: Path, pr: str) -> dict[str, Any]:
58
+ """Title and counts for a PR, or empty if gh cannot answer."""
59
+ if not pr:
60
+ return {}
61
+ raw = _run(
62
+ [
63
+ "gh",
64
+ "pr",
65
+ "view",
66
+ pr,
67
+ "--json",
68
+ "number,title,url,additions,deletions,changedFiles,state",
69
+ ],
70
+ repo,
71
+ )
72
+ try:
73
+ return dict(json.loads(raw)) if raw else {}
74
+ except json.JSONDecodeError:
75
+ return {}
76
+
77
+
78
+ def _changed_files(repo: Path, merge_base: str, head: str) -> list[str]:
79
+ """Every path the diff touches, split on NUL so spaces in names survive."""
80
+ out = _run(["git", "diff", "--name-only", "-z", merge_base, head, "--no-renames"], repo)
81
+ return [f for f in out.split("\0") if f]
82
+
83
+
84
+ def _path_module(repo: Path, path: str, roots: list[tuple[Path, str]]) -> str | None:
85
+ """The dotted module a repo-relative path implements, or None.
86
+
87
+ Derived from the path alone so a file DELETED by the branch still maps:
88
+ the facts are built from the head tree and cannot know a module that is
89
+ gone from it.
90
+ """
91
+ if not path.endswith(".py"):
92
+ return None
93
+ absolute = repo / path
94
+ for pkg_dir, pkg_name in roots:
95
+ if absolute.is_relative_to(pkg_dir):
96
+ return module_of(absolute, pkg_dir, pkg_name)
97
+ return None
98
+
99
+
100
+ def _is_test_file(path: str, tests_dirs: tuple[str, ...]) -> bool:
101
+ if not path.endswith(".py") or not path.split("/")[-1].startswith("test_"):
102
+ return False
103
+ return any(rel and path.startswith(rel.rstrip("/") + "/") for rel in tests_dirs)
104
+
105
+
106
+ def _empty_surface() -> dict[str, Any]:
107
+ return {"functions": [], "classes": [], "errors": [], "constants": []}
108
+
109
+
110
+ def _identity(surface: dict[str, Any]) -> dict[str, dict[str, str]]:
111
+ """bucket -> name -> the fingerprint whose change means redefinition."""
112
+ return {
113
+ "operations": {f["name"]: f["signature"] for f in surface["functions"]},
114
+ "types": {c["name"]: ",".join(c["methods"]) for c in surface["classes"]},
115
+ "refusals": {e["name"]: ",".join(e["methods"]) for e in surface["errors"]},
116
+ "constants": {c["name"]: c["value"] for c in surface["constants"]},
117
+ }
118
+
119
+
120
+ def surface_delta(base_raw: str, head_raw: str) -> dict[str, Any] | None:
121
+ """What one module's public surface gained, lost, and changed.
122
+
123
+ None means a side had source that does not parse, which is "cannot tell",
124
+ never "nothing changed".
125
+ """
126
+ base = parse_surface(base_raw) if base_raw else _empty_surface()
127
+ head = parse_surface(head_raw) if head_raw else _empty_surface()
128
+ if base is None or head is None:
129
+ return None
130
+ before, after = _identity(base), _identity(head)
131
+ delta: dict[str, Any] = {"added": {}, "removed": {}, "changed": {}}
132
+ for bucket in BUCKETS:
133
+ b, a = before[bucket], after[bucket]
134
+ delta["added"][bucket] = sorted(set(a) - set(b))
135
+ delta["removed"][bucket] = sorted(set(b) - set(a))
136
+ delta["changed"][bucket] = sorted(n for n in set(a) & set(b) if a[n] != b[n])
137
+ return delta
138
+
139
+
140
+ def _merge_names(target: dict[str, list[str]], extra: dict[str, list[str]]) -> None:
141
+ for bucket, names in extra.items():
142
+ target[bucket] = sorted(set(target[bucket]) | set(names))
143
+
144
+
145
+ def _touched_names(delta: dict[str, Any]) -> set[str]:
146
+ return {
147
+ name
148
+ for part in ("added", "removed", "changed")
149
+ for names in delta[part].values()
150
+ for name in names
151
+ }
152
+
153
+
154
+ def compute(
155
+ cfg: Config,
156
+ model: Model,
157
+ base: str,
158
+ facts: dict[str, Any],
159
+ head: str = "HEAD",
160
+ artifact_owner: dict[str, str] | None = None,
161
+ ) -> dict[str, Any]:
162
+ """Everything the change view needs, or an empty change if there is none.
163
+
164
+ `head` names the tip under study. It is not always the checked-out branch:
165
+ pull requests stack, so a lesson or a review may ask about
166
+ `origin/<branch>` while the tree sits on something else. Both refs are
167
+ explicit for that reason. `artifact_owner` maps a flow label to the
168
+ module that defines what travels on it; without one no flow is ever lit
169
+ by a redefinition.
170
+ """
171
+ repo = cfg.root
172
+ roots = cfg.roots
173
+ if artifact_owner is None:
174
+ artifact_owner = {}
175
+
176
+ empty: dict[str, Any] = {
177
+ "has_change": False,
178
+ "direct": set(),
179
+ "adjacent": set(),
180
+ "modules": set(),
181
+ "artifacts": set(),
182
+ "flow_artifacts": set(),
183
+ "per_component": {},
184
+ "files": 0,
185
+ "base": base,
186
+ "head": head,
187
+ "reach_known": True,
188
+ "unparsed": [],
189
+ }
190
+ merge_base = _run(["git", "merge-base", base, head], repo).strip()
191
+ if not merge_base:
192
+ return empty
193
+ files = _changed_files(repo, merge_base, head)
194
+ if not files:
195
+ return empty
196
+
197
+ # Each changed source module: its surface delta, from the two git blobs.
198
+ deltas: dict[str, dict[str, Any]] = {}
199
+ unparsed: list[str] = []
200
+ for path in files:
201
+ module = _path_module(repo, path, roots)
202
+ if not module or _is_test_file(path, cfg.test_dirs):
203
+ continue
204
+ delta = surface_delta(_show(repo, merge_base, path), _show(repo, head, path))
205
+ if delta is None:
206
+ unparsed.append(module)
207
+ continue
208
+ deltas[module] = delta
209
+ modules = set(deltas) | set(unparsed)
210
+
211
+ # Changed test files: added and removed tests, attributed to every module
212
+ # the test file imports, the same rule collect_tests uses for guards.
213
+ prefixes = set(facts.get("packages", []))
214
+ known = set(facts.get("components", {})) | modules
215
+ tests_added: dict[str, set[str]] = {}
216
+ tests_removed: dict[str, set[str]] = {}
217
+ for path in files:
218
+ if not _is_test_file(path, cfg.test_dirs):
219
+ continue
220
+ base_raw = _show(repo, merge_base, path)
221
+ head_raw = _show(repo, head, path)
222
+ before_t, after_t = set(test_names(base_raw)), set(test_names(head_raw))
223
+ if before_t == after_t:
224
+ continue
225
+ targets: set[str] = set()
226
+ for raw in (base_raw, head_raw):
227
+ targets |= set(internal_uses(raw, prefixes, known))
228
+ for target in targets:
229
+ tests_added.setdefault(target, set()).update(after_t - before_t)
230
+ tests_removed.setdefault(target, set()).update(before_t - after_t)
231
+
232
+ direct: set[str] = set()
233
+ per_component: dict[str, dict[str, Any]] = {}
234
+ for c in model.components:
235
+ implemented = list(c.implemented_by)
236
+ module_ids = [m for m in implemented if "/" not in m]
237
+ path_prefixes = [m for m in implemented if "/" in m]
238
+ # The modules this component claims, among the changed ones and the
239
+ # ones whose tests changed; a `pkg.*` entry claims the subtree.
240
+ owned = sorted(
241
+ m
242
+ for m in modules | set(tests_added) | set(tests_removed)
243
+ if any(module_matches(p, m) for p in module_ids)
244
+ )
245
+ hit = sorted(m for m in owned if m in modules)
246
+ path_hit = any(
247
+ f == prefix or f.startswith(prefix + "/") for prefix in path_prefixes for f in files
248
+ )
249
+ test_hit = sorted(m for m in owned if tests_added.get(m) or tests_removed.get(m))
250
+ if not hit and not path_hit and not test_hit:
251
+ continue
252
+ direct.add(c.id)
253
+ surface: dict[str, Any] = {
254
+ part: {bucket: [] for bucket in BUCKETS} for part in ("added", "removed", "changed")
255
+ }
256
+ for m in hit:
257
+ for part in ("added", "removed", "changed"):
258
+ _merge_names(surface[part], deltas[m][part])
259
+ surface["tests_added"] = sorted({t for m in owned for t in tests_added.get(m, set())})
260
+ surface["tests_removed"] = sorted({t for m in owned for t in tests_removed.get(m, set())})
261
+ gained = {
262
+ bucket: len(surface["added"][bucket])
263
+ for bucket in ("operations", "types", "refusals")
264
+ if surface["added"][bucket]
265
+ }
266
+ if surface["tests_added"]:
267
+ gained["tests"] = len(surface["tests_added"])
268
+ per_component[c.id] = {
269
+ "modules": hit,
270
+ "gained": gained,
271
+ "surface": surface,
272
+ }
273
+
274
+ # Redefined on the wire: an exported name whose definition changed and that
275
+ # some other module imports by name.
276
+ imported_names: dict[str, set[str]] = {}
277
+ fact_components = facts.get("components", {})
278
+ reach_known = any("uses" in r for r in fact_components.values())
279
+ for record in fact_components.values():
280
+ for target, names in record.get("uses", {}).items():
281
+ if names != [WHOLE_MODULE]:
282
+ imported_names.setdefault(target, set()).update(names)
283
+ artifacts = {
284
+ f"{module}.{name}"
285
+ for module, delta in deltas.items()
286
+ for name in _touched_names(delta) & imported_names.get(module, set())
287
+ }
288
+
289
+ # The drawing overlay: authored flow labels whose owning module redefined
290
+ # part of its surface, so the diagram can highlight the affected wires.
291
+ redefined_modules = {m for m, d in deltas.items() if _touched_names(d)}
292
+ flow_artifacts = {
293
+ label
294
+ for label, owner in artifact_owner.items()
295
+ if owner in redefined_modules or owner in unparsed
296
+ }
297
+
298
+ # Reach: every component with a module that imports a changed module.
299
+ def owner_of(module_id: str) -> str:
300
+ for c in model.components:
301
+ if any(module_matches(p, module_id) for p in c.implemented_by if "/" not in p):
302
+ return c.id
303
+ return ""
304
+
305
+ adjacent: set[str] = set()
306
+ for module_id, record in fact_components.items():
307
+ if module_id in modules:
308
+ continue
309
+ if modules & set(record.get("uses", {})):
310
+ cid = owner_of(module_id)
311
+ if cid:
312
+ adjacent.add(cid)
313
+ adjacent -= direct
314
+
315
+ return {
316
+ "has_change": True,
317
+ "direct": direct,
318
+ "adjacent": adjacent,
319
+ "modules": modules,
320
+ "artifacts": artifacts,
321
+ "flow_artifacts": flow_artifacts,
322
+ "per_component": per_component,
323
+ "files": len(files),
324
+ "base": base,
325
+ "head": head,
326
+ "reach_known": reach_known,
327
+ "unparsed": sorted(unparsed),
328
+ }