sourcecode 2.6.2__py3-none-any.whl → 2.6.5__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.
- sourcecode/__init__.py +1 -1
- sourcecode/cli.py +152 -3
- sourcecode/mcp/registry.py +49 -1
- sourcecode/parse_cache.py +138 -0
- sourcecode/repository_ir.py +61 -12
- sourcecode/spring_impact.py +1 -1
- sourcecode/spring_tx_analyzer.py +141 -4
- sourcecode/verify_edit.py +588 -0
- sourcecode/verify_rules.py +304 -0
- {sourcecode-2.6.2.dist-info → sourcecode-2.6.5.dist-info}/METADATA +1 -1
- {sourcecode-2.6.2.dist-info → sourcecode-2.6.5.dist-info}/RECORD +14 -11
- {sourcecode-2.6.2.dist-info → sourcecode-2.6.5.dist-info}/WHEEL +0 -0
- {sourcecode-2.6.2.dist-info → sourcecode-2.6.5.dist-info}/entry_points.txt +0 -0
- {sourcecode-2.6.2.dist-info → sourcecode-2.6.5.dist-info}/licenses/LICENSE +0 -0
sourcecode/__init__.py
CHANGED
sourcecode/cli.py
CHANGED
|
@@ -2,6 +2,7 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import hashlib
|
|
4
4
|
import json
|
|
5
|
+
import difflib
|
|
5
6
|
import os
|
|
6
7
|
import sys
|
|
7
8
|
import threading
|
|
@@ -254,6 +255,8 @@ _SUBCOMMANDS: frozenset[str] = frozenset(
|
|
|
254
255
|
"explain",
|
|
255
256
|
# Spring Boot 2→3 migration readiness
|
|
256
257
|
"migrate-check",
|
|
258
|
+
# In-loop semantic diff gate (working tree vs HEAD)
|
|
259
|
+
"verify-edit",
|
|
257
260
|
# Native file rename (BLOCKER-A)
|
|
258
261
|
"rename-class",
|
|
259
262
|
# Large file semantic chunking (BLOCKER-B)
|
|
@@ -329,6 +332,54 @@ def _reject_path_before_subcommand(path_token: str, subcommand: str) -> "NoRetur
|
|
|
329
332
|
raise SystemExit(2)
|
|
330
333
|
|
|
331
334
|
|
|
335
|
+
def _reject_unknown_command(token: str) -> "NoReturn":
|
|
336
|
+
"""Refuse a first positional that is neither a known subcommand nor a real path.
|
|
337
|
+
|
|
338
|
+
`ask` accepts a bare repository path (`ask ./repo`) as an implicit scan, so a
|
|
339
|
+
mistyped subcommand used to be swallowed as a path and then surfaced a
|
|
340
|
+
misleading error naming the *wrong* token — `ask spring-audi` complained the
|
|
341
|
+
directory 'spring-audi' did not exist, and `ask notacommand /tmp` complained
|
|
342
|
+
'No such command /tmp' (the path, not the typo). Name the token the user
|
|
343
|
+
actually got wrong, and suggest the closest real commands.
|
|
344
|
+
"""
|
|
345
|
+
matches = difflib.get_close_matches(token, sorted(_SUBCOMMANDS), n=3, cutoff=0.6)
|
|
346
|
+
first = f"error: '{token}' is not a known command"
|
|
347
|
+
if matches:
|
|
348
|
+
first += f". Did you mean: {', '.join(matches)}?"
|
|
349
|
+
else:
|
|
350
|
+
first += " and is not an existing directory to scan."
|
|
351
|
+
print(
|
|
352
|
+
first + "\n run 'ask --help' to list commands, or pass an existing "
|
|
353
|
+
"repository path.",
|
|
354
|
+
file=sys.stderr,
|
|
355
|
+
)
|
|
356
|
+
raise SystemExit(2)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _has_trailing_nonsubcommand_positional(args: list[str], after: int) -> bool:
|
|
360
|
+
"""True when a bare positional that is NOT a subcommand appears after index
|
|
361
|
+
``after`` (options and the values they consume are skipped).
|
|
362
|
+
|
|
363
|
+
The implicit scan (`ask <path>`) owns exactly one positional, and a valid
|
|
364
|
+
invocation with two positionals always starts with a subcommand. So a first
|
|
365
|
+
non-subcommand positional followed by another non-subcommand positional —
|
|
366
|
+
`ask notacommand /tmp` — is malformed: the user meant a command. A trailing
|
|
367
|
+
token that IS a subcommand is left for ``_reject_path_before_subcommand``."""
|
|
368
|
+
skip_next = False
|
|
369
|
+
for arg in args[after + 1:]:
|
|
370
|
+
if skip_next:
|
|
371
|
+
skip_next = False
|
|
372
|
+
continue
|
|
373
|
+
if arg.startswith("-"):
|
|
374
|
+
if arg.split("=")[0] in _OPTIONS_WITH_VALUE and "=" not in arg:
|
|
375
|
+
skip_next = True
|
|
376
|
+
continue
|
|
377
|
+
if arg in _SUBCOMMANDS:
|
|
378
|
+
return False # wrong-order path/subcommand — handled elsewhere
|
|
379
|
+
return True
|
|
380
|
+
return False
|
|
381
|
+
|
|
382
|
+
|
|
332
383
|
def _preprocess_args(args: list[str]) -> list[str]:
|
|
333
384
|
"""Extract a repository path token from an args list and store it in _detected_path.
|
|
334
385
|
|
|
@@ -361,7 +412,13 @@ def _preprocess_args(args: list[str]) -> list[str]:
|
|
|
361
412
|
return result # known subcommand — leave for Click to dispatch
|
|
362
413
|
if _path_index >= 0:
|
|
363
414
|
continue # a later positional is the subcommand's own business
|
|
364
|
-
# First genuine positional
|
|
415
|
+
# First genuine positional. `ask` treats it as the repository path to scan
|
|
416
|
+
# (existence is validated downstream, not here). But if it is followed by
|
|
417
|
+
# another non-subcommand positional, the one-path scan cannot own both —
|
|
418
|
+
# `ask notacommand /tmp` — so the user meant a command: name the token they
|
|
419
|
+
# got wrong instead of swallowing it and erroring on the next one.
|
|
420
|
+
if _has_trailing_nonsubcommand_positional(result, i):
|
|
421
|
+
_reject_unknown_command(arg)
|
|
365
422
|
_set_detected_path(arg)
|
|
366
423
|
_path_index = i
|
|
367
424
|
if _path_index >= 0:
|
|
@@ -1276,11 +1333,23 @@ def main(
|
|
|
1276
1333
|
_raw_path_input = _get_detected_path()
|
|
1277
1334
|
target = Path(_raw_path_input).resolve()
|
|
1278
1335
|
if not target.exists():
|
|
1336
|
+
# A non-existent path that closely matches a command name is almost always a
|
|
1337
|
+
# mistyped subcommand (`ask spring-audi`) swallowed as an implicit-scan path,
|
|
1338
|
+
# not a real directory. Point at the likely command instead of only the path.
|
|
1339
|
+
_cmd_matches = difflib.get_close_matches(
|
|
1340
|
+
_raw_path_input, sorted(_SUBCOMMANDS), n=3, cutoff=0.6
|
|
1341
|
+
)
|
|
1342
|
+
_hint = "Pass an existing repository directory."
|
|
1343
|
+
if _cmd_matches:
|
|
1344
|
+
_hint = (
|
|
1345
|
+
f"If you meant a command, try: {', '.join('ask ' + m for m in _cmd_matches)}. "
|
|
1346
|
+
"Otherwise pass an existing repository directory."
|
|
1347
|
+
)
|
|
1279
1348
|
_emit_error_json(
|
|
1280
1349
|
INVALID_INPUT_CODE,
|
|
1281
1350
|
f"Directory '{_raw_path_input}' does not exist.",
|
|
1282
1351
|
path=_raw_path_input,
|
|
1283
|
-
hint=
|
|
1352
|
+
hint=_hint,
|
|
1284
1353
|
expected="An existing directory path.",
|
|
1285
1354
|
)
|
|
1286
1355
|
raise typer.Exit(code=1)
|
|
@@ -5526,7 +5595,7 @@ def spring_audit_cmd(
|
|
|
5526
5595
|
help="Accepted for compatibility; this command always reads fresh source (no snapshot cache). No-op.",
|
|
5527
5596
|
),
|
|
5528
5597
|
) -> None:
|
|
5529
|
-
"""Spring semantic audit: TX anomalies (TX-001..
|
|
5598
|
+
"""Spring semantic audit: TX anomalies (TX-001..006) + security surface (SEC-001..003).
|
|
5530
5599
|
|
|
5531
5600
|
\b
|
|
5532
5601
|
Detects:
|
|
@@ -5535,6 +5604,7 @@ def spring_audit_cmd(
|
|
|
5535
5604
|
TX-003 readOnly=true boundary propagating to write operation
|
|
5536
5605
|
TX-004 NOT_SUPPORTED/NEVER within active TX chain
|
|
5537
5606
|
TX-005 Exception swallowing inside @Transactional
|
|
5607
|
+
TX-006 Self-invocation of @Transactional sibling (proxy bypass)
|
|
5538
5608
|
SEC-001 Unsecured endpoint in annotation_based security model
|
|
5539
5609
|
SEC-002 CVE-2025-41248: @PreAuthorize on inherited method from generic supertype
|
|
5540
5610
|
SEC-003 @Transactional on @Controller/@RestController (TX in wrong layer)
|
|
@@ -5678,6 +5748,85 @@ def spring_audit_cmd(
|
|
|
5678
5748
|
raise typer.Exit(code=1)
|
|
5679
5749
|
|
|
5680
5750
|
|
|
5751
|
+
# ── verify-edit: in-loop semantic diff gate ───────────────────────────────────
|
|
5752
|
+
|
|
5753
|
+
|
|
5754
|
+
@app.command("verify-edit")
|
|
5755
|
+
def verify_edit_cmd(
|
|
5756
|
+
path: Path = typer.Argument(
|
|
5757
|
+
Path("."),
|
|
5758
|
+
help="Repository path (default: current directory). Diffs the working tree vs HEAD.",
|
|
5759
|
+
),
|
|
5760
|
+
output_path: Optional[Path] = typer.Option(
|
|
5761
|
+
None, "--output", "-o", help="Write the verdict JSON to a file instead of stdout."
|
|
5762
|
+
),
|
|
5763
|
+
format: str = typer.Option("json", "--format", help="Output format: json."),
|
|
5764
|
+
ci: bool = typer.Option(
|
|
5765
|
+
True,
|
|
5766
|
+
"--ci/--no-ci",
|
|
5767
|
+
help="Exit non-zero on a broken/unverified verdict (default on — for gates and hooks).",
|
|
5768
|
+
),
|
|
5769
|
+
install_hook: Optional[str] = typer.Option(
|
|
5770
|
+
None,
|
|
5771
|
+
"--install-hook",
|
|
5772
|
+
help="Install a git hook (pre-commit|pre-push) that runs this gate, then exit. Does not verify.",
|
|
5773
|
+
),
|
|
5774
|
+
) -> None:
|
|
5775
|
+
"""Semantic diff gate: did the working-tree edits change runtime behavior?
|
|
5776
|
+
|
|
5777
|
+
Deterministic, in-loop verdict over the diff of the working tree against HEAD:
|
|
5778
|
+
public contract, @Transactional proxy boundary, security surface, bean wiring,
|
|
5779
|
+
custom domain rules, and blast radius. Built for the agent write-loop (MCP) and
|
|
5780
|
+
git hooks. Only regressions the edit INTRODUCED (vs HEAD) block — pre-existing
|
|
5781
|
+
debt never fails an unrelated commit.
|
|
5782
|
+
|
|
5783
|
+
Custom rules: drop a `.ask/verify-rules.json` at the repo root to enforce your own
|
|
5784
|
+
invariants (e.g. "no @RestController injects a *DaoJpa", "every /payroll endpoint
|
|
5785
|
+
requires role X"). They gate the same way as the built-in axes.
|
|
5786
|
+
|
|
5787
|
+
Exit codes (with --ci, the default): 0 = pass, 1 = break (a blocking axis proved
|
|
5788
|
+
a regression), 2 = unverified (a blocking axis could not be computed — never a
|
|
5789
|
+
silent pass) or the path is not a git repository.
|
|
5790
|
+
|
|
5791
|
+
Examples:
|
|
5792
|
+
ask verify-edit # verify the current working tree
|
|
5793
|
+
ask verify-edit /path/to/repo
|
|
5794
|
+
ask verify-edit --no-ci # always exit 0 (report only)
|
|
5795
|
+
ask verify-edit --install-hook pre-commit
|
|
5796
|
+
"""
|
|
5797
|
+
from sourcecode import verify_edit as _ve
|
|
5798
|
+
|
|
5799
|
+
if install_hook is not None:
|
|
5800
|
+
try:
|
|
5801
|
+
_hook_path = _ve.install_git_hook(path, install_hook)
|
|
5802
|
+
except _ve.VerifyEditError as exc:
|
|
5803
|
+
_emit_error_json(
|
|
5804
|
+
INVALID_INPUT_CODE,
|
|
5805
|
+
str(exc),
|
|
5806
|
+
hint=f"Choose a hook type: {' | '.join(_ve.HOOK_TYPES)}. The repo must be a git repository.",
|
|
5807
|
+
)
|
|
5808
|
+
raise typer.Exit(code=2)
|
|
5809
|
+
typer.echo(f"Installed verify-edit {install_hook} hook: {_hook_path}", err=True)
|
|
5810
|
+
typer.echo(f"It runs `ask verify-edit --ci` and blocks on a break; bypass with git --no-verify.", err=True)
|
|
5811
|
+
return
|
|
5812
|
+
|
|
5813
|
+
try:
|
|
5814
|
+
v = _ve.verify_edit(path)
|
|
5815
|
+
except _ve.VerifyEditError as exc:
|
|
5816
|
+
_emit_error_json(
|
|
5817
|
+
INVALID_INPUT_CODE,
|
|
5818
|
+
str(exc),
|
|
5819
|
+
hint="verify-edit needs a git repository with a HEAD commit (it diffs the working tree vs HEAD).",
|
|
5820
|
+
)
|
|
5821
|
+
raise typer.Exit(code=2 if ci else 0)
|
|
5822
|
+
|
|
5823
|
+
output = _serialize_dict(v.to_dict(), format)
|
|
5824
|
+
_emit_command_output(output, output_path, False,
|
|
5825
|
+
success_msg=f"verify-edit verdict written to {output_path}")
|
|
5826
|
+
if ci and v.exit_code != 0:
|
|
5827
|
+
raise typer.Exit(code=v.exit_code)
|
|
5828
|
+
|
|
5829
|
+
|
|
5681
5830
|
# ── Spring Boot Migration Check ───────────────────────────────────────────────
|
|
5682
5831
|
|
|
5683
5832
|
|
sourcecode/mcp/registry.py
CHANGED
|
@@ -1269,6 +1269,7 @@ _MCP_HIDDEN_CANONICAL_TOOLS: frozenset[str] = frozenset({
|
|
|
1269
1269
|
"spring_audit", # curated: repo_path + scope + min_severity only (strips output_path/format/copy)
|
|
1270
1270
|
"impact_chain", # curated: repo_path + symbol + depth + query_type with choices
|
|
1271
1271
|
"migrate_check", # curated: repo_path + min_severity only (strips output_path/format/copy/ci)
|
|
1272
|
+
"verify_edit", # curated: repo_path only (report-only --no-ci; strips output_path/format/ci)
|
|
1272
1273
|
# MCP self-management (an agent is not the MCP client admin)
|
|
1273
1274
|
"mcp_init",
|
|
1274
1275
|
"mcp_serve",
|
|
@@ -1450,7 +1451,54 @@ min_severity: "low" (default) | "medium" | "high" | "critical" — filter thresh
|
|
|
1450
1451
|
docstring_override=_MIGRATE_CHECK_DOC,
|
|
1451
1452
|
)
|
|
1452
1453
|
|
|
1453
|
-
|
|
1454
|
+
_VERIFY_EDIT_DOC = """\
|
|
1455
|
+
Semantic diff gate: did the working-tree edits change runtime behavior? JAVA/SPRING.
|
|
1456
|
+
|
|
1457
|
+
When to call: right AFTER editing Java source, BEFORE proposing a commit — the
|
|
1458
|
+
in-loop guardrail. Deterministic verdict over the diff of the working tree vs HEAD.
|
|
1459
|
+
|
|
1460
|
+
Report-only over MCP: it ALWAYS returns the verdict payload (never errors on a
|
|
1461
|
+
break) so you can read the result and auto-correct. Read `verdict`:
|
|
1462
|
+
"pass" — no runtime-behavior regression proven; safe to proceed.
|
|
1463
|
+
"break" — a blocking axis proved a regression; fix before committing. See
|
|
1464
|
+
`axes` + `reasons`.
|
|
1465
|
+
"unverified" — an axis could not be computed (e.g. parse failure); do not treat
|
|
1466
|
+
as safe.
|
|
1467
|
+
|
|
1468
|
+
Axes (each a diff HEAD→working):
|
|
1469
|
+
contract_broken — public API removed / visibility-downgraded / signature changed
|
|
1470
|
+
tx_boundary_changed — @Transactional now on a private/final method = silent CGLIB
|
|
1471
|
+
proxy bypass (TX ignored at runtime)
|
|
1472
|
+
security_delta — a new security finding the edit introduced
|
|
1473
|
+
new_orphan_bean — a bean that lost all its injection wiring
|
|
1474
|
+
blast_radius — informational: entry points reached by the changed files
|
|
1475
|
+
|
|
1476
|
+
Needs a git repository with a HEAD commit (it diffs the working tree vs HEAD).
|
|
1477
|
+
"""
|
|
1478
|
+
|
|
1479
|
+
verify_edit = _alias_spec(
|
|
1480
|
+
"verify_edit",
|
|
1481
|
+
"Semantic diff gate over working-tree vs HEAD: contract / TX / security / bean-wiring. JAVA/SPRING.",
|
|
1482
|
+
("verify-edit",),
|
|
1483
|
+
(
|
|
1484
|
+
ToolParamSpec("repo_path", "argument", str, required=False, default=".", is_path=True,
|
|
1485
|
+
help="Absolute path to the git repository (default: current directory)."),
|
|
1486
|
+
),
|
|
1487
|
+
# Report-only: --no-ci so the tool always returns the verdict JSON (a break is
|
|
1488
|
+
# data for the agent, not a command failure that would surface as an error).
|
|
1489
|
+
lambda inputs: [
|
|
1490
|
+
"verify-edit",
|
|
1491
|
+
str(inputs.get("repo_path", ".")),
|
|
1492
|
+
"--no-ci",
|
|
1493
|
+
"--format", "json",
|
|
1494
|
+
],
|
|
1495
|
+
supported_targets=("repo_path",),
|
|
1496
|
+
unsupported_targets=("file_path",),
|
|
1497
|
+
validator=validate_repo_path,
|
|
1498
|
+
docstring_override=_VERIFY_EDIT_DOC,
|
|
1499
|
+
)
|
|
1500
|
+
|
|
1501
|
+
return [spring_audit, impact_chain, migrate_check, verify_edit]
|
|
1454
1502
|
|
|
1455
1503
|
|
|
1456
1504
|
@lru_cache(maxsize=1)
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Content-addressed per-file parse cache (verify-edit Fase V4 — sub-second loop).
|
|
2
|
+
|
|
3
|
+
The bottleneck, measured: on a 1-file edit in a large repo, ``build_repo_ir`` re-parses
|
|
4
|
+
*every* file, and per-file symbol extraction dominates the working-tree CIR build (~85%
|
|
5
|
+
of warm time; ~1.0s of 1.16s at 4.8k symbols). Yet the parse of an unchanged file is a
|
|
6
|
+
**pure function of its bytes** — so it can be memoised across builds.
|
|
7
|
+
|
|
8
|
+
This cache stores the output of ``_extract_symbols`` — ``(package, imports, symbols)`` —
|
|
9
|
+
keyed by a content hash of ``(rel_path, capture_signature, source)``. Properties that
|
|
10
|
+
make it safe:
|
|
11
|
+
|
|
12
|
+
* **Content-addressed ⇒ never stale.** The key *is* the content; a changed file yields
|
|
13
|
+
a different key and misses (re-parses), it never serves an old parse. There is no
|
|
14
|
+
invalidation to get wrong — unlike a signature-keyed cache.
|
|
15
|
+
* **Correctness never depends on it.** A miss, a corrupt entry, or an unwritable dir all
|
|
16
|
+
degrade to "parse it" — the CIR is byte-identical whether the cache hit or missed
|
|
17
|
+
(proven by the cir_hash-equivalence test, not assumed).
|
|
18
|
+
* **Isolated from the whole-CIR cache.** Its own directory tree; it can never poison the
|
|
19
|
+
``java-cir`` knowledge entry that ``explain``/``impact``/``review-pr`` share.
|
|
20
|
+
|
|
21
|
+
Deserialisation was measured at ~5× cheaper than re-parsing (38ms vs 197ms for 4.8k
|
|
22
|
+
symbols), so the round-trip is a real win, not a wash.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import dataclasses
|
|
27
|
+
import hashlib
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import TYPE_CHECKING, Optional
|
|
32
|
+
|
|
33
|
+
from sourcecode.context_cache import _atomic_write, _base_dir
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from sourcecode.repository_ir import SymbolRecord
|
|
37
|
+
|
|
38
|
+
_CACHE_SUBDIR = "parse-cache-v1" # bump when the SymbolRecord shape or extractor changes
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def is_enabled() -> bool:
|
|
42
|
+
"""On unless explicitly disabled (shares the context-cache kill switch). Correctness
|
|
43
|
+
is identical either way; this only trades disk for CPU."""
|
|
44
|
+
return os.environ.get("SOURCECODE_CONTEXT_CACHE_DISABLE", "") not in ("1", "true", "yes")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _cache_root() -> Path:
|
|
48
|
+
return _base_dir() / _CACHE_SUBDIR
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def file_key(rel_path: str, source: str, capture_sig: str) -> str:
|
|
52
|
+
"""Content hash of everything ``_extract_symbols`` depends on. Two identical inputs
|
|
53
|
+
⇒ same key (reuse); any change ⇒ different key (miss, re-parse)."""
|
|
54
|
+
h = hashlib.sha256()
|
|
55
|
+
h.update(rel_path.encode("utf-8", "replace"))
|
|
56
|
+
h.update(b"\x00")
|
|
57
|
+
h.update(capture_sig.encode("utf-8", "replace"))
|
|
58
|
+
h.update(b"\x00")
|
|
59
|
+
h.update(source.encode("utf-8", "replace"))
|
|
60
|
+
return h.hexdigest()[:32]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _path_for(key: str) -> Path:
|
|
64
|
+
# Shard by the first 2 hex chars so no single directory grows unbounded.
|
|
65
|
+
return _cache_root() / key[:2] / f"{key}.json"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def get(key: str) -> "Optional[tuple[str, list[str], list[SymbolRecord]]]":
|
|
69
|
+
"""Return the cached ``(package, imports, symbols)`` for *key*, or None on any miss.
|
|
70
|
+
Best-effort: a missing file, unreadable bytes, or a decode/shape error all read as a
|
|
71
|
+
miss (the caller then parses) — never an exception."""
|
|
72
|
+
if not is_enabled():
|
|
73
|
+
return None
|
|
74
|
+
from sourcecode.repository_ir import SymbolRecord
|
|
75
|
+
|
|
76
|
+
p = _path_for(key)
|
|
77
|
+
try:
|
|
78
|
+
raw = p.read_bytes()
|
|
79
|
+
except OSError:
|
|
80
|
+
return None
|
|
81
|
+
try:
|
|
82
|
+
d = json.loads(raw)
|
|
83
|
+
pkg = d["p"]
|
|
84
|
+
imports = list(d["i"])
|
|
85
|
+
symbols = [SymbolRecord(**sd) for sd in d["s"]]
|
|
86
|
+
except (ValueError, KeyError, TypeError):
|
|
87
|
+
return None # corrupt or shape-drifted entry — treat as absent, will rebuild
|
|
88
|
+
return pkg, imports, symbols
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def put(key: str, package: str, imports: list[str], symbols: "list[SymbolRecord]") -> None:
|
|
92
|
+
"""Store a parse result. Best-effort and side-effect-free on failure: caching is a
|
|
93
|
+
performance aid, never a correctness dependency."""
|
|
94
|
+
if not is_enabled():
|
|
95
|
+
return
|
|
96
|
+
try:
|
|
97
|
+
payload = {
|
|
98
|
+
"p": package,
|
|
99
|
+
"i": list(imports),
|
|
100
|
+
"s": [dataclasses.asdict(s) for s in symbols],
|
|
101
|
+
}
|
|
102
|
+
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
103
|
+
p = _path_for(key)
|
|
104
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
_atomic_write(p, data)
|
|
106
|
+
except Exception:
|
|
107
|
+
pass # unwritable / serialisation fault — silently skip; correctness unaffected
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ── generic JSON blob (V4b: the per-file *body-fact* bundle) ─────────────────────
|
|
111
|
+
# The Pass-2 fact extractors (body/literal/guard/field-type/…) are, like symbol
|
|
112
|
+
# extraction, pure functions of the file's bytes, so their combined output is memoised
|
|
113
|
+
# under the SAME content key with a distinct suffix. Values are already plain JSON dicts
|
|
114
|
+
# (atomic-fact IR), so no dataclass reconstruction is needed. Same best-effort contract:
|
|
115
|
+
# a miss/corrupt entry recomputes; the CIR is byte-identical either way.
|
|
116
|
+
def _blob_path(key: str) -> Path:
|
|
117
|
+
return _cache_root() / key[:2] / f"{key}.blob.json"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def get_blob(key: str) -> Optional[dict]:
|
|
121
|
+
if not is_enabled():
|
|
122
|
+
return None
|
|
123
|
+
try:
|
|
124
|
+
return json.loads(_blob_path(key).read_bytes())
|
|
125
|
+
except (OSError, ValueError):
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def put_blob(key: str, data: dict) -> None:
|
|
130
|
+
if not is_enabled():
|
|
131
|
+
return
|
|
132
|
+
try:
|
|
133
|
+
raw = json.dumps(data, ensure_ascii=False).encode("utf-8")
|
|
134
|
+
p = _blob_path(key)
|
|
135
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
136
|
+
_atomic_write(p, raw)
|
|
137
|
+
except Exception:
|
|
138
|
+
pass
|
sourcecode/repository_ir.py
CHANGED
|
@@ -14,6 +14,7 @@ No inference, approximation, or heuristics.
|
|
|
14
14
|
|
|
15
15
|
from __future__ import annotations
|
|
16
16
|
|
|
17
|
+
import hashlib
|
|
17
18
|
import random
|
|
18
19
|
import re
|
|
19
20
|
import subprocess
|
|
@@ -2097,6 +2098,21 @@ def _extract_body_facts(
|
|
|
2097
2098
|
receiver, callee = m.group(1), m.group(2)
|
|
2098
2099
|
if callee in _CALL_KEYWORDS:
|
|
2099
2100
|
continue
|
|
2101
|
+
if receiver is None:
|
|
2102
|
+
# A chained/qualified call — `expr().foo()`, `getBean().foo()`,
|
|
2103
|
+
# `a.b().foo()` — leaves the receiver group empty because the
|
|
2104
|
+
# receiver is not a bare identifier. It must NOT be mistaken for an
|
|
2105
|
+
# unqualified self-call: if the callee is immediately preceded by '.'
|
|
2106
|
+
# the call is qualified (goes through whatever the preceding
|
|
2107
|
+
# expression returns, e.g. a Spring proxy), so mark it as a
|
|
2108
|
+
# non-self expression receiver. (openmrs OrderServiceImpl routes
|
|
2109
|
+
# REQUIRES_NEW through Context.getOrderService()....() precisely to
|
|
2110
|
+
# keep the proxy — that is correct code, not a self-invocation.)
|
|
2111
|
+
j = m.start() - 1
|
|
2112
|
+
while j >= 0 and body[j] in " \t\r\n":
|
|
2113
|
+
j -= 1
|
|
2114
|
+
if j >= 0 and body[j] == ".":
|
|
2115
|
+
receiver = "<expr>"
|
|
2100
2116
|
resolved: Optional[str] = None
|
|
2101
2117
|
if receiver in (None, "this") and callee in sib:
|
|
2102
2118
|
cands = [f for f in sib[callee] if f != caller.symbol]
|
|
@@ -4968,6 +4984,15 @@ def build_repo_ir(
|
|
|
4968
4984
|
custom_security = _load_custom_security(root)
|
|
4969
4985
|
_custom_sec_tuple = tuple(custom_security)
|
|
4970
4986
|
_extra_capture = _capture_markers(custom_security)
|
|
4987
|
+
# V4: content-addressed per-file parse cache. The symbol extraction of an unchanged
|
|
4988
|
+
# file is a pure function of its bytes (+ the capture markers), so it is memoised
|
|
4989
|
+
# across builds — a 1-file edit re-parses 1 file, not the whole repo. The cache never
|
|
4990
|
+
# changes the result (a miss just re-parses); the capture signature keys entries so a
|
|
4991
|
+
# different custom-security config cannot serve a parse produced under another.
|
|
4992
|
+
from sourcecode import parse_cache as _pc
|
|
4993
|
+
_capture_sig = hashlib.sha256(
|
|
4994
|
+
repr(sorted(_extra_capture)).encode("utf-8", "replace")
|
|
4995
|
+
).hexdigest()[:16] if _extra_capture else "-"
|
|
4971
4996
|
|
|
4972
4997
|
all_symbols: list[SymbolRecord] = []
|
|
4973
4998
|
all_relations: list[RelationEdge] = []
|
|
@@ -5029,9 +5054,15 @@ def build_repo_ir(
|
|
|
5029
5054
|
_meta_files_read += 1
|
|
5030
5055
|
_meta_lines_read += source.count("\n") + (1 if source and not source.endswith("\n") else 0)
|
|
5031
5056
|
_meta_chars_read += len(source)
|
|
5032
|
-
|
|
5033
|
-
|
|
5034
|
-
|
|
5057
|
+
_pkey = _pc.file_key(rel_path, source, _capture_sig)
|
|
5058
|
+
_cached = _pc.get(_pkey)
|
|
5059
|
+
if _cached is not None:
|
|
5060
|
+
package, raw_imports, symbols = _cached
|
|
5061
|
+
else:
|
|
5062
|
+
package, symbols, raw_imports = _extract_symbols(
|
|
5063
|
+
source, rel_path, extra_capture=_extra_capture
|
|
5064
|
+
)
|
|
5065
|
+
_pc.put(_pkey, package, raw_imports, symbols)
|
|
5035
5066
|
all_symbols.extend(symbols)
|
|
5036
5067
|
# P1-E (parse-coverage reconciliation): a file that declares a type but
|
|
5037
5068
|
# yielded zero symbols is silently invisible to the graph. Record the
|
|
@@ -5060,15 +5091,33 @@ def build_repo_ir(
|
|
|
5060
5091
|
pkg_type_map=_same_pkg_map,
|
|
5061
5092
|
)
|
|
5062
5093
|
if emit_body_facts:
|
|
5063
|
-
|
|
5064
|
-
|
|
5065
|
-
|
|
5066
|
-
|
|
5067
|
-
|
|
5068
|
-
|
|
5069
|
-
|
|
5070
|
-
|
|
5071
|
-
|
|
5094
|
+
# V4b: the per-file body-fact extractors are pure functions of the file's
|
|
5095
|
+
# bytes, so their combined output is memoised under the same content key.
|
|
5096
|
+
# A warm hit skips all of them; the CIR is byte-identical (equivalence test).
|
|
5097
|
+
_fkey = _pc.file_key(rel_path, source, _capture_sig)
|
|
5098
|
+
_blob = _pc.get_blob(_fkey)
|
|
5099
|
+
if _blob is None:
|
|
5100
|
+
_bf, _sf = _extract_body_facts(symbols, source, rel_path)
|
|
5101
|
+
_f_imports = _file_import_map(source)
|
|
5102
|
+
_blob = {
|
|
5103
|
+
"body": _bf,
|
|
5104
|
+
"span": _sf,
|
|
5105
|
+
"literal": _extract_literal_facts(symbols, source),
|
|
5106
|
+
"guard": _extract_guard_facts(symbols, source),
|
|
5107
|
+
"ctref": _extract_class_type_refs(symbols),
|
|
5108
|
+
"annarg": _parse_annotation_arg_values(symbols),
|
|
5109
|
+
"ftypes": _extract_field_types(source, imports=_f_imports),
|
|
5110
|
+
"fimports": _f_imports,
|
|
5111
|
+
}
|
|
5112
|
+
_pc.put_blob(_fkey, _blob)
|
|
5113
|
+
_f_imports = _blob["fimports"]
|
|
5114
|
+
_all_body_facts.update(_blob["body"])
|
|
5115
|
+
_all_span_facts.update(_blob["span"])
|
|
5116
|
+
_all_literal_facts.update(_blob["literal"])
|
|
5117
|
+
_all_guard_facts.update(_blob["guard"])
|
|
5118
|
+
_all_class_type_refs.update(_blob["ctref"])
|
|
5119
|
+
_all_annotation_arg_values.update(_blob["annarg"])
|
|
5120
|
+
_all_field_types.update(_blob["ftypes"])
|
|
5072
5121
|
# Every type declared in this file resolves simple names through this
|
|
5073
5122
|
# file's imports — the fact `_static_typed_call_edges` needs to bind a
|
|
5074
5123
|
# `Type.method(...)` receiver to a type (P1-A's rule, applied to statics).
|
sourcecode/spring_impact.py
CHANGED
|
@@ -1036,7 +1036,7 @@ class ImpactOrchestrator:
|
|
|
1036
1036
|
)
|
|
1037
1037
|
else:
|
|
1038
1038
|
warnings.append(
|
|
1039
|
-
f"Self-referential exclusion
|
|
1039
|
+
f"Self-referential exclusion: {self_excluded} member(s) of the "
|
|
1040
1040
|
f"analyzed class were dropped from callers — a class's own methods are "
|
|
1041
1041
|
f"members, not external callers (they do not count toward blast radius)."
|
|
1042
1042
|
)
|