sourcecode 1.32.6__py3-none-any.whl → 1.33.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.
sourcecode/__init__.py CHANGED
@@ -1,3 +1,3 @@
1
1
  """sourcecode — Deterministic codebase context maps for AI coding agents."""
2
2
 
3
- __version__ = "1.32.6"
3
+ __version__ = "1.33.0"
sourcecode/cli.py CHANGED
@@ -155,11 +155,20 @@ def _build_help_text() -> str:
155
155
  text = f"""\
156
156
  [bold]sourcecode[/bold] {plan_badge}
157
157
 
158
- Deterministic codebase context for AI coding agents.
158
+ Persistent structural context and ultra-fast repeated analysis for AI coding agents.
159
+
160
+ Cache warms on first scan; every subsequent call returns pre-built context in milliseconds.
161
+ Cold scan: 2–10s depending on repo size. Warm cache: 0.3–0.6s.
159
162
 
160
163
  [bold]Primary usage:[/bold]
161
- sourcecode --compact high-signal summary (~600-800 tokens)
164
+ sourcecode --compact high-signal summary (~2,500–4,000 tokens)
162
165
  sourcecode --compact --git-context include git hotspots and uncommitted files
166
+ sourcecode --agent full structured JSON for AI agents
167
+
168
+ [bold]Cache commands:[/bold]
169
+ cache status [dim]# cache size, hit keys, last-warmed timestamp[/dim]
170
+ cache warm [dim]# pre-build cache ahead of an agent session[/dim]
171
+ cache clear [dim]# clear all cached results for this repo[/dim]
163
172
 
164
173
  [bold]Examples:[/bold]
165
174
  sourcecode saint-server --compact
@@ -3753,6 +3762,24 @@ def config_cmd() -> None:
3753
3762
  typer.echo(" sourcecode telemetry status")
3754
3763
 
3755
3764
 
3765
+ # ── cold-start (RIS bootstrap for external MCP and agents) ───────────────────
3766
+
3767
+ @app.command("cold-start")
3768
+ def cold_start_cmd(
3769
+ path: Path = typer.Argument(Path("."), help="Repository path (default: current directory)"),
3770
+ ) -> None:
3771
+ """Output Repository Intelligence Snapshot bootstrap context as JSON.
3772
+
3773
+ Returns instantly from persisted RIS — zero re-analysis cost.
3774
+ status: cold_start_ready | cold_start_stale | no_ris
3775
+ """
3776
+ import json as _json
3777
+ from sourcecode.ris import get_cold_start_context as _gcs
3778
+ target = Path(path).resolve()
3779
+ result = _gcs(target)
3780
+ typer.echo(_json.dumps(result, indent=2, ensure_ascii=False))
3781
+
3782
+
3756
3783
  # ── analyze (legacy alias) ────────────────────────────────────────────────────
3757
3784
 
3758
3785
  @app.command("analyze", hidden=True)
@@ -4207,11 +4234,13 @@ def cache_warm_cmd(
4207
4234
  agent: bool = typer.Option(False, "--agent", help="Also warm agent view."),
4208
4235
  ) -> None:
4209
4236
  """Pre-populate the cache by running a fresh analysis."""
4237
+ import shutil as _shutil
4210
4238
  import subprocess as _sub
4211
4239
  import sys as _sys
4212
4240
  target = Path(path).resolve()
4213
4241
  typer.echo(f"Warming cache for {target} …", err=True)
4214
- cmd = [_sys.executable, "-m", "sourcecode", str(target)]
4242
+ _sc_bin = _shutil.which("sourcecode") or _sys.argv[0]
4243
+ cmd = [_sc_bin, str(target)]
4215
4244
  if compact:
4216
4245
  cmd.append("--compact")
4217
4246
  if agent:
@@ -734,6 +734,77 @@ class TaskContextBuilder:
734
734
  def __init__(self, root: Path) -> None:
735
735
  self.root = root
736
736
 
737
+ # ------------------------------------------------------------------
738
+ # RIS fast-path: serve onboard/explain from warm snapshot (<50ms)
739
+ # ------------------------------------------------------------------
740
+
741
+ def _try_ris_fast_path(self, task_name: str, spec: "TaskSpec") -> Optional[TaskOutput]:
742
+ """Return TaskOutput from a warm RIS without running the full scan.
743
+
744
+ Only activated for onboard/explain when git HEAD matches stored RIS.
745
+ Falls through (returns None) on any error or cache miss.
746
+ """
747
+ try:
748
+ import subprocess as _sp
749
+ from sourcecode.ris import load_ris as _lris
750
+ _ris = _lris(self.root)
751
+ if _ris is None or not _ris.compact_summary:
752
+ return None
753
+ _r = _sp.run(
754
+ ["git", "-C", str(self.root), "rev-parse", "--short", "HEAD"],
755
+ capture_output=True, text=True, timeout=2,
756
+ )
757
+ if _r.returncode != 0 or _r.stdout.strip() != _ris.git_head:
758
+ return None
759
+
760
+ compact = _ris.compact_summary
761
+ struct = _ris.structural_map
762
+
763
+ entry_points = struct.get("entrypoints") or compact.get("entry_points") or []
764
+ controllers = struct.get("controllers") or []
765
+ services = struct.get("services") or []
766
+
767
+ _seen: set = set()
768
+ relevant: list[RelevantFile] = []
769
+ for fp in entry_points[:10]:
770
+ if isinstance(fp, str) and fp not in _seen:
771
+ _seen.add(fp)
772
+ relevant.append(RelevantFile(path=fp, role="entrypoint", score=1.0, reason="entry_point", why="Primary entry point"))
773
+ for fp in controllers[:8]:
774
+ if isinstance(fp, str) and fp not in _seen:
775
+ _seen.add(fp)
776
+ relevant.append(RelevantFile(path=fp, role="source", score=0.9, reason="controller", why="Controller"))
777
+ for fp in services[:8]:
778
+ if isinstance(fp, str) and fp not in _seen:
779
+ _seen.add(fp)
780
+ relevant.append(RelevantFile(path=fp, role="source", score=0.8, reason="service", why="Service layer"))
781
+
782
+ # compact_summary uses "analysis_gaps" (list[dict]) not "gaps" (list[str])
783
+ _raw_gaps = compact.get("gaps") or compact.get("analysis_gaps") or []
784
+ _gap_strs: list[str] = [
785
+ g.get("reason", str(g)) if isinstance(g, dict) else str(g)
786
+ for g in _raw_gaps
787
+ if g
788
+ ]
789
+
790
+ return TaskOutput(
791
+ task=task_name,
792
+ goal=spec.goal,
793
+ project_summary=compact.get("project_summary") or compact.get("summary"),
794
+ architecture_summary=compact.get("architecture_summary"),
795
+ relevant_files=relevant,
796
+ suspected_areas=[],
797
+ improvement_opportunities=[],
798
+ test_gaps=[],
799
+ key_dependencies=compact.get("key_dependencies") or [],
800
+ code_notes_summary=None,
801
+ limitations=[],
802
+ confidence=compact.get("confidence") or compact.get("confidence_summary") or "high",
803
+ gaps=_gap_strs,
804
+ )
805
+ except Exception:
806
+ return None
807
+
737
808
  def build(self, task_name: str, *, since: Optional[str] = None, symptom: Optional[str] = None, fast: bool = False, include_config: bool = False, all_gaps: bool = False) -> TaskOutput:
738
809
  if task_name not in TASKS:
739
810
  raise ValueError(
@@ -741,6 +812,12 @@ class TaskContextBuilder:
741
812
  )
742
813
  spec = TASKS[task_name]
743
814
 
815
+ # ── RIS fast-path (onboard / explain only) ────────────────────────────
816
+ if task_name in ("onboard", "explain") and not fast:
817
+ _warm = self._try_ris_fast_path(task_name, spec)
818
+ if _warm is not None:
819
+ return _warm
820
+
744
821
  # ── 0. review-pr: git-first scope resolution (before any filesystem scan) ─
745
822
  _pr_git_root: Optional[Path] = None
746
823
  _pr_scope_files: Optional[list[str]] = None
sourcecode/ris.py CHANGED
@@ -362,7 +362,8 @@ def get_cold_start_context(repo_root: Path) -> dict:
362
362
  current_head = _current_git_head(repo_root)
363
363
  stale = bool(current_head and ris.git_head and current_head != ris.git_head)
364
364
 
365
- return {
365
+ endpoints = ris.api_surface.get("endpoints", [])
366
+ result: dict = {
366
367
  "status": "cold_start_stale" if stale else "cold_start_ready",
367
368
  "repo_id": ris.repo_id,
368
369
  "git_head": ris.git_head,
@@ -370,8 +371,18 @@ def get_cold_start_context(repo_root: Path) -> dict:
370
371
  "last_updated_at": ris.last_updated_at,
371
372
  "summary": ris.compact_summary,
372
373
  "entrypoints": ris.structural_map.get("entrypoints", []),
373
- "endpoints": ris.api_surface.get("endpoints", []),
374
+ "endpoints": endpoints,
374
375
  "hotspots": ris.git_context_snapshot.get("hotspots", []),
375
376
  }
377
+ if not endpoints:
378
+ _is_java = (repo_root / "pom.xml").exists() or \
379
+ (repo_root / "build.gradle").exists() or \
380
+ (repo_root / "build.gradle.kts").exists()
381
+ if _is_java:
382
+ result["endpoints_hint"] = (
383
+ "Java repo detected but no endpoint index found. "
384
+ "Call get_endpoints (or: sourcecode endpoints <path>) to populate."
385
+ )
386
+ return result
376
387
  except Exception:
377
388
  return {"status": "no_ris"}
@@ -0,0 +1,437 @@
1
+ Metadata-Version: 2.4
2
+ Name: sourcecode
3
+ Version: 1.33.0
4
+ Summary: Persistent structural context and ultra-fast repeated analysis for AI coding agents
5
+ License-File: LICENSE
6
+ Keywords: agents,ai,codebase,context,developer-tools,llm
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Topic :: Utilities
19
+ Requires-Python: >=3.9
20
+ Requires-Dist: mcp>=1.0.0
21
+ Requires-Dist: pathspec>=1.0
22
+ Requires-Dist: ruamel-yaml>=0.18
23
+ Requires-Dist: tomli>=2.0; python_version < '3.11'
24
+ Requires-Dist: typer>=0.24
25
+ Provides-Extra: ast
26
+ Requires-Dist: tree-sitter-javascript>=0.21; extra == 'ast'
27
+ Requires-Dist: tree-sitter-typescript>=0.21; extra == 'ast'
28
+ Requires-Dist: tree-sitter>=0.21; extra == 'ast'
29
+ Provides-Extra: dev
30
+ Requires-Dist: mcp>=1.0.0; extra == 'dev'
31
+ Requires-Dist: mypy>=1.10; extra == 'dev'
32
+ Requires-Dist: pytest>=8; extra == 'dev'
33
+ Requires-Dist: ruff>=0.15; extra == 'dev'
34
+ Provides-Extra: mcp
35
+ Requires-Dist: mcp>=1.0.0; extra == 'mcp'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # sourcecode
39
+
40
+ **Persistent structural context and ultra-fast repeated analysis for AI coding agents.**
41
+
42
+ ![Version](https://img.shields.io/badge/version-1.33.0-blue)
43
+ ![Python](https://img.shields.io/badge/python-3.10%2B-green)
44
+
45
+ ---
46
+
47
+ ## The problem
48
+
49
+ Every time an AI coding agent starts a new session, it has to re-parse the repository from scratch. For a large Java or TypeScript monolith, that means 5–15 seconds per invocation. Multiply by dozens of agent turns per hour, and repo context acquisition becomes a real bottleneck — not just latency, but tokens, compute, and iteration velocity.
50
+
51
+ `sourcecode` solves this with a persistent structural cache keyed on file content hashes. After the first scan, every subsequent invocation returns pre-built context in milliseconds. The repo doesn't change? The cache doesn't expire.
52
+
53
+ **The cache is not a performance optimization. It is what makes sourcecode usable as infrastructure rather than a one-off tool.**
54
+
55
+ ---
56
+
57
+ ## Cache performance — measured on real repos
58
+
59
+ | Repo | Size | Cold scan | Cache hit | Speedup |
60
+ |------|------|-----------|-----------|---------|
61
+ | Keycloak | 7,885 Java files | 10.5s | 0.6s | **~17x** |
62
+ | BroadleafCommerce | 2,985 Java files | 2.7s | 0.3s | **~9x** |
63
+
64
+ Cache keyed on content hashes — invalidated only when source changes. On repeated agent sessions against the same codebase, nearly every invocation is a cache hit.
65
+
66
+ **Token output (measured):**
67
+
68
+ | Mode | BroadleafCommerce | Keycloak |
69
+ |------|------------------|---------|
70
+ | `--compact` | ~2,900 | ~4,000 |
71
+ | `--agent` | ~4,800 | ~5,500 |
72
+ | `onboard` | ~2,600 | n/a |
73
+ | `fix-bug` (trimmed) | ~27,000 | ~4,600 |
74
+
75
+ ---
76
+
77
+ ## What changes at 0.3s vs 2.7s
78
+
79
+ At 2.7s per call, you use sourcecode to occasionally inspect a repo.
80
+
81
+ At 0.3s per call, you use sourcecode as **constant infrastructure** inside agent loops:
82
+
83
+ ```
84
+ agent loop iteration:
85
+ 1. sourcecode . --compact # 0.3s — instant structural context
86
+ 2. sourcecode impact PaymentService . --depth 1 # 0.4s — blast radius check
87
+ 3. agent makes targeted change
88
+ 4. repeat
89
+ ```
90
+
91
+ Sub-second context retrieval changes the cost model for agent workflows. You can call sourcecode before every edit, before every PR review, before every test run — without batching or caching calls manually.
92
+
93
+ ---
94
+
95
+ ## Installation
96
+
97
+ ### Homebrew (macOS / Linux)
98
+
99
+ ```bash
100
+ brew tap haroundominique/sourcecode
101
+ brew install sourcecode
102
+ ```
103
+
104
+ ### pip / pipx
105
+
106
+ ```bash
107
+ pip install sourcecode
108
+ # or with isolation:
109
+ pipx install sourcecode
110
+ ```
111
+
112
+ ### Verify
113
+
114
+ ```bash
115
+ sourcecode version
116
+ # sourcecode 1.33.0
117
+ ```
118
+
119
+ ---
120
+
121
+ ## Quickstart
122
+
123
+ ```bash
124
+ # High-signal summary — warm cache: ~0.3s, cold: 2–10s depending on repo size
125
+ sourcecode --compact
126
+
127
+ # Add git hotspots and uncommitted file count
128
+ sourcecode --compact --git-context
129
+
130
+ # Structured output for AI agents — bounded, noise-free, ready to inject
131
+ sourcecode --agent
132
+
133
+ # Blast radius: what breaks if this class changes?
134
+ sourcecode impact OrderService /path/to/repo
135
+
136
+ # REST endpoint surface
137
+ sourcecode endpoints /path/to/repo
138
+
139
+ # Onboard to an unfamiliar codebase
140
+ sourcecode onboard /path/to/repo
141
+
142
+ # PR review: risk, test gaps, changed modules
143
+ sourcecode review-pr /path/to/repo --since main
144
+
145
+ # Bug triage: risk-ranked files by symptom
146
+ sourcecode fix-bug /path/to/repo --symptom "NullPointerException in checkout"
147
+ ```
148
+
149
+ ---
150
+
151
+ ## Cache system
152
+
153
+ sourcecode maintains a persistent cache at `.sourcecode-cache/` inside each repository. Two layers:
154
+
155
+ - **L1 (core):** analysis result keyed by `(git_sha, analysis_flags)`. Survives format changes — you can regenerate `--compact` vs `--agent` views from the same core.
156
+ - **L2 (view):** rendered output keyed by `(core_hash, view_flags)`. Exact output match — no recomputation.
157
+
158
+ **Lookup order:** L2 exact hit → L1 hit + view rebuild → full cold scan
159
+
160
+ **Cache invalidation:** Keyed on git commit SHA. Any commit invalidates the core cache for that repo. Uncommitted changes are not cached.
161
+
162
+ ```bash
163
+ # Inspect cache state
164
+ sourcecode cache status
165
+
166
+ # Warm the cache ahead of an agent session
167
+ sourcecode cache warm
168
+
169
+ # Clear cache
170
+ sourcecode cache clear
171
+ ```
172
+
173
+ **`--no-cache`** bypasses both layers and forces a fresh scan. Use in CI or when you need to verify a fresh result.
174
+
175
+ **Visibility:** Cache hits are silent. Use `sourcecode cache status` to see cache size, hit keys, and last-warmed timestamp.
176
+
177
+ ---
178
+
179
+ ## Agent workflow patterns
180
+
181
+ ### Start of session — structural grounding
182
+
183
+ ```bash
184
+ # Inject as first message to agent (bounded, deterministic)
185
+ sourcecode /repo --compact # ~2,500–4,000 tokens
186
+ sourcecode /repo --agent # ~4,500–5,500 tokens — more detail
187
+ sourcecode onboard /repo # task-structured: entry points, key files, gaps
188
+ ```
189
+
190
+ ### Before every change — blast radius check
191
+
192
+ ```bash
193
+ # Always target the INTERFACE in Spring projects, not the implementation:
194
+ sourcecode impact OrderService /repo # ✓ 30 callers, 11 endpoints
195
+ sourcecode impact OrderServiceImpl /repo # ✗ 0 callers (Spring DI blindness)
196
+
197
+ # Large hub interfaces — depth=1 is faster and still the most actionable signal:
198
+ sourcecode impact KeycloakSession /repo --depth 1
199
+ ```
200
+
201
+ ### Continuous agent loop — delta context
202
+
203
+ ```bash
204
+ # Only changed files + their transitive importers — minimal token cost:
205
+ sourcecode prepare-context delta /repo --since HEAD~1
206
+ sourcecode . --changed-only --git-context
207
+ ```
208
+
209
+ ### PR review — structured risk signal
210
+
211
+ ```bash
212
+ # JSON for programmatic use:
213
+ sourcecode review-pr /repo --since main --output review.json
214
+ jq '.ci_decision' review.json # "analysis_success" | "git_ref_error"
215
+
216
+ # Markdown for GitHub comment:
217
+ sourcecode review-pr /repo --since main --format github-comment
218
+ ```
219
+
220
+ ### Bug triage — symptom-driven
221
+
222
+ ```bash
223
+ # Specific symptoms produce the best signal:
224
+ sourcecode fix-bug /repo --symptom "OIDC token refresh fails after realm update"
225
+ sourcecode fix-bug /repo --symptom "NullPointerException in OrderService during checkout"
226
+
227
+ # Generic symptoms produce noisy output — be specific.
228
+ sourcecode fix-bug /repo --symptom "payment timeout" --output triage.json
229
+ ```
230
+
231
+ ### In CI — cached, deterministic, fast
232
+
233
+ ```bash
234
+ # Content-hash cached — safe to run on every commit; cold only when code changes
235
+ sourcecode /repo --compact --output context.json
236
+
237
+ # PR gate
238
+ sourcecode review-pr /repo --since $BASE_REF --output review.json
239
+ DECISION=$(jq -r '.ci_decision' review.json)
240
+ if [ "$DECISION" != "analysis_success" ]; then echo "Review failed: $DECISION"; fi
241
+ ```
242
+
243
+ ---
244
+
245
+ ## What sourcecode does (and doesn't)
246
+
247
+ **sourcecode reduces exploration cost.** It accelerates context acquisition and minimizes repeated repo parsing. It does not replace reading code — it reduces how often an agent needs to.
248
+
249
+ Specifically:
250
+
251
+ - Extracts structural signals: entry points, Spring roles, REST surfaces, dependency graphs, transactional boundaries
252
+ - Builds and caches these on first scan; serves from cache on subsequent calls
253
+ - Produces bounded, noise-free JSON designed for direct injection into agent context windows
254
+ - Computes blast radius (impact graph) from a class or interface, traversing reverse dependencies
255
+
256
+ **What it does NOT do:**
257
+
258
+ - No runtime analysis — all signals are static (annotation, import graph, file structure)
259
+ - No semantic code understanding — reads structure, not logic
260
+ - No replacement for reading code — reduces how often that's needed, not whether
261
+ - Architecture pattern detection best for Spring MVC layered apps; SPI/plugin architectures (e.g. Quarkus extension model) may be misclassified
262
+ - Endpoint recall for JAX-RS subresource locator pattern is ~65%
263
+ - `impact` on implementation classes (e.g. `OrderServiceImpl`) returns 0 callers in Spring Boot — callers inject the interface via `@Autowired`. Always target the interface. When `direct_callers: []` with `confidence_level: high` for a `@Service` class, re-query the interface.
264
+ - `no_security_signal` on endpoints means no method-level annotations found — does **not** mean the endpoint is unsecured. Projects using Spring Security filter chains show 100% `no_security_signal` even when fully secured.
265
+
266
+ ---
267
+
268
+ ## Command reference
269
+
270
+ ### `--compact` and `--agent`
271
+
272
+ Core flags. Feed directly to AI agents as first-message context.
273
+
274
+ | Flag | Output | Tokens |
275
+ |------|--------|--------|
276
+ | `--compact` | High-signal summary: stacks, entry points, dependencies, confidence, gaps | ~2,500–4,000 |
277
+ | `--agent` | Structured JSON: identity, entry points, architecture, event flows | ~4,500–5,500 |
278
+
279
+ ### `impact` — blast-radius analysis
280
+
281
+ ```bash
282
+ sourcecode impact ClassName /path/to/repo
283
+ sourcecode impact org.example.OrderService /path/to/repo # FQN also accepted
284
+ sourcecode impact OrderService . --depth 2 # limit BFS depth
285
+ ```
286
+
287
+ | Field | Description |
288
+ |-------|-------------|
289
+ | `direct_callers` | Classes that directly import or inject the target |
290
+ | `indirect_callers` | Transitive callers up to `--depth` (default: 4) |
291
+ | `endpoints_affected` | HTTP endpoints whose call chain includes the target |
292
+ | `transactional_boundaries_touched` | `@Transactional` classes in the blast cone |
293
+ | `mappers_affected` | `@Repository` / `@Mapper` / DAO classes in the blast cone |
294
+ | `security_surface_affected` | Security policies on affected endpoints |
295
+ | `cross_module_impact` | Subsystems touched, ordered by affected symbol count |
296
+ | `risk_score` | 0–100 quantified change risk |
297
+ | `confidence_score` | 0–1 confidence in the analysis |
298
+ | `explanation` | Human-readable risk summary |
299
+ | `candidates` | On partial match: up to 10 FQNs ranked by relevance |
300
+
301
+ **Best practices:**
302
+ - Target **interfaces**, not implementations: `impact OrderService` > `impact OrderServiceImpl`
303
+ - Use `--depth 1` when target has 200+ callers — direct endpoints are already the most actionable signal
304
+ - Second `impact` run on the same repo is significantly faster (cache applies to underlying IR scan)
305
+
306
+ ### `endpoints` — REST API surface
307
+
308
+ ```bash
309
+ sourcecode endpoints /path/to/repo
310
+ sourcecode endpoints /path/to/repo --output endpoints.json
311
+ ```
312
+
313
+ Extracts all Spring MVC (`@GetMapping`, `@PostMapping`, `@RequestMapping`, etc.) and JAX-RS (`@GET`, `@POST`, `@Path`) endpoint methods. Returns HTTP method, path, controller class, and handler method.
314
+
315
+ ### `repo-ir` — symbol-level IR
316
+
317
+ ```bash
318
+ sourcecode repo-ir /path/to/repo --summary-only # ~20K tokens
319
+ sourcecode repo-ir /path/to/repo --since HEAD~1 # symbol-level diff
320
+ sourcecode repo-ir /path/to/repo --files src/.../OrderService.java
321
+ ```
322
+
323
+ Builds a deterministic symbol graph: classes, methods, import/injection edges, Spring roles, subsystems.
324
+
325
+ **Size warning:** Without `--summary-only`, output can exceed 1MB for mid-size repos. Always use `--summary-only` unless you need the full graph for downstream tooling.
326
+
327
+ ### `onboard` — codebase orientation
328
+
329
+ ```bash
330
+ sourcecode onboard /path/to/repo
331
+ ```
332
+
333
+ Entry points, architecture summary, key files, confidence level, and gaps. Designed to be injected as agent context at the start of a session.
334
+
335
+ ### `review-pr` — [Pro] PR review context
336
+
337
+ ```bash
338
+ sourcecode review-pr /path/to/repo --since main
339
+ sourcecode review-pr /path/to/repo --since HEAD~3
340
+ ```
341
+
342
+ Changed files, risk ranking, test coverage gaps, affected modules, and blast radius of changed classes. Returns a `ci_decision` field for CI/CD integration.
343
+
344
+ ### `fix-bug` — [Pro] Bug triage context
345
+
346
+ ```bash
347
+ sourcecode fix-bug /path/to/repo --symptom "NullPointerException in checkout"
348
+ ```
349
+
350
+ Risk-ranked file list correlated to the symptom: keyword extraction, path matching, content matching, git commit correlation.
351
+
352
+ ### `modernize` — [Pro] Modernization planning
353
+
354
+ ```bash
355
+ sourcecode modernize /path/to/repo
356
+ ```
357
+
358
+ High-coupling nodes (high fan-in = risky to change), dead zone candidates (isolated symbols), subsystem tangles.
359
+
360
+ ### `prepare-context` — task-specific context
361
+
362
+ Low-level access to all tasks with full options:
363
+
364
+ ```bash
365
+ sourcecode prepare-context TASK [PATH] [OPTIONS]
366
+ ```
367
+
368
+ | Task | What it surfaces |
369
+ |------|-----------------|
370
+ | `explain` | Architecture, entry points, key dependencies |
371
+ | `onboard` | Full structural context for new agents/developers |
372
+ | `fix-bug` | Files ranked by symptom correlation, risk, annotations |
373
+ | `refactor` | Structural issues, improvement opportunities |
374
+ | `generate-tests` | Source files without test pairs, coverage gap analysis |
375
+ | `review-pr` | PR diff with risk ranking, test gaps, module impact |
376
+ | `delta` | Incremental context: git-changed files + transitive import graph |
377
+
378
+ ---
379
+
380
+ ## Flags reference
381
+
382
+ | Flag | Alias | Default | Description |
383
+ |------|-------|---------|-------------|
384
+ | `--compact` | | off | High-signal summary (typically 2,500–4,000 tokens for mid-to-large Java repos): stacks, entry points, dependencies, confidence, gaps. |
385
+ | `--agent` | | off | Structured JSON for AI agents: project identity, entry points, architecture, dependencies, confidence. ~4,500–5,500 tokens. |
386
+ | `--full` | | off | Remove truncation limits on `transactional_boundaries`, `mybatis.dto_mappers`, and other capped lists. |
387
+ | `--git-context` | `-g` | off | Include git activity: recent commits, change hotspots, and uncommitted file count. |
388
+ | `--changed-only` | | off | Limit output to git-modified files (staged, unstaged, untracked). |
389
+ | `--depth` | | `4` | File tree traversal depth (1–20). Java/Maven projects auto-adjust to 12. |
390
+ | `--format` | `-f` | `json` | Output format: `json` or `yaml`. |
391
+ | `--output` | `-o` | stdout | Write output to a file instead of stdout. |
392
+ | `--no-cache` | | off | Bypass scan cache and force a fresh analysis. |
393
+ | `--copy` | `-c` | off | Copy output to clipboard after a successful run. |
394
+ | `--no-redact` | | off | Disable automatic secret redaction. |
395
+ | `--version` | `-v` | — | Show version and exit. |
396
+
397
+ ---
398
+
399
+ ## Output schema
400
+
401
+ All outputs include:
402
+ - `schema_version`: output format version
403
+ - `confidence_summary`: `overall`, `stack`, `entry_points` confidence levels (`high`/`medium`/`low`)
404
+ - `analysis_gaps`: list of what could not be analyzed and why
405
+
406
+ ### Java/Spring-specific fields (when detected)
407
+
408
+ | Field | Description |
409
+ |-------|-------------|
410
+ | `language_version` | Java version from `maven.compiler.source` or equivalent |
411
+ | `deployment.spring_boot_version` | Spring Boot version |
412
+ | `deployment.packaging` | `jar` or `war` |
413
+ | `mybatis` | Mapper interface / XML file pairing summary |
414
+ | `transactional_boundaries` | Classes annotated with `@Transactional` |
415
+ | `deployment_risks` | Static risk flags: `spring-boot-2.x-eol`, `legacy-java-runtime` |
416
+
417
+ ---
418
+
419
+ ## Telemetry
420
+
421
+ Anonymous, opt-in. Collects: version, OS, commands, flags, duration, repo size range, errors. No source code, paths, secrets, or output content.
422
+
423
+ ```bash
424
+ sourcecode telemetry status
425
+ sourcecode telemetry enable
426
+ sourcecode telemetry disable
427
+ ```
428
+
429
+ Or: `export SOURCECODE_TELEMETRY=0`
430
+
431
+ ---
432
+
433
+ ## Configuration
434
+
435
+ ```bash
436
+ sourcecode config # show version, config file path, telemetry status
437
+ ```
@@ -1,4 +1,4 @@
1
- sourcecode/__init__.py,sha256=KgyhBn2jfjwXzdBpdStMZoNfqCUlHHAwk1wuU3Nez1M,103
1
+ sourcecode/__init__.py,sha256=Fk3-VcGm9_CNfTjflFer8o6KMnle3o1Zvum4r66pj4E,103
2
2
  sourcecode/adaptive_scanner.py,sha256=XffluXKzJUXrMtjEiAOnSNPZnztdIcts17T9ouHeID0,10521
3
3
  sourcecode/architecture_analyzer.py,sha256=qh749a7ykPtGmQI1MR9y6j8TtL_jBdVYFx9YRsLqOMw,44121
4
4
  sourcecode/architecture_summary.py,sha256=z34_6v7cSwy98cof2UVciGho7SCrZ93tiqMmq5WNzRQ,20405
@@ -7,7 +7,7 @@ sourcecode/cache.py,sha256=h1BT-9PG_7HK---ZzH0j5u3PN0dz2s6IRAUOjQIPYH4,28055
7
7
  sourcecode/cache.tmp_new,sha256=-IvV7CojiZjqeKMln1m-lqI0QVA2uFGWmYir4XRFOUk,27970
8
8
  sourcecode/canonical_ir.py,sha256=_HM3AUmKSdna9u4dCoU6rpgSA6HdF8gzOKZykIUCNGY,23277
9
9
  sourcecode/classifier.py,sha256=2lYoSH3vOTkXZYPU7Go2WIet1-IuNzTWVhc-ULnXtgw,8024
10
- sourcecode/cli.py,sha256=PJbs8ltIdsBmedJlBJ6HG9UCRBLDtUhG_eIqyazP_sU,170992
10
+ sourcecode/cli.py,sha256=fIY-kaSbQ_YilCwR9jqsm8n2_kMfyYrHrudee6KQaQE,172312
11
11
  sourcecode/code_notes_analyzer.py,sha256=EJemNCNc9Dn-1RZYu-aNbK0ELzmsyC4s6FdHi3XyNEI,9392
12
12
  sourcecode/confidence_analyzer.py,sha256=_jckZSxksV-OU38vbkxfVNBnWCtlCq8Vwfg23x1uspA,19054
13
13
  sourcecode/context_scorer.py,sha256=QpChSpsmaAYz91rXA4Ue5xzQmNz_ZboZN09YOHScq1U,14679
@@ -29,14 +29,14 @@ sourcecode/metrics_analyzer.py,sha256=m0ENgtqKeBL17kUIK3fmGkgo7UfXBNHxCMj0H_Y5K7
29
29
  sourcecode/output_budget.py,sha256=43307mJEyUPU3MI-QEQoVxrcAvNyUzdzF_SAPgisBQE,6603
30
30
  sourcecode/path_filters.py,sha256=ROFRQ8eSLBEMiixK9f45-RO7um4VEEcjoD5AA4I427I,3739
31
31
  sourcecode/pr_comment_renderer.py,sha256=smHslxiG14lrytCkq5nFrFu-qTHgA-t-LFYfdrfjz2o,14423
32
- sourcecode/prepare_context.py,sha256=TFg8GDJ8kotJtR4rOTAvwQGVNSj0x-Usamy-mtjxeqs,201681
32
+ sourcecode/prepare_context.py,sha256=uZo0r7QBXUmQdfTp3w_A1XI-OzFAlcoH7F76_p7IQjo,205311
33
33
  sourcecode/progress.py,sha256=qn30sWaHOkjTgXsSBmiPkz7Rsbwc5oSlIe6JNEMYp_k,3149
34
34
  sourcecode/ranking_engine.py,sha256=ZAucq_YX2KkWUuAZf4P0lhtQ_38vEFnUhuGtSZd1S0E,12970
35
35
  sourcecode/redactor.py,sha256=SB4hwIvg8h-hvcqKcDWaZvA-aSyn-at-BIRwa0tUv5E,3227
36
36
  sourcecode/relevance_scorer.py,sha256=MYF4FFkveAQps9SmTeTlh6ODiBz2F--_hWNeHMLtUHQ,8405
37
37
  sourcecode/repo_classifier.py,sha256=FG1vaWKdWXsWdl-S8hjVMiTqcwgaRXkDyvK4rPcOGtQ,22681
38
38
  sourcecode/repository_ir.py,sha256=-NjBQUT7zyya4ng8Hq0-ChoiHZkUif9lr-Q878gmj8M,153163
39
- sourcecode/ris.py,sha256=CqNfiIbzfHZQZx0mWLjyVD4o8u5ZLnbv3Ia7D7gYhQY,14212
39
+ sourcecode/ris.py,sha256=2pQcNN-5akweoBjjWAk_x3QpJ06wukQInmMlMj7WxwI,14737
40
40
  sourcecode/runtime_classifier.py,sha256=uTAD6BDCiBLUZEDRfqk718kM4RTT_vAbfkcOI2_Xx58,18432
41
41
  sourcecode/scanner.py,sha256=WdOQ78mMzjR1NjmKTlbxdgwinnCTfAhxCVLBEFQiFHU,8899
42
42
  sourcecode/schema.py,sha256=aHNXDf8LGyUC8ZDE_VS9kiskC2-Oswhi_WnpdGy6HDw,24897
@@ -80,8 +80,8 @@ sourcecode/telemetry/consent.py,sha256=wLMvGNJeSSyZoNkQXpoUioY6mMv4Qdvuw7S9jAEWn
80
80
  sourcecode/telemetry/events.py,sha256=oEvvulfsv5GIDWG2174gSS6tNB95w38AIYiYeifGKlE,2294
81
81
  sourcecode/telemetry/filters.py,sha256=Asa71oRl7q3Wt_FMwuufIZJFzSYdgRNKS8LHCIyFeYE,4805
82
82
  sourcecode/telemetry/transport.py,sha256=KJeIPCPWMdmbCP3ySGs2iUlia34U6vWne2dZsUezesw,1560
83
- sourcecode-1.32.6.dist-info/METADATA,sha256=Aa7pmdWB0T8LkQYd6rihJOQQwE1Ts_nJ7AHUyYT2gF0,19120
84
- sourcecode-1.32.6.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
85
- sourcecode-1.32.6.dist-info/entry_points.txt,sha256=ex3F9rmbXeyDIoFQHtkEqTsKSaJow8F0LrVu8XfIktQ,57
86
- sourcecode-1.32.6.dist-info/licenses/LICENSE,sha256=7DdHrU9Z_3e7dSvq4ISijZNjnuHo5NIHNiHDouMQ9JU,10491
87
- sourcecode-1.32.6.dist-info/RECORD,,
83
+ sourcecode-1.33.0.dist-info/METADATA,sha256=2Xbq33fdfqhc4P5EfadeJgzSkGCcJ-c1DdZJiwiGch8,16440
84
+ sourcecode-1.33.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
85
+ sourcecode-1.33.0.dist-info/entry_points.txt,sha256=ex3F9rmbXeyDIoFQHtkEqTsKSaJow8F0LrVu8XfIktQ,57
86
+ sourcecode-1.33.0.dist-info/licenses/LICENSE,sha256=7DdHrU9Z_3e7dSvq4ISijZNjnuHo5NIHNiHDouMQ9JU,10491
87
+ sourcecode-1.33.0.dist-info/RECORD,,
@@ -1,456 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: sourcecode
3
- Version: 1.32.6
4
- Summary: Deterministic codebase context for AI coding agents
5
- License-File: LICENSE
6
- Keywords: agents,ai,codebase,context,developer-tools,llm
7
- Classifier: Development Status :: 4 - Beta
8
- Classifier: Environment :: Console
9
- Classifier: Intended Audience :: Developers
10
- Classifier: License :: OSI Approved :: Apache Software License
11
- Classifier: Operating System :: OS Independent
12
- Classifier: Programming Language :: Python :: 3
13
- Classifier: Programming Language :: Python :: 3.9
14
- Classifier: Programming Language :: Python :: 3.10
15
- Classifier: Programming Language :: Python :: 3.11
16
- Classifier: Programming Language :: Python :: 3.12
17
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
- Classifier: Topic :: Utilities
19
- Requires-Python: >=3.9
20
- Requires-Dist: mcp>=1.0.0
21
- Requires-Dist: pathspec>=1.0
22
- Requires-Dist: ruamel-yaml>=0.18
23
- Requires-Dist: tomli>=2.0; python_version < '3.11'
24
- Requires-Dist: typer>=0.24
25
- Provides-Extra: ast
26
- Requires-Dist: tree-sitter-javascript>=0.21; extra == 'ast'
27
- Requires-Dist: tree-sitter-typescript>=0.21; extra == 'ast'
28
- Requires-Dist: tree-sitter>=0.21; extra == 'ast'
29
- Provides-Extra: dev
30
- Requires-Dist: mcp>=1.0.0; extra == 'dev'
31
- Requires-Dist: mypy>=1.10; extra == 'dev'
32
- Requires-Dist: pytest>=8; extra == 'dev'
33
- Requires-Dist: ruff>=0.15; extra == 'dev'
34
- Provides-Extra: mcp
35
- Requires-Dist: mcp>=1.0.0; extra == 'mcp'
36
- Description-Content-Type: text/markdown
37
-
38
- # sourcecode
39
-
40
- **AI-ready change intelligence for Java/Spring enterprise monoliths.**
41
-
42
- ![Version](https://img.shields.io/badge/version-1.32.0-blue)
43
- ![Python](https://img.shields.io/badge/python-3.10%2B-green)
44
-
45
- ---
46
-
47
- ## What is it?
48
-
49
- `sourcecode` analyzes a Java/Spring repository and produces structured JSON designed to be fed directly to AI agents or used in CI/CD pipelines. It solves two hard problems:
50
-
51
- **1. "What breaks if I change X?"** — `sourcecode impact ClassName /repo` traverses the reverse dependency graph and returns every HTTP endpoint, transactional boundary, and downstream module affected by a change. In seconds, not hours.
52
-
53
- **2. "What does this codebase do before I touch it?"** — `sourcecode onboard /repo` produces a bounded, AI-ready context bundle: entry points, architecture, key files, confidence, and gaps. Feed it directly to Claude/GPT-4 as a system prompt.
54
-
55
- **Optimized for:** Spring Boot / Spring MVC monoliths. Works with JAX-RS (Quarkus, Jersey) at ~65% endpoint recall. Works on any codebase for stack detection and onboarding context.
56
-
57
- ---
58
-
59
- ## Installation
60
-
61
- ### Homebrew (macOS / Linux)
62
-
63
- ```bash
64
- brew tap haroundominique/sourcecode
65
- brew install sourcecode
66
- ```
67
-
68
- ### pip / pipx
69
-
70
- ```bash
71
- pip install sourcecode
72
- # or with isolation:
73
- pipx install sourcecode
74
- ```
75
-
76
- ### Verify
77
-
78
- ```bash
79
- sourcecode version
80
- # sourcecode 1.32.0
81
- ```
82
-
83
- ---
84
-
85
- ## Quickstart
86
-
87
- ```bash
88
- # High-signal summary (typically 2000–4000 tokens depending on repo size)
89
- sourcecode --compact
90
-
91
- # Add git hotspots and uncommitted file count
92
- sourcecode --compact --git-context
93
-
94
- # Structured output for AI agents — bounded, noise-free, ready to inject
95
- sourcecode --agent
96
-
97
- # Blast radius: what breaks if this class changes?
98
- sourcecode impact OrderService /path/to/repo
99
-
100
- # REST endpoint surface
101
- sourcecode endpoints /path/to/repo
102
-
103
- # Onboard to an unfamiliar codebase
104
- sourcecode onboard /path/to/repo
105
-
106
- # PR review: risk, test gaps, changed modules
107
- sourcecode review-pr /path/to/repo --since main
108
-
109
- # Bug triage: risk-ranked files by symptom
110
- sourcecode fix-bug /path/to/repo --symptom "NullPointerException in checkout"
111
- ```
112
-
113
- ---
114
-
115
- ## Real-world benchmarks
116
-
117
- Measured against open-source enterprise Java repos:
118
-
119
- | Repo | Java files | Cold scan (`--compact`) | Cache hit | Cache speedup | Endpoints found |
120
- |------|-----------|------------------------|-----------|---------------|----------------|
121
- | BroadleafCommerce | 2,985 | 2.9s | 0.20s | ~13x | 130 |
122
- | Keycloak | 7,885 | 9.0s | 0.27s | ~33x | 693 |
123
-
124
- The cache is keyed on file content hashes — invalidated only when source changes. Speedup varies by repo size and OS I/O.
125
-
126
- **Token sizes (measured):**
127
-
128
- | Mode | BroadleafCommerce | Keycloak |
129
- |------|------------------|---------|
130
- | `--compact` | ~2,900 | ~4,000 |
131
- | `--agent` | ~4,800 | ~5,500 |
132
- | `onboard` | ~2,600 | n/a |
133
- | `fix-bug` (trimmed) | ~27,000 | ~4,600 |
134
-
135
- **`impact` on high-fan-in classes:**
136
- For hub interfaces (1000+ direct dependents), use `--depth 1` — direct endpoints are already the most actionable signal. Depth=4 on very large repos may take 90+ seconds.
137
-
138
- ---
139
-
140
- ## Flags reference
141
-
142
- | Flag | Alias | Default | Description |
143
- |------|-------|---------|-------------|
144
- | `--compact` | | off | High-signal summary (typically 2,500–4,000 tokens for mid-to-large Java repos): stacks, entry points, dependencies, confidence, gaps. Includes `transactional_boundaries` for Spring projects. |
145
- | `--agent` | | off | Structured JSON for AI agents: project identity, entry points, architecture, dependencies, confidence. More detail than `--compact`. ~4500–5500 tokens. |
146
- | `--full` | | off | Remove truncation limits on `transactional_boundaries`, `mybatis.dto_mappers`, and other capped lists. |
147
- | `--git-context` | `-g` | off | Include git activity: recent commits, change hotspots, and uncommitted file count. |
148
- | `--changed-only` | | off | Limit output to git-modified files (staged, unstaged, untracked). |
149
- | `--depth` | | `4` | File tree traversal depth (1–20). Java/Maven projects auto-adjust to 12. |
150
- | `--format` | `-f` | `json` | Output format: `json` or `yaml`. |
151
- | `--output` | `-o` | stdout | Write output to a file instead of stdout. |
152
- | `--no-cache` | | off | Bypass scan cache and force a fresh analysis. |
153
- | `--copy` | `-c` | off | Copy output to clipboard after a successful run. |
154
- | `--no-redact` | | off | Disable automatic secret redaction. |
155
- | `--version` | `-v` | — | Show version and exit. |
156
-
157
- ---
158
-
159
- ## `impact` — Blast-radius analysis
160
-
161
- **Who calls this class, and what breaks if it changes?**
162
-
163
- ```bash
164
- sourcecode impact ClassName /path/to/repo
165
- sourcecode impact org.example.OrderService /path/to/repo # FQN also accepted
166
- sourcecode impact OrderService . --depth 2 # limit BFS depth
167
- ```
168
-
169
- **Output fields:**
170
-
171
- | Field | Description |
172
- |-------|-------------|
173
- | `direct_callers` | Classes that directly import or inject the target |
174
- | `indirect_callers` | Transitive callers up to `--depth` (default: 4) |
175
- | `endpoints_affected` | HTTP endpoints whose call chain includes the target |
176
- | `transactional_boundaries_touched` | `@Transactional` classes in the blast cone |
177
- | `mappers_affected` | `@Repository` / `@Mapper` / DAO classes in the blast cone |
178
- | `security_surface_affected` | Security policies on affected endpoints |
179
- | `cross_module_impact` | Subsystems touched, ordered by affected symbol count |
180
- | `risk_score` | 0–100 quantified change risk |
181
- | `confidence_score` | 0–1 confidence in the analysis |
182
- | `explanation` | Human-readable risk summary |
183
- | `candidates` | On partial match: up to 10 FQNs ranked by relevance |
184
-
185
- **Best practices:**
186
- - Target **interfaces**, not implementations: `impact OrderService` > `impact OrderServiceImpl`. In Spring projects, callers inject the interface via `@Autowired` — the impl has zero direct callers in the graph even though it runs all the code. Querying the impl returns `direct_callers: []` with no error; querying the interface returns the real blast radius.
187
- - Use `--depth 1` when the target has 200+ callers — direct endpoints are already the most actionable signal.
188
- - The cache applies to the underlying IR scan — second `impact` run on the same repo is significantly faster.
189
- - When you get `direct_callers: 0` for a `@Service` or `@Repository` class, that is almost certainly the interface-injection pattern. Re-run with the interface name.
190
-
191
- **Supported targets:**
192
- - Simple class name: `OrderService`
193
- - Fully-qualified name: `org.broadleafcommerce.core.order.service.OrderService`
194
- - File path: `src/main/java/.../OrderService.java`
195
-
196
- ---
197
-
198
- ## `endpoints` — REST API surface
199
-
200
- ```bash
201
- sourcecode endpoints /path/to/repo
202
- sourcecode endpoints /path/to/repo --output endpoints.json
203
- ```
204
-
205
- Extracts all Spring MVC (`@GetMapping`, `@PostMapping`, `@RequestMapping`, etc.) and JAX-RS (`@GET`, `@POST`, `@Path`) endpoint methods. Returns HTTP method, path, controller class, and handler method.
206
-
207
- **Scope limitations:**
208
- - JAX-RS subresource locators (endpoints mounted dynamically without class-level `@Path`) are not counted as standalone endpoints — they appear in `impact` output when transitively reached.
209
- - Security context on endpoints reflects method-level annotations (`@PreAuthorize`, `@Secured`). Class-level or programmatic security shows as `no_security_signal`.
210
-
211
- ---
212
-
213
- ## `repo-ir` — Symbol-level IR
214
-
215
- ```bash
216
- sourcecode repo-ir /path/to/repo --summary-only # recommended: analysis + impact, no full graph (~20K tokens)
217
- sourcecode repo-ir /path/to/repo --since HEAD~1 # symbol-level diff
218
- sourcecode repo-ir /path/to/repo --files src/.../OrderService.java # single-file IR
219
- sourcecode repo-ir /path/to/repo --max-nodes 200 --max-edges 500 # limits forward graph only — see note below
220
- ```
221
-
222
- Builds a deterministic symbol graph: classes, methods, import/injection edges, Spring roles, subsystems. Output is JSON with `graph`, `reverse_graph`, `impact`, `subsystems`, and `route_surface`.
223
-
224
- **Size warning:** Without `--summary-only`, output can exceed 1MB for mid-size repos. `--max-nodes`/`--max-edges` limit the forward `graph` section only — the `reverse_graph` section is not bounded by these flags and is the largest component. Always use `--summary-only` unless you need the full graph for downstream tooling.
225
-
226
- ---
227
-
228
- ## `onboard` — [OSS Core] Codebase orientation
229
-
230
- ```bash
231
- sourcecode onboard /path/to/repo
232
- ```
233
-
234
- Entry points, architecture summary, key files, confidence level, and gaps. Designed to be injected as AI agent context at the start of a session.
235
-
236
- ---
237
-
238
- ## `review-pr` — [Pro] PR review context
239
-
240
- ```bash
241
- sourcecode review-pr /path/to/repo --since main
242
- sourcecode review-pr /path/to/repo --since HEAD~3
243
- ```
244
-
245
- Changed files, risk ranking, test coverage gaps, affected modules, and blast radius of changed classes. Returns a structured `ci_decision` field for CI/CD integration.
246
-
247
- **Test coverage note:** Coverage gaps are detected by stem matching (e.g. `OrderService.java` ↔ `OrderServiceTest.java`). Tests in the same diff are counted.
248
-
249
- ---
250
-
251
- ## `fix-bug` — [Pro] Bug triage context
252
-
253
- ```bash
254
- sourcecode fix-bug /path/to/repo --symptom "NullPointerException in checkout"
255
- ```
256
-
257
- Risk-ranked file list correlated to the symptom: keyword extraction, path matching, content matching, and git commit correlation. Output includes `symptom_explain` with the full evidence chain.
258
-
259
- ---
260
-
261
- ## `modernize` — [Pro] Modernization planning
262
-
263
- ```bash
264
- sourcecode modernize /path/to/repo
265
- ```
266
-
267
- Identifies high-coupling nodes (high fan-in = risky to change), dead zone candidates (isolated symbols), and subsystem tangles.
268
-
269
- **Interpreting output:** `hotspot_candidates` is a subset of `high_coupling_nodes` filtered to service/repository/controller roles. In annotation-heavy codebases, the highest-coupled nodes are often annotation types or JPA entities — check `high_coupling_nodes` directly for the full coupling picture.
270
-
271
- ---
272
-
273
- ## `prepare-context` — Task-specific context
274
-
275
- Low-level access to all tasks with full options:
276
-
277
- ```bash
278
- sourcecode prepare-context TASK [PATH] [OPTIONS]
279
- ```
280
-
281
- | Task | What it surfaces |
282
- |------|-----------------|
283
- | `explain` | Architecture, entry points, key dependencies |
284
- | `onboard` | Full structural context for new agents/developers |
285
- | `fix-bug` | Files ranked by symptom correlation, risk, annotations |
286
- | `refactor` | Structural issues, improvement opportunities |
287
- | `generate-tests` | Source files without test pairs, coverage gap analysis |
288
- | `review-pr` | PR diff with risk ranking, test gaps, module impact |
289
- | `delta` | Incremental context: git-changed files + transitive import graph |
290
-
291
- ```bash
292
- sourcecode prepare-context fix-bug --symptom "NullPointerException in OrderService"
293
- sourcecode prepare-context review-pr --since main --format github-comment
294
- sourcecode prepare-context onboard --llm-prompt
295
- sourcecode prepare-context --task-help # list all tasks
296
- ```
297
-
298
- Note: `sourcecode onboard`, `sourcecode fix-bug`, `sourcecode review-pr`, and `sourcecode modernize` are shorthand aliases for the corresponding `prepare-context` tasks — output is identical.
299
-
300
- ---
301
-
302
- ## How to use sourcecode effectively
303
-
304
- ### Onboarding — new repo, new agent session
305
-
306
- ```bash
307
- # Bounded context at session start (~2,500–5,500 tokens)
308
- sourcecode /repo --compact # fast overview
309
- sourcecode /repo --agent # more detail: file relevance, architecture, event flows
310
- sourcecode onboard /repo # task-structured: entry points, key files, gaps
311
- ```
312
-
313
- Use `--compact` or `--agent` as first-prompt injection for AI coding agents. Both are bounded and deterministic.
314
-
315
- ### Impact analysis — before touching a class
316
-
317
- ```bash
318
- # Always target the INTERFACE in Spring projects:
319
- sourcecode impact OrderService /repo # ✓ correct: 30 callers, 11 endpoints
320
- sourcecode impact OrderServiceImpl /repo # ✗ wrong: 0 callers (Spring DI blindness)
321
-
322
- # Large hub interfaces — depth=1 is faster and still actionable:
323
- sourcecode impact KeycloakSession /repo --depth 1
324
-
325
- # If you get direct_callers:[] for a @Service class, re-query the interface.
326
- ```
327
-
328
- ### Bug triage — symptom-driven
329
-
330
- ```bash
331
- # Specific symptoms produce the best signal:
332
- sourcecode fix-bug /repo --symptom "OIDC token refresh fails after realm update"
333
- sourcecode fix-bug /repo --symptom "NullPointerException in OrderService during checkout"
334
-
335
- # Generic symptoms produce noisy output (100s of files) — be specific.
336
- # Use --output to capture full output without budget truncation.
337
- sourcecode fix-bug /repo --symptom "payment timeout" --output triage.json
338
- ```
339
-
340
- ### PR review
341
-
342
- ```bash
343
- # JSON for programmatic use:
344
- sourcecode review-pr /repo --since main --output review.json
345
- jq '.ci_decision' review.json # "analysis_success" | "git_ref_error"
346
-
347
- # Markdown for GitHub comment:
348
- sourcecode review-pr /repo --since main --format github-comment
349
-
350
- # CI/CD gate — parse risk and test coverage fields:
351
- jq '{ci_decision, test_coverage_risk, impact_summary}' review.json
352
- ```
353
-
354
- ### Modernization planning
355
-
356
- ```bash
357
- sourcecode modernize /repo
358
- # high_coupling_nodes: classes most risky to change (by fan-in degree)
359
- # dead_zone_candidates: classes with zero callers — safe to remove or refactor
360
- # Note: hotspot_candidates may be empty in annotation-heavy codebases —
361
- # check high_coupling_nodes directly for coupling signal.
362
- ```
363
-
364
- ### Symbol IR for downstream tooling
365
-
366
- ```bash
367
- # Always use --summary-only unless you need the full graph:
368
- sourcecode repo-ir /repo --summary-only --output ir.json # ~20K tokens
369
- sourcecode repo-ir /repo --since HEAD~3 --summary-only # changed symbols only
370
-
371
- # Full graph warning: output can exceed 1MB for mid-size repos.
372
- # --max-nodes/--max-edges only limit the forward graph, not reverse_graph.
373
- ```
374
-
375
- ### With AI agents (Claude, GPT-4, etc.)
376
-
377
- ```bash
378
- # Start agent session with bounded context:
379
- sourcecode /repo --agent --output context.json && cat context.json | agent-cli
380
-
381
- # For a specific change task, combine context + impact:
382
- sourcecode /repo --compact > context.json
383
- sourcecode impact PaymentService /repo --depth 1 >> impact.json
384
- # Feed both to agent: "Given this context and impact, what are the risks of changing PaymentService?"
385
-
386
- # For PR review:
387
- sourcecode review-pr /repo --since main --format github-comment
388
- # Paste directly into GitHub PR description or feed to agent
389
- ```
390
-
391
- ### In CI/CD pipelines
392
-
393
- ```bash
394
- # Deterministic, content-hash cached — safe to run on every commit
395
- sourcecode /repo --compact --no-cache --output context.json
396
-
397
- # PR gate
398
- sourcecode review-pr /repo --since $BASE_REF --output review.json
399
- DECISION=$(jq -r '.ci_decision' review.json)
400
- if [ "$DECISION" != "analysis_success" ]; then echo "Review failed: $DECISION"; fi
401
- ```
402
-
403
- ---
404
-
405
- ## What sourcecode does NOT do
406
-
407
- - No runtime analysis — all signals are static (annotation, import graph, file structure)
408
- - No semantic code understanding — it reads structure, not logic
409
- - Architecture pattern detection works best for Spring MVC layered apps; SPI/plugin architectures (e.g. Quarkus extension model) are classified as "layered" which may be inaccurate
410
- - Endpoint recall for JAX-RS subresource locator pattern is ~65% — endpoints mounted dynamically via factory methods are not individually counted. JAX-RS sub-resource paths (method-level `@Path` inside a `@Path`-annotated class) are extracted as relative paths, not the fully composed URL.
411
- - `impact` on implementation classes (e.g. `OrderServiceImpl`) reflects callers of the implementation specifically — **in Spring Boot projects this is almost always zero**, because callers inject the interface via `@Autowired`. Always target the interface (`OrderService`) to get the real blast radius. The tool does not auto-resolve impl → interface. When `direct_callers: []` is returned with `confidence_level: high` for a `@Service` class, treat it as a prompt to re-query the interface.
412
- - `no_security_signal` on endpoints means no method-level security annotations (`@PreAuthorize`, `@Secured`) were found — it does **not** mean the endpoint is unsecured. Projects using Spring Security filter chains, XML security config, or custom filters will show 100% `no_security_signal` even when fully secured.
413
- - `hotspot_candidates` in `modernize` output reflects graph coupling, not git churn — in annotation-heavy codebases it is often empty even though real hotspots exist. Check `high_coupling_nodes` directly for the coupling picture.
414
- - `project_summary` is extracted from the repository README — it may reflect marketing language rather than architectural description
415
-
416
- ---
417
-
418
- ## Output schema
419
-
420
- All outputs include:
421
- - `schema_version`: output format version
422
- - `confidence_summary`: `overall`, `stack`, `entry_points` confidence levels (`high`/`medium`/`low`)
423
- - `analysis_gaps`: list of what could not be analyzed and why
424
-
425
- ### Java/Spring-specific fields (when detected)
426
-
427
- | Field | Description |
428
- |-------|-------------|
429
- | `language_version` | Java version from `maven.compiler.source` or equivalent |
430
- | `deployment.spring_boot_version` | Spring Boot version |
431
- | `deployment.packaging` | `jar` or `war` |
432
- | `mybatis` | Mapper interface / XML file pairing summary |
433
- | `transactional_boundaries` | Classes annotated with `@Transactional` |
434
- | `deployment_risks` | Static risk flags: `spring-boot-2.x-eol`, `legacy-java-runtime` |
435
-
436
- ---
437
-
438
- ## Telemetry
439
-
440
- Anonymous, opt-in. Collects: version, OS, commands, flags, duration, repo size range, errors. No source code, paths, secrets, or output content.
441
-
442
- ```bash
443
- sourcecode telemetry status
444
- sourcecode telemetry enable
445
- sourcecode telemetry disable
446
- ```
447
-
448
- Or: `export SOURCECODE_TELEMETRY=0`
449
-
450
- ---
451
-
452
- ## Configuration
453
-
454
- ```bash
455
- sourcecode config # show version, config file path, telemetry status
456
- ```