graphite-code 1.4.0__py3-none-any.whl → 1.5.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.
graphite/__init__.py CHANGED
@@ -38,4 +38,4 @@ __all__ = ["__version__"]
38
38
  #: Coarse and hand-maintained by construction. It is a release label, not
39
39
  #: evidence that a given fix is present -- to answer that, survey for the marker
40
40
  #: the fix introduced, or compare `graphite --version` fingerprints.
41
- __version__ = "1.4.0"
41
+ __version__ = "1.5.0"
graphite/agent_hooks.py CHANGED
@@ -136,6 +136,7 @@ def handle_session_start(payload: dict[str, Any]) -> dict[str, Any] | None:
136
136
  cwd = _payload_cwd(payload)
137
137
  root = _repo_root(cwd)
138
138
  _activate(root)
139
+ _open_session_books(root, str(payload.get("session_id") or ""), str(payload.get("source") or ""))
139
140
  if (root / "graph-out" / "graph.json").is_file():
140
141
  state, reason = _freshness_within_budget(root)
141
142
  if state == "stale":
@@ -1295,6 +1296,43 @@ def _strict_denial(payload: dict[str, Any], root: Path, cwd: Path | None = None)
1295
1296
  MAX_CURSOR_SESSIONS = 20
1296
1297
 
1297
1298
 
1299
+ def _keep_newest_sessions(sessions: dict[str, Any]) -> None:
1300
+ while len(sessions) > MAX_CURSOR_SESSIONS:
1301
+ sessions.pop(next(iter(sessions)))
1302
+
1303
+
1304
+ def _open_session_books(root: Path, session_id: str, source: str) -> None:
1305
+ """Start a new session's savings books where the usage ledger ends now.
1306
+
1307
+ The ledger holds every session's entries, so a session that counted from
1308
+ byte 0 took all of them as its own (#108). A session the cursor already
1309
+ knows keeps its totals: SessionStart fires again on a resume or a compact.
1310
+ On a resume its books move to the ledger's end as well: what the ledger
1311
+ gained while it was away is other sessions' use, and a turn of its own
1312
+ whose Stop never fired is not counted. A compact falls inside a turn, so
1313
+ the books stay where they are.
1314
+ """
1315
+ try:
1316
+ if not session_id:
1317
+ return
1318
+ sessions = usage_ledger.read_cursor(root).get("sessions")
1319
+ if not isinstance(sessions, dict):
1320
+ sessions = {}
1321
+ known = sessions.pop(session_id, None)
1322
+ if isinstance(known, dict) and source != "resume":
1323
+ return
1324
+ ledger = usage_ledger.ledger_path(root)
1325
+ ledger_stat = ledger.stat() if ledger.is_file() else None
1326
+ books = known if isinstance(known, dict) else {"tokens": 0, "seconds": 0.0}
1327
+ books["offset"] = ledger_stat.st_size if ledger_stat is not None else 0
1328
+ books["ino"] = ledger_stat.st_ino if ledger_stat is not None else None
1329
+ sessions[session_id] = books
1330
+ _keep_newest_sessions(sessions)
1331
+ usage_ledger.write_cursor(root, {"sessions": sessions})
1332
+ except Exception:
1333
+ return
1334
+
1335
+
1298
1336
  def _entries_between(path: Path, start: int, end: int) -> list[dict[str, Any]]:
1299
1337
  entries: list[dict[str, Any]] = []
1300
1338
  with open(path, "rb") as handle:
@@ -1310,6 +1348,21 @@ def _entries_between(path: Path, start: int, end: int) -> list[dict[str, Any]]:
1310
1348
  return entries
1311
1349
 
1312
1350
 
1351
+ def _entry_is_this_session(entry: dict[str, Any], session_id: str) -> bool:
1352
+ """Whether a ledger entry is this session's own use.
1353
+
1354
+ An entry that names no session is counted, as it was: a person running
1355
+ graphite in a terminal in the same repository is real use, and dropping
1356
+ it would understate what the graph saved. An entry that names another
1357
+ session is that session's, and where two sessions are open at once each
1358
+ one's Stop would otherwise claim the other's use as its own (#110).
1359
+ """
1360
+ tag = entry.get("session")
1361
+ if not isinstance(tag, str) or not tag:
1362
+ return True
1363
+ return tag == session_id
1364
+
1365
+
1313
1366
  def _cursor_number(value: Any, cast: type) -> Any:
1314
1367
  """Coerce a possibly-corrupted cursor field; non-numeric (or bool) -> 0.
1315
1368
 
@@ -1348,7 +1401,11 @@ def handle_stop(payload: dict[str, Any]) -> dict[str, Any] | None:
1348
1401
  sessions = {}
1349
1402
  state = sessions.pop(session_id, None)
1350
1403
  if not isinstance(state, dict):
1351
- state = {"offset": 0, "tokens": 0, "seconds": 0.0, "ino": current_ino}
1404
+ # No books were opened for this session: its SessionStart was not
1405
+ # seen, or the session was pruned from the cursor. What the ledger
1406
+ # holds now is other sessions' history (#108), so the books start
1407
+ # at its end. This turn's own entries are lost; none are invented.
1408
+ state = {"offset": size, "tokens": 0, "seconds": 0.0, "ino": current_ino}
1352
1409
  offset = state.get("offset", 0)
1353
1410
  stored_ino = state.get("ino")
1354
1411
  # A stored `ino` that isn't an int (missing key on the older 3-key cursor
@@ -1367,9 +1424,12 @@ def handle_stop(payload: dict[str, Any]) -> dict[str, Any] | None:
1367
1424
  if not isinstance(offset, int) or offset > size or rotated:
1368
1425
  offset = 0 # ledger rotated or cursor damaged; resync
1369
1426
  new_entries = _entries_between(ledger, offset, size) if size > offset else []
1427
+ # The ledger holds every session's entries, and where two sessions are
1428
+ # open at once each one's Stop must claim only its own use (#110).
1429
+ own_entries = [entry for entry in new_entries if _entry_is_this_session(entry, session_id)]
1370
1430
  turn_tokens = 0
1371
1431
  turn_seconds = 0.0
1372
- for entry in new_entries:
1432
+ for entry in own_entries:
1373
1433
  est = savings_model.estimate_entry(entry)
1374
1434
  turn_tokens += est["tokens_saved"]
1375
1435
  turn_seconds += est["seconds_saved"]
@@ -1378,10 +1438,9 @@ def handle_stop(payload: dict[str, Any]) -> dict[str, Any] | None:
1378
1438
  state["tokens"] = _cursor_number(state.get("tokens", 0), int) + turn_tokens
1379
1439
  state["seconds"] = _cursor_number(state.get("seconds", 0.0), float) + turn_seconds
1380
1440
  sessions[session_id] = state # re-insert -> newest position
1381
- while len(sessions) > MAX_CURSOR_SESSIONS:
1382
- sessions.pop(next(iter(sessions)))
1441
+ _keep_newest_sessions(sessions)
1383
1442
  usage_ledger.write_cursor(root, {"sessions": sessions})
1384
- if not new_entries or not usage_ledger.savings_display_enabled(root):
1443
+ if not own_entries or not usage_ledger.savings_display_enabled(root):
1385
1444
  return None
1386
1445
  turn_text = savings_model.format_compact(turn_tokens, turn_seconds)
1387
1446
  session_text = savings_model.format_compact(state["tokens"], state["seconds"])
graphite/extract/ast.py CHANGED
@@ -1,6 +1,7 @@
1
1
  """Deterministic structural extraction via tree-sitter."""
2
2
  from __future__ import annotations
3
3
 
4
+ import builtins
4
5
  import hashlib
5
6
  import importlib
6
7
  import re
@@ -15,7 +16,7 @@ from ..cache import Cache
15
16
  from ..config import Config
16
17
  from ..graph import normalize_id
17
18
  from ..ingest import LANGUAGE_BY_EXT, FileEntry
18
- from ..resolve import SourceIndex, should_keep_call_target
19
+ from ..resolve import MAX_REEXPORT_HOPS, SourceIndex, python_reexports_of, should_keep_call_target
19
20
  from .pyscope import (
20
21
  PyScope,
21
22
  Resolution,
@@ -1420,6 +1421,30 @@ def _python_import_bindings(
1420
1421
  return out
1421
1422
 
1422
1423
 
1424
+ def _python_module_reexports(
1425
+ file_id: str, rel_path: str, source: bytes, source_index: SourceIndex
1426
+ ) -> dict[str, str]:
1427
+ """`<module>.<name>` -> where the module's own `from X import name` says it is (#107).
1428
+
1429
+ The key is the id a call of `module.name` gets, `_make_id(<file id>,
1430
+ <name>)`; the value is the id of `name` in the file `X` resolves to. Only
1431
+ a name the module binds by that one statement is recorded (the rule #87
1432
+ applies to a package's `__init__.py`), and one that names a submodule
1433
+ (`from pkg import sub`) is not: `pkg.sub` is the module, not a name of
1434
+ `pkg`. The dispatch post-pass follows these across files, so a value
1435
+ depends on the module's own bytes and the file set alone, as its cache
1436
+ key does.
1437
+ """
1438
+ out: dict[str, str] = {}
1439
+ for (_, local), (module, level, original) in python_reexports_of(rel_path, source).items():
1440
+ if source_index.resolve_python_module(rel_path, f"{module}.{original}", level):
1441
+ continue
1442
+ defining = source_index.resolve_python_module(rel_path, module, level)
1443
+ if defining:
1444
+ out[_make_id(file_id, local)] = _make_id(_file_node_id(defining, source_index), original)
1445
+ return out
1446
+
1447
+
1423
1448
  def _python_definition_name(node: Any) -> str | None:
1424
1449
  """A def/class node's name exactly as its graph node records it."""
1425
1450
  name_node = node.child_by_field_name("name")
@@ -1559,14 +1584,21 @@ def _python_attribute_root(node: Any) -> str | None:
1559
1584
  return None
1560
1585
 
1561
1586
 
1562
- def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, source_index: SourceIndex | None = None) -> ExtractionResult:
1587
+ def _extract_python(file_id: str, rel_path: str, source: bytes, tree: Any, source_index: SourceIndex | None = None) -> ExtractionResult:
1563
1588
  result = ExtractionResult()
1564
1589
  root = tree.root_node
1565
1590
 
1566
1591
  def _line(node: Any) -> int:
1567
1592
  return node.start_point[0] + 1
1568
1593
 
1569
- result.nodes.append(_node(file_id, "file", Path(rel_path).name, rel_path))
1594
+ file_node = _node(file_id, "file", Path(rel_path).name, rel_path)
1595
+ if source_index is not None:
1596
+ # For the dispatch post-pass, which takes it off again: what a call of
1597
+ # `<this module>.<name>` reaches where the module only imports the name.
1598
+ reexports = _python_module_reexports(file_id, rel_path, source, source_index)
1599
+ if reexports:
1600
+ file_node["_reexports"] = reexports
1601
+ result.nodes.append(file_node)
1570
1602
 
1571
1603
  # One pass builds every Python scope and what each binds (#70, #71). The walk
1572
1604
  # below reads it: each def/class gets its scope-qualified identity, and each
@@ -1604,8 +1636,9 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
1604
1636
  class_node = _node(did, "class", name, rel_path, _line(node), {"qualname": qualname})
1605
1637
  body_scope = table.class_scope.get(node.id)
1606
1638
  if body_scope is not None and body_scope.parent is not None:
1607
- # For the dispatch post-pass (#73), which takes all five off
1608
- # again: the bases in order, the names the body binds in some
1639
+ # For the dispatch post-pass (#73), which takes all six off
1640
+ # again: the bases in order, which of them are builtin classes
1641
+ # (#106), the names the body binds in some
1609
1642
  # other way than one `def` written straight in it (a `def`
1610
1643
  # under an `if` is there only if the `if` ran it, and one
1611
1644
  # under `global` or `nonlocal` binds the name somewhere
@@ -1614,7 +1647,9 @@ def _extract_python(file_id: str, rel_path: str, _source: bytes, tree: Any, sour
1614
1647
  # is made beyond its body and bases. With them `self.m()` and
1615
1648
  # `super().m()` are bound to the method Python finds, not to
1616
1649
  # every method called `m`.
1617
- class_node["_bases"] = _python_class_bases(node, body_scope.parent, table, ids)
1650
+ class_node["_bases"], class_node["_builtin_bases"] = _python_class_bases(
1651
+ node, body_scope.parent, table, ids
1652
+ )
1618
1653
  class_node["_stops"] = sorted(
1619
1654
  {
1620
1655
  bound for bound, binders in body_scope.binders.items()
@@ -2254,7 +2289,7 @@ _MAX_METHOD_DISPATCH_CANDIDATES = 3
2254
2289
 
2255
2290
  def _python_class_bases(
2256
2291
  node: Any, scope: PyScope, table: ScopeTable, ids: dict[tuple[str, bool], str]
2257
- ) -> list[str | None]:
2292
+ ) -> tuple[list[str | None], list[str | None]]:
2258
2293
  """Each base of a class statement, in order: the id of the class it names, or None.
2259
2294
 
2260
2295
  A base is resolved where the source states it: a bare name that denotes a
@@ -2264,15 +2299,26 @@ def _python_class_bases(
2264
2299
  It may bind any name, and it may derive from a class that was read.
2265
2300
  `object` is left out: it is last in every linearisation and defines no
2266
2301
  method of the repository. Class keywords (`metaclass=...`) are not bases.
2302
+
2303
+ The second list is as long as the first: the name of the builtin class a
2304
+ base is, where it is one (a bare name the file does not bind), and None
2305
+ elsewhere. Only `super()` reads it (#106): no class of the repository
2306
+ stands behind a builtin, so where the method `super()` finds is a
2307
+ builtin's, it is none of the repository's. A star import may bind the
2308
+ name; `super()` itself is not read beside one (`_is_bare_super`), so the
2309
+ list needs no check of its own for it.
2267
2310
  """
2268
2311
  bases: list[str | None] = []
2312
+ builtin_bases: list[str | None] = []
2269
2313
  arguments = node.child_by_field_name("superclasses")
2270
2314
  for arg in arguments.named_children if arguments is not None else ():
2271
2315
  if arg.type in ("comment", "keyword_argument", "dictionary_splat"):
2272
2316
  continue
2273
- found = resolve(scope, arg.text.decode("utf-8", errors="ignore")) if arg.type == "identifier" else None
2317
+ written = arg.text.decode("utf-8", errors="ignore")
2318
+ found = resolve(scope, written) if arg.type == "identifier" else None
2274
2319
  if found is not None and found.kind in ("def", "symbol"):
2275
2320
  bases.append(_python_definition_id(found, ids))
2321
+ builtin_bases.append(None)
2276
2322
  elif (
2277
2323
  found is not None and found.kind == "none"
2278
2324
  and arg.text == b"object" and not table.module.star_import
@@ -2280,7 +2326,28 @@ def _python_class_bases(
2280
2326
  continue
2281
2327
  else:
2282
2328
  bases.append(None)
2283
- return bases
2329
+ builtin = (
2330
+ found is not None and found.kind == "none"
2331
+ and isinstance(getattr(builtins, written, None), type)
2332
+ )
2333
+ builtin_bases.append(written if builtin else None)
2334
+ return bases, builtin_bases
2335
+
2336
+
2337
+ #: What `class_method` answers where the method `super()` finds is a builtin's (#106).
2338
+ _A_BUILTIN_S_METHOD = "<builtin>"
2339
+
2340
+
2341
+ def _a_builtin_has(builtin_names: Collection[str], method: str) -> bool:
2342
+ """Whether a method lookup that reaches these builtin classes finds `method`
2343
+ in one of them or in a class they derive from (`object` among them).
2344
+
2345
+ Each class's own namespace is read, not `hasattr`: `hasattr(dict, "mro")`
2346
+ is true because `type` defines `mro`, and `super()` never looks there.
2347
+ """
2348
+ return any(
2349
+ method in vars(cls) for name in builtin_names for cls in getattr(builtins, name).__mro__
2350
+ )
2284
2351
 
2285
2352
 
2286
2353
  def _python_class_making(node: Any, scope: PyScope, table: ScopeTable) -> list[str]:
@@ -2527,6 +2594,46 @@ def _dispatch_is_gated(source_file: str | None) -> bool:
2527
2594
  return language in _DISPATCH_GATED_LANGUAGES
2528
2595
 
2529
2596
 
2597
+ def _follow_python_reexports(nodes: list[dict[str, Any]], edges: list[dict[str, Any]]) -> None:
2598
+ """Re-point each id of a name a Python module only imports to its definition (#107).
2599
+
2600
+ `front.target(x)`, where `front.py` binds `target` only by `from pkg.impl
2601
+ import target`, was extracted as a call of `pkg_front_py_target`, which no
2602
+ file defines; so were `t = front.target; t(x)`, `from pkg.front import
2603
+ target` and a base class or receiver named that way. Each module's own
2604
+ imports are on its file node (`_reexports`); here they are followed across
2605
+ files, for as many hops as the source states, to the id the last module
2606
+ names. A definition is never moved: a module that defines a name binds it
2607
+ twice, and such a name is not recorded. A cycle stops at
2608
+ `MAX_REEXPORT_HOPS`, on an id no file defines.
2609
+
2610
+ Edge targets of every relation are re-pointed, and so are ``_receiver``
2611
+ on an edge and ``_bases`` on a class node, the other two places a
2612
+ definition id is read; ``_reexports`` is taken off every node.
2613
+ """
2614
+ hops: dict[str, str] = {}
2615
+ for n in nodes:
2616
+ hops.update(n.pop("_reexports", None) or {})
2617
+ if not hops:
2618
+ return
2619
+
2620
+ def follow(target: str) -> str:
2621
+ for _ in range(MAX_REEXPORT_HOPS):
2622
+ hop = hops.get(target)
2623
+ if hop is None:
2624
+ break
2625
+ target = hop
2626
+ return target
2627
+
2628
+ for e in edges:
2629
+ e["target"] = follow(e["target"])
2630
+ if e.get("_receiver") is not None:
2631
+ e["_receiver"] = follow(e["_receiver"])
2632
+ for n in nodes:
2633
+ if n.get("_bases") is not None:
2634
+ n["_bases"] = [None if base is None else follow(base) for base in n["_bases"]]
2635
+
2636
+
2530
2637
  def _resolve_method_dispatch(
2531
2638
  nodes: list[dict[str, Any]], edges: list[dict[str, Any]]
2532
2639
  ) -> list[dict[str, Any]]:
@@ -2590,9 +2697,23 @@ def _resolve_method_dispatch(
2590
2697
  `__init_subclass__` there can set a name on the class itself, over its own
2591
2698
  `def`. So "bound" says what the classes that were read state, and not more.
2592
2699
 
2700
+ One case of a base that was not read is read for `super()` alone (#106):
2701
+ a builtin class, named in ``_builtin_bases``. No class of the repository
2702
+ stands behind a builtin. So where no class that was read binds the name,
2703
+ every base that was not read is a builtin, and a builtin (or `object`)
2704
+ has the name, what `super()` finds is the builtin's, and the call gets no
2705
+ edge, as a call of a builtin gets none. Bound by name, it was a call to
2706
+ every method of the name in reach.
2707
+
2708
+ Before any of it, a name a Python module only imports is followed to its
2709
+ definition (`_follow_python_reexports`, #107), so the ids read below are
2710
+ the definitions' own.
2711
+
2593
2712
  ``_member``, ``_receiver`` and ``_walk`` are stripped from every returned
2594
- edge, and the five class tags from every node, so none leaks into the graph.
2713
+ edge, and the six class tags and ``_reexports`` from every node, so none
2714
+ leaks into the graph.
2595
2715
  """
2716
+ _follow_python_reexports(nodes, edges)
2596
2717
  # method name (casefolded) -> set of definition node ids. A set collapses the
2597
2718
  # same method appearing twice in the pre-dedup node list, so the cap counts
2598
2719
  # distinct definitions.
@@ -2617,14 +2738,17 @@ def _resolve_method_dispatch(
2617
2738
  instance_binds_of: dict[str, frozenset[str]] = {}
2618
2739
  class_binds_of: dict[str, frozenset[str]] = {}
2619
2740
  made_of: dict[str, frozenset[str]] = {}
2741
+ builtin_bases_of: dict[str, list[str | None]] = {}
2620
2742
  for n in nodes:
2621
2743
  bases = n.pop("_bases", None)
2744
+ builtin_bases = n.pop("_builtin_bases", None)
2622
2745
  stops = n.pop("_stops", None)
2623
2746
  instance_binds = n.pop("_self_binds", None)
2624
2747
  class_binds = n.pop("_class_binds", None)
2625
2748
  made = n.pop("_made", None)
2626
2749
  if bases is not None:
2627
2750
  bases_of[n["id"]] = bases
2751
+ builtin_bases_of[n["id"]] = list(builtin_bases or ())
2628
2752
  stops_of[n["id"]] = frozenset(stops or ())
2629
2753
  instance_binds_of[n["id"]] = frozenset(instance_binds or ())
2630
2754
  class_binds_of[n["id"]] = frozenset(class_binds or ())
@@ -2687,6 +2811,21 @@ def _resolve_method_dispatch(
2687
2811
  if (walk == "self" if current == cls else not private)
2688
2812
  and ("decorator" in made_of[current] or body_binds(current, method))
2689
2813
  ]
2814
+ if walk == "super" and not binders and unread:
2815
+ # No class that was read binds the name. Where every base that
2816
+ # was not read is a builtin, no class of the repository stands
2817
+ # behind any of them, and one of them has the name, `super()`
2818
+ # finds a builtin's method (#106).
2819
+ builtin_names: list[str] = []
2820
+ for current, position in unread:
2821
+ named = builtin_bases_of.get(current, [])
2822
+ builtin = named[position] if position < len(named) else None
2823
+ if builtin is None:
2824
+ break
2825
+ builtin_names.append(builtin)
2826
+ else:
2827
+ if _a_builtin_has(builtin_names, method):
2828
+ return _A_BUILTIN_S_METHOD
2690
2829
  if not unread:
2691
2830
  # Every base was read, so the order is Python's own.
2692
2831
  line = _c3_linearisation(cls, bases_of, linearisations) or ()
@@ -2768,6 +2907,10 @@ def _resolve_method_dispatch(
2768
2907
  # `self.m()` / `super().m()`: the first `m` along the bases of the
2769
2908
  # class the call is written in (#73).
2770
2909
  own = class_method(receiver, method, walk)
2910
+ if own == _A_BUILTIN_S_METHOD:
2911
+ # What runs is a builtin's method: no edge, as a call of a
2912
+ # builtin has none (#106).
2913
+ continue
2771
2914
  else:
2772
2915
  own = own_methods.get(receiver, {}).get(method) if receiver else None
2773
2916
  if own is not None:
graphite/resolve.py CHANGED
@@ -34,9 +34,9 @@ def _rel_path_set_digest(rel_paths: frozenset[str]) -> str:
34
34
 
35
35
  #: How many re-exports one name is followed through. A real package chain is a
36
36
  #: hop or two; the bound only has to be finite beside the cycle guard.
37
- _MAX_REEXPORT_HOPS: Final = 8
37
+ MAX_REEXPORT_HOPS: Final = 8
38
38
 
39
- #: `(package __init__ path, name it binds) -> (module, leading dots, name there)`
39
+ #: `(module path, name it binds) -> (module, leading dots, name there)`
40
40
  ReexportTable = dict[tuple[str, str], tuple[str, int, str]]
41
41
 
42
42
 
@@ -46,7 +46,9 @@ def _module_level_bindings(body: list[ast.stmt]) -> dict[str, list[ast.stmt]]:
46
46
  A name bound under `if` or `try` counts as bound there, and so does a
47
47
  name an `import` or `def` binds: the statement list is what lets the caller
48
48
  tell a name bound exactly once, by one `from X import name`, from a name
49
- the package binds some other way too.
49
+ the module binds some other way too. So does a `global` declaration of the
50
+ name in any function or class of the module, which binds it from there
51
+ (#107).
50
52
  """
51
53
  bound: dict[str, list[ast.stmt]] = {}
52
54
 
@@ -76,16 +78,22 @@ def _module_level_bindings(body: list[ast.stmt]) -> dict[str, list[ast.stmt]]:
76
78
  add(node.name, stmt)
77
79
 
78
80
  visit(body)
81
+ for stmt in body:
82
+ for node in ast.walk(stmt):
83
+ if isinstance(node, ast.Global):
84
+ for name in node.names:
85
+ add(name, node)
79
86
  return bound
80
87
 
81
88
 
82
- def _package_reexports(rel_path: str, source: bytes) -> ReexportTable:
83
- """The names one `__init__.py` binds only by a top-level `from X import name`.
89
+ def python_reexports_of(rel_path: str, source: bytes) -> ReexportTable:
90
+ """The names one module binds only by a top-level `from X import name`.
84
91
 
85
92
  A name the file binds any other way too (assigned, defined, imported a
86
- second time, imported under a condition) is left out, and so is a file that
87
- does not parse: `from pkg import name` then stays bound to the package, as
88
- it was before re-exports were followed.
93
+ second time, imported under a condition, rebound under `global`) is left
94
+ out, and so is a file that does not parse: the name then stays bound to
95
+ the module, as it was before re-exports were followed. A star import is
96
+ not read.
89
97
  """
90
98
  try:
91
99
  tree = ast.parse(source)
@@ -116,7 +124,7 @@ def _python_reexports(entries: Iterable[FileEntry]) -> ReexportTable:
116
124
  source = Path(entry.abs_path).read_bytes()
117
125
  except OSError:
118
126
  continue
119
- table.update(_package_reexports(rel_path, source))
127
+ table.update(python_reexports_of(rel_path, source))
120
128
  return table
121
129
 
122
130
 
@@ -233,11 +241,11 @@ class SourceIndex:
233
241
  Follows `from X import name` statements the package `__init__.py`
234
242
  makes, for as many steps as the source states. It stops where a hop does
235
243
  not resolve to a file of the tree, where a name is bound some other way,
236
- at a cycle, and at `_MAX_REEXPORT_HOPS`; each returns the last place
244
+ at a cycle, and at `MAX_REEXPORT_HOPS`; each returns the last place
237
245
  reached, which is `(rel_path, name)` itself when nothing is followed.
238
246
  """
239
247
  seen = {(rel_path, name)}
240
- for _ in range(_MAX_REEXPORT_HOPS):
248
+ for _ in range(MAX_REEXPORT_HOPS):
241
249
  hop = self.python_reexports.get((rel_path, name))
242
250
  if hop is None:
243
251
  break
graphite/usage_ledger.py CHANGED
@@ -20,6 +20,30 @@ MAX_FILES_PER_ENTRY = 100
20
20
  _FILE_KEYS = frozenset({"source_file", "file", "path"})
21
21
  _FILE_LIST_KEYS = frozenset({"impacted_files", "likely_tests", "files"})
22
22
 
23
+ # The session a process belongs to, looked for in this order: graphite's own
24
+ # name first, then the harness's. The first one that is set wins.
25
+ ENV_SESSION_ID = "GRAPHITE_SESSION_ID"
26
+ SESSION_ENV_VARS = (
27
+ ENV_SESSION_ID,
28
+ "CLAUDE_CODE_SESSION_ID",
29
+ "CODEX_COMPANION_SESSION_ID",
30
+ )
31
+
32
+
33
+ def current_session_id() -> str:
34
+ """The session this process belongs to, or "" when it cannot know one.
35
+
36
+ The Stop hook's payload carries the session id, and the environment every
37
+ process the agent spawns carries the same string, so a command can record
38
+ which session made it. Where no variable is set -- a person at a
39
+ terminal -- the entry stays untagged and is counted as it was.
40
+ """
41
+ for name in SESSION_ENV_VARS:
42
+ value = os.environ.get(name, "").strip()
43
+ if value:
44
+ return value
45
+ return ""
46
+
23
47
 
24
48
  def local_dir(root: Path) -> Path:
25
49
  return root / ".graphite" / "local"
@@ -94,6 +118,9 @@ def record_usage(root: Path, *, cmd: str, wall_ms: int, result: Any) -> None:
94
118
  "output_bytes": output_bytes,
95
119
  "files": collect_answer_files(result, root),
96
120
  }
121
+ session = current_session_id()
122
+ if session:
123
+ entry["session"] = session
97
124
  path = ledger_path(root)
98
125
  path.parent.mkdir(parents=True, exist_ok=True)
99
126
  if path.exists() and path.stat().st_size > MAX_LEDGER_BYTES:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: graphite-code
3
- Version: 1.4.0
3
+ Version: 1.5.0
4
4
  Summary: Local-first, zero-LLM knowledge graph extraction for codebases.
5
5
  Project-URL: Homepage, https://github.com/jared0565/graphite
6
6
  Project-URL: Repository, https://github.com/jared0565/graphite
@@ -48,7 +48,7 @@ Description-Content-Type: text/markdown
48
48
 
49
49
  Local-first, deterministic knowledge graph extraction for codebases — zero-LLM, daemon-maintained, agent-agnostic.
50
50
 
51
- **Status: 1.4.0, production/stable.** Published on PyPI as
51
+ **Status: 1.5.0, production/stable.** Published on PyPI as
52
52
  [`graphite-code`](https://pypi.org/project/graphite-code/) with PEP 740
53
53
  attestations; supported on Windows, Linux and macOS with Python 3.11–3.14
54
54
  (every cell gates CI). What 1.x promises — CLI, JSON outputs, `graph.json`,
@@ -1,9 +1,9 @@
1
- graphite/__init__.py,sha256=GC0juqOmVzk_zpoOBLn2WPHFXWWoxCfPb4CvSCEqyCs,2181
1
+ graphite/__init__.py,sha256=VfpD_3BtqjwPagz-Kd69EN_1s535eWo6uOTT7piVIFw,2181
2
2
  graphite/__main__.py,sha256=Bp5bcXE6M0AnuNW1LjOXOEvGG5r0fXZoeRb_k5Yxphs,149
3
3
  graphite/_cleanup_worker.py,sha256=oIXOPa1jHVP8ePRSwn27nZEHOAc4DSBrjeH2Ds9wuq8,19619
4
4
  graphite/_win32_ctypes.py,sha256=YLH4kpKjL7zUUOs9E8C-Kjdy45PJBd6eRUeKwiKdSV4,1476
5
5
  graphite/activation.py,sha256=Jcgk8AFvqbMNQiPAa2MTzSO0BAYRC5FX6MsZUjbDe1I,5249
6
- graphite/agent_hooks.py,sha256=rIeA6ofRLDMSdf4MfFMUpnXHVcHHzht6NZpfgSOgZd4,64248
6
+ graphite/agent_hooks.py,sha256=lahVeyEAkO9V7HEEDyrhzHjn9wX51GyVh8m4zDDxX5Q,67168
7
7
  graphite/agent_settings.py,sha256=Ec95ilPhkPOM3vW67pdsjYivnCyc5uCqWfCBu-DLI3A,11085
8
8
  graphite/analyze.py,sha256=BwiZ4lkQ8Oo8WvnIGLI03YSNUpynYvV46tVbzHH5iWQ,9304
9
9
  graphite/answer_contract.py,sha256=KTnGmtT6gvi28-PhLZp9vaj7FDvGrqLW_BvhAa-VPR4,31237
@@ -54,13 +54,13 @@ graphite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
54
54
  graphite/query.py,sha256=qOObUOJGtHTf_MWrxNM1ykfl7TR2aqZ7MBvjib4i01Y,29659
55
55
  graphite/query_plan.py,sha256=TLGwOnsL6Ia1hCsDzmWWBwtcn37Dn6aOuAvGowtgSXg,3768
56
56
  graphite/replacement_audit.py,sha256=AR97eZ0h8Rx5VWOW2rJSqDGwEVwEDj08kcSiepyidaE,12393
57
- graphite/resolve.py,sha256=FMaOCWbCGD7aEpN5WOmdLs5Y35nGdw_G8SUuHtxqjV0,34778
57
+ graphite/resolve.py,sha256=bjpi2Lzti3GZheIJa8hM6HSOu9uKqiHz8vNGfq2pNOY,35103
58
58
  graphite/review.py,sha256=Dd35aA8n5R1Osoop769uymdOFFZMB4BFexAKJD9bO7o,27810
59
59
  graphite/savings.py,sha256=W5FbXScpteMTwngVUtDqPct99tHY7W8s3XlT4hbPJCY,3175
60
60
  graphite/systemd_unit.py,sha256=oPfdHwFJpfW1RnQeIkyVnOYvDhSRjll57424whQYWg4,4503
61
61
  graphite/ts_bridge.py,sha256=ZlSdG7knixFyTPWm8WANb5u0PnmoSvORB8ZASaPeTW8,6099
62
62
  graphite/typescript_activation.py,sha256=id1wJIVWVZeVT5Xr17PTsEZKYSpI4nUY6z6JDW3IVbE,53523
63
- graphite/usage_ledger.py,sha256=tvBBCnWvw5ooDQOJQH7pUNQoKbHMI0UKn16ZDs7D1X0,5206
63
+ graphite/usage_ledger.py,sha256=HISve2-iRFbxx9yb4KNaTE3SBNW3zCh2Xp_-O_baZJw,6145
64
64
  graphite/validation.py,sha256=C_t-kKba64Tcs7zTY_dmHX29KYoIDDaO8gn7DRCRVlM,6739
65
65
  graphite/watch.py,sha256=a5sM9g6auHmXwdfKFdpmCin0jkcZlw9_PzBqic0lSTc,5125
66
66
  graphite/windows_job.py,sha256=A57fUfLD-5_Xi9fD7yLgyUzj_pWaC2AE6ZIsmBRl_qU,18750
@@ -71,7 +71,7 @@ graphite/export/html.py,sha256=WB-9p0fpjFh-bTpHl5aYg1UdM_PGXwaZEtyR3lleNZU,8949
71
71
  graphite/export/json.py,sha256=oUrR1aXE5eiRDrj1_oXIl6qOPsTiqP3rmGtLfHF_nJc,1267
72
72
  graphite/export/md.py,sha256=JqxULAZHdsxBsbgeZVzZ08C0_ZmQ9Tsln_dAmvHmbjY,2557
73
73
  graphite/extract/__init__.py,sha256=HsF3yU1VcT3EsvUfxMJ0iVW2Ud_XrivnBGmdi9QTK3M,118
74
- graphite/extract/ast.py,sha256=l5M6m768RtxWBj8eHMMLY8sLV4ChABAWZbybGRtHOIA,144260
74
+ graphite/extract/ast.py,sha256=A7MrdPg-ibVyqTvi3Rtqbs3LR6u4iZbTxbTjJUws3QY,151139
75
75
  graphite/extract/pyscope.py,sha256=bLsH5vJI10nLM12lGEeyvI3uG5uKXX0Jq4wl5TjfJc4,36460
76
76
  graphite/routing/__init__.py,sha256=QlzeC4TbkzJNPn6vVrMH36FmpHrH0ZoJzjK_ckF-Z54,177
77
77
  graphite/routing/approval.py,sha256=9roEO0d5hBhg3VgUaN8cw4wxzgJn6oKzhO7eQQ9cShQ,13872
@@ -113,8 +113,8 @@ graphite/routing/zai_edit.py,sha256=Kra2tI9GkntQAhV1vNHlFlp4sY-ksq2-bY4N9fEfLEc,
113
113
  graphite/routing/zai_executor.py,sha256=cHUl7DbWRUhYg9Lwm3OiP6H3dI70y_b8iAWCyfgOPi0,6636
114
114
  graphite/routing/zai_probe.py,sha256=HL2vM8s2J4-n8Bp3l7QLpWLEk-PhZrt_rLc2cY65hvU,4771
115
115
  graphite/ts_resolver.mjs,sha256=wiKDWkJIC9__3wL49ty4W8hRc5biisNNtFhH1aFA47A,10822
116
- graphite_code-1.4.0.dist-info/METADATA,sha256=5UbiMIRD_tve4MYmsHClCpKWc7IfospT5PDnSsxTu7Q,48476
117
- graphite_code-1.4.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
118
- graphite_code-1.4.0.dist-info/entry_points.txt,sha256=-BpYAYFyn58DYi-hrFW9hMz6mTwNsYI44s9gaef4MiM,87
119
- graphite_code-1.4.0.dist-info/licenses/LICENSE,sha256=mfotJ1Lk0VVUgoEPOIR7-x5cvYiz2UkuVH7e3fhoDiY,1066
120
- graphite_code-1.4.0.dist-info/RECORD,,
116
+ graphite_code-1.5.0.dist-info/METADATA,sha256=sjTxZm56X2dnl0G-urx--t-eSfiv0mZ6U2EKwLQioxc,48476
117
+ graphite_code-1.5.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
118
+ graphite_code-1.5.0.dist-info/entry_points.txt,sha256=-BpYAYFyn58DYi-hrFW9hMz6mTwNsYI44s9gaef4MiM,87
119
+ graphite_code-1.5.0.dist-info/licenses/LICENSE,sha256=mfotJ1Lk0VVUgoEPOIR7-x5cvYiz2UkuVH7e3fhoDiY,1066
120
+ graphite_code-1.5.0.dist-info/RECORD,,