graphite-code 1.8.2__py3-none-any.whl → 1.9.1__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.8.2"
41
+ __version__ = "1.9.1"
graphite/agent_hooks.py CHANGED
@@ -19,10 +19,12 @@ from . import usage_ledger
19
19
  from .activation import mark_active
20
20
  from .config import Config
21
21
  from .freshness import check_graph_freshness
22
+ from .graph import edge_relations
22
23
  from .graph_io import load_validated_graph_bundle
23
24
  from .health import _edge_language, is_placeholder, persisted_resolution
24
25
  from .incident_ledger import record_incident, repo_ledger_dir
25
26
  from .ingest import enclosing_git_root, repository_root
27
+ from .query import _CALL_RELATIONS
26
28
 
27
29
  SESSION_CONTRACT = (
28
30
  "graphite-first: this repo uses a shared code graph. For cross-file questions "
@@ -236,27 +238,137 @@ def _without_fused_escapes(pattern: str) -> str:
236
238
  return _FUSED_ESCAPE_RE.sub(lambda found: found.group() if found.group() == "\\\\" else " ", pattern)
237
239
 
238
240
 
239
- def _pattern_tokens(pattern: str, fold_case: bool) -> list[str]:
241
+ # A run of literal whitespace in a pattern. Tab counts: a pattern may be
242
+ # written with one.
243
+ _WHITESPACE_RUN_RE = re.compile(r"[ \t]+")
244
+ # The characters that end a branch, a group, a character class, a repetition
245
+ # or an anchor's span. A run next to one of them sits at the edge of what the
246
+ # pattern matches rather than inside a phrase, so it is not a joining
247
+ # character: `dependents |zzqx` is the first branch `dependents ` and
248
+ # `zzqx| dependents` is the second branch ` dependents`, and both are the
249
+ # bare name with a space at the edge of it.
250
+ _BOUNDARY_CHARS = frozenset("|()[]{}^$")
251
+ # A quantifier or an escape after a space. The space may be absent -- `?`,
252
+ # `*` and `{0` in ERE, `\\?` and `\\{0,1\\}` in BRE -- or the construct is one
253
+ # this hook cannot parse, and a parse it does not understand fails closed.
254
+ # Either way the space is not something the matched text must carry, so the
255
+ # bare name is still what the search may be looking for.
256
+ _QUANTIFIER_OR_ESCAPE_AFTER = frozenset("?*+{\\")
257
+
258
+
259
+ def _required_interior_whitespace(pattern: str) -> list[tuple[int, int]]:
260
+ """Spans of whitespace a matched text must carry, with text on both sides.
261
+
262
+ A literal space inside a pattern is part of the text the search must
263
+ match: `email you` finds the phrase, not the bare word. The rule that
264
+ already skips a piece of a path, a file's name or a hyphenated option is
265
+ the same one -- a fragment of a longer literal is not judged alone -- and
266
+ a required space beside a word is that kind of joining character. So a
267
+ prose search is not refused for a word the repo happens to call `email`
268
+ (round 331), and the refusal no longer depends on where the word falls
269
+ in the sentence.
270
+
271
+ Two conditions keep this from becoming a way past the gate:
272
+
273
+ - the space must be REQUIRED. A quantifier or an escape after it may make
274
+ the space absent, and an absent space can still find the bare name.
275
+ - it must be INTERIOR: text on both sides, within the same branch and
276
+ group. A space at the edge of either -- leading, trailing, or against
277
+ an alternation, a group or an anchor -- would let any pattern smuggle a
278
+ bare symbol past the gate by adding one space, so it is not treated as
279
+ a joining character.
280
+
281
+ The engine's dialect is not read, and where it would matter the space is
282
+ judged rather than excused: a bare `?` is a quantifier in ERE and a
283
+ literal character in BRE, and the hook cannot tell which it is looking
284
+ at, so `email ?you` is judged in both. That refuses a search the pattern
285
+ may have allowed, and refusing is the safe direction.
286
+
287
+ A regex escape is not a space. `\\s` is an operator, so
288
+ `^\\s*def\\s+dependents\\b` still names the symbol and is still judged,
289
+ and the name beside an escape is judged exactly as it was.
290
+ """
291
+ spans: list[tuple[int, int]] = []
292
+ for found in _WHITESPACE_RUN_RE.finditer(pattern):
293
+ start, end = found.start(), found.end()
294
+ before = pattern[start - 1] if start else ""
295
+ after = pattern[end] if end < len(pattern) else ""
296
+ if not before or not after:
297
+ continue # at the edge of the pattern
298
+ if before in _BOUNDARY_CHARS or after in _BOUNDARY_CHARS:
299
+ continue # at the edge of a branch, a group or an anchor
300
+ if after in _QUANTIFIER_OR_ESCAPE_AFTER:
301
+ continue # the space may be absent, or the parse is unknown
302
+ spans.append((start, end))
303
+ return spans
304
+
305
+
306
+ def _beside_a_required_space(start: int, end: int, spaces: list[tuple[int, int]]) -> bool:
307
+ """Whether the token at `start:end` sits against a required interior space."""
308
+ return any(run_end == start or run_start == end for run_start, run_end in spaces)
309
+
310
+
311
+ def _receiver_of(pattern: str, start: int) -> str | None:
312
+ """The identifier the word at `start` is qualified by, or None.
313
+
314
+ `env.put(` and `env\\.put(` both qualify `put` by `env`. A word that is
315
+ not behind a dot is qualified by nothing.
316
+ """
317
+ index = start - 1
318
+ if index < 0:
319
+ return None
320
+ if pattern[index] == "\\":
321
+ index -= 1
322
+ if index < 0 or pattern[index] != ".":
323
+ return None
324
+ index -= 1 # past the dot
325
+ if index >= 0 and pattern[index] == "\\":
326
+ index -= 1 # and past the backslash of an escaped dot
327
+ end = index + 1
328
+ while index >= 0 and (pattern[index].isalnum() or pattern[index] == "_"):
329
+ index -= 1
330
+ if index + 1 == end:
331
+ return None # nothing before the dot
332
+ return pattern[index + 1:end]
333
+
334
+
335
+ def _pattern_tokens(pattern: str, fold_case: bool) -> list[tuple[str, str | None]]:
240
336
  """Identifier-like tokens from a grep pattern, deduplicated, capped.
241
337
 
242
338
  Two spellings of one word are one token only when the search folds case.
243
339
  Otherwise `Done|done` would keep `Done` alone and never check `done`.
340
+
341
+ Each token carries the identifier it is qualified by, or None when the
342
+ word appears without one. A word that appears bare anywhere in the
343
+ pattern is never a qualified member: `install|env.install(` is a search
344
+ for the bare name as well.
244
345
  """
245
- seen: set[str] = set()
246
- tokens: list[str] = []
346
+ seen: dict[str, str] = {}
347
+ receivers: dict[str, str | None] = {}
348
+ # The spaces are read from the pattern as written: `_without_fused_escapes`
349
+ # blanks an escape into spaces of its own, and a blanked escape is an
350
+ # operator, not a space the matched text must carry.
351
+ spaces = _required_interior_whitespace(pattern)
247
352
  pattern = _without_fused_escapes(pattern)
248
353
  for found in _IDENTIFIER_RE.finditer(pattern):
249
354
  if _is_literal_fragment(pattern, found.start(), found.end()):
250
355
  continue
356
+ if _beside_a_required_space(found.start(), found.end(), spaces):
357
+ continue
251
358
  token = found.group()
252
359
  key = token.lower() if fold_case else token
360
+ receiver = _receiver_of(pattern, found.start())
253
361
  if key in seen:
362
+ # Qualified somewhere and bare somewhere else is a search for the
363
+ # bare name too, so the word is not a qualified member.
364
+ if receivers[key] != receiver:
365
+ receivers[key] = None
254
366
  continue
255
- seen.add(key)
256
- tokens.append(token)
257
- if len(tokens) >= _MAX_TOKENS_CHECKED:
367
+ seen[key] = token
368
+ receivers[key] = receiver
369
+ if len(seen) >= _MAX_TOKENS_CHECKED:
258
370
  break
259
- return tokens
371
+ return [(seen[key], receivers[key]) for key in seen]
260
372
 
261
373
 
262
374
  def _hook_graph(root: Path) -> Any | None:
@@ -268,7 +380,74 @@ def _hook_graph(root: Path) -> Any | None:
268
380
  return graph
269
381
 
270
382
 
271
- def _graph_symbol(graph: Any, tokens: list[str], fold_case: bool) -> tuple[str, str] | None:
383
+ def _defines(graph: Any, word: str, fold_case: bool) -> bool:
384
+ """Whether this repo defines something by this word.
385
+
386
+ A placeholder does not count: `json` is in the graph because a file
387
+ imports it, not because the repo defines it.
388
+ """
389
+ key = word.lower() if fold_case else word
390
+ for node_id, data in graph.nodes(data=True):
391
+ if is_placeholder(data):
392
+ continue
393
+ for candidate in (node_id, str(data.get("name", ""))):
394
+ candidate_key = candidate.lower() if fold_case else candidate
395
+ if candidate_key and candidate_key == key:
396
+ return True
397
+ return False
398
+
399
+
400
+ def _has_callers(graph: Any, node_id: str) -> bool:
401
+ """Whether the graph's own `callers` listing for this node is non-empty.
402
+
403
+ The same relations `query "callers"` counts: an inbound edge whose
404
+ relations include a call or a reference. Nesting (`contains`) is not a
405
+ call -- a nested function is contained by its parent, not called by it.
406
+ """
407
+ return any(
408
+ any(relation in _CALL_RELATIONS for relation in edge_relations(graph[source][node_id]))
409
+ for source in graph.predecessors(node_id)
410
+ )
411
+
412
+
413
+ def _exempt_member(graph: Any, word: str, receiver: str | None, fold_case: bool) -> bool:
414
+ """Whether a qualified member is something the graph cannot answer for.
415
+
416
+ The receiver is not something this repo defines, so the member is a call
417
+ on something the graph does not model -- a runtime binding, or a test
418
+ double's namesake. And nothing in this repo calls anything of that name,
419
+ so the route the refusal offers (`callers <word>`) would resolve the word
420
+ to a node with no callers and answer with an empty list (round 332).
421
+
422
+ Both conditions are needed, and each of them alone would undo a decision
423
+ this gate already made:
424
+
425
+ - the receiver alone would excuse `self.check(`, where the graph does
426
+ know who calls the method;
427
+ - the callers alone would excuse `graph.jsonify`, where the receiver is
428
+ a symbol this repo defines.
429
+ """
430
+ if receiver is None:
431
+ return False
432
+ if _defines(graph, receiver, fold_case):
433
+ return False
434
+ key = word.lower() if fold_case else word
435
+ for node_id, data in graph.nodes(data=True):
436
+ if is_placeholder(data):
437
+ continue
438
+ name = str(data.get("name", ""))
439
+ name_key = name.lower() if fold_case else name
440
+ id_key = node_id.lower() if fold_case else node_id
441
+ if name_key != key and id_key != key:
442
+ continue
443
+ if _has_callers(graph, node_id):
444
+ return False
445
+ return True
446
+
447
+
448
+ def _graph_symbol(
449
+ graph: Any, tokens: list[tuple[str, str | None]], fold_case: bool
450
+ ) -> tuple[str, str] | None:
272
451
  """First token that IS something this repo defines (exact id or name), else None.
273
452
 
274
453
  A placeholder does not count. `json` is in the graph because a file imports
@@ -278,15 +457,26 @@ def _graph_symbol(graph: Any, tokens: list[str], fold_case: bool) -> tuple[str,
278
457
 
279
458
  Case is compared the way the search compares it. A case-exact search for
280
459
  `DONE` cannot find a function `done`, so it is not a search for one.
460
+
461
+ A qualified member the graph cannot answer for is not a symbol this
462
+ search is about, and does not refuse it (round 332).
281
463
  """
282
- wanted = {(token.lower() if fold_case else token): token for token in tokens}
464
+ wanted = {(token.lower() if fold_case else token): token for token, _ in tokens}
465
+ receivers = {(token.lower() if fold_case else token): receiver for token, receiver in tokens}
466
+ exempt: set[str] = set()
283
467
  for node_id, data in graph.nodes(data=True):
284
468
  if is_placeholder(data):
285
469
  continue
286
470
  for candidate in (node_id, str(data.get("name", ""))):
287
471
  key = candidate.lower() if fold_case else candidate
288
- if key and key in wanted:
289
- return node_id, wanted[key]
472
+ if not (key and key in wanted):
473
+ continue
474
+ if key in exempt:
475
+ continue
476
+ if _exempt_member(graph, key, receivers.get(key), fold_case):
477
+ exempt.add(key)
478
+ continue
479
+ return node_id, wanted[key]
290
480
  return None
291
481
 
292
482
 
graphite/cli.py CHANGED
@@ -42,7 +42,7 @@ from .daemon_health import HealthOptions, evaluate_daemon_health, format_health_
42
42
  from . import buildlock
43
43
  from .detach import spawn_detached
44
44
  from .doctor import format_doctor_text, run_doctor
45
- from .engine_identity import engine_identity
45
+ from .engine_identity import engine_identity, engine_identity_and_files
46
46
  from .export.html import to_html as export_html
47
47
  from .export.json import build_bundle, to_json as export_json
48
48
  from .export.md import to_markdown as export_md
@@ -277,10 +277,18 @@ def _scan(args: argparse.Namespace, cfg: Config) -> tuple[dict[str, Any], list[A
277
277
 
278
278
  start = time.time()
279
279
  entries = collect_files(root, cfg)
280
+ # One pass over the engine's files yields both the identity and the
281
+ # inventory, so the inventory costs nothing beyond what the fingerprint
282
+ # already cost.
283
+ engine, engine_files = engine_identity_and_files(cfg.cache_version)
280
284
  manifest = {
281
285
  "root": root.name,
282
286
  "file_count": len(entries),
283
- "engine": engine_identity(cfg.cache_version),
287
+ "engine": engine,
288
+ # The engine's own files, so a later `check` can name WHICH of them
289
+ # moved when the identity does. The fingerprint alone cannot: it says
290
+ # that something under the package directory changed and not what.
291
+ "engine_files": engine_files,
284
292
  "files": [
285
293
  {"rel_path": e.rel_path, "language": e.language, "size": e.size, "hash": e.content_hash}
286
294
  for e in entries
@@ -809,6 +817,29 @@ def _short_value(value: Any, limit: int = 12) -> str:
809
817
  return text if len(text) <= limit else text[:limit] + "..."
810
818
 
811
819
 
820
+ def _print_engine_files(files: Any) -> None:
821
+ """Name the engine's own files that moved, when they are known.
822
+
823
+ `engine_changed` otherwise says only THAT the engine moved. The file
824
+ names are what a consumer can act on, and they are what the 1.7.0 gate
825
+ could not report.
826
+ """
827
+ if not isinstance(files, dict):
828
+ return
829
+ named: list[str] = []
830
+ for key in ("changed", "added", "removed"):
831
+ values = files.get(key)
832
+ if not isinstance(values, list):
833
+ continue
834
+ for name in values:
835
+ named.append(f"{key}: {name}")
836
+ if not named:
837
+ return
838
+ print(" engine files that moved:")
839
+ for line in named:
840
+ print(f" {line}")
841
+
842
+
812
843
  def cmd_check(args: argparse.Namespace) -> int:
813
844
  root = Path(args.path).resolve()
814
845
  # Below a repository's root there is no graph to be fresh or stale, and
@@ -855,6 +886,7 @@ def cmd_check(args: argparse.Namespace) -> int:
855
886
  if reason == "engine_changed":
856
887
  print(" graphite was updated since this graph was built; rebuild to refresh")
857
888
  _print_engine_delta(status.get("engine_delta"))
889
+ _print_engine_files(status.get("engine_files"))
858
890
  for key in ("added", "changed", "removed"):
859
891
  if status.get(key):
860
892
  print(f" {key}: {', '.join(status[key])}")
@@ -1383,6 +1415,29 @@ def cmd_query(args: argparse.Namespace) -> int:
1383
1415
  return 0
1384
1416
 
1385
1417
 
1418
+ def _search_summary(result: dict[str, Any]) -> str:
1419
+ """The one line that says what was shown, how much exists, and how to see it.
1420
+
1421
+ `20 match(es)` reads as the total, and an agent that reads it that way
1422
+ believes the graph fell short and falls back to searching files one at a
1423
+ time -- the outcome the graph-first rule exists to prevent. The full
1424
+ answer was one flag away, so the line now says so (round 330). The JSON
1425
+ form already carried both figures and is unchanged.
1426
+ """
1427
+ count = result["count"]
1428
+ query = result["query"]
1429
+ if not result.get("truncated"):
1430
+ return f"[graphite] {count} match(es) for: {query}"
1431
+ total = result["total_matches"]
1432
+ if total <= MAX_SEARCH_LIMIT:
1433
+ way_out = f"pass --limit {total} to see all"
1434
+ else:
1435
+ # `--limit` is capped, so naming a number above the cap would be a
1436
+ # false instruction. Say the cap instead.
1437
+ way_out = f"--limit caps at {MAX_SEARCH_LIMIT}"
1438
+ return f"[graphite] {count} of {total} match(es) for: {query} (truncated; {way_out})"
1439
+
1440
+
1386
1441
  def cmd_search(args: argparse.Namespace) -> int:
1387
1442
  started = time.perf_counter()
1388
1443
  g = _load_cli_graph(args)
@@ -1394,8 +1449,7 @@ def cmd_search(args: argparse.Namespace) -> int:
1394
1449
  elif not result["results"]:
1395
1450
  print(f"[graphite] no matches for: {result['query']}")
1396
1451
  else:
1397
- suffix = " (truncated)" if result["truncated"] else ""
1398
- print(f"[graphite] {result['count']} match(es) for: {result['query']}{suffix}")
1452
+ print(_search_summary(result))
1399
1453
  for item in result["results"]:
1400
1454
  location = f" ({item['source_file']})" if item["source_file"] else ""
1401
1455
  print(f" - {item['id']} [{item['kind']}, {item['match_type']}]{location}")
@@ -3330,7 +3384,12 @@ def build_parser() -> argparse.ArgumentParser:
3330
3384
  default=_DEFAULT_GRAPH_JSON,
3331
3385
  help="Path to graph.json",
3332
3386
  )
3333
- p_search.add_argument("--limit", type=int, default=DEFAULT_SEARCH_LIMIT, help="Maximum results")
3387
+ p_search.add_argument(
3388
+ "--limit",
3389
+ type=int,
3390
+ default=DEFAULT_SEARCH_LIMIT,
3391
+ help=f"Maximum results (default: {DEFAULT_SEARCH_LIMIT})",
3392
+ )
3334
3393
  p_search.add_argument("--json", action="store_true", help="Emit machine-readable JSON")
3335
3394
  p_search.set_defaults(func=cmd_search)
3336
3395
 
@@ -5,6 +5,7 @@ import hashlib
5
5
  import json
6
6
  import os
7
7
  import stat
8
+ from collections.abc import Iterator
8
9
  from importlib import metadata
9
10
  from pathlib import Path
10
11
  from typing import Final
@@ -172,7 +173,36 @@ def _parser_record(name: str) -> str:
172
173
  return f"{name}=absent"
173
174
 
174
175
 
175
- def engine_identity(
176
+ def _read_engine_files(
177
+ root: Path,
178
+ *,
179
+ max_files: int,
180
+ max_file_bytes: int,
181
+ max_total_bytes: int,
182
+ ) -> Iterator[tuple[str, bytes]]:
183
+ """Every engine source file, in a stable order, with the byte budget enforced.
184
+
185
+ One pass, so that the fingerprint and the file inventory cost what the
186
+ fingerprint alone used to cost: reading the package twice would double
187
+ every build.
188
+ """
189
+ paths = _collect_engine_files(root, max_files=max_files)
190
+ inventory: list[tuple[str, Path]] = [(_contained_relative(path, root), path) for path in paths]
191
+ total_bytes = 0
192
+ for relative, path in sorted(inventory, key=lambda item: item[0]):
193
+ try:
194
+ data = _read_stable_file(path, root, max_file_bytes)
195
+ except EngineIdentityError:
196
+ raise
197
+ except OSError as exc:
198
+ raise EngineIdentityError("engine_file_unreadable") from exc
199
+ total_bytes += len(data)
200
+ if total_bytes > max_total_bytes:
201
+ raise EngineIdentityError("engine_total_too_large")
202
+ yield relative, data
203
+
204
+
205
+ def engine_identity_and_files(
176
206
  cache_version: str,
177
207
  *,
178
208
  package_root: Path | None = None,
@@ -181,8 +211,16 @@ def engine_identity(
181
211
  max_files: int = MAX_ENGINE_FILES,
182
212
  max_file_bytes: int = MAX_ENGINE_FILE_BYTES,
183
213
  max_total_bytes: int = MAX_ENGINE_TOTAL_BYTES,
184
- ) -> dict[str, str]:
185
- """Return a public, path-free identity for trusted packaged engine files."""
214
+ ) -> tuple[dict[str, str], dict[str, str]]:
215
+ """The engine's identity, and the inventory of the files it covers.
216
+
217
+ The fingerprint says THAT the engine changed; the inventory says WHICH file
218
+ changed. The fingerprint covers the PACKAGE directory, so a source edit
219
+ moves it without touching the repository being checked, while the
220
+ repository's file-level diff covers the REPOSITORY and so names nothing.
221
+ That asymmetry is why `check` reported `engine_changed` with empty
222
+ added/changed/removed lists and no actor -- the 1.7.0 gate hit exactly it.
223
+ """
186
224
  if isinstance(max_file_bytes, bool) or max_file_bytes <= 0:
187
225
  raise EngineIdentityError("engine_file_too_large")
188
226
  if isinstance(max_total_bytes, bool) or max_total_bytes <= 0:
@@ -207,7 +245,6 @@ def engine_identity(
207
245
  root = candidate_root.resolve(strict=True)
208
246
  except OSError as exc:
209
247
  raise EngineIdentityError("engine_root_invalid") from exc
210
- paths = _collect_engine_files(root, max_files=max_files)
211
248
 
212
249
  header = {
213
250
  "cache_version": cache_version,
@@ -217,22 +254,78 @@ def engine_identity(
217
254
  }
218
255
  digest = hashlib.sha256()
219
256
  digest.update(json.dumps(header, sort_keys=True, separators=(",", ":")).encode("utf-8"))
220
- total_bytes = 0
221
- inventory: list[tuple[str, Path]] = [(_contained_relative(path, root), path) for path in paths]
222
- for relative, path in sorted(inventory, key=lambda item: item[0]):
223
- try:
224
- data = _read_stable_file(path, root, max_file_bytes)
225
- except EngineIdentityError:
226
- raise
227
- except OSError as exc:
228
- raise EngineIdentityError("engine_file_unreadable") from exc
229
- total_bytes += len(data)
230
- if total_bytes > max_total_bytes:
231
- raise EngineIdentityError("engine_total_too_large")
257
+ files: dict[str, str] = {}
258
+ for relative, data in _read_engine_files(
259
+ root,
260
+ max_files=max_files,
261
+ max_file_bytes=max_file_bytes,
262
+ max_total_bytes=max_total_bytes,
263
+ ):
232
264
  encoded_name = relative.encode("utf-8")
233
265
  digest.update(len(encoded_name).to_bytes(4, "big"))
234
266
  digest.update(encoded_name)
235
267
  digest.update(len(data).to_bytes(8, "big"))
236
268
  digest.update(data)
269
+ files[relative] = hashlib.sha256(data).hexdigest()
270
+
271
+ return {**header, "fingerprint": digest.hexdigest()}, files
272
+
237
273
 
238
- return {**header, "fingerprint": digest.hexdigest()}
274
+ def engine_identity(
275
+ cache_version: str,
276
+ *,
277
+ package_root: Path | None = None,
278
+ parsers: str | None = None,
279
+ version: str | None = None,
280
+ max_files: int = MAX_ENGINE_FILES,
281
+ max_file_bytes: int = MAX_ENGINE_FILE_BYTES,
282
+ max_total_bytes: int = MAX_ENGINE_TOTAL_BYTES,
283
+ ) -> dict[str, str]:
284
+ """Return a public, path-free identity for trusted packaged engine files."""
285
+ identity, _ = engine_identity_and_files(
286
+ cache_version,
287
+ package_root=package_root,
288
+ parsers=parsers,
289
+ version=version,
290
+ max_files=max_files,
291
+ max_file_bytes=max_file_bytes,
292
+ max_total_bytes=max_total_bytes,
293
+ )
294
+ return identity
295
+
296
+
297
+ def engine_file_inventory(
298
+ package_root: Path | None = None,
299
+ *,
300
+ max_files: int = MAX_ENGINE_FILES,
301
+ max_file_bytes: int = MAX_ENGINE_FILE_BYTES,
302
+ max_total_bytes: int = MAX_ENGINE_TOTAL_BYTES,
303
+ ) -> dict[str, str]:
304
+ """The engine's own source files, keyed by path relative to the package
305
+ root and valued by the hash of their bytes.
306
+
307
+ The fingerprint says THAT the engine changed. This says WHICH file changed,
308
+ and it is the only thing that can: the fingerprint covers the PACKAGE
309
+ directory, so a source edit moves it without touching the repository being
310
+ checked, while the file-level diff covers the REPOSITORY and so names
311
+ nothing. That asymmetry is why `check` reported `engine_changed` with empty
312
+ added/changed/removed lists and no actor -- the 1.7.0 gate hit exactly it.
313
+
314
+ Keys are relative and carry no absolute path, so an inventory can be
315
+ recorded in the manifest and in a diagnostic without disclosing where the
316
+ engine is installed.
317
+ """
318
+ candidate_root = package_root if package_root is not None else Path(__file__).parent
319
+ try:
320
+ root = candidate_root.resolve(strict=True)
321
+ except OSError as exc:
322
+ raise EngineIdentityError("engine_root_invalid") from exc
323
+ return {
324
+ relative: hashlib.sha256(data).hexdigest()
325
+ for relative, data in _read_engine_files(
326
+ root,
327
+ max_files=max_files,
328
+ max_file_bytes=max_file_bytes,
329
+ max_total_bytes=max_total_bytes,
330
+ )
331
+ }
graphite/freshness.py CHANGED
@@ -6,7 +6,7 @@ from pathlib import Path
6
6
  from typing import Any
7
7
 
8
8
  from .config import Config
9
- from .engine_identity import EngineIdentityError, engine_identity
9
+ from .engine_identity import EngineIdentityError, engine_identity_and_files
10
10
  from .ingest import collect_files
11
11
 
12
12
  _DOCTOR_FILE_LIMIT = 10_000
@@ -62,6 +62,31 @@ def engine_identity_delta(previous: Any, current: dict[str, Any]) -> dict[str, A
62
62
  }
63
63
 
64
64
 
65
+ def engine_file_diff(recorded: Any, current: dict[str, str]) -> dict[str, Any] | None:
66
+ """Which of the engine's own files moved, when the manifest recorded them.
67
+
68
+ `engine_changed` says the engine moved and nothing else, and the
69
+ repository's added/changed/removed lists are empty BY CONSTRUCTION on that
70
+ path -- the file diff is never computed. So the actor stayed unnamed: the
71
+ 1.7.0 pre-push gate reported `engine_changed` on two tests in two workers
72
+ and could say nothing about what had moved.
73
+
74
+ The manifest records the engine's file inventory, so the difference names
75
+ the file. `None` means the question cannot be answered -- a manifest
76
+ written before the inventory was recorded -- and it is reported as absent
77
+ rather than as "nothing changed", which would be a different and false
78
+ claim.
79
+ """
80
+ if not isinstance(recorded, dict) or not recorded:
81
+ return None
82
+ added = sorted(set(current) - set(recorded))
83
+ removed = sorted(set(recorded) - set(current))
84
+ changed = sorted(
85
+ name for name in set(current) & set(recorded) if current[name] != recorded[name]
86
+ )
87
+ return {"added": added, "changed": changed, "removed": removed}
88
+
89
+
65
90
  def graph_engine_changed(cfg: Config, current_engine: dict[str, Any]) -> bool:
66
91
  """True when a built graph records an engine identity other than the current one.
67
92
 
@@ -127,7 +152,7 @@ def check_graph_freshness(
127
152
  raise FreshnessLimitError("freshness file limit exceeded")
128
153
  if not ignore_engine:
129
154
  try:
130
- current_engine = engine_identity(cfg.cache_version)
155
+ current_engine, current_files = engine_identity_and_files(cfg.cache_version)
131
156
  except EngineIdentityError:
132
157
  return {
133
158
  "stale": True,
@@ -141,6 +166,7 @@ def check_graph_freshness(
141
166
  "stale": True,
142
167
  "reason": "engine_changed",
143
168
  "engine_delta": engine_identity_delta(previous.get("engine"), current_engine),
169
+ "engine_files": engine_file_diff(previous.get("engine_files"), current_files),
144
170
  "added": [],
145
171
  "changed": [],
146
172
  "removed": [],
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: graphite-code
3
- Version: 1.8.2
3
+ Version: 1.9.1
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
@@ -49,7 +49,7 @@ Description-Content-Type: text/markdown
49
49
 
50
50
  Local-first, deterministic knowledge graph extraction for codebases — zero-LLM, daemon-maintained, agent-agnostic.
51
51
 
52
- **Status: 1.8.0, production/stable.** Published on PyPI as
52
+ **Status: 1.9.1, production/stable.** Published on PyPI as
53
53
  [`graphite-code`](https://pypi.org/project/graphite-code/) with PEP 740
54
54
  attestations; supported on Windows, Linux and macOS with Python 3.11–3.14
55
55
  (every cell gates CI). What 1.x promises — CLI, JSON outputs, `graph.json`,
@@ -1,9 +1,9 @@
1
- graphite/__init__.py,sha256=yFVfDAknH4Qw5mLU4UT9fdViz7Y752yfgC3Cgh3zMqA,2181
1
+ graphite/__init__.py,sha256=_eFv1YrMH5u50nLWZL2_Z7LN22zTt5OjF9Ci5M3_8b4,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=lahVeyEAkO9V7HEEDyrhzHjn9wX51GyVh8m4zDDxX5Q,67168
6
+ graphite/agent_hooks.py,sha256=uZDxS2moMwnj8_xhXiIgP7sWkRpstz9dWJSkIZ3oJVc,75857
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
@@ -11,7 +11,7 @@ graphite/bootstrap.py,sha256=OPDzN9jSr8IE1N7xOnVKk3FgO2UqBTOUNcNV-pZAsus,8448
11
11
  graphite/buildlock.py,sha256=QXo4cnGGCmhxuuYdy6f5OHF82Yg6zHUMxLVdxwG49ic,5393
12
12
  graphite/cache.py,sha256=Mh28dYg9irXBvH-oa8jpFSM-ehXcs5FuNVHVzF_WRA8,9143
13
13
  graphite/channel.py,sha256=UNFAGuws6XFbkBu0fnVLepBDxT1BWAJlW33IPVlDi9M,72908
14
- graphite/cli.py,sha256=RKJwpIp5XKBHK8Cir4va7pMkTony8golsIN-TxXAHrs,164102
14
+ graphite/cli.py,sha256=kjTdUwP2t0OxLLxJkQb9K7azu89is9U-x4f_ulczd7I,166397
15
15
  graphite/cluster.py,sha256=j5dFT40DD7scD4h8d7XJoAGQIcJKpsKsrFceiJkOuzw,4066
16
16
  graphite/config.py,sha256=ZWhWOWYEyKGoHCp6vWI4M4NQM57ohf5BaX0Ty8HfWYM,9267
17
17
  graphite/context.py,sha256=vWMuFxqDGby-9Gs_t9XNJzKR-nZqwMdbU2y6N_GypWU,13215
@@ -23,8 +23,8 @@ graphite/dependency_install.py,sha256=JpuIGFzGfZZYDA-ymnBVDiG3t-brpDZ4rwF99HxY7n
23
23
  graphite/detach.py,sha256=BlUjeh_UcjpQ9DMRZFOgxhk83zUbMSTPmXe6t1FFEKE,1270
24
24
  graphite/doctor.py,sha256=CknFB3EeBiiWbQc9IePBDuQWf6foMbI9Bbq871SNxvg,35249
25
25
  graphite/doctor_probes.py,sha256=x2WgaQfUwT0cXspKXWqmrWdQ6-3NtUB0au27XED4z2M,92885
26
- graphite/engine_identity.py,sha256=hZYA9fBsg2fj_61Rtkc84XzJrdsa2MaDFOLZJV4I7eE,8951
27
- graphite/freshness.py,sha256=zBREb_Llvh1Rq2Dairjrh_yCkEy-WRSh2xv5JWYvOgQ,6557
26
+ graphite/engine_identity.py,sha256=fXyc7hMFayqDzeIq_NzOtAkK6N1D8U2Rz8-H7CQuD10,12395
27
+ graphite/freshness.py,sha256=Rr3h0xxuD-GN83ESa_8GFpZZBB-2cdmyk_ULALbrlig,7892
28
28
  graphite/git.py,sha256=3dWIVVBkEKK8IPIYx_vfAL6E6Syk26RSv_LONUQ7FpI,16047
29
29
  graphite/graph.py,sha256=2mhbIrx4ekidgXnw3gLWDtGcVdvOmYfpZ4oATtwbao0,4284
30
30
  graphite/graph_io.py,sha256=rWjc3_Lq7DOg1_XuM4eY8GH9GwIHowo0CcABTIRtLyc,6563
@@ -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.8.2.dist-info/METADATA,sha256=c_EXphDQPbhwa8n3VNbmx2bnh89QvUpfZyBLMvSnqHQ,48525
117
- graphite_code-1.8.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
118
- graphite_code-1.8.2.dist-info/entry_points.txt,sha256=-BpYAYFyn58DYi-hrFW9hMz6mTwNsYI44s9gaef4MiM,87
119
- graphite_code-1.8.2.dist-info/licenses/LICENSE,sha256=mfotJ1Lk0VVUgoEPOIR7-x5cvYiz2UkuVH7e3fhoDiY,1066
120
- graphite_code-1.8.2.dist-info/RECORD,,
116
+ graphite_code-1.9.1.dist-info/METADATA,sha256=nSC2uqjvGmoD0XZFe0yXT2vmim8mHzo41JeEf88ze7Q,48525
117
+ graphite_code-1.9.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
118
+ graphite_code-1.9.1.dist-info/entry_points.txt,sha256=-BpYAYFyn58DYi-hrFW9hMz6mTwNsYI44s9gaef4MiM,87
119
+ graphite_code-1.9.1.dist-info/licenses/LICENSE,sha256=mfotJ1Lk0VVUgoEPOIR7-x5cvYiz2UkuVH7e3fhoDiY,1066
120
+ graphite_code-1.9.1.dist-info/RECORD,,