java-codebase-rag 0.12.0__py3-none-any.whl → 0.12.2__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.
Files changed (77) hide show
  1. java_codebase_rag-0.12.2.dist-info/METADATA +35 -0
  2. java_codebase_rag-0.12.2.dist-info/RECORD +4 -0
  3. {java_codebase_rag-0.12.0.dist-info → java_codebase_rag-0.12.2.dist-info}/WHEEL +1 -1
  4. java_codebase_rag/_deprecation.py +0 -103
  5. java_codebase_rag/_fdlimit.py +0 -56
  6. java_codebase_rag/_stdio.py +0 -32
  7. java_codebase_rag/_version.py +0 -35
  8. java_codebase_rag/absence/__init__.py +0 -0
  9. java_codebase_rag/absence/absence_diagnosis.py +0 -700
  10. java_codebase_rag/absence/absence_types.py +0 -124
  11. java_codebase_rag/absence/absence_vocab.py +0 -460
  12. java_codebase_rag/analysis/__init__.py +0 -0
  13. java_codebase_rag/analysis/pr_analysis.py +0 -563
  14. java_codebase_rag/analysis/resolve_service.py +0 -740
  15. java_codebase_rag/ast/__init__.py +0 -0
  16. java_codebase_rag/ast/ast_java.py +0 -2847
  17. java_codebase_rag/ast/ast_kotlin.py +0 -1794
  18. java_codebase_rag/ast/brownfield_events.py +0 -58
  19. java_codebase_rag/ast/chunk_heuristics.py +0 -83
  20. java_codebase_rag/ast/language.py +0 -117
  21. java_codebase_rag/cli.py +0 -1215
  22. java_codebase_rag/cli_dispatch.py +0 -251
  23. java_codebase_rag/cli_format.py +0 -85
  24. java_codebase_rag/cli_progress.py +0 -94
  25. java_codebase_rag/config.py +0 -833
  26. java_codebase_rag/eval/__init__.py +0 -1
  27. java_codebase_rag/eval/ground_truth.py +0 -100
  28. java_codebase_rag/eval/metrics.py +0 -107
  29. java_codebase_rag/eval/runner.py +0 -556
  30. java_codebase_rag/graph/__init__.py +0 -0
  31. java_codebase_rag/graph/build_ast_graph.py +0 -4593
  32. java_codebase_rag/graph/graph_enrich.py +0 -1940
  33. java_codebase_rag/graph/graph_types.py +0 -224
  34. java_codebase_rag/graph/java_ontology.py +0 -465
  35. java_codebase_rag/graph/ladybug_queries.py +0 -2213
  36. java_codebase_rag/graph/path_filtering.py +0 -509
  37. java_codebase_rag/index/__init__.py +0 -0
  38. java_codebase_rag/index/java_index_flow_lancedb.py +0 -879
  39. java_codebase_rag/index/java_index_v1_common.py +0 -33
  40. java_codebase_rag/install_data/__init__.py +0 -0
  41. java_codebase_rag/install_data/agents/explorer-rag-cli.md +0 -110
  42. java_codebase_rag/install_data/agents/explorer-rag-enhanced.md +0 -152
  43. java_codebase_rag/install_data/skills/explore-codebase/SKILL.md +0 -165
  44. java_codebase_rag/install_data/skills/explore-codebase-cli/SKILL.md +0 -107
  45. java_codebase_rag/installer.py +0 -2188
  46. java_codebase_rag/jrag.py +0 -4545
  47. java_codebase_rag/jrag_envelope.py +0 -1107
  48. java_codebase_rag/jrag_hints.py +0 -204
  49. java_codebase_rag/jrag_render.py +0 -926
  50. java_codebase_rag/lance_optimize.py +0 -264
  51. java_codebase_rag/mcp/__init__.py +0 -0
  52. java_codebase_rag/mcp/mcp_hints.py +0 -932
  53. java_codebase_rag/mcp/mcp_v2.py +0 -1916
  54. java_codebase_rag/mcp/server.py +0 -886
  55. java_codebase_rag/pipeline.py +0 -531
  56. java_codebase_rag/progress.py +0 -570
  57. java_codebase_rag/read_payloads.py +0 -781
  58. java_codebase_rag/search/__init__.py +0 -0
  59. java_codebase_rag/search/index_common.py +0 -10
  60. java_codebase_rag/search/search_lancedb.py +0 -1296
  61. java_codebase_rag/search/search_lexical.py +0 -449
  62. java_codebase_rag/search/search_scoring.py +0 -537
  63. java_codebase_rag/watch/__init__.py +0 -0
  64. java_codebase_rag/watch/client.py +0 -230
  65. java_codebase_rag/watch/daemon.py +0 -396
  66. java_codebase_rag/watch/lock.py +0 -201
  67. java_codebase_rag/watch/paths.py +0 -76
  68. java_codebase_rag/watch/protocol.py +0 -122
  69. java_codebase_rag/watch/server.py +0 -273
  70. java_codebase_rag/watch/warm.py +0 -105
  71. java_codebase_rag/watch/watcher.py +0 -394
  72. java_codebase_rag-0.12.0.dist-info/METADATA +0 -340
  73. java_codebase_rag-0.12.0.dist-info/RECORD +0 -75
  74. java_codebase_rag-0.12.0.dist-info/entry_points.txt +0 -5
  75. java_codebase_rag-0.12.0.dist-info/licenses/LICENSE +0 -21
  76. java_codebase_rag-0.12.0.dist-info/top_level.txt +0 -1
  77. /java_codebase_rag/__init__.py → /java_codebase_rag-0.12.2.dist-info/top_level.txt +0 -0
java_codebase_rag/jrag.py DELETED
@@ -1,4545 +0,0 @@
1
- """jrag - agent-facing CLI (PR-JRAG-1a foundation).
2
-
3
- Compose-and-render layer over the existing backend (``resolve_v2``,
4
- ``LadybugGraph``, ``mcp_v2`` handlers, ``run_search``). v1 loads the index
5
- in-process per call (no daemon); reuses the operator's index directory and
6
- config resolver (``resolve_operator_config`` + ``apply_to_os_environ``).
7
-
8
- PR-JRAG-1a ships only the foundation: ``build_parser`` (with ``--offset``
9
- intentionally NOT global - registered only on find/search in PR-1b/PR-4),
10
- ``_resolve_cfg`` (operator config reuse), ``_load_graph`` (actionable error
11
- envelopes), ``main`` (``raise_fd_limit`` first; stdout envelope + stderr
12
- traceback on error), and the ``status`` command. Later PRs add subcommands and
13
- fill the ``agent_next_actions`` hook.
14
-
15
- Lazy-import invariant: ``build_parser()`` imports NO backend modules - so
16
- ``jrag --help`` stays fast and free of torch/sentence_transformers/mcp_v2.
17
- Backend imports (``resolve_service``, ``ladybug_queries``,
18
- ``resolve_operator_config``, ``jrag_envelope`` helpers) live inside command
19
- handlers. Sentinel:
20
- python -c "import java_codebase_rag.jrag as j; j.build_parser()"
21
- loads no torch / sentence_transformers / mcp_v2.
22
- """
23
- from __future__ import annotations
24
-
25
- import argparse
26
- import os
27
- import signal
28
- import sys
29
- import time
30
- import traceback
31
- from pathlib import Path
32
-
33
- from java_codebase_rag._fdlimit import raise_fd_limit
34
- from java_codebase_rag._stdio import force_utf8_stdio
35
- from java_codebase_rag._version import version_string
36
-
37
- __all__ = ["build_parser", "main", "_console_script_main"]
38
-
39
-
40
- class _IndexNotFound(RuntimeError):
41
- """Raised when no LadybugDB graph exists at the resolved path."""
42
-
43
-
44
- class _IndexStale(RuntimeError):
45
- """Raised when the on-disk graph's ontology is older than required."""
46
-
47
-
48
- # Generous limit for the topics --consumer-in / listeners --topic-contains
49
- # compose fetches (these resolve cross-topic edges and should not silently
50
- # truncate the listener/consumer set under typical fixture sizes).
51
- _CONSUMER_FETCH_LIMIT = 200
52
-
53
-
54
- # Framework tag -> the type-level annotations a Symbol's declaring type carries
55
- # when it participates in that framework. The graph stores `framework` only on
56
- # Route nodes (Route.framework = spring_mvc | webflux | kafka | ...); Symbol
57
- # nodes have no framework field, so `search --framework <name>` (a symbol result
58
- # set) maps the framework back onto the declaring type via these annotations and
59
- # post-filters. Mirrors the indexer's own classification heuristic.
60
- _FRAMEWORK_ANNOTATIONS: dict[str, frozenset[str]] = {
61
- "spring_mvc": frozenset({
62
- "RestController", "Controller", "RestControllerAdvice", "RequestMapping",
63
- "GetMapping", "PostMapping", "PutMapping", "DeleteMapping", "PatchMapping",
64
- }),
65
- "webflux": frozenset({
66
- "RestController", "Controller", "RequestMapping",
67
- }),
68
- "kafka": frozenset({"EnableKafka", "KafkaStreams", "KafkaStream"}),
69
- "rabbitmq": frozenset({"EnableRabbit", "RabbitListener"}),
70
- "jms": frozenset({"EnableJms", "JmsListener"}),
71
- "stream": frozenset({"EnableBinding", "StreamBridge", "EnableStream"}),
72
- "feign": frozenset({"FeignClient", "EnableFeignClients"}),
73
- }
74
-
75
-
76
- def _framework_type_fqns(graph, framework: str) -> set[str]:
77
- """Return the set of type-level Symbol FQNs whose annotations match the
78
- given framework tag (per :data:`_FRAMEWORK_ANNOTATIONS`).
79
-
80
- One focused Cypher lookup, cached implicitly per-process (the CLI is
81
- short-lived). Used by ``search --framework`` as a post-filter on the
82
- primary-type FQN each SearchHit carries.
83
- """
84
- anns = _FRAMEWORK_ANNOTATIONS.get(framework)
85
- if not anns:
86
- return set()
87
- # Ladybug has no parameterized list membership; expand the fixed annotation
88
- # set as ORed ``list_contains`` predicates (same pattern as trace_flow's
89
- # capability expansion).
90
- predicates = " OR ".join(f"list_contains(s.annotations, '{a}')" for a in anns)
91
- rows = graph._rows( # noqa: SLF001 - focused lookup (same pattern as _resolve_topic_consumers)
92
- f"MATCH (s:Symbol) WHERE s.kind IN ['class','interface','annotation'] "
93
- f"AND ({predicates}) RETURN DISTINCT s.fqn AS fqn",
94
- {},
95
- )
96
- return {str(r.get("fqn") or "") for r in rows if r.get("fqn")}
97
-
98
-
99
- def _apply_auto_scope(args: argparse.Namespace, cfg, graph) -> None:
100
- """Default ``args.service`` to the microservice implied by cwd (MCP parity).
101
-
102
- Mirrors ``server.py`` ``ScopeManager``: when cwd sits inside one
103
- microservice of a system-level index, behave as if the agent had typed
104
- ``--service <that microservice>`` so the other services' results do not
105
- leak in. No-op unless the command opted in via
106
- ``set_defaults(auto_scope=True)`` and the caller did not pass ``--service``.
107
-
108
- Detection reuses ``graph_enrich.detect_microservice_from_path``; the
109
- candidate is validated against ``graph.microservice_counts()`` and dropped
110
- if absent (a mislabeled non-microservice dir would otherwise yield zero
111
- matches). When the known set is empty/unreadable we KEEP the candidate
112
- (transient graph error) — same as ``server.py:130-132``. Detection returns
113
- ``None`` at the system root or outside it, so auto-scope never fires for
114
- estate-wide work.
115
-
116
- Records ``args._service_user`` (caller passed ``--service``) for warning
117
- distinction and ``args._service_auto`` (detected name) for the
118
- transparency notice.
119
-
120
- NOTE: three commands inline their graph load and bypass
121
- ``_load_graph_or_error`` — ``find``, ``inspect``, ``status``. ``find`` is
122
- opted in and calls this helper itself; ``inspect``/``status`` are NOT
123
- opted in (they don't use ``--service`` as a result filter today). If
124
- either is ever opted in, it must call this helper in its own load path.
125
- """
126
- # ``--service`` lives on the ``_common_parser``; a few commands (status,
127
- # microservices) use a bare ``_core_parser`` without it. Gate on opt-in
128
- # FIRST so those never reach the ``args.service`` read below.
129
- if not getattr(args, "auto_scope", False):
130
- return
131
- args._service_user = getattr(args, "service", None) is not None
132
- if getattr(args, "service", None) is not None: # explicit --service wins
133
- return
134
- if getattr(args, "no_auto_scope", False) or os.environ.get("JRAG_NO_AUTO_SCOPE"):
135
- return
136
- source_root = cfg.source_root if cfg.source_root else None
137
- if not source_root:
138
- return
139
- from java_codebase_rag.graph.graph_enrich import detect_microservice_from_path
140
-
141
- candidate = detect_microservice_from_path(Path.cwd(), Path(source_root))
142
- if not candidate:
143
- return
144
- try:
145
- known = {name for name in (graph.microservice_counts() or {}) if name}
146
- except Exception:
147
- known = set()
148
- if known and candidate not in known:
149
- return
150
- args.service = candidate
151
- args._service_auto = candidate
152
- print(f"[jrag] auto-scope: --service {candidate} (cwd)", file=sys.stderr)
153
-
154
-
155
- def _auto_scope_notice(args: argparse.Namespace) -> list[str]:
156
- """Envelope ``warnings[]`` line telling the agent results are auto-scoped.
157
-
158
- Models often do not see stderr (where the ``[jrag] auto-scope`` line goes),
159
- so this also surfaces the scope in the rendered output. Returns ``[]`` when
160
- auto-scope did not fire (no detected service) or the command opted out.
161
- """
162
- svc = getattr(args, "_service_auto", None)
163
- if not svc:
164
- return []
165
- return [
166
- f"auto-scope: --service {svc} (inferred from cwd; "
167
- f"pass --no-auto-scope to disable)"
168
- ]
169
-
170
-
171
- def _load_graph_or_error(args: argparse.Namespace):
172
- """Resolve config + load graph; on missing/stale index, print an error
173
- envelope and return ``(cfg, graph_or_None, rc)``.
174
-
175
- Shared by every listing command so the cfg/load/error frame is not
176
- hand-copied. ``rc`` is 2 on error (envelope already printed), 0 on success.
177
- """
178
- from java_codebase_rag.jrag_envelope import Envelope
179
- from java_codebase_rag.jrag_render import render
180
-
181
- cfg = _resolve_cfg(args)
182
- try:
183
- graph = _load_graph(cfg)
184
- except (_IndexNotFound, _IndexStale) as exc:
185
- env = Envelope(status="error", message=str(exc))
186
- print(render(env, fmt=args.format, detail=args.detail))
187
- return cfg, None, 2
188
- # Default --service from cwd before the handler reads it (MCP parity).
189
- # No-op unless the command opted in via set_defaults(auto_scope=True).
190
- _apply_auto_scope(args, cfg, graph)
191
- return cfg, graph, 0
192
-
193
-
194
- def _clamped_limit(args: argparse.Namespace) -> int:
195
- """Return the limit clamped so ``limit+1 <= 500`` (backend clamp)."""
196
- raw_limit = args.limit if args.limit is not None else 20
197
- return min(raw_limit, 499)
198
-
199
-
200
- def _emit(env, args: argparse.Namespace, *, noun: str = "",
201
- shape: str | None = None, next_offset: int | None = None) -> int:
202
- """Final render+print funnel honoring ``--count`` / ``--exists`` / ``--fields``;
203
- returns the exit code.
204
-
205
- The single output seam every ok / not_found / ambiguous result routes
206
- through. The shared helpers (:func:`_render_listing`, :func:`_emit_traversal`)
207
- delegate their tail here; inline success render sites call it directly. True
208
- usage / setup errors (missing index, kind guard, ``neighbors_v2`` failure,
209
- argparse errors) bypass it — those render normally via :func:`render`, since a
210
- count/exists shape would hide the actionable error message.
211
-
212
- Exit code: ``--exists`` forces 0 when results are present and 2 otherwise
213
- (resolve miss AND empty ok both count as absent), computed via
214
- :func:`jrag_render.has_results` so output and exit code agree. Without
215
- ``--exists``, rc follows the envelope (error -> 2, else 0); ``--count`` does
216
- not gate (a zero count on an ok envelope stays exit 0).
217
-
218
- ``getattr`` defaults keep this safe for parsers that lack the flags
219
- (``_core_parser`` commands), though only ``_common_parser`` commands are
220
- routed here today.
221
- """
222
- from java_codebase_rag.jrag_render import has_results, render
223
-
224
- print(render(
225
- env,
226
- fmt=getattr(args, "format", "text"),
227
- detail=getattr(args, "detail", "normal"),
228
- noun=noun,
229
- next_offset=next_offset,
230
- shape=shape,
231
- count=getattr(args, "count", False),
232
- exists=getattr(args, "exists", False),
233
- fields=getattr(args, "fields", None),
234
- ))
235
- if getattr(args, "exists", False):
236
- return 0 if has_results(env, shape) else 2
237
- return 2 if env.status == "error" else 0
238
-
239
-
240
- def _render_listing(rows, *, limit: int, args: argparse.Namespace, noun: str,
241
- extra_hints: list[str] | None = None) -> int:
242
- """Apply +1-fetch truncation, build the envelope, render as a listing.
243
-
244
- Shared by the listing commands whose backend returns a flat row list
245
- (routes / clients / producers). ``rows`` must already be the limit+1
246
- fetch. Renders as the default shape (no ``shape=``).
247
-
248
- ``extra_hints`` are merged into ``agent_next_actions`` AFTER the
249
- edge/breadcrumb-derived hints (deduped, capped at 5). Used by listings
250
- whose rows map to a natural ``jrag inspect <fqn>`` drill-down
251
- (jobs / listeners / entities).
252
- """
253
- from java_codebase_rag.jrag_envelope import Envelope, mark_truncated, next_actions_hook, to_envelope_rows
254
-
255
- node_list = to_envelope_rows(rows) if rows and not isinstance(rows[0], dict) else list(rows)
256
- display_nodes_list, truncated = mark_truncated(node_list, limit)
257
- display_nodes = {node["id"]: node for node in display_nodes_list}
258
-
259
- env = Envelope(
260
- status="ok", nodes=display_nodes, truncated=truncated,
261
- warnings=_auto_scope_notice(args),
262
- )
263
- next_actions_hook(env, command=getattr(args, "command", None))
264
- if extra_hints:
265
- seen = set(env.agent_next_actions)
266
- for h in extra_hints:
267
- if h and h not in seen:
268
- seen.add(h)
269
- env.agent_next_actions.append(h)
270
- env.agent_next_actions = env.agent_next_actions[:5]
271
- return _emit(env, args, noun=noun)
272
-
273
-
274
- def _symbol_hit_to_dict(hit) -> dict:
275
- """Convert a ``SymbolHit`` (dataclass) to the envelope node dict shape.
276
-
277
- Carries the FULL ``SymbolHit``: ``filename`` / ``start_line`` so the
278
- projector can compose the ``file`` field at ``--detail normal``, and
279
- ``signature`` / ``annotations`` / ``capabilities`` / ``modifiers`` /
280
- ``package`` / ``parent_id`` / ``resolved`` so ``--detail full`` is genuinely
281
- rich. The projector (:func:`jrag_envelope.project_node`) trims per detail
282
- level at render time — callers build rich and let the seam trim, inverting
283
- the old "trim at construction" that coupled detail to format. Empty values
284
- are dropped by the projector, so carrying them here is harmless. Byte
285
- offsets (``start_byte`` / ``end_byte``) are intentionally dropped — pure
286
- noise, never a display field.
287
- """
288
- return {
289
- "id": hit.id,
290
- "kind": "symbol",
291
- "fqn": hit.fqn,
292
- "name": hit.name,
293
- "symbol_kind": hit.kind,
294
- "microservice": hit.microservice,
295
- "module": hit.module,
296
- "role": hit.role,
297
- "filename": hit.filename,
298
- "start_line": hit.start_line,
299
- "end_line": hit.end_line,
300
- "signature": hit.signature,
301
- "annotations": list(hit.annotations or []),
302
- "capabilities": list(hit.capabilities or []),
303
- "modifiers": list(hit.modifiers or []),
304
- "package": hit.package,
305
- "parent_id": hit.parent_id,
306
- "resolved": hit.resolved,
307
- }
308
-
309
-
310
- class _EnvelopeArgumentParser(argparse.ArgumentParser):
311
- """ArgumentParser subclass that routes ``error()`` to a raised exception.
312
-
313
- Stock argparse ``error()`` prints ``usage:`` to stderr and calls SystemExit
314
- — a raw, non-envelope shape that ignores ``--format json``. With
315
- ``exit_on_error=False`` the base class raises :class:`argparse.ArgumentError`
316
- instead, but STILL prints the usage text first. This override suppresses the
317
- usage dump so :func:`main` can emit a clean ``status: error`` envelope
318
- honoring ``--format`` (consistent with not_found / missing-index errors).
319
- """
320
-
321
- def error(self, message: str) -> None: # type: ignore[override]
322
- raise argparse.ArgumentError(None, message)
323
-
324
-
325
- _PREPARSE_PARSER = argparse.ArgumentParser(add_help=False)
326
- _PREPARSE_PARSER.add_argument("--format", default=None)
327
- _PREPARSE_PARSER.add_argument("--detail", default=None)
328
-
329
-
330
- def _preparse_render_flags(raw: list[str]) -> tuple[str | None, str | None, list[str]]:
331
- """Extract ``--format`` / ``--detail`` from raw argv via a minimal parser.
332
-
333
- Used by :func:`main` to honor render flags when argparse bailed before
334
- populating ``args`` (missing required positional, unknown subcommand).
335
- Returns ``(format, detail, leftover_argv)`` where ``leftover_argv`` has the
336
- consumed flag tokens stripped so the first remaining non-dash token is the
337
- subcommand name (not a flag value like the ``json`` in ``--format json``).
338
- """
339
- try:
340
- ns, leftover = _PREPARSE_PARSER.parse_known_args(raw)
341
- return ns.format, ns.detail, list(leftover)
342
- except Exception:
343
- return None, None, list(raw)
344
-
345
-
346
- # Closed enum taxonomies for the --role / --exclude-role / --java-kind /
347
- # --framework / --capability filters. Sourced from the canonical literals
348
- # (mcp_v2.Role, mcp_v2.DeclarationSymbolKind, mcp_v2.Framework) and
349
- # java_ontology.VALID_CAPABILITIES, and cross-checked by test_jrag_enum_choices.
350
- # Hardcoded here (not imported) so `jrag --help` stays fast — build_parser
351
- # imports no backend modules, and importing mcp_v2 costs ~0.7s.
352
- _ROLE_CHOICES = (
353
- "CONTROLLER", "SERVICE", "REPOSITORY", "COMPONENT", "CONFIG",
354
- "ENTITY", "CLIENT", "MAPPER", "DTO", "OTHER",
355
- )
356
- _JAVA_KIND_CHOICES = (
357
- "class", "interface", "enum", "record", "annotation", "method", "constructor",
358
- )
359
- _FRAMEWORK_CHOICES = (
360
- "spring_mvc", "webflux", "kafka", "rabbitmq", "jms", "stream", "feign",
361
- )
362
- _CAPABILITY_CHOICES = (
363
- "MESSAGE_LISTENER", "MESSAGE_PRODUCER", "HTTP_CLIENT",
364
- "SCHEDULED_TASK", "EXCEPTION_HANDLER",
365
- )
366
-
367
-
368
- def _upper_snake(value: str) -> str:
369
- """Normalize a role/capability value to its stored UPPER_SNAKE form so
370
- argparse ``choices=`` accepts flexible casing (``controller`` /
371
- ``scheduled-task`` -> ``CONTROLLER`` / ``SCHEDULED_TASK``). Mirrors the
372
- role/capability branch of jrag_envelope.normalize_enum."""
373
- return value.strip().upper().replace("-", "_").replace(" ", "_")
374
-
375
-
376
- def _lower_snake(value: str) -> str:
377
- """Normalize a java-kind/framework value to its stored lowercase form so
378
- argparse ``choices=`` accepts flexible casing (``Spring-MVC`` ->
379
- ``spring_mvc``). Mirrors the framework/java_kind branch of
380
- jrag_envelope.normalize_enum."""
381
- return value.strip().lower().replace("-", "_").replace(" ", "_")
382
-
383
-
384
- def build_parser() -> argparse.ArgumentParser:
385
- """Argparse builder. Imports no backend modules.
386
-
387
- ``--offset`` is intentionally NOT a global flag (PR-JRAG-1a contract): it
388
- is added only to ``find`` / ``search`` subparsers in PR-JRAG-1b / PR-JRAG-4
389
- (those commands route through ``find_v2`` / ``search_v2`` which take an
390
- ``offset``). In 1a, no subparser has ``--offset``.
391
- """
392
- description = (
393
- "jrag - agent-facing CLI for graph-native code intelligence.\n\n"
394
- "Every <query> command resolves the identifier (FQN / simple name /\n"
395
- "route path / topic) as the first step and maps one/many/none onto a\n"
396
- "single envelope. Default output is compact text; `--format json` emits\n"
397
- "the envelope verbatim.\n\n"
398
- "Commands by group:\n"
399
- " health: status\n"
400
- " locate: find, inspect\n"
401
- " listings: routes, clients, producers, topics, jobs, listeners,\n"
402
- " entities\n"
403
- " traversal: callers, callees, hierarchy, implementations, subclasses,\n"
404
- " overrides, overridden-by, dependents, impact, decompose,\n"
405
- " flow, dependencies, connection, outline, imports\n"
406
- " orientation: microservices, map, conventions, overview\n"
407
- " search: search\n\n"
408
- "Run `jrag <command> --help` for command-specific options."
409
- )
410
- parser = _EnvelopeArgumentParser(
411
- prog="jrag",
412
- description=description,
413
- formatter_class=argparse.RawDescriptionHelpFormatter,
414
- exit_on_error=False,
415
- )
416
- parser.add_argument(
417
- "--version",
418
- action="version",
419
- version=version_string(parser.prog),
420
- )
421
- subparsers = parser.add_subparsers(dest="command", parser_class=_EnvelopeArgumentParser)
422
-
423
- # Common flags applied per command via parents=[_common_parser()]. NOT
424
- # global so commands can override defaults (e.g. inspect/orientation
425
- # default --detail to full). The helper builds a FRESH parser each call so every subparser
426
- # owns its own --detail Action object — argparse `parents` shares Action
427
- # objects by reference, and `set_defaults(detail=...)` mutates the shared
428
- # action's default (CPython walks `self._actions`), so a single shared
429
- # `common` made `status.set_defaults(detail="full")` poison every other
430
- # subparser into defaulting to "full". A fresh parser per subparser isolates
431
- # the override to the command that asked for it.
432
- def _common_parser() -> argparse.ArgumentParser:
433
- common = argparse.ArgumentParser(add_help=False)
434
- common.add_argument("--service", type=str, default=None, help="Filter by microservice.")
435
- common.add_argument("--module", type=str, default=None, help="Filter by module.")
436
- common.add_argument(
437
- "--no-auto-scope",
438
- dest="no_auto_scope",
439
- action="store_true",
440
- default=False,
441
- help=(
442
- "Disable cwd-derived auto --service scoping so cross-service "
443
- "results are visible (also disabled via JRAG_NO_AUTO_SCOPE=1)."
444
- ),
445
- )
446
- common.add_argument(
447
- "--limit", type=int, default=20, help="Cap on results (default 20)."
448
- )
449
- common.add_argument(
450
- "--index-dir",
451
- type=str,
452
- default=None,
453
- dest="index_dir",
454
- help="Index directory override (default: discovered from cwd).",
455
- )
456
- common.add_argument(
457
- "--format",
458
- choices=("text", "json"),
459
- default="text",
460
- help="Output format (default: text).",
461
- )
462
- common.add_argument(
463
- "--detail",
464
- choices=("brief", "normal", "full"),
465
- default="normal",
466
- help=(
467
- "Output detail level (default normal) — ORTHOGONAL to --format: both "
468
- "text and json honor it. brief = identity only (name @service); "
469
- "normal = +module/role/file/score; full = +signature/annotations/snippet."
470
- ),
471
- )
472
- # Output-shaping flags (issue #376). NOT on _core_parser: status /
473
- # microservices are aggregate rollups (a count there is meaningless) and
474
- # vocab-index prints plain text outside the render path, so adding them
475
- # there would create silently-ignored flags (violates the
476
- # "inapplicable flags never silently ignored" principle).
477
- common.add_argument(
478
- "--count",
479
- action="store_true",
480
- default=False,
481
- help=(
482
- "Print only the result count (no rows) — bare int in text, "
483
- "{\"status\",\"count\"} in json. Counts nodes (listing), edges "
484
- "(traversal), or 1 (inspect)."
485
- ),
486
- )
487
- common.add_argument(
488
- "--exists",
489
- action="store_true",
490
- default=False,
491
- help=(
492
- "Print only an exists boolean (true/false, or "
493
- "{\"status\",\"exists\"} in json). Exit 0 when results exist, "
494
- "2 otherwise (incl. resolve miss / empty result)."
495
- ),
496
- )
497
- common.add_argument(
498
- "--fields",
499
- type=str,
500
- default=None,
501
- metavar="LIST",
502
- help=(
503
- "Comma-separated node-field allowlist that overrides --detail "
504
- "(e.g. fqn,role,signature). Ignored with --count/--exists; "
505
- "primarily a --format json lever; text still labels rows from "
506
- "whatever identity fields survive."
507
- ),
508
- )
509
- return common
510
-
511
- # Core-only parser for AGGREGATE commands (status / microservices) that have
512
- # no per-row filtering surface. Excludes --service / --module / --limit so
513
- # the surface is honest: those flags are REJECTED at parse time (clean
514
- # error envelope) rather than accepted-then-warned-as-no-op. Keeps
515
- # --index-dir / --format / --detail.
516
- def _core_parser() -> argparse.ArgumentParser:
517
- core = argparse.ArgumentParser(add_help=False)
518
- core.add_argument(
519
- "--index-dir",
520
- type=str,
521
- default=None,
522
- dest="index_dir",
523
- help="Index directory override (default: discovered from cwd).",
524
- )
525
- core.add_argument(
526
- "--format",
527
- choices=("text", "json"),
528
- default="text",
529
- help="Output format (default: text).",
530
- )
531
- core.add_argument(
532
- "--detail",
533
- choices=("brief", "normal", "full"),
534
- default="normal",
535
- help=(
536
- "Output detail level (default normal) — ORTHOGONAL to --format: both "
537
- "text and json honor it. brief = identity only (name @service); "
538
- "normal = +module/role/file/score; full = +signature/annotations/snippet."
539
- ),
540
- )
541
- return core
542
-
543
- status = subparsers.add_parser(
544
- "status",
545
- help="Print index freshness, ontology version, and counts.",
546
- parents=[_core_parser()],
547
- description=(
548
- "Index health and freshness. Reports ontology version, source root, "
549
- "built_at, parse_errors, edge counts, and the counts dictionary from "
550
- "GraphMeta. Exits 2 with an actionable envelope if the index is "
551
- "missing or stale. An aggregate view: --service / --module / --limit "
552
- "are NOT accepted (rejected at parse time)."
553
- ),
554
- )
555
- status.set_defaults(handler=_cmd_status, detail="full")
556
-
557
- # find subparser (PR-JRAG-1b)
558
- find = subparsers.add_parser(
559
- "find",
560
- help="Find nodes by query or filter.",
561
- parents=[_common_parser()],
562
- description=(
563
- "Find nodes by query or filter. Two modes:\n"
564
- " Query mode (positional <query>): search by name/FQN (symbols only); --fuzzy\n"
565
- " falls back exact -> prefix -> substring when the exact match is empty.\n"
566
- " Filter mode (no positional): apply structured filters (NodeFilter flags).\n"
567
- "Kind inference: domain flags (--http-method, --client-kind, --producer-kind) imply\n"
568
- "route/client/producer when --kind is omitted. Contradiction emits an error envelope.\n"
569
- "Query mode + non-symbol kind (explicit or inferred) errors: name/FQN lookup only\n"
570
- "searches symbols; drop the positional <query> and use filter mode for routes/clients/producers."
571
- ),
572
- )
573
- find.add_argument("query", nargs="?", default=None, help="Search query (name/FQN). Omit for filter mode.")
574
- find.add_argument(
575
- "--kind",
576
- choices=("symbol", "route", "client", "producer"),
577
- default=None,
578
- help="Node kind (omit for auto-inference from domain flags).",
579
- )
580
- find.add_argument("--role", type=_upper_snake, choices=_ROLE_CHOICES, default=None, help="Filter by role.")
581
- find.add_argument("--exclude-role", type=_upper_snake, choices=_ROLE_CHOICES, default=None, help="Exclude by role.")
582
- find.add_argument("--java-kind", type=_lower_snake, choices=_JAVA_KIND_CHOICES, default=None, help="Filter by Java symbol kind.")
583
- find.add_argument("--annotation", type=str, default=None, help="Filter by annotation.")
584
- find.add_argument("--capability", type=_upper_snake, choices=_CAPABILITY_CHOICES, default=None, help="Filter by capability.")
585
- find.add_argument("--framework", type=_lower_snake, choices=_FRAMEWORK_CHOICES, default=None, help="Filter by framework.")
586
- find.add_argument("--source-layer", type=str, default=None, help="Filter by source layer.")
587
- find.add_argument("--fqn-contains", type=str, default=None, help="Filter by FQN substring.")
588
- find.add_argument(
589
- "--fuzzy",
590
- action="store_true",
591
- help="Query mode: fall back from exact name/FQN to prefix then substring "
592
- "(case-sensitive) when the exact match is empty.",
593
- )
594
- find.add_argument("--http-method", type=str, default=None, help="Filter by HTTP method (route).")
595
- find.add_argument("--path-contains", type=str, default=None, help="Filter by path substring (route).")
596
- find.add_argument("--client-kind", type=str, default=None, help="Filter by client kind (client).")
597
- find.add_argument("--calls-service", type=str, default=None, help="Filter by target service (client).")
598
- find.add_argument("--calls-path-contains", type=str, default=None, help="Filter by target path substring (client).")
599
- find.add_argument("--producer-kind", type=str, default=None, help="Filter by producer kind (producer).")
600
- find.add_argument("--topic-contains", type=str, default=None, help="Filter by topic substring (producer).")
601
- find.add_argument(
602
- "--offset",
603
- type=int,
604
- default=0,
605
- help="Page offset (filter mode only; ignored in query mode).",
606
- )
607
- find.set_defaults(handler=_cmd_find, auto_scope=True)
608
-
609
- # inspect subparser (PR-JRAG-1b)
610
- inspect = subparsers.add_parser(
611
- "inspect",
612
- help="Inspect a node by query.",
613
- parents=[_common_parser()],
614
- description=(
615
- "Inspect a node by resolving a query (name/FQN) and returning its full details\n"
616
- "including edge_summary. Uses resolve_v2 internally; on ambiguous candidates,\n"
617
- "returns them (no auto-pick). On not_found, returns an error envelope."
618
- ),
619
- )
620
- inspect.add_argument("query", help="Search query (name/FQN).")
621
- inspect.add_argument(
622
- "--kind",
623
- choices=("symbol", "route", "client", "producer"),
624
- default=None,
625
- help="Hint for resolve (omitted for broad search).",
626
- )
627
- inspect.add_argument("--java-kind", type=_lower_snake, choices=_JAVA_KIND_CHOICES, default=None, help="Post-filter by Java symbol kind.")
628
- inspect.add_argument("--role", type=_upper_snake, choices=_ROLE_CHOICES, default=None, help="Post-filter by role.")
629
- inspect.add_argument("--fqn-contains", type=str, default=None, help="Post-filter by FQN substring.")
630
- inspect.set_defaults(handler=_cmd_inspect, detail="full")
631
-
632
- # http-routes subparser (PR-JRAG-2)
633
- http_routes = subparsers.add_parser(
634
- "http-routes",
635
- help="List HTTP routes.",
636
- parents=[_common_parser()],
637
- description=(
638
- "List HTTP routes by microservice, framework, path substring, or method. "
639
- "Returns route nodes (no resolve step). HTTP-server-route surface only — "
640
- "kafka topics live under `topics`."
641
- ),
642
- )
643
- http_routes.add_argument("--framework", type=_lower_snake, choices=_FRAMEWORK_CHOICES, default=None, help="Filter by framework.")
644
- http_routes.add_argument("--path-contains", type=str, default=None, help="Filter by path substring.")
645
- http_routes.add_argument("--method", type=str, default=None, help="Filter by HTTP method.")
646
- http_routes.set_defaults(handler=_cmd_routes, detail="full", auto_scope=True)
647
-
648
- # http-clients subparser (PR-JRAG-2)
649
- http_clients = subparsers.add_parser(
650
- "http-clients",
651
- help="List HTTP clients.",
652
- parents=[_common_parser()],
653
- description=(
654
- "List HTTP clients by microservice, client kind, target service, or path substring. "
655
- "Returns client nodes (no resolve step)."
656
- ),
657
- )
658
- http_clients.add_argument("--client-kind", type=str, default=None, help="Filter by client kind.")
659
- http_clients.add_argument("--calls-service", type=str, default=None, help="Filter by target service.")
660
- http_clients.add_argument("--path-contains", type=str, default=None, help="Filter by path substring.")
661
- http_clients.set_defaults(handler=_cmd_clients, detail="full", auto_scope=True)
662
-
663
- # producers subparser (PR-JRAG-2)
664
- producers = subparsers.add_parser(
665
- "producers",
666
- help="List async message producers.",
667
- parents=[_common_parser()],
668
- description=(
669
- "List async message producers by microservice, producer kind, or topic substring. "
670
- "Returns producer nodes (no resolve step)."
671
- ),
672
- )
673
- producers.add_argument("--producer-kind", type=str, default=None, help="Filter by producer kind.")
674
- producers.add_argument("--topic-contains", type=str, default=None, help="Filter by topic substring.")
675
- producers.set_defaults(handler=_cmd_producers, detail="full", auto_scope=True)
676
-
677
- # topics subparser (PR-JRAG-2)
678
- topics = subparsers.add_parser(
679
- "topics",
680
- help="List message topics (producer-grouped).",
681
- parents=[_common_parser()],
682
- description=(
683
- "List message topics grouped by producer. "
684
- "No :Topic node exists; this command groups producers by topic name. "
685
- "--consumer-in resolves consumers (listener methods) via EXPOSES edges to Route(topic)."
686
- ),
687
- )
688
- topics.add_argument("--topic-contains", type=str, default=None, help="Filter by topic substring.")
689
- topics.add_argument("--producer-in", type=str, default=None, help="Scope producers to this microservice.")
690
- topics.add_argument("--consumer-in", type=str, default=None, help="Show consumers from this microservice.")
691
- topics.set_defaults(handler=_cmd_topics, detail="full", auto_scope=True)
692
-
693
- # jobs subparser (PR-JRAG-2)
694
- jobs = subparsers.add_parser(
695
- "jobs",
696
- help="List scheduled tasks.",
697
- parents=[_common_parser()],
698
- description=(
699
- "List scheduled task symbols (capability=SCHEDULED_TASK). "
700
- "Returns Symbol nodes with the SCHEDULED_TASK capability."
701
- ),
702
- )
703
- jobs.set_defaults(handler=_cmd_jobs, detail="full", auto_scope=True)
704
-
705
- # listeners subparser (PR-JRAG-2)
706
- listeners = subparsers.add_parser(
707
- "listeners",
708
- help="List message listeners.",
709
- parents=[_common_parser()],
710
- description=(
711
- "List message listener symbols (capability=MESSAGE_LISTENER). "
712
- "Returns Symbol nodes with the MESSAGE_LISTENER capability."
713
- ),
714
- )
715
- listeners.add_argument("--topic-contains", type=str, default=None, help="Filter by topic substring (on producer member).")
716
- listeners.set_defaults(handler=_cmd_listeners, detail="full", auto_scope=True)
717
-
718
- # entities subparser (PR-JRAG-2)
719
- entities = subparsers.add_parser(
720
- "entities",
721
- help="List JPA entities.",
722
- parents=[_common_parser()],
723
- description=(
724
- "List JPA entity symbols (role=ENTITY). "
725
- "Returns Symbol nodes with the ENTITY role."
726
- ),
727
- )
728
- entities.set_defaults(handler=_cmd_entities, detail="full", auto_scope=True)
729
-
730
- # ---- Traversal commands (PR-JRAG-3a) ----
731
- # Shared resolve-disambiguation flags (PR-JRAG-1a contract: only --kind is a
732
- # true resolve input; the rest are client-side post-filters on resolve's
733
- # candidate set). Traversals are resolve-first; --offset is NOT registered
734
- # on any traversal subparser (none of the backends take offset).
735
- resolve_parent = argparse.ArgumentParser(add_help=False)
736
- resolve_parent.add_argument(
737
- "--kind",
738
- choices=("symbol", "route", "client", "producer"),
739
- default=None,
740
- help="Hint for resolve (omit for broad search).",
741
- )
742
- resolve_parent.add_argument("--java-kind", type=_lower_snake, choices=_JAVA_KIND_CHOICES, default=None, help="Post-filter by Java symbol kind.")
743
- resolve_parent.add_argument("--role", type=_upper_snake, choices=_ROLE_CHOICES, default=None, help="Post-filter by role.")
744
- resolve_parent.add_argument("--fqn-contains", type=str, default=None, help="Post-filter by FQN substring.")
745
-
746
- callers = subparsers.add_parser(
747
- "callers",
748
- help="Who calls this symbol or route?",
749
- parents=[_common_parser(), resolve_parent],
750
- description=(
751
- "Resolve <query> then traverse the call graph inbound (who calls me?). "
752
- "Symbol -> g.find_callers (CALLS edges, --service/--module pushed down). "
753
- "Route -> g.find_route_callers; route callers are cross-service by "
754
- "construction, so --service narrows WHICH route resolves (a resolve-time "
755
- "filter) rather than filtering the resulting callers. "
756
- "--include-external controls whether external (JDK/Spring/Lombok) callers "
757
- "are excluded (default: excluded)."
758
- ),
759
- )
760
- callers.add_argument("query", help="Symbol FQN/name (e.g. 'pkg.Svc#method(Arg)') or route path.")
761
- callers.add_argument("--depth", type=int, default=1, help="Call-graph depth (default 1).")
762
- callers.add_argument(
763
- "--min-confidence",
764
- type=float,
765
- default=0.0,
766
- dest="min_confidence",
767
- help="Minimum CALLS edge confidence in [0.0, 1.0].",
768
- )
769
- callers.add_argument(
770
- "--include-external",
771
- action="store_true",
772
- help="Include external (JDK/Spring/Lombok) callers/callees (default excluded).",
773
- )
774
- callers.set_defaults(handler=_cmd_callers, auto_scope=True)
775
-
776
- callees = subparsers.add_parser(
777
- "callees",
778
- help="What does this symbol call?",
779
- parents=[_common_parser(), resolve_parent],
780
- description=(
781
- "Resolve <query> (Symbol) then traverse the call graph outbound (what do I "
782
- "call?). Calls g.find_callees; --include-external is symmetric with callers."
783
- ),
784
- )
785
- callees.add_argument("query", help="Symbol FQN/name (e.g. 'pkg.Svc#method(Arg)').")
786
- callees.add_argument("--depth", type=int, default=1, help="Call-graph depth (default 1).")
787
- callees.add_argument(
788
- "--min-confidence",
789
- type=float,
790
- default=0.0,
791
- dest="min_confidence",
792
- help="Minimum CALLS edge confidence in [0.0, 1.0].",
793
- )
794
- callees.add_argument(
795
- "--include-external",
796
- action="store_true",
797
- help="Include external (JDK/Spring/Lombok) callees (default excluded).",
798
- )
799
- callees.set_defaults(handler=_cmd_callees, auto_scope=True)
800
-
801
- hierarchy = subparsers.add_parser(
802
- "hierarchy",
803
- help="Type hierarchy (parents and children).",
804
- parents=[_common_parser(), resolve_parent],
805
- description=(
806
- "Resolve <query> (type Symbol) then walk EXTENDS/IMPLEMENTS both directions: "
807
- "out = supertypes (parents), in = subtypes (children). No --service/--module "
808
- "push-down (structural edges)."
809
- ),
810
- )
811
- hierarchy.add_argument("query", help="Class/interface FQN or name.")
812
- hierarchy.set_defaults(handler=_cmd_hierarchy)
813
-
814
- implementations = subparsers.add_parser(
815
- "implementations",
816
- help="Classes implementing an interface.",
817
- parents=[_common_parser(), resolve_parent],
818
- description=(
819
- "Resolve <query> (interface Symbol) then call g.find_implementors. "
820
- "--service/--module pushed down; --capability pushed down to the backend "
821
- "(find_implementors accepts a capability filter)."
822
- ),
823
- )
824
- implementations.add_argument("query", help="Interface FQN or name.")
825
- implementations.add_argument("--capability", type=_upper_snake, choices=_CAPABILITY_CHOICES, default=None, help="Filter implementors by capability.")
826
- implementations.set_defaults(handler=_cmd_implementations, auto_scope=True)
827
-
828
- subclasses = subparsers.add_parser(
829
- "subclasses",
830
- help="Classes extending a type.",
831
- parents=[_common_parser(), resolve_parent],
832
- description=(
833
- "Resolve <query> (class Symbol) then call g.find_subclasses (EXTENDS inbound). "
834
- "--service/--module pushed down."
835
- ),
836
- )
837
- subclasses.add_argument("query", help="Class FQN or name.")
838
- subclasses.set_defaults(handler=_cmd_subclasses, auto_scope=True)
839
-
840
- overrides = subparsers.add_parser(
841
- "overrides",
842
- help="Methods this method overrides (dispatch UP to declaration).",
843
- parents=[_common_parser(), resolve_parent],
844
- description=(
845
- "Resolve <query> (method Symbol) then neighbors_v2([id], 'out', ['OVERRIDES']). "
846
- "The stored OVERRIDES edge runs overrider -> declaration (subtype method -> "
847
- "supertype declared method), so 'out' dispatches UP the hierarchy."
848
- ),
849
- )
850
- overrides.add_argument("query", help="Method FQN or name (e.g. 'pkg.Impl#method(Arg)').")
851
- overrides.set_defaults(handler=_cmd_overrides)
852
-
853
- overridden_by = subparsers.add_parser(
854
- "overridden-by",
855
- help="Methods overriding this one (dispatch DOWN to overriders).",
856
- parents=[_common_parser(), resolve_parent],
857
- description=(
858
- "Resolve <query> (method Symbol) then neighbors_v2([id], 'in', ['OVERRIDES']) "
859
- "(= virtual OVERRIDDEN_BY out). 'in' traverses the stored OVERRIDES edge "
860
- "backward, dispatching DOWN from declaration to overriders."
861
- ),
862
- )
863
- overridden_by.add_argument("query", help="Method FQN or name (e.g. 'pkg.Iface#method(Arg)').")
864
- overridden_by.set_defaults(handler=_cmd_overridden_by)
865
-
866
- dependents = subparsers.add_parser(
867
- "dependents",
868
- help="Who injects this type?",
869
- parents=[_common_parser(), resolve_parent],
870
- description=(
871
- "Resolve <query> (type Symbol) then call g.find_injectors (INJECTS inbound: "
872
- "classes that inject this type). --service/--module pushed down."
873
- ),
874
- )
875
- dependents.add_argument("query", help="Type FQN or name.")
876
- dependents.set_defaults(handler=_cmd_dependents, auto_scope=True)
877
-
878
- impact = subparsers.add_parser(
879
- "impact",
880
- help="Fleet-wide blast radius (INJECTS/IMPLEMENTS/EXTENDS reverse closure).",
881
- parents=[_common_parser(), resolve_parent],
882
- description=(
883
- "Resolve <query> then call g.impact_analysis (reverse closure over "
884
- "INJECTS+IMPLEMENTS+EXTENDS: who breaks if this changes). --service is a "
885
- "CLIENT-SIDE post-filter (impact_analysis has no microservice param); "
886
- "surfaced as a warnings[] entry."
887
- ),
888
- )
889
- impact.add_argument("query", help="Symbol FQN or name.")
890
- impact.add_argument("--depth", type=int, default=2, help="Closure depth (default 2).")
891
- impact.set_defaults(handler=_cmd_impact, auto_scope=True)
892
-
893
- decompose = subparsers.add_parser(
894
- "decompose",
895
- help="Role-waterfall flow from an entrypoint.",
896
- parents=[_common_parser(), resolve_parent],
897
- description=(
898
- "Resolve <query> (entrypoint Symbol) then call g.trace_flow. Walks "
899
- "CONTROLLER -> SERVICE/COMPONENT -> CLIENT/REPOSITORY/MAPPER stages via "
900
- "INJECTS+EXTENDS+IMPLEMENTS (optionally + CALLS hops). --service/--module "
901
- "pushed down; --depth clamped to 1..3."
902
- ),
903
- )
904
- decompose.add_argument("query", help="Entrypoint symbol FQN or name.")
905
- decompose.add_argument("--depth", type=int, default=2, help="Neighbour hop count per stage (clamped 1..3, default 2).")
906
- decompose.add_argument(
907
- "--follow-calls",
908
- action=argparse.BooleanOptionalAction,
909
- default=True,
910
- dest="follow_calls",
911
- help=(
912
- "Top up each stage with DECLARES+CALLS type-to-type hops when the "
913
- "structural INJECTS/EXTENDS/IMPLEMENTS pass under-fills it (default: "
914
- "on). --no-follow-calls restricts the waterfall to structural edges."
915
- ),
916
- )
917
- decompose.add_argument(
918
- "--per-stage-limit",
919
- type=int,
920
- default=20,
921
- dest="per_stage_limit",
922
- help="Cap on symbols per stage (stage_limit, default 20). Not a stage-count knob.",
923
- )
924
- decompose.add_argument(
925
- "--min-confidence",
926
- type=float,
927
- default=0.0,
928
- dest="min_confidence",
929
- help="Min CALLS confidence when --follow-calls is on.",
930
- )
931
- decompose.add_argument(
932
- "--include-external",
933
- action="store_true",
934
- help="Include external types reached via the CALLS hop (default excluded).",
935
- )
936
- decompose.set_defaults(handler=_cmd_decompose, auto_scope=True)
937
-
938
- flow = subparsers.add_parser(
939
- "flow",
940
- help="Request flow through a route (inbound callers + outbound CALLS hops).",
941
- parents=[_common_parser()],
942
- description=(
943
- "Resolve <query> to a Route then call g.trace_request_flow. Inbound = "
944
- "cross-service HTTP/async callers (Client/Producer two-hop); outbound = "
945
- "CALLS hops from the route handler. Intra-service is an INDEX-TIME data "
946
- "property: CALLS edges are intra-codebase by construction, and the query "
947
- "carries no microservice predicate, so the result reflects whatever the "
948
- "fixture indexed (no query-time constraint). --depth clamped to 1..8."
949
- ),
950
- )
951
- flow.add_argument(
952
- "query",
953
- help=(
954
- "Route path (e.g. '/chat/assign') or Kafka topic name (e.g. "
955
- "'banking.chat.compliance.review'). Resolved with hint_kind=route; "
956
- "kafka_topic Routes match on topic."
957
- ),
958
- )
959
- # Primary flag is --depth (consistent with callers/callees/impact/decompose).
960
- # --max-hops is kept as a hidden back-compat alias (same dest).
961
- flow.add_argument(
962
- "--depth", type=int, default=5, dest="depth",
963
- help="Max CALLS hops (clamped 1..8, default 5).",
964
- )
965
- flow.add_argument(
966
- "--max-hops", type=int, dest="depth",
967
- default=argparse.SUPPRESS, help=argparse.SUPPRESS,
968
- )
969
- flow.set_defaults(handler=_cmd_flow)
970
-
971
- # ---- Compose traversals + file inspection (PR-JRAG-3b) ----
972
- # callees (Client/Producer variant) re-uses the existing _cmd_callees
973
- # handler from PR-JRAG-3a; the help text below updates to advertise the
974
- # Client/Producer dispatch (Symbol path is unchanged). --kind picks the
975
- # resolve hint; the handler dispatches on the resolved node's kind.
976
- #
977
- # (The callees subparser was registered above with the Symbol-only help
978
- # text; we patch its description here to advertise the new variant without
979
- # duplicating the parser construction.)
980
- callees.epilog = (
981
- "Symbol root lists the methods this code calls (CALLS out). Client and\n"
982
- "Producer roots follow their call edge to the Route they target:\n"
983
- " Client root -> the :Route it requests (HTTP_CALLS out)\n"
984
- " Producer root -> the :Route (kafka_topic) it publishes to (ASYNC_CALLS out)\n"
985
- "--include-external applies to the Symbol path; Client/Producer edges are\n"
986
- "structural (Client/Producer -> :Route) and have no external-exclusion analog."
987
- )
988
-
989
- dependencies = subparsers.add_parser(
990
- "dependencies",
991
- help="Types this Symbol injects (INJECTS out).",
992
- parents=[_common_parser(), resolve_parent],
993
- description=(
994
- "Resolve <query> (type Symbol) then neighbors_v2([id], 'out', ['INJECTS']) "
995
- "= the types this class injects (its direct dependencies). INJECTS is "
996
- "Symbol -> Symbol (declaring type -> injected type), so 'out' traverses "
997
- "from the injector to its dependencies. --service/--module are NOT "
998
- "applied (INJECTS is a structural edge with no microservice predicate); "
999
- "they surface as warnings[]. --include-external is accepted for surface "
1000
- "symmetry with callers/callees but is a warned no-op here (INJECTS has "
1001
- "no external-exclusion analog at the neighbors_v2 layer)."
1002
- ),
1003
- )
1004
- dependencies.add_argument("query", help="Symbol FQN or name (e.g. 'pkg.Svc').")
1005
- dependencies.add_argument(
1006
- "--include-external",
1007
- action="store_true",
1008
- help="Accepted for symmetry; warned no-op on dependencies (INJECTS is structural).",
1009
- )
1010
- dependencies.set_defaults(handler=_cmd_dependencies)
1011
-
1012
- connection = subparsers.add_parser(
1013
- "connection",
1014
- help="Cross-service connections for a microservice (inbound/outbound).",
1015
- parents=[_common_parser()],
1016
- description=(
1017
- "RESOLVE-FIRST EXCEPTION: the first positional is a microservice NAME "
1018
- "(e.g. 'chat-core'), NOT a query — it is passed literally to list_clients/"
1019
- "list_producers/find_route_callers; resolve_v2 is NEVER run on it.\n\n"
1020
- "Direction (default --both): clients/producers in OTHER services "
1021
- "targeting this service. HTTP via list_clients(target_service=<svc>) + "
1022
- "async via find_route_callers on this service's topic Routes.\n"
1023
- "--outbound: clients/producers IN this service. HTTP via "
1024
- "list_clients(microservice=<svc>) + producers via "
1025
- "list_producers(microservice=<svc>).\n"
1026
- "--both: render both inbound and outbound sections.\n\n"
1027
- "--http-method and --calls-service filter HTTP callers only (clients "
1028
- "have a target_service; producers do not). Producers are KEPT under "
1029
- "--calls-service so the async channel stays visible; a warnings[] entry "
1030
- "is emitted when --calls-service bypasses producers."
1031
- ),
1032
- )
1033
- connection.add_argument(
1034
- "microservice",
1035
- help="Microservice NAME (literal — NOT resolved as a query).",
1036
- )
1037
- connection.add_argument(
1038
- "--inbound",
1039
- dest="direction",
1040
- action="store_const",
1041
- const="inbound",
1042
- default=None,
1043
- help="Show only inbound connections (default is --both).",
1044
- )
1045
- connection.add_argument(
1046
- "--outbound",
1047
- dest="direction",
1048
- action="store_const",
1049
- const="outbound",
1050
- help="Show only outbound connections (default is --both).",
1051
- )
1052
- connection.add_argument(
1053
- "--both",
1054
- dest="direction",
1055
- action="store_const",
1056
- const="both",
1057
- help="Show both inbound and outbound sections (this is the default).",
1058
- )
1059
- connection.add_argument(
1060
- "--http-method",
1061
- type=str,
1062
- default=None,
1063
- help="Filter HTTP callers by method (e.g. POST). Applies to clients only.",
1064
- )
1065
- connection.add_argument(
1066
- "--calls-service",
1067
- type=str,
1068
- default=None,
1069
- help=(
1070
- "Narrow to edges involving this other service. Outbound: clients with "
1071
- "target_service == <svc> (producers kept with a warning — no service "
1072
- "target on ASYNC channels). Inbound: callers from microservice == <svc>."
1073
- ),
1074
- )
1075
- connection.set_defaults(handler=_cmd_connection)
1076
-
1077
- outline = subparsers.add_parser(
1078
- "outline",
1079
- help="List symbols declared in a file.",
1080
- parents=[_common_parser()],
1081
- description=(
1082
- "List all Symbol nodes whose declared location is in <file>. Calls "
1083
- "find_symbols_in_file_range(graph, filename=<file>, start_line=1, "
1084
- "end_line=2**31-1) — the start_line=1 is required (the backend returns "
1085
- "[] for start_line<1). --limit caps the entry count (the file's "
1086
- "symbol table is otherwise unbounded); truncated is set when more "
1087
- "entries exist. --offset is rejected (the backend takes no offset)."
1088
- ),
1089
- )
1090
- outline.add_argument("file", help="File path as stored in the graph (POSIX-relative to source root).")
1091
- outline.set_defaults(handler=_cmd_outline)
1092
-
1093
- imports = subparsers.add_parser(
1094
- "imports",
1095
- help="List imports declared in a file (tree-sitter parse + resolve_v2).",
1096
- parents=[_common_parser()],
1097
- description=(
1098
- "Parse <file> with tree-sitter via the language backend "
1099
- "(backend_for(...).parse — parse_java for .java, parse_kotlin for "
1100
- ".kt), walk its import nodes, and resolve each imported FQN via resolve_v2 "
1101
- "against the graph. Returns one node per import: resolved graph Symbol "
1102
- "when resolve_v2 hits, or an unresolved placeholder carrying the raw FQN "
1103
- "otherwise. Static and wildcard imports are included (marked in the row)."
1104
- " --offset is rejected."
1105
- ),
1106
- )
1107
- imports.add_argument("file", help="File path (POSIX-relative to source root, or absolute).")
1108
- imports.set_defaults(handler=_cmd_imports)
1109
-
1110
- # ---- Orientation commands (PR-JRAG-4) ----
1111
- microservices = subparsers.add_parser(
1112
- "microservices",
1113
- help="List microservices with resolved type counts.",
1114
- parents=[_core_parser()],
1115
- description=(
1116
- "List every microservice with its resolved type-symbol count. "
1117
- "Calls g.microservice_counts(). Renders as a counts listing. "
1118
- "An aggregate view: --service / --module / --limit are NOT accepted "
1119
- "(rejected at parse time)."
1120
- ),
1121
- )
1122
- microservices.set_defaults(handler=_cmd_microservices, detail="full")
1123
-
1124
- map_cmd = subparsers.add_parser(
1125
- "map",
1126
- help="Symbol counts per kind, grouped by service or module.",
1127
- parents=[_common_parser()],
1128
- description=(
1129
- "Count resolved type Symbols (class/interface/enum/record/annotation) "
1130
- "grouped by microservice or module. --by {microservice,module} selects "
1131
- "the grouping axis (default microservice); --service / --module narrow "
1132
- "the count to one service or module (filters, independent of --by)."
1133
- ),
1134
- )
1135
- map_cmd.add_argument(
1136
- "--by",
1137
- dest="by",
1138
- choices=("microservice", "module"),
1139
- default=None,
1140
- help="Grouping axis: microservice (default) or module. When --module is "
1141
- "set without --by, the axis defaults to module (the user's focus is the "
1142
- "module axis); pass --by microservice to keep microservice grouping.",
1143
- )
1144
- map_cmd.set_defaults(handler=_cmd_map, detail="full")
1145
-
1146
- conventions = subparsers.add_parser(
1147
- "conventions",
1148
- help="Dominant roles + framework tallies.",
1149
- parents=[_common_parser()],
1150
- description=(
1151
- "Report the dominant roles among resolved Symbols and the route framework "
1152
- "distribution. --service narrows the role tally to one microservice."
1153
- ),
1154
- )
1155
- conventions.set_defaults(handler=_cmd_conventions, detail="full")
1156
-
1157
- overview = subparsers.add_parser(
1158
- "overview",
1159
- help="Bundle for a microservice, route, or topic.",
1160
- parents=[_common_parser()],
1161
- description=(
1162
- "Dispatch on the positional <subject>:\n"
1163
- " Route path (starts with '/') -> trace_request_flow (same as `flow`).\n"
1164
- " Microservice name -> routes + clients + producers bundle.\n"
1165
- " Topic string -> producers + consumers for the topic.\n"
1166
- "--as {microservice,route,topic} overrides auto-detection.\n"
1167
- "Auto-detection: starts with '/' -> route; matches a known microservice -> "
1168
- "microservice; otherwise -> topic."
1169
- ),
1170
- )
1171
- overview.add_argument(
1172
- "subject",
1173
- nargs="?",
1174
- default=None,
1175
- help="Microservice name, route path (starts with '/'), or topic string.",
1176
- )
1177
- overview.add_argument(
1178
- "--as",
1179
- dest="as_type",
1180
- choices=("microservice", "route", "topic"),
1181
- default=None,
1182
- help="Override auto-detection of subject type.",
1183
- )
1184
- overview.set_defaults(handler=_cmd_overview, detail="full")
1185
-
1186
- # ---- Search command (PR-JRAG-4) ----
1187
- search = subparsers.add_parser(
1188
- "search",
1189
- help="Semantic search over Lance tables.",
1190
- parents=[_common_parser()],
1191
- description=(
1192
- "Semantic search via search_v2 over the Lance index (java/sql/yaml tables). "
1193
- "--table all searches all three. --hybrid enables vector+keyword hybrid. "
1194
- "--offset paginates. --path-contains narrows by file path substring. "
1195
- "Filters (NodeFilter flags) narrow results.\n\n"
1196
- "--fuzzy is accepted as a no-op (search is inherently semantic; "
1197
- "--fuzzy is implicit). It is kept registered so callers that pass "
1198
- "it don't hit an argparse error, and is silently ignored."
1199
- ),
1200
- )
1201
- search.add_argument("query", help="Natural-language search query.")
1202
- search.add_argument(
1203
- "--table",
1204
- choices=("java", "sql", "yaml", "all"),
1205
- default="java",
1206
- help="Lance table to search (default: java; all = java+sql+yaml).",
1207
- )
1208
- search.add_argument(
1209
- "--hybrid", action="store_true", help="Enable vector+keyword hybrid search."
1210
- )
1211
- search.add_argument(
1212
- "--explain", action="store_true", help="Show score breakdown per hit."
1213
- )
1214
- search.add_argument(
1215
- "--path-contains", type=str, default=None, dest="path_contains",
1216
- help="Narrow to chunks whose filename contains this substring.",
1217
- )
1218
- search.add_argument(
1219
- "--fuzzy", action="store_true",
1220
- help="Accepted as a no-op (search is always semantic; --fuzzy is implicit).",
1221
- )
1222
- search.add_argument(
1223
- "--min-score", type=float, default=0.0, dest="min_score",
1224
- help=(
1225
- "Drop hits with a relevance score below this floor. Default 0.0 drops "
1226
- "negative-score noise (chunks farther than orthogonal to the query); "
1227
- "raise to tighten precision."
1228
- ),
1229
- )
1230
- # NodeFilter flags (same set as `find` filter mode, minus the query-only ones).
1231
- search.add_argument("--role", type=_upper_snake, choices=_ROLE_CHOICES, default=None, help="Filter by role.")
1232
- search.add_argument("--exclude-role", type=_upper_snake, choices=_ROLE_CHOICES, default=None, dest="exclude_role", help="Exclude by role.")
1233
- search.add_argument("--java-kind", type=_lower_snake, choices=_JAVA_KIND_CHOICES, default=None, dest="java_kind", help="Filter by Java symbol kind.")
1234
- search.add_argument("--annotation", type=str, default=None, help="Filter by annotation.")
1235
- search.add_argument("--capability", type=_upper_snake, choices=_CAPABILITY_CHOICES, default=None, help="Filter by capability.")
1236
- search.add_argument("--framework", type=_lower_snake, choices=_FRAMEWORK_CHOICES, default=None, help="Filter by framework.")
1237
- search.add_argument("--fqn-contains", type=str, default=None, dest="fqn_contains", help="Filter by FQN substring.")
1238
- search.add_argument(
1239
- "--offset",
1240
- type=int,
1241
- default=0,
1242
- help="Page offset (passed to search_v2; paginated via +1-fetch).",
1243
- )
1244
- search.add_argument(
1245
- "--chunks",
1246
- action="store_true",
1247
- help="Show every chunk (default collapses to one row per symbol/type).",
1248
- )
1249
- search.set_defaults(handler=_cmd_search, auto_scope=True)
1250
-
1251
- # ---- vocab-index subparser (PR-ABS-1) ----
1252
- vocab_index = subparsers.add_parser(
1253
- "vocab-index",
1254
- help="Rebuild the vocabulary index (absence diagnosis).",
1255
- parents=[_core_parser()],
1256
- description=(
1257
- "Rebuild the vocabulary index sidecar from the current Ladybug graph. "
1258
- "The index is a search-optimized projection of Symbol nodes used for "
1259
- "did-you-mean suggestions and external membership checks in absence "
1260
- "diagnosis. Printed on success: symbol count and sidecar path."
1261
- ),
1262
- )
1263
- vocab_index.set_defaults(handler=_cmd_vocab_index, detail="full")
1264
-
1265
- # ---- watch subparser (jrag watch foreground/detach/stop/status) ----
1266
- # Uses _core_parser (no auto-scope): watch is a long-lived daemon over a
1267
- # whole index, not a per-query command, so --service/--module/--limit would
1268
- # be dishonest on this surface. Keeps --index-dir/--format/--detail so the
1269
- # daemon anchors and so --status output respects --format.
1270
- watch = subparsers.add_parser(
1271
- "watch",
1272
- help="keep the index fresh and serve warm queries while running",
1273
- parents=[_core_parser()],
1274
- description=(
1275
- "Long-lived daemon: watches the source tree for changes (reindexing "
1276
- "vectors/graph on a debounce) and serves the read commands (search/find/"
1277
- "inspect/callers/callees/flow) over a warm Unix socket so queries skip the "
1278
- "cold-start model/graph load.\n\n"
1279
- "Lifecycle:\n"
1280
- " jrag watch run in the foreground (Ctrl+C / SIGTERM to stop)\n"
1281
- " jrag watch --detach start as a background daemon and return\n"
1282
- " jrag watch --status report up/down + pid + socket + last reindex\n"
1283
- " jrag watch --stop SIGTERM a running daemon (SIGKILL after 5s)\n"
1284
- "Only one daemon may run per index (project lock). --status/--stop do NOT "
1285
- "acquire the lock."
1286
- ),
1287
- )
1288
- watch.add_argument(
1289
- "--detach",
1290
- action="store_true",
1291
- help="Start the daemon as a detached background process and return.",
1292
- )
1293
- watch.add_argument(
1294
- "--stop",
1295
- action="store_true",
1296
- help="Stop a running daemon (SIGTERM; SIGKILL after 5s).",
1297
- )
1298
- watch.add_argument(
1299
- "--status",
1300
- action="store_true",
1301
- help="Print whether the daemon is up or down and exit.",
1302
- )
1303
- watch.add_argument(
1304
- "--debounce-ms",
1305
- type=int,
1306
- default=None,
1307
- dest="debounce_ms",
1308
- help="Reindex debounce window in ms (overrides YAML `watch:debounce_ms`).",
1309
- )
1310
- watch.add_argument(
1311
- "--backend",
1312
- choices=("auto", "watchdog", "polling"),
1313
- default=None,
1314
- help="File-watch backend (overrides YAML `watch:backend`).",
1315
- )
1316
- watch.set_defaults(handler=_cmd_watch)
1317
-
1318
- return parser
1319
-
1320
-
1321
- def _resolve_cfg(args: argparse.Namespace): # type: ignore[no-untyped-def]
1322
- """Resolve operator config (reuses the operator's cocoindex-free resolver).
1323
-
1324
- Mirrors ``java_codebase_rag.cli._resolved_from_ns``: pass ``source_root=None``
1325
- so ``resolve_operator_config`` honors ``JAVA_CODEBASE_RAG_SOURCE_ROOT`` first,
1326
- then a YAML ``source_root`` field, then walks up from cwd to find a project
1327
- root. Passing a discovered root explicitly here would OVERRIDE a set env var
1328
- whenever any ancestor dir has a ``.java-codebase-rag`` marker — silently
1329
- ignoring the documented subprocess source-root mechanism that
1330
- ``pipeline.subprocess_env`` sets for the cocoindex child (and that operators
1331
- set directly).
1332
-
1333
- When the anchor is an index dir with no YAML beside it, resolution follows
1334
- that index's ``config_source`` pointer (see ``config._effective_config_dir``)
1335
- so a config living in a sibling dir is still found from inside a microservice.
1336
- Applies CLI ``--index-dir`` if given and calls ``apply_to_os_environ`` so
1337
- downstream modules see a consistent env (critically SBERT_MODEL for ``jrag
1338
- search``).
1339
- """
1340
- from java_codebase_rag.config import resolve_operator_config
1341
-
1342
- cfg = resolve_operator_config(
1343
- source_root=None,
1344
- cli_index_dir=getattr(args, "index_dir", None),
1345
- # ``jrag watch`` CLI overrides for the watch block (absent / None for
1346
- # every other subcommand via getattr default; resolve_operator_config
1347
- # treats ``None`` as "not provided" so non-watch commands are unaffected).
1348
- cli_watch_debounce_ms=getattr(args, "debounce_ms", None),
1349
- cli_watch_backend=getattr(args, "backend", None),
1350
- )
1351
- cfg.apply_to_os_environ()
1352
- return cfg
1353
-
1354
-
1355
- def _load_graph(cfg): # type: ignore[no-untyped-def]
1356
- """Load the LadybugGraph with actionable error envelopes.
1357
-
1358
- * missing index -> ``_IndexNotFound`` (caught in ``main`` -> envelope with
1359
- a ``jrag init --source-root <root>`` remediation).
1360
- * ontology-mismatch (``RuntimeError`` from ``LadybugGraph.get``) ->
1361
- ``_IndexStale`` (caught in ``main`` -> envelope with a rebuild hint).
1362
- """
1363
- from java_codebase_rag.graph.ladybug_queries import LadybugGraph
1364
-
1365
- ladybug_path = str(cfg.ladybug_path)
1366
- if not LadybugGraph.exists(ladybug_path):
1367
- raise _IndexNotFound(
1368
- f"No index at {cfg.ladybug_path}. "
1369
- "Run: jrag init --source-root <root>"
1370
- )
1371
- try:
1372
- return LadybugGraph.get(ladybug_path)
1373
- except RuntimeError as exc:
1374
- raise _IndexStale(str(exc)) from exc
1375
-
1376
-
1377
- def _cmd_vocab_index(args: argparse.Namespace) -> int:
1378
- """Rebuild the vocabulary index sidecar from the Ladybug graph."""
1379
- from java_codebase_rag.ast.ast_java import ONTOLOGY_VERSION
1380
- from java_codebase_rag.absence.absence_vocab import VocabularyIndex, VOCAB_INDEX_FILENAME
1381
-
1382
- cfg = _resolve_cfg(args)
1383
- try:
1384
- graph = _load_graph(cfg)
1385
- except (_IndexNotFound, _IndexStale) as exc:
1386
- print(f"[error] {exc}", file=sys.stderr)
1387
- return 2
1388
-
1389
- # Build vocabulary index
1390
- try:
1391
- index = VocabularyIndex.build(graph, q=cfg.absence_ngram_q)
1392
- except Exception as e:
1393
- print(f"[error] Vocabulary index build failed: {e}", file=sys.stderr)
1394
- return 1
1395
-
1396
- # Save to sidecar
1397
- sidecar_path = cfg.ladybug_path.parent / VOCAB_INDEX_FILENAME
1398
- try:
1399
- index.save(sidecar_path, ontology_version=ONTOLOGY_VERSION)
1400
- except Exception as e:
1401
- print(f"[error] Failed to save vocabulary index: {e}", file=sys.stderr)
1402
- return 1
1403
-
1404
- # Print success message (simple format for admin command)
1405
- print(f"Vocabulary index rebuilt successfully:")
1406
- print(f" Symbol count: {index.symbol_count}")
1407
- print(f" Sidecar path: {sidecar_path}")
1408
- return 0
1409
-
1410
-
1411
- # ---------------------------------------------------------------------------
1412
- # jrag watch — long-lived daemon lifecycle (foreground / --detach / --stop / --status)
1413
- #
1414
- # ``--status``/``--stop`` are OUT-OF-PROCESS verbs: they read the lock holder
1415
- # (``ProjectLock.read_holder``) and never acquire the lock themselves. Only the
1416
- # running daemon (foreground or detached) holds the lock.
1417
- # ---------------------------------------------------------------------------
1418
-
1419
-
1420
- def _watch_child_argv(extra_args: list[str]) -> list[str]:
1421
- """Build the argv for the detached ``jrag watch`` child process.
1422
-
1423
- Invokes the daemon via ``python -m java_codebase_rag.jrag`` (NOT the
1424
- module's file path): running ``python src/.../jrag.py`` directly would put
1425
- the package directory on ``sys.path[0]`` and shadow the stdlib ``ast``
1426
- module with the project's ``java_codebase_rag.ast`` package (breaking
1427
- ``inspect``). ``-m`` runs the module as ``__main__`` within its package
1428
- context, so stdlib imports resolve correctly. A separate function (rather
1429
- than inline) so a test can swap in a stub child.
1430
- """
1431
- return [sys.executable, "-m", "java_codebase_rag.jrag", "watch"] + list(extra_args)
1432
-
1433
-
1434
- def _watch_passthrough_args(args: argparse.Namespace) -> list[str]:
1435
- """Reconstruct the watch flags to pass through to a detached child.
1436
-
1437
- Only re-emits the flags that influence the daemon's behavior; --index-dir is
1438
- included so the child anchors on the same index without re-discovering it.
1439
- """
1440
- out: list[str] = []
1441
- if getattr(args, "index_dir", None):
1442
- out += ["--index-dir", str(args.index_dir)]
1443
- if getattr(args, "debounce_ms", None) is not None:
1444
- out += ["--debounce-ms", str(args.debounce_ms)]
1445
- if getattr(args, "backend", None) is not None:
1446
- out += ["--backend", str(args.backend)]
1447
- return out
1448
-
1449
-
1450
- def _cmd_watch_status(cfg) -> int:
1451
- """``jrag watch --status``: print up/down + pid + socket + last reindex.
1452
-
1453
- Does NOT acquire the lock. Returns 0 if a daemon is alive, 1 otherwise.
1454
- """
1455
- from java_codebase_rag.watch import paths
1456
- from java_codebase_rag.watch.client import is_daemon_alive
1457
- from java_codebase_rag.watch.lock import ProjectLock
1458
-
1459
- sock = paths.socket_path(cfg.index_dir)
1460
- alive = is_daemon_alive(cfg.index_dir)
1461
- pid = ProjectLock.read_holder(cfg.index_dir)
1462
- state = _read_state_file(cfg.index_dir)
1463
- if alive:
1464
- print(f"jrag watch: up (pid {pid}, socket {sock})")
1465
- if state:
1466
- if state.get("mode") == "lexical":
1467
- print(" mode: lexical (graph-only)")
1468
- kind = state.get("last_reindex_kind")
1469
- at = state.get("last_reindex_at")
1470
- count = state.get("reindex_count", 0)
1471
- if kind and at:
1472
- when = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(at))
1473
- print(f" last reindex: {kind} at {when} (total {count})")
1474
- else:
1475
- print(f" last reindex: none (total {count})")
1476
- return 0
1477
- print(f"jrag watch: down (no daemon at {sock})")
1478
- return 1
1479
-
1480
-
1481
- def _cmd_watch_stop(cfg) -> int:
1482
- """``jrag watch --stop``: SIGTERM the daemon, SIGKILL after 5s if needed.
1483
-
1484
- Polls for socket removal (the daemon's own shutdown unlinks it). Always
1485
- cleans a leftover socket/state so a fresh start isn't blocked by a corpse.
1486
- Returns 0 if a daemon was stopped, 1 if none was running.
1487
- """
1488
- from java_codebase_rag.watch import paths
1489
- from java_codebase_rag.watch.lock import ProjectLock
1490
-
1491
- sock = paths.socket_path(cfg.index_dir)
1492
- state_path = paths.state_path(cfg.index_dir)
1493
- pid = ProjectLock.read_holder(cfg.index_dir)
1494
- if pid is None:
1495
- print("jrag watch: not running")
1496
- _watch_unlink(sock)
1497
- _watch_unlink(state_path)
1498
- return 1
1499
-
1500
- _watch_signal(pid, signal.SIGTERM)
1501
- # Poll for the socket's removal (the daemon unlinks it on clean shutdown).
1502
- deadline = time.monotonic() + _WATCH_STOP_TIMEOUT_S
1503
- while time.monotonic() < deadline:
1504
- if not sock.exists():
1505
- break
1506
- if not _watch_pid_alive(pid):
1507
- break
1508
- time.sleep(0.05)
1509
- # If still alive after the timeout, escalate to SIGKILL.
1510
- if _watch_pid_alive(pid):
1511
- _watch_signal(pid, signal.SIGKILL)
1512
- _watch_unlink(sock)
1513
- _watch_unlink(state_path)
1514
- print(f"jrag watch: stopped (pid {pid})")
1515
- return 0
1516
-
1517
-
1518
- def _cmd_watch_detach(args: argparse.Namespace, cfg) -> int:
1519
- """``jrag watch --detach``: spawn the daemon detached and wait until it serves.
1520
-
1521
- ``start_new_session=True`` detaches the child from the controlling terminal
1522
- (setsid); stdio is redirected to a per-index log under ``paths.runtime_dir``
1523
- so the parent can return. Waits until ``is_daemon_alive`` (socket bound AND a
1524
- live holder pid) or a timeout, then prints the socket path + pid. Returns 0
1525
- on success, 2 on timeout / child exit.
1526
- """
1527
- import subprocess
1528
-
1529
- from java_codebase_rag.watch import paths
1530
- from java_codebase_rag.watch.client import is_daemon_alive
1531
- from java_codebase_rag.watch.lock import ProjectLock
1532
-
1533
- child_argv = _watch_child_argv(_watch_passthrough_args(args))
1534
- log_path = paths.runtime_dir() / f"jrag-watch-{paths.project_key(cfg.index_dir)}.log"
1535
- try:
1536
- log_fh = open(log_path, "ab")
1537
- except OSError:
1538
- log_fh = None
1539
- try:
1540
- proc = subprocess.Popen(
1541
- child_argv,
1542
- stdin=subprocess.DEVNULL,
1543
- stdout=log_fh,
1544
- stderr=log_fh,
1545
- start_new_session=True, # setsid: detach from the controlling terminal
1546
- close_fds=True,
1547
- )
1548
- finally:
1549
- if log_fh is not None:
1550
- log_fh.close()
1551
-
1552
- deadline = time.monotonic() + _WATCH_DETACH_TIMEOUT_S
1553
- child_exited = False
1554
- while time.monotonic() < deadline:
1555
- if is_daemon_alive(cfg.index_dir):
1556
- break
1557
- # Fail fast: a child that crashes on startup (model-load/import failure)
1558
- # should not make the parent wait the whole timeout. proc.poll() is None
1559
- # while the child lives; a non-None return code means it has exited.
1560
- if proc.poll() is not None:
1561
- child_exited = True
1562
- break
1563
- time.sleep(0.1)
1564
- if is_daemon_alive(cfg.index_dir):
1565
- pid = ProjectLock.read_holder(cfg.index_dir)
1566
- print(
1567
- f"jrag watch: detached (pid {pid}, socket "
1568
- f"{paths.socket_path(cfg.index_dir)}, log {log_path})"
1569
- )
1570
- return 0
1571
- if child_exited:
1572
- print(
1573
- f"jrag watch: child exited before serving (see {log_path})",
1574
- file=sys.stderr,
1575
- )
1576
- else:
1577
- print(
1578
- f"jrag watch: failed to start within {_WATCH_DETACH_TIMEOUT_S}s "
1579
- f"(see {log_path})",
1580
- file=sys.stderr,
1581
- )
1582
- return 2
1583
-
1584
-
1585
- def _cmd_watch(args: argparse.Namespace) -> int:
1586
- """Dispatch ``jrag watch`` to its lifecycle verb (or the foreground daemon).
1587
-
1588
- The lightweight probe verbs (``--status``/``--stop``/``--detach``) must NOT
1589
- import the daemon module: that import eagerly pulls torch/
1590
- sentence_transformers/lancedb/pyarrow (~2.5s + ~1GB), defeating their purpose.
1591
- ``WatchDaemon`` is therefore imported inline ONLY on the foreground path below.
1592
- """
1593
- cfg = _resolve_cfg(args)
1594
- if args.status:
1595
- return _cmd_watch_status(cfg)
1596
- if args.stop:
1597
- return _cmd_watch_stop(cfg)
1598
- if args.detach:
1599
- return _cmd_watch_detach(args, cfg)
1600
- # default: run the daemon in the foreground. Ends with os._exit(0) on the
1601
- # serving path; only the early-failure returns (lock held / model load) come
1602
- # back here with a non-zero int.
1603
- from java_codebase_rag.watch.daemon import WatchDaemon
1604
-
1605
- return WatchDaemon(cfg).run_foreground()
1606
-
1607
-
1608
- # Small lifecycle helpers (kept here, not in daemon.py, so --stop/--status have
1609
- # zero coupling to the heavy daemon import path).
1610
-
1611
-
1612
- def _watch_pid_alive(pid: int) -> bool:
1613
- """True iff ``pid`` is currently a live process (best-effort signal-0 probe)."""
1614
- try:
1615
- os.kill(pid, 0)
1616
- except ProcessLookupError:
1617
- return False
1618
- except PermissionError:
1619
- return True # exists, just not signalable by us
1620
- except OSError:
1621
- return False
1622
- return True
1623
-
1624
-
1625
- def _watch_signal(pid: int, sig: int) -> None:
1626
- """Send ``sig`` to ``pid``, swallowing ProcessLookupError (already gone)."""
1627
- try:
1628
- os.kill(pid, sig)
1629
- except ProcessLookupError:
1630
- pass
1631
-
1632
-
1633
- def _watch_unlink(path) -> None:
1634
- """Idempotent, best-effort unlink."""
1635
- try:
1636
- path.unlink()
1637
- except FileNotFoundError:
1638
- pass
1639
- except OSError:
1640
- pass
1641
-
1642
-
1643
- def _read_state_file(index_dir) -> dict | None:
1644
- """Return the parsed daemon state JSON, or ``None`` if missing/unreadable.
1645
-
1646
- Kept HERE (not in ``watch.daemon``) so ``jrag watch --status`` can read the
1647
- last reindex WITHOUT importing the daemon module — that import eagerly pulls
1648
- torch/sentence_transformers/lancedb/pyarrow (~2.5s + ~1GB). A corrupt/partial
1649
- file yields ``None`` rather than raising.
1650
- """
1651
- import json
1652
-
1653
- from java_codebase_rag.watch import paths
1654
-
1655
- path = paths.state_path(index_dir)
1656
- try:
1657
- raw = path.read_text()
1658
- except (FileNotFoundError, OSError):
1659
- return None
1660
- try:
1661
- obj = json.loads(raw)
1662
- except (ValueError, OSError):
1663
- return None
1664
- return obj if isinstance(obj, dict) else None
1665
-
1666
-
1667
- # The daemon's shutdown (watcher.stop joins the debounce thread up to 10s, then
1668
- # server.shutdown joins the accept thread up to 2s) is well under this on an
1669
- # idle watcher; 5s is the brief's prescribed SIGTERM->SIGKILL grace window.
1670
- _WATCH_STOP_TIMEOUT_S = 5.0
1671
- # Model warm-up dominates the detach readiness window on a cold cache; generous
1672
- # so a fresh start isn't reported as a failure while the SBERT model loads.
1673
- _WATCH_DETACH_TIMEOUT_S = 60.0
1674
-
1675
-
1676
- def _cmd_status(args: argparse.Namespace) -> int:
1677
- from java_codebase_rag.jrag_envelope import Envelope
1678
- from java_codebase_rag.jrag_render import render
1679
-
1680
- cfg = _resolve_cfg(args)
1681
- try:
1682
- graph = _load_graph(cfg)
1683
- except (_IndexNotFound, _IndexStale) as exc:
1684
- env = Envelope(
1685
- status="error",
1686
- message=str(exc),
1687
- )
1688
- print(render(env, fmt=args.format, detail=args.detail))
1689
- return 2
1690
-
1691
- meta = graph.meta()
1692
- if "error" in meta:
1693
- env = Envelope(
1694
- status="error",
1695
- message=f"Index meta read failed: {meta['error']}",
1696
- )
1697
- print(render(env, fmt=args.format, detail=args.detail))
1698
- return 2
1699
-
1700
- counts = meta.get("counts") or {}
1701
- edge_counts = meta.get("edge_counts") or {}
1702
- # Single notional "index" node carrying kv fields + nested counts/edges
1703
- # as top-level dict-valued fields. The renderer's inspect-shape dispatch
1704
- # fires on ANY dict-typed value (structural signal, not name-based), so
1705
- # ``counts`` / ``edges`` render as indented alphabetical sections without
1706
- # abusing ``edge_summary`` (which is reserved for PR-JRAG-3 real edge
1707
- # data). See jrag_render._render_inspect / _render_text_shape.
1708
- # --service / --module / --limit are rejected at the argparse layer
1709
- # (status uses _core_parser), so no no-op warning is needed here.
1710
- env = Envelope(
1711
- status="ok",
1712
- nodes={
1713
- "index": {
1714
- "ontology_version": int(meta.get("ontology_version") or 0),
1715
- "built_at": int(meta.get("built_at") or 0),
1716
- "source_root": str(meta.get("source_root") or ""),
1717
- "db_path": str(meta.get("db_path") or ""),
1718
- "parse_errors": int(meta.get("parse_errors") or 0),
1719
- "index_dir": str(cfg.index_dir.resolve()),
1720
- "ladybug_path": str(cfg.ladybug_path.resolve()),
1721
- "counts": dict(counts),
1722
- "edges": dict(edge_counts),
1723
- },
1724
- },
1725
- )
1726
- print(render(env, fmt=args.format, detail=args.detail, noun="status", shape="inspect"))
1727
- return 0
1728
-
1729
-
1730
- def _infer_kind(args: argparse.Namespace) -> str | None:
1731
- """Infer kind from domain flags when --kind is omitted.
1732
-
1733
- Inference rules (PR-JRAG-1b):
1734
- - --http-method or --path-contains → route
1735
- - --client-kind or --calls-service or --calls-path-contains → client
1736
- - --producer-kind or --topic-contains → producer
1737
- - else → symbol (default)
1738
- Returns None if no flags are set (symbol default in callers).
1739
- """
1740
- if args.kind is not None:
1741
- return args.kind
1742
- if args.http_method or args.path_contains:
1743
- return "route"
1744
- if args.client_kind or args.calls_service or args.calls_path_contains:
1745
- return "client"
1746
- if args.producer_kind or args.topic_contains:
1747
- return "producer"
1748
- return "symbol"
1749
-
1750
-
1751
- def _check_kind_contradiction(args: argparse.Namespace, inferred: str | None) -> tuple[bool, str | None]:
1752
- """Check if domain flags contradict explicit --kind.
1753
-
1754
- Returns (is_contradiction, error_message). Contradiction pairs:
1755
- - --kind symbol + any route flag (--http-method, --path-contains)
1756
- - --kind symbol + any client flag (--client-kind, --calls-service, --calls-path-contains)
1757
- - --kind symbol + any producer flag (--producer-kind, --topic-contains)
1758
- - (and similarly for route + non-route flags, etc.)
1759
- """
1760
- if args.kind is None:
1761
- return False, None
1762
- explicit = args.kind
1763
- route_flags = args.http_method or args.path_contains
1764
- client_flags = args.client_kind or args.calls_service or args.calls_path_contains
1765
- producer_flags = args.producer_kind or args.topic_contains
1766
- if explicit == "symbol" and (route_flags or client_flags or producer_flags):
1767
- return True, "--kind symbol conflicts with domain flags (route/client/producer flags require matching --kind)"
1768
- if explicit == "route" and (client_flags or producer_flags):
1769
- return True, "--kind route conflicts with client/producer flags"
1770
- if explicit == "client" and (route_flags or producer_flags):
1771
- return True, "--kind client conflicts with route/producer flags"
1772
- if explicit == "producer" and (route_flags or client_flags):
1773
- return True, "--kind producer conflicts with route/client flags"
1774
- return False, None
1775
-
1776
-
1777
- def _cmd_find(args: argparse.Namespace) -> int:
1778
- from java_codebase_rag.jrag_envelope import Envelope
1779
- from java_codebase_rag.jrag_render import render
1780
- from java_codebase_rag.read_payloads import PayloadError, find_payload
1781
- from java_codebase_rag.watch.client import get_payload
1782
-
1783
- cfg = _resolve_cfg(args)
1784
- try:
1785
- graph = _load_graph(cfg)
1786
- except (_IndexNotFound, _IndexStale) as exc:
1787
- env = Envelope(status="error", message=str(exc))
1788
- print(render(env, fmt=args.format, detail=args.detail))
1789
- return 2
1790
-
1791
- # find inlines its graph load (not via _load_graph_or_error), so wire the
1792
- # auto-scope default here too (MCP parity).
1793
- _apply_auto_scope(args, cfg, graph)
1794
-
1795
- # find_payload does the mode selection (query vs filter), kind-contradiction
1796
- # check, and the backend call (find_by_name_or_fqn + post-filters, or find_v2).
1797
- # Rendering (nodes/warnings/empty-result hint/offset) is split into the two
1798
- # render helpers below, branch by payload["mode"].
1799
- try:
1800
- payload = get_payload("find", vars(args), cfg, cold_core=find_payload)
1801
- except PayloadError as pe:
1802
- print(render(pe.env, fmt=args.format, detail=args.detail))
1803
- return pe.rc
1804
-
1805
- if payload["mode"] == "query":
1806
- return _render_find_query(args, payload)
1807
- return _render_find_filter(args, payload)
1808
-
1809
-
1810
- def _render_find_query(args: argparse.Namespace, payload) -> int:
1811
- """Render find query-mode payload (rows from find_by_name_or_fqn + post-filters).
1812
-
1813
- The backend call + post-filters live in ``read_payloads.find_payload``; this
1814
- builds the envelope node dicts, warnings, and empty-result hint, then renders.
1815
- With ``--fuzzy``, ``find_payload`` widens an empty exact result to prefix then
1816
- substring (issue #375) and reports the matched tier via ``payload["matched_mode"]``
1817
- (exact/prefix/contains) plus ``payload["identifier_matched"]`` for the hint.
1818
- """
1819
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
1820
- from java_codebase_rag.jrag_render import render
1821
-
1822
- rows = payload["rows"]
1823
- raw_truncated = payload["raw_truncated"]
1824
- post_filter_active = payload["post_filter_active"]
1825
- limit = payload["limit"]
1826
- query = payload["query"]
1827
- matched_mode = payload["matched_mode"]
1828
- identifier_matched = payload["identifier_matched"]
1829
-
1830
- # Build warnings for filters that cannot apply in query mode. SymbolHit
1831
- # carries no framework/source_layer fields; rather than silently dropping
1832
- # the user's filter, surface a warning so they know to switch to filter mode.
1833
- warnings: list[str] = []
1834
- if args.framework:
1835
- warnings.append(
1836
- "--framework ignored in query mode (applies to routes/clients/producers; use filter mode)"
1837
- )
1838
- if args.source_layer:
1839
- warnings.append(
1840
- "--source-layer ignored in query mode (applies to routes; use filter mode)"
1841
- )
1842
- # When post-filters apply after a capped fetch, `truncated` reflects the
1843
- # pre-filter name-match count and cannot know whether MORE filtered matches
1844
- # exist beyond the fetch — surface that honestly.
1845
- if raw_truncated and post_filter_active:
1846
- warnings.append(
1847
- "results truncated before --role/--annotation/--capability filters; "
1848
- "additional filtered matches may exist beyond the fetch"
1849
- )
1850
-
1851
- # Display at most `limit` of the (post-filtered) rows.
1852
- display_rows = rows[:limit]
1853
- # Map internal mode -> user-facing term (help/empty-hint say "substring").
1854
- mode_label = "substring" if matched_mode == "contains" else matched_mode
1855
- if matched_mode != "exact" and display_rows:
1856
- warnings.append(
1857
- f"no exact name/FQN match; --fuzzy matched via {mode_label}"
1858
- )
1859
- nodes = {}
1860
- for row in display_rows:
1861
- node_id = row.id
1862
- # Carry the full SymbolHit field set (signature/annotations/modifiers/
1863
- # package/raw location columns). The projector trims to the requested
1864
- # detail level (signature/annotations/... appear only at ``full``),
1865
- # so populating them here is what makes ``find <fqn> --detail full``
1866
- # honor the contract (jrag_render keeps signature/annotations at full).
1867
- # Without this, find --detail full showed only identity+classification
1868
- # because the node never carried the content fields.
1869
- nodes[node_id] = {
1870
- "id": node_id,
1871
- "kind": "symbol",
1872
- "fqn": row.fqn,
1873
- "name": row.name,
1874
- "symbol_kind": row.kind,
1875
- "microservice": row.microservice,
1876
- "module": row.module,
1877
- "role": row.role,
1878
- "package": row.package,
1879
- "signature": row.signature,
1880
- "annotations": list(row.annotations or []),
1881
- "capabilities": list(row.capabilities or []),
1882
- "modifiers": list(row.modifiers or []),
1883
- "filename": row.filename,
1884
- "start_line": row.start_line,
1885
- "end_line": row.end_line,
1886
- }
1887
-
1888
- env = Envelope(
1889
- status="ok", nodes=nodes, truncated=raw_truncated,
1890
- warnings=warnings + _auto_scope_notice(args),
1891
- )
1892
- next_actions_hook(env)
1893
-
1894
- # Empty-result discoverability: a partial like `find ChatManag` returns 0
1895
- # under exact match. Three cases: (1) some tier matched the identifier but
1896
- # --role/--exclude-role/--annotation/--capability removed every hit — blame
1897
- # the filter, not the query; (2) --fuzzy widened to prefix/substring and
1898
- # still found nothing; (3) no --fuzzy, so suggest it. Carried as `message`
1899
- # (inline) + `agent_next_actions` (`next:`/JSON).
1900
- if not nodes and query:
1901
- if identifier_matched and post_filter_active:
1902
- hint = (
1903
- f"matched {query!r} (via {mode_label}), but "
1904
- "--role/--exclude-role/--annotation/--capability removed all hits"
1905
- )
1906
- elif getattr(args, "fuzzy", False):
1907
- hint = f"no match for {query!r} (tried exact, prefix, substring)"
1908
- env.agent_next_actions = [f"jrag find --fqn-contains {query}"]
1909
- else:
1910
- hint = f"no exact match for {query!r} — try `jrag find {query} --fuzzy`"
1911
- env.agent_next_actions = [f"jrag find {query} --fuzzy"]
1912
- env.message = hint
1913
-
1914
- # Offset is not supported in query mode (find_by_name_or_fqn has no offset).
1915
- return _emit(env, args, noun="symbol")
1916
-
1917
-
1918
-
1919
- def _build_node_filter_or_error(filter_dict: dict):
1920
- """Build a ``NodeFilter`` from ``filter_dict``; on pydantic validation
1921
- failure return ``(None, error_envelope)`` so the caller can render a clean
1922
- ``status: error`` envelope instead of letting the ValidationError propagate
1923
- to the top-level handler (which renders "internal error" + a traceback).
1924
-
1925
- A bad enum (e.g. ``--role FOO``) should be a user-facing validation error,
1926
- not an internal crash. Returns ``(node_filter, None)`` on success.
1927
- """
1928
- from java_codebase_rag.mcp import mcp_v2
1929
-
1930
- from java_codebase_rag.jrag_envelope import Envelope
1931
- from pydantic import ValidationError
1932
-
1933
- try:
1934
- nf = mcp_v2.NodeFilter.model_validate(filter_dict) if filter_dict else mcp_v2.NodeFilter()
1935
- return nf, None
1936
- except ValidationError as exc:
1937
- parts: list[str] = []
1938
- for err in exc.errors():
1939
- loc = ".".join(str(x) for x in err.get("loc", []) if x != "")
1940
- msg = str(err.get("msg") or "").strip()
1941
- parts.append(f"{loc}: {msg}" if loc else msg)
1942
- message = "; ".join(parts) if parts else str(exc)
1943
- return None, Envelope(status="error", message=f"invalid filter: {message}")
1944
-
1945
-
1946
- def _render_find_filter(args: argparse.Namespace, payload) -> int:
1947
- """Render find filter-mode payload (a FindOutput from find_v2).
1948
-
1949
- The backend call + NodeFilter construction live in
1950
- ``read_payloads.find_payload``; this slices to the limit, builds the envelope
1951
- node dicts, and renders — verbatim from the original
1952
- ``_cmd_find_filter_mode`` render portion.
1953
- """
1954
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook, to_envelope_rows
1955
- from java_codebase_rag.jrag_render import render
1956
-
1957
- out = payload["out"]
1958
- kind = payload["kind"]
1959
- limit = payload["limit"]
1960
-
1961
- if not out.success:
1962
- env = Envelope(status="error", message=out.message)
1963
- print(render(env, fmt=args.format, detail=args.detail))
1964
- return 2
1965
-
1966
- # Convert results to envelope rows. Slice to `limit`: find_v2 was called with
1967
- # limit+1, so when exactly user_limit+1 matches exist `out.results` carries
1968
- # one extra row that must be dropped (off-by-one guard). `truncated` is True
1969
- # when the backend reports more OR the +1 row is present.
1970
- results = list(out.results)
1971
- truncated = bool(out.has_more_results) or len(results) > limit
1972
- display_refs = results[:limit]
1973
- nodes_dict = {ref.id: to_envelope_rows([ref])[0] for ref in display_refs}
1974
-
1975
- env = Envelope(
1976
- status="ok", nodes=nodes_dict, truncated=truncated,
1977
- warnings=_auto_scope_notice(args),
1978
- )
1979
- next_actions_hook(env)
1980
-
1981
- # Render with offset hint if truncated
1982
- next_offset = args.offset + limit if truncated else None
1983
- return _emit(env, args, noun=kind, next_offset=next_offset)
1984
-
1985
-
1986
-
1987
- def _cmd_inspect(args: argparse.Namespace) -> int:
1988
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
1989
- from java_codebase_rag.jrag_render import render
1990
-
1991
- cfg = _resolve_cfg(args)
1992
- try:
1993
- graph = _load_graph(cfg)
1994
- except (_IndexNotFound, _IndexStale) as exc:
1995
- env = Envelope(status="error", message=str(exc))
1996
- print(render(env, fmt=args.format, detail=args.detail))
1997
- return 2
1998
-
1999
- # inspect_payload resolves the query (forwarding --service/--module, same as
2000
- # before) and calls describe_v2. It returns the DescribeOutput plus the
2001
- # resolve-derived node id/fqn and file_location the flatten+render below
2002
- # needs (file_location lives on the resolve Envelope, not on DescribeOutput).
2003
- # On resolve failure it raises PayloadError carrying that Envelope + rc.
2004
- from java_codebase_rag.read_payloads import PayloadError, inspect_payload
2005
- from java_codebase_rag.watch.client import get_payload
2006
-
2007
- try:
2008
- payload = get_payload("inspect", vars(args), cfg, cold_core=inspect_payload)
2009
- except PayloadError as pe:
2010
- # Resolve-miss: route through _emit so --exists/--count shape it
2011
- # (inspect Missing --exists -> false, rc 2), mirroring master's inspect
2012
- # resolve-miss path. No flag -> rc matches the prior 2-if-error-else-0.
2013
- return _emit(pe.env, args)
2014
- desc_out = payload["describe"]
2015
-
2016
- if not desc_out.success or desc_out.record is None:
2017
- env = Envelope(status="error", message=desc_out.message or "describe failed")
2018
- print(render(env, fmt=args.format, detail=args.detail))
2019
- return 2
2020
-
2021
- # Convert NodeRecord to envelope format.
2022
- #
2023
- # NodeRecord nests the symbol's payload inside a ``data`` sub-dict (kind,
2024
- # name, package, module, microservice, role, signature, annotations,
2025
- # capabilities, modifiers, filename, start_line, ...). The envelope
2026
- # projector's identity/classification keys (``_BRIEF_NODE_KEYS`` /
2027
- # ``_NORMAL_NODE_KEYS``) live at the TOP level, so without flattening they
2028
- # never reach the nested data and inspect renders only the outer kind/fqn
2029
- # at every level (brief == normal, the bug). Flatten ``data`` to the top
2030
- # level so:
2031
- # * brief picks up kind/fqn/name/microservice (identity).
2032
- # * normal additionally picks up module/role/symbol_kind/file
2033
- # (classification + location).
2034
- # * full additionally keeps signature/annotations/modifiers/package/
2035
- # capabilities/edge_summary (content).
2036
- #
2037
- # The outer ``kind`` is the node category ("symbol"); the inner
2038
- # ``data.kind`` is the symbol sub-kind ("class"/"interface"/"method"/...),
2039
- # renamed ``symbol_kind`` to match find/search/listings (which use
2040
- # ``symbol_kind`` for the sub-kind and reserve ``kind`` for the category).
2041
- record_dict = desc_out.record.model_dump()
2042
- node_id = record_dict.get("id") or payload["node_id"]
2043
- data = record_dict.get("data") or {}
2044
- flat: dict[str, Any] = {
2045
- "kind": record_dict.get("kind") or "symbol",
2046
- "fqn": record_dict.get("fqn") or data.get("fqn") or payload["node_fqn"],
2047
- }
2048
- # Promote inner data fields. Skip ``kind`` here — renamed to symbol_kind.
2049
- for src_key, dest_key in (
2050
- ("name", "name"),
2051
- ("kind", "symbol_kind"),
2052
- ("package", "package"),
2053
- ("module", "module"),
2054
- ("microservice", "microservice"),
2055
- ("role", "role"),
2056
- ("signature", "signature"),
2057
- ("annotations", "annotations"),
2058
- ("capabilities", "capabilities"),
2059
- ("modifiers", "modifiers"),
2060
- ("filename", "filename"),
2061
- ("start_line", "start_line"),
2062
- ("end_line", "end_line"),
2063
- ):
2064
- val = data.get(src_key)
2065
- if val not in (None, "", [], {}):
2066
- flat[dest_key] = val
2067
- # edge_summary is a top-level field on NodeRecord (not inside data) — keep
2068
- # it so --detail full renders it as a nested kv-block (brief/normal drop
2069
- # it via the scalar allow-list since the inspect subject has identity and
2070
- # so takes the strict-scalar projection branch).
2071
- if record_dict.get("edge_summary"):
2072
- flat["edge_summary"] = record_dict["edge_summary"]
2073
-
2074
- env = Envelope(
2075
- status="ok",
2076
- nodes={node_id: flat},
2077
- root=node_id,
2078
- file_location=payload["file_location"], # Preserve file_location from resolve
2079
- )
2080
- next_actions_hook(env, root=node_id, edge_summary=record_dict.get("edge_summary"))
2081
-
2082
- # Render with inspect shape
2083
- return _emit(env, args, shape="inspect")
2084
-
2085
-
2086
- def _backfill_service_from_filename(row: dict) -> None:
2087
- """Derive ``microservice`` / ``module`` from ``filename`` when empty.
2088
-
2089
- Kafka-topic Route nodes are created without ``microservice``/``module`` in
2090
- the graph builder, so the routes listing rendered them with no ``@service``
2091
- (or as blank lines when the topic was also empty). The filename carries the
2092
- info reliably (``<microservice>/<module>/src/...`` or
2093
- ``<microservice>/src/...``) — the same path-based resolution graph_enrich
2094
- uses — so backfill from it for display without forcing a reindex.
2095
- """
2096
- fn = str(row.get("filename") or "").strip()
2097
- if not fn:
2098
- return
2099
- parts = fn.split("/")
2100
- if "src" not in parts:
2101
- return
2102
- idx = parts.index("src")
2103
- if idx >= 1 and not (row.get("microservice") or "").strip():
2104
- row["microservice"] = parts[0]
2105
- if idx >= 2 and not (row.get("module") or "").strip():
2106
- row["module"] = parts[1]
2107
-
2108
-
2109
- def _cmd_routes(args: argparse.Namespace) -> int:
2110
- from java_codebase_rag.jrag_envelope import normalize_enum
2111
-
2112
- _, graph, rc = _load_graph_or_error(args)
2113
- if rc:
2114
- return rc
2115
- limit = _clamped_limit(args)
2116
-
2117
- # Normalize framework if provided
2118
- framework = normalize_enum(args.framework, kind="framework") if args.framework else None
2119
-
2120
- rows = graph.list_routes(
2121
- microservice=args.service,
2122
- framework=framework,
2123
- path_contains=args.path_contains,
2124
- method=args.method,
2125
- limit=limit + 1, # +1 for truncated detection
2126
- # `http-routes` is the HTTP-server-route surface (external entrypoints
2127
- # you'd run `callers` on): exclude kafka topics (→ `topics`) and client
2128
- # http_endpoint mirrors (call-sites). Pinned to include_kafka=False —
2129
- # the backend default (True) would re-admit kafka topics.
2130
- server_exposed=True,
2131
- include_kafka=False,
2132
- )
2133
- for row in rows:
2134
- _backfill_service_from_filename(row)
2135
- return _render_listing(rows, limit=limit, args=args, noun="route")
2136
-
2137
-
2138
- def _cmd_clients(args: argparse.Namespace) -> int:
2139
- from java_codebase_rag.jrag_envelope import normalize_enum
2140
-
2141
- _, graph, rc = _load_graph_or_error(args)
2142
- if rc:
2143
- return rc
2144
- limit = _clamped_limit(args)
2145
-
2146
- # Normalize client_kind via lookup table (feign → feign_method, etc.)
2147
- client_kind = normalize_enum(args.client_kind, kind="client_kind") if args.client_kind else None
2148
-
2149
- rows = graph.list_clients(
2150
- microservice=args.service,
2151
- client_kind=client_kind,
2152
- target_service=args.calls_service,
2153
- path_contains=args.path_contains,
2154
- limit=limit + 1, # +1 for truncated detection
2155
- )
2156
- return _render_listing(rows, limit=limit, args=args, noun="client")
2157
-
2158
-
2159
- def _cmd_producers(args: argparse.Namespace) -> int:
2160
- from java_codebase_rag.jrag_envelope import normalize_enum
2161
-
2162
- _, graph, rc = _load_graph_or_error(args)
2163
- if rc:
2164
- return rc
2165
- limit = _clamped_limit(args)
2166
-
2167
- # Normalize producer_kind via lookup table (kafka → kafka_send, etc.)
2168
- producer_kind = normalize_enum(args.producer_kind, kind="producer_kind") if args.producer_kind else None
2169
-
2170
- rows = graph.list_producers(
2171
- microservice=args.service,
2172
- producer_kind=producer_kind,
2173
- topic_contains=args.topic_contains,
2174
- limit=limit + 1, # +1 for truncated detection
2175
- )
2176
- return _render_listing(rows, limit=limit, args=args, noun="producer")
2177
-
2178
-
2179
- def _producer_summary(producer: dict) -> dict:
2180
- """Display-oriented producer dict for the ``topics`` grouping.
2181
-
2182
- The raw ``list_producers`` row carries 11 fields (incl. empty ``broker``,
2183
- raw ``filename``/``start_line``/``end_line``, ``direction``, ``source_layer``)
2184
- which the text renderer used to collapse into one unreadable comma-line.
2185
- This folds location into a single ``file`` and keeps only the fields an
2186
- operator needs to identify the producer under a topic header (the topic
2187
- itself is the group header, so it's dropped here). Empty values omitted.
2188
- """
2189
- member_fqn = str(producer.get("member_fqn") or "")
2190
- member_simple = member_fqn.rsplit(".", 1)[-1] if member_fqn else ""
2191
- filename = str(producer.get("filename") or "")
2192
- start_line = producer.get("start_line")
2193
- try:
2194
- sl = int(start_line) if start_line not in (None, "") else None
2195
- except (TypeError, ValueError):
2196
- sl = None
2197
- file_loc = f"{filename}:{sl}" if filename and sl else filename
2198
- out: dict = {}
2199
- if member_simple:
2200
- out["member"] = member_simple
2201
- if file_loc:
2202
- out["file"] = file_loc
2203
- # ``direction`` is intentionally omitted: every Producer is built with
2204
- # direction="producer" (build_ast_graph), so it's a constant that only
2205
- # inflates each block with zero information.
2206
- for k in ("microservice", "module", "producer_kind", "broker"):
2207
- v = producer.get(k)
2208
- if v not in (None, "", []):
2209
- out[k] = v
2210
- resolved = producer.get("resolved")
2211
- if resolved is not None:
2212
- out["resolved"] = bool(resolved)
2213
- return out
2214
-
2215
-
2216
- def _cmd_topics(args: argparse.Namespace) -> int:
2217
- from java_codebase_rag.jrag_envelope import Envelope, mark_truncated, next_actions_hook
2218
-
2219
- _, graph, rc = _load_graph_or_error(args)
2220
- if rc:
2221
- return rc
2222
- limit = _clamped_limit(args)
2223
-
2224
- # Scope producers by --producer-in if provided (else --service push-down).
2225
- producer_microservice = args.producer_in or args.service
2226
-
2227
- # Call list_producers to get producers (grouped by topic)
2228
- rows = graph.list_producers(
2229
- microservice=producer_microservice,
2230
- topic_contains=args.topic_contains,
2231
- limit=limit + 1, # +1 for truncated detection
2232
- )
2233
-
2234
- # Group by topic name. Track no-topic producers so they surface as a
2235
- # warning (distinguishable from "no producers at all").
2236
- topics_dict: dict[str, dict] = {}
2237
- no_topic_count = 0
2238
- for producer in rows:
2239
- topic = producer.get("topic") or ""
2240
- if not topic:
2241
- no_topic_count += 1
2242
- continue
2243
- if topic not in topics_dict:
2244
- topics_dict[topic] = {
2245
- "topic": topic,
2246
- "producers": [],
2247
- "broker": producer.get("broker") or "",
2248
- }
2249
- topics_dict[topic]["producers"].append(_producer_summary(producer))
2250
-
2251
- warnings: list[str] = []
2252
- if no_topic_count:
2253
- warnings.append(
2254
- f"{no_topic_count} producer(s) had no topic and were excluded"
2255
- )
2256
- # list_producers has no module kwarg (only microservice/topic_contains); --module
2257
- # would be silently dropped — surface it (use --producer-in to scope by svc).
2258
- if getattr(args, "module", None):
2259
- warnings.append(
2260
- "--module is not applied on topics (list_producers has no module param; "
2261
- "use --producer-in to scope producers by microservice)"
2262
- )
2263
-
2264
- # If --consumer-in is provided, resolve consumers for each topic group.
2265
- # A consumer of a topic IS a listener: the edge path is
2266
- # listener_class -[:DECLARES]-> listener_method -[:EXPOSES]-> Route(topic)
2267
- # (ASYNC_CALLS run Producer -> Route per java_ontology.py:415-416, so the
2268
- # inbound-ASYNC_CALLS traversal the original PR shipped returned empty on
2269
- # every graph — corrected here to use the EXPOSES-based resolver shared
2270
- # with `listeners --topic-contains`.)
2271
- if args.consumer_in and topics_dict:
2272
- for topic_name, topic_group in topics_dict.items():
2273
- consumers = _resolve_topic_consumers(
2274
- graph,
2275
- topic=topic_name,
2276
- microservice=args.consumer_in,
2277
- contains=False, # exact match on the producer's topic literal
2278
- )
2279
- if consumers:
2280
- topic_group["consumers"] = consumers
2281
-
2282
- # Convert to list and apply truncation
2283
- topic_list = list(topics_dict.values())
2284
- display_topics_list, truncated = mark_truncated(topic_list, limit)
2285
-
2286
- # Build envelope with topic nodes
2287
- nodes = {}
2288
- for i, topic in enumerate(display_topics_list):
2289
- node_id = f"topic:{i}"
2290
- nodes[node_id] = topic
2291
-
2292
- env = Envelope(
2293
- status="ok", nodes=nodes, truncated=truncated,
2294
- warnings=warnings + _auto_scope_notice(args),
2295
- )
2296
- next_actions_hook(env, command=getattr(args, "command", None))
2297
- return _emit(env, args, noun="topic")
2298
-
2299
-
2300
- def _inspect_hints_for_rows(rows: list[dict], *, limit: int = 2) -> list[str]:
2301
- """Build ``jrag inspect <fqn>`` hints for the first ``limit`` rows that
2302
- carry an FQN. Used by jobs/listeners/entities to surface a per-row
2303
- drill-down (text renderer shows up to 2 as ``next:`` lines; JSON carries
2304
- up to 5 — callers pass ``limit=2`` for the visible cap).
2305
- """
2306
- hints: list[str] = []
2307
- for r in rows:
2308
- fqn = r.get("fqn") if isinstance(r, dict) else getattr(r, "fqn", None)
2309
- if fqn:
2310
- hints.append(f"jrag inspect {fqn}")
2311
- if len(hints) >= limit:
2312
- break
2313
- return hints
2314
-
2315
-
2316
- def _cmd_jobs(args: argparse.Namespace) -> int:
2317
- _, graph, rc = _load_graph_or_error(args)
2318
- if rc:
2319
- return rc
2320
- limit = _clamped_limit(args)
2321
-
2322
- symbol_hits = graph.list_by_capability(
2323
- capability="SCHEDULED_TASK",
2324
- module=args.module,
2325
- microservice=args.service,
2326
- limit=limit + 1, # +1 for truncated detection
2327
- )
2328
- rows = [_symbol_hit_to_dict(h) for h in symbol_hits]
2329
- # Per-row drill-down: the agent's natural next step on a job/listener/entity
2330
- # is to inspect it (signature, edges, callers). Cap visible hints at 2 so
2331
- # text output stays tight; the JSON cap (5) is applied in _render_listing.
2332
- hints = _inspect_hints_for_rows(rows[:limit], limit=2)
2333
- return _render_listing(rows, limit=limit, args=args, noun="symbol", extra_hints=hints)
2334
-
2335
-
2336
- def _resolve_topic_consumers(
2337
- graph,
2338
- *,
2339
- topic: str,
2340
- microservice: str | None = None,
2341
- contains: bool = False,
2342
- ) -> list[dict]:
2343
- """Resolve listener classes that consume a topic via EXPOSES on Route.
2344
-
2345
- The graph models the listener→topic edge path as:
2346
- listener_class -[:DECLARES]-> listener_method -[:EXPOSES]-> Route(topic)
2347
-
2348
- This is the correct consumer-resolution path for async messaging topics:
2349
- ``ASYNC_CALLS`` run ``Producer → Route`` (java_ontology.py:415-416), so
2350
- there is no inbound ``ASYNC_CALLS`` edge into Producer nodes to traverse
2351
- via ``neighbors_v2(direction="in")``. The ``Route.topic`` property is not
2352
- projected onto the ``NodeRef`` returned by ``neighbors_v2``, so a
2353
- single-purpose Cypher lookup is used here — the same pattern as
2354
- ``jrag_envelope._node_file_location`` (``graph._rows`` for a focused
2355
- property fetch). This is a CLI-layer compose query, not a reimplementation
2356
- of backend traversal logic.
2357
-
2358
- Args:
2359
- topic: Topic string to match (exact unless ``contains=True``).
2360
- microservice: Optional microservice filter on the listener class.
2361
- contains: If True, match topic as a substring (``CONTAINS``);
2362
- if False (default), exact equality.
2363
-
2364
- Returns:
2365
- List of consumer dicts (``id``, ``fqn``, ``kind``, ``microservice``).
2366
- """
2367
- if not topic:
2368
- return []
2369
- match_clause = "r.topic CONTAINS $topic" if contains else "r.topic = $topic"
2370
- params: dict = {"topic": topic}
2371
- ms_clause = ""
2372
- if microservice:
2373
- ms_clause = " AND cls.microservice = $ms"
2374
- params["ms"] = microservice
2375
- rows = graph._rows( # noqa: SLF001 - focused property lookup (same as _node_file_location)
2376
- f"MATCH (cls:Symbol)-[:DECLARES]->(mth:Symbol)-[:EXPOSES]->(r:Route) "
2377
- f"WHERE {match_clause}{ms_clause} "
2378
- f"RETURN DISTINCT cls.id AS cid, cls.fqn AS cfqn, cls.microservice AS cms",
2379
- params,
2380
- )
2381
- return [
2382
- {
2383
- "id": str(r.get("cid") or ""),
2384
- "fqn": str(r.get("cfqn") or ""),
2385
- "kind": "symbol",
2386
- "microservice": str(r.get("cms") or ""),
2387
- }
2388
- for r in rows
2389
- if r.get("cid")
2390
- ]
2391
-
2392
-
2393
- def _listener_ids_for_topic_contains(graph, listener_ids: list[str], contains: str) -> set[str]:
2394
- """Resolve which listener classes consume a topic containing the given substring.
2395
-
2396
- Thin wrapper over :func:`_resolve_topic_consumers` intersected with the
2397
- pre-fetched ``listener_ids`` (from ``list_by_capability``). Retained as a
2398
- separate function so ``_cmd_listeners`` can narrow the SymbolHit list in
2399
- place (the capability fetch carries SymbolHit fields the resolver does not
2400
- project). See ``_resolve_topic_consumers`` for the edge-model rationale.
2401
- """
2402
- if not listener_ids or not contains:
2403
- return set(listener_ids)
2404
- consumers = _resolve_topic_consumers(graph, topic=contains, contains=True)
2405
- matching = {c["id"] for c in consumers}
2406
- return {lid for lid in listener_ids if lid in matching}
2407
-
2408
-
2409
- def _cmd_listeners(args: argparse.Namespace) -> int:
2410
- _, graph, rc = _load_graph_or_error(args)
2411
- if rc:
2412
- return rc
2413
- limit = _clamped_limit(args)
2414
-
2415
- symbol_hits = graph.list_by_capability(
2416
- capability="MESSAGE_LISTENER",
2417
- module=args.module,
2418
- microservice=args.service,
2419
- limit=_CONSUMER_FETCH_LIMIT, # generous pre-filter fetch; truncation applies after
2420
- )
2421
-
2422
- # --topic-contains: narrow to listeners consuming a topic containing that substring.
2423
- # The listener class itself carries no topic; its listener method EXPOSES
2424
- # a Route whose ``topic`` property holds the consumed topic name (resolved
2425
- # or as a constant reference). See _listener_ids_for_topic_contains.
2426
- if args.topic_contains and symbol_hits:
2427
- matching_ids = _listener_ids_for_topic_contains(
2428
- graph, [h.id for h in symbol_hits], args.topic_contains
2429
- )
2430
- symbol_hits = [h for h in symbol_hits if h.id in matching_ids]
2431
-
2432
- # Apply the user-facing limit + 1 truncation AFTER the topic filter.
2433
- capped = symbol_hits[: limit + 1]
2434
- rows = [_symbol_hit_to_dict(h) for h in capped]
2435
- hints = _inspect_hints_for_rows(rows[:limit], limit=2)
2436
- return _render_listing(rows, limit=limit, args=args, noun="symbol", extra_hints=hints)
2437
-
2438
-
2439
- def _cmd_entities(args: argparse.Namespace) -> int:
2440
- _, graph, rc = _load_graph_or_error(args)
2441
- if rc:
2442
- return rc
2443
- limit = _clamped_limit(args)
2444
-
2445
- symbol_hits = graph.list_by_role(
2446
- role="ENTITY",
2447
- module=args.module,
2448
- microservice=args.service,
2449
- limit=limit + 1, # +1 for truncated detection
2450
- )
2451
- rows = [_symbol_hit_to_dict(h) for h in symbol_hits]
2452
- hints = _inspect_hints_for_rows(rows[:limit], limit=2)
2453
- return _render_listing(rows, limit=limit, args=args, noun="symbol", extra_hints=hints)
2454
-
2455
-
2456
- # ============================================================================
2457
- # PR-JRAG-3a: traversal helpers + 11 traversal command handlers.
2458
- #
2459
- # Every traversal is resolve-first (resolve_query), then calls a LadybugGraph
2460
- # method (or neighbors_v2 for the override axis), then renders via the
2461
- # traversal shape (envelope.root + edge rows). --offset is NOT supported on
2462
- # any traversal subparser. --limit uses +1-fetch where the method takes a
2463
- # limit; client-side slice otherwise.
2464
- #
2465
- # Backend signatures verified against source (ladybug_queries.py / mcp_v2.py /
2466
- # java_ontology.py) at PR-JRAG-3a time. Adaptations from the brief:
2467
- # * find_implementors / find_subclasses / find_injectors DO accept a
2468
- # `capability` kwarg (the brief claimed they did not); --capability is
2469
- # PUSHED DOWN on `implementations` (more efficient + matches the global
2470
- # principle "pushed down where the method takes it").
2471
- # * OVERRIDES edge direction confirmed: overrider -> declaration (subtype
2472
- # method -> supertype method), so `out`=dispatch UP (overrides) and
2473
- # `in`=dispatch DOWN (overridden-by). Brief was correct.
2474
- # ============================================================================
2475
-
2476
-
2477
- def _resolve_traversal_node(
2478
- args: argparse.Namespace,
2479
- *,
2480
- cfg,
2481
- graph,
2482
- hint_kind,
2483
- apply_scope: bool = False,
2484
- ):
2485
- """Resolve-first frame shared by every traversal command.
2486
-
2487
- Returns ``(node, env, rc)``. On resolve failure (ambiguous / not_found /
2488
- error), renders the envelope and returns ``(None, env, rc)`` with rc=2 on
2489
- error, 0 on ambiguous/not_found (matches the inspect command convention).
2490
-
2491
- ``apply_scope`` opts a command into pushing ``--service``/``--module`` down
2492
- into resolve as resolve-time filters (via :func:`resolve_query`). Most
2493
- traversal commands keep the default ``False`` to preserve their existing
2494
- resolve semantics (structural-edge commands warn-and-ignore ``--service``;
2495
- symbol traversals use ``--service`` as a result filter via find_callers/
2496
- find_callees). ``callers`` opts in so ``--service`` narrows WHICH route
2497
- resolves for the cross-service route-caller flow.
2498
- """
2499
- from java_codebase_rag.jrag_envelope import resolve_query
2500
-
2501
- node, env = resolve_query(
2502
- args.query,
2503
- hint_kind=hint_kind,
2504
- java_kind=getattr(args, "java_kind", None),
2505
- role=getattr(args, "role", None),
2506
- fqn_contains=getattr(args, "fqn_contains", None),
2507
- cfg=cfg,
2508
- graph=graph,
2509
- microservice=(getattr(args, "service", None) or "") if apply_scope else "",
2510
- module=(getattr(args, "module", None) or "") if apply_scope else "",
2511
- )
2512
- if env.status != "ok":
2513
- # Route through _emit so --exists/--count shape a resolve miss (e.g.
2514
- # `callers Missing --exists` -> false, rc 2) instead of rendering the
2515
- # not_found body. rc matches the prior 2-if-error-else-0 when no flag.
2516
- return None, env, _emit(env, args)
2517
- return node, env, 0
2518
-
2519
-
2520
- def _noderef_to_node_dict(ref) -> dict:
2521
- """NodeRef (pydantic, from neighbors_v2 / resolve) -> envelope node dict."""
2522
- return ref.model_dump()
2523
-
2524
-
2525
- def _dedupe_traversal_edges(edges: list[dict]) -> list[dict]:
2526
- """Drop edges with an empty ``other_id`` and dedupe by ``(other_id, edge_type)``.
2527
-
2528
- ``find_callees`` can emit the same callee twice (a method reached via
2529
- multiple call sites / strategies), and a CLIENT-role aggregation can surface
2530
- a Client row whose id never resolved. Both produce noisy traversal rows:
2531
- duplicates inflate the count, and an empty ``other_id`` becomes a phantom
2532
- edge the id-free renderer cannot key. Keep the FIRST occurrence (results are
2533
- confidence-sorted, so the first is the highest-confidence edge).
2534
- """
2535
- seen: set[tuple[str, str]] = set()
2536
- out: list[dict] = []
2537
- for e in edges:
2538
- oid = e.get("other_id")
2539
- if not oid:
2540
- continue
2541
- key = (str(oid), str(e.get("edge_type") or ""))
2542
- if key in seen:
2543
- continue
2544
- seen.add(key)
2545
- out.append(e)
2546
- return out
2547
-
2548
-
2549
- def _emit_traversal(
2550
- args: argparse.Namespace,
2551
- *,
2552
- root_id: str,
2553
- nodes: dict[str, dict],
2554
- edges: list[dict],
2555
- noun: str,
2556
- warnings: list[str] | None = None,
2557
- truncated: bool = False,
2558
- is_external_entrypoint: bool = False,
2559
- extra_hints: list[str] | None = None,
2560
- ) -> int:
2561
- """Build the traversal envelope (root + nodes + edges) and render.
2562
-
2563
- The traversal shape requires ``envelope.root`` so the renderer uses the
2564
- traversal shape (root + edge rows). ``next_offset`` is left None on every
2565
- traversal (non-offset -> "truncated: more results - narrow your query").
2566
- ``is_external_entrypoint`` flags a server-exposed route with zero in-repo
2567
- callers so the renderer emits an honest "external entrypoint" note instead
2568
- of a bare, bug-looking ``0 callers`` line.
2569
-
2570
- ``extra_hints`` are merged into ``agent_next_actions`` AFTER the
2571
- edge-derived hints (deduped, capped at 5). Used by commands with a known
2572
- cross-ref for an empty/edge case (e.g. ``subclasses <interface>`` ->
2573
- ``jrag implementations <fqn>``).
2574
- """
2575
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
2576
-
2577
- env = Envelope(
2578
- status="ok",
2579
- nodes=dict(nodes),
2580
- edges=list(edges),
2581
- root=root_id,
2582
- warnings=(warnings or []) + _auto_scope_notice(args),
2583
- truncated=truncated,
2584
- is_external_entrypoint=is_external_entrypoint,
2585
- )
2586
- next_actions_hook(env, root=root_id, result_edges=edges, command=getattr(args, "command", None))
2587
- if extra_hints:
2588
- seen = set(env.agent_next_actions)
2589
- for h in extra_hints:
2590
- if h and h not in seen:
2591
- seen.add(h)
2592
- env.agent_next_actions.append(h)
2593
- env.agent_next_actions = env.agent_next_actions[:5]
2594
- return _emit(env, args, noun=noun)
2595
-
2596
-
2597
- def _require_kind(
2598
- node,
2599
- *,
2600
- expected: str,
2601
- kinds: tuple[str, ...],
2602
- args: argparse.Namespace,
2603
- hint: str = "",
2604
- java_kinds: tuple[str, ...] | None = None,
2605
- roles: tuple[str, ...] | None = None,
2606
- ) -> int | None:
2607
- """Kind guard shared by traversal handlers (DRY for the 11x guard block).
2608
-
2609
- Returns ``None`` when ``node.kind`` is in ``kinds`` (caller proceeds). On
2610
- mismatch, prints a ``status: error`` envelope and returns 2. ``expected``
2611
- is the human-readable root description (e.g. ``"overrides expects a method
2612
- Symbol root"``); ``hint`` is an optional trailing suggestion (e.g. ``"Use
2613
- --kind symbol to narrow resolve."``). Callers whose kind-dispatch is more
2614
- complex (e.g. ``callers`` accepts Symbol OR Route and routes between them)
2615
- keep an inline guard.
2616
-
2617
- ``java_kinds`` / ``roles`` add an OPTIONAL Java-level check applied AFTER
2618
- the graph-label check passes. Graph ``kind=="symbol"`` covers class,
2619
- interface, enum, AND method alike, so a label-only guard lets a class
2620
- through a command that expects an interface (e.g. ``implementations``).
2621
- When provided, ``node.symbol_kind`` must be in ``java_kinds`` (lowercased,
2622
- dashes->underscores; e.g. ``("interface",)``) and ``node.role`` in
2623
- ``roles`` (case-insensitive); otherwise a clear ``status: error`` is
2624
- emitted instead of the silent empty result the backend returns.
2625
- """
2626
- from java_codebase_rag.jrag_envelope import Envelope
2627
- from java_codebase_rag.jrag_render import render
2628
-
2629
- def _emit(msg: str) -> int:
2630
- if hint:
2631
- msg = f"{msg} {hint}"
2632
- print(render(Envelope(status="error", message=msg), fmt=args.format, detail=args.detail))
2633
- return 2
2634
-
2635
- if node.kind not in kinds:
2636
- return _emit(f"{expected}; resolved kind is {node.kind!r}.")
2637
-
2638
- # Java-level guard (optional): symbol_kind / role on the resolved NodeRef.
2639
- # symbol_kind is stored LOWERCASE (class/method/interface/...); normalize
2640
- # both sides to lowercase + dashes->underscores before comparing.
2641
- if java_kinds:
2642
- actual = (node.symbol_kind or "").lower().replace("-", "_")
2643
- want = tuple(k.lower().replace("-", "_") for k in java_kinds)
2644
- if actual not in want:
2645
- return _emit(
2646
- f"{expected}; resolved Java kind is {node.symbol_kind!r} "
2647
- f"(expected {' or '.join(java_kinds)})."
2648
- )
2649
- if roles:
2650
- actual_role = (node.role or "").upper()
2651
- want_roles = tuple(r.upper() for r in roles)
2652
- if actual_role not in want_roles:
2653
- return _emit(
2654
- f"{expected}; resolved role is {node.role!r} "
2655
- f"(expected {' or '.join(roles)})."
2656
- )
2657
- return None
2658
-
2659
-
2660
- def _validate_known_microservice(graph, name: str, args: argparse.Namespace) -> int | None:
2661
- """Return ``None`` when ``name`` is a known microservice; else emit a
2662
- ``status: error`` envelope and return 2.
2663
-
2664
- Used by ``connection``/``overview`` so a BOGUS microservice surfaces a clear
2665
- "unknown microservice 'X'; run `jrag microservices`" error instead of an
2666
- empty ``status: ok`` (which reads as "this service genuinely has no
2667
- connections/entries" — a silent wrong answer).
2668
- """
2669
- from java_codebase_rag.jrag_envelope import Envelope
2670
- from java_codebase_rag.jrag_render import render
2671
-
2672
- try:
2673
- known = graph.microservice_counts()
2674
- except Exception:
2675
- known = {}
2676
- if name in known:
2677
- return None
2678
- msg = f"unknown microservice {name!r}; run `jrag microservices` to list known services"
2679
- print(render(Envelope(status="error", message=msg), fmt=args.format, detail=args.detail))
2680
- return 2
2681
-
2682
-
2683
- def _warn_unapplied_scope(args: argparse.Namespace, *, reason: str) -> list[str]:
2684
- """Build warnings[] for --service/--module that cannot be applied.
2685
-
2686
- Used by hierarchy/overrides/overridden-by/flow, where the backend query
2687
- has no microservice/module predicate (structural edges / index-time data
2688
- property). The plan principle "inapplicable flags never silently ignored"
2689
- requires surfacing these as warnings rather than dropping them.
2690
- """
2691
- warnings: list[str] = []
2692
- if args.service:
2693
- warnings.append(f"--service is not applied on this command ({reason})")
2694
- if getattr(args, "module", None):
2695
- warnings.append(f"--module is not applied on this command ({reason})")
2696
- return warnings
2697
-
2698
-
2699
- def _warn_inapplicable_common(
2700
- args: argparse.Namespace, *, service: bool, module: bool, limit: bool
2701
- ) -> list[str]:
2702
- """Warn when common flags that don't apply to a command are set.
2703
-
2704
- Companion to :func:`_warn_unapplied_scope` for the aggregate / orientation
2705
- commands (status / microservices / map / conventions) which inherit the
2706
- ``common`` parent parser (``--service`` / ``--module`` / ``--limit``) but
2707
- don't apply all of them. Each kwarg names whether THAT flag is inapplicable
2708
- for this command (``True`` -> warn if the user set it). The plan principle
2709
- "inapplicable flags never silently ignored" requires the warning; with the
2710
- renderer now printing ``warning:`` lines, this is visible to text consumers
2711
- too (not just ``--format json``).
2712
- """
2713
- warnings: list[str] = []
2714
- if service and args.service:
2715
- warnings.append("--service is not applied on this command")
2716
- if module and getattr(args, "module", None):
2717
- warnings.append("--module is not applied on this command")
2718
- if limit and getattr(args, "limit", None) is not None and args.limit != 20:
2719
- warnings.append("--limit is not applied on this command")
2720
- return warnings
2721
-
2722
-
2723
- def _cmd_callers(args: argparse.Namespace) -> int:
2724
- cfg, graph, rc = _load_graph_or_error(args)
2725
- if rc:
2726
- return rc
2727
- from java_codebase_rag.read_payloads import PayloadError, callers_payload
2728
- from java_codebase_rag.watch.client import get_payload
2729
-
2730
- try:
2731
- payload = get_payload("callers", vars(args), cfg, cold_core=callers_payload)
2732
- except PayloadError as pe:
2733
- # Resolve-miss: route through _emit so --exists/--count shape it
2734
- # (callers Missing --exists -> false, rc 2), mirroring master's
2735
- # _resolve_traversal_node resolve-miss path.
2736
- return _emit(pe.env, args)
2737
- return _emit_traversal(
2738
- args, root_id=payload["root_id"], nodes=payload["nodes"], edges=payload["edges"],
2739
- noun=payload["noun"], warnings=payload["warnings"], truncated=payload["truncated"],
2740
- is_external_entrypoint=payload["is_external_entrypoint"],
2741
- )
2742
-
2743
-
2744
- def _cmd_callees(args: argparse.Namespace) -> int:
2745
- cfg, graph, rc = _load_graph_or_error(args)
2746
- if rc:
2747
- return rc
2748
- from java_codebase_rag.read_payloads import PayloadError, callees_payload
2749
- from java_codebase_rag.watch.client import get_payload
2750
-
2751
- try:
2752
- payload = get_payload("callees", vars(args), cfg, cold_core=callees_payload)
2753
- except PayloadError as pe:
2754
- # Resolve-miss: route through _emit so --exists/--count shape it
2755
- # (callees Missing --exists -> false, rc 2), mirroring master's
2756
- # _resolve_traversal_node resolve-miss path.
2757
- return _emit(pe.env, args)
2758
- return _emit_traversal(
2759
- args, root_id=payload["root_id"], nodes=payload["nodes"], edges=payload["edges"],
2760
- noun=payload["noun"], warnings=payload["warnings"], truncated=payload["truncated"],
2761
- is_external_entrypoint=payload["is_external_entrypoint"],
2762
- )
2763
-
2764
-
2765
-
2766
- def _cmd_hierarchy(args: argparse.Namespace) -> int:
2767
- from java_codebase_rag.mcp import mcp_v2
2768
-
2769
- cfg, graph, rc = _load_graph_or_error(args)
2770
- if rc:
2771
- return rc
2772
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
2773
- if rrc or node is None:
2774
- return rrc
2775
- limit = _clamped_limit(args)
2776
-
2777
- guard = _require_kind(
2778
- node, expected="hierarchy expects a type Symbol root", kinds=("symbol",), args=args,
2779
- )
2780
- if guard is not None:
2781
- return guard
2782
-
2783
- warnings = _warn_unapplied_scope(
2784
- args, reason="neighbors_v2 walks structural EXTENDS/IMPLEMENTS edges with no microservice predicate"
2785
- )
2786
-
2787
- root_id = node.id
2788
- # Fetch both directions with limit+1 for +1-fetch truncation on each axis.
2789
- fetch = limit + 1
2790
- up = mcp_v2.neighbors_v2(
2791
- [root_id], direction="out", edge_types=["EXTENDS", "IMPLEMENTS"],
2792
- limit=fetch, graph=graph,
2793
- )
2794
- dn = mcp_v2.neighbors_v2(
2795
- [root_id], direction="in", edge_types=["EXTENDS", "IMPLEMENTS"],
2796
- limit=fetch, graph=graph,
2797
- )
2798
- from java_codebase_rag.jrag_envelope import Envelope
2799
- from java_codebase_rag.jrag_render import render
2800
-
2801
- if not up.success:
2802
- print(render(Envelope(status="error", message=up.message or "neighbors_v2 failed"), fmt=args.format, detail=args.detail))
2803
- return 2
2804
-
2805
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
2806
- # Build up/down edges separately so the limit applies PER DIRECTION
2807
- # (Fix 5: combined-list truncation could starve `down` behind a full `up`).
2808
- up_edges: list[dict] = []
2809
- for e in up.results:
2810
- nodes[e.other.id] = _noderef_to_node_dict(e.other)
2811
- up_edges.append({"other_id": e.other.id, "edge_type": e.edge_type, "direction": "up"})
2812
- dn_edges: list[dict] = []
2813
- for e in dn.results:
2814
- nodes[e.other.id] = _noderef_to_node_dict(e.other)
2815
- dn_edges.append({"other_id": e.other.id, "edge_type": e.edge_type, "direction": "down"})
2816
-
2817
- # Per-direction +1-fetch truncation: each side independently drops its
2818
- # overflow row and flags truncation if it had limit+1 rows.
2819
- truncated = len(up_edges) > limit or len(dn_edges) > limit
2820
- up_display = up_edges[:limit]
2821
- dn_display = dn_edges[:limit]
2822
- display_edges = up_display + dn_display
2823
- # Drop nodes no longer referenced after per-direction truncation (keep root).
2824
- referenced = {root_id} | {e["other_id"] for e in display_edges}
2825
- nodes = {nid: nd for nid, nd in nodes.items() if nid in referenced}
2826
- return _emit_traversal(
2827
- args, root_id=root_id, nodes=nodes, edges=display_edges,
2828
- noun="hierarchy", warnings=warnings, truncated=truncated,
2829
- )
2830
-
2831
-
2832
- def _cmd_implementations(args: argparse.Namespace) -> int:
2833
- cfg, graph, rc = _load_graph_or_error(args)
2834
- if rc:
2835
- return rc
2836
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
2837
- if rrc or node is None:
2838
- return rrc
2839
- limit = _clamped_limit(args)
2840
-
2841
- guard = _require_kind(
2842
- node, expected="implementations expects an interface Symbol root", kinds=("symbol",),
2843
- java_kinds=("interface",), args=args,
2844
- )
2845
- if guard is not None:
2846
- return guard
2847
-
2848
- from java_codebase_rag.jrag_envelope import mark_truncated
2849
-
2850
- # ADAPTATION: find_implementors DOES accept a `capability` kwarg (brief
2851
- # claimed otherwise). Push --capability down (matches the global principle
2852
- # "pushed down where the method takes it"); --service/--module also pushed.
2853
- impls = graph.find_implementors(
2854
- node.fqn,
2855
- microservice=args.service,
2856
- module=args.module,
2857
- capability=args.capability,
2858
- limit=limit + 1,
2859
- )
2860
- display, truncated = mark_truncated(impls, limit)
2861
- root_id = node.id
2862
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
2863
- edges: list[dict] = []
2864
- for hit in display:
2865
- nodes[hit.id] = _symbol_hit_to_dict(hit)
2866
- edges.append({"other_id": hit.id, "edge_type": "IMPLEMENTS"})
2867
- return _emit_traversal(
2868
- args, root_id=root_id, nodes=nodes, edges=edges,
2869
- noun="implementations", truncated=truncated,
2870
- )
2871
-
2872
-
2873
- def _cmd_subclasses(args: argparse.Namespace) -> int:
2874
- cfg, graph, rc = _load_graph_or_error(args)
2875
- if rc:
2876
- return rc
2877
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
2878
- if rrc or node is None:
2879
- return rrc
2880
- limit = _clamped_limit(args)
2881
-
2882
- guard = _require_kind(
2883
- node, expected="subclasses expects a class Symbol root", kinds=("symbol",),
2884
- java_kinds=("class", "interface"), args=args,
2885
- )
2886
- if guard is not None:
2887
- return guard
2888
-
2889
- from java_codebase_rag.jrag_envelope import mark_truncated
2890
-
2891
- subs = graph.find_subclasses(
2892
- node.fqn,
2893
- microservice=args.service,
2894
- module=args.module,
2895
- limit=limit + 1,
2896
- )
2897
- display, truncated = mark_truncated(subs, limit)
2898
- root_id = node.id
2899
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
2900
- edges: list[dict] = []
2901
- for hit in display:
2902
- nodes[hit.id] = _symbol_hit_to_dict(hit)
2903
- edges.append({"other_id": hit.id, "edge_type": "EXTENDS"})
2904
- # Cross-ref hint: when the root is an interface, classes implementing it
2905
- # arrive via IMPLEMENTS (not EXTENDS) — `find_subclasses` (EXTENDS inbound)
2906
- # only catches sub-interfaces, so the common agent question "what classes
2907
- # implement this interface?" is answered by `implementations <fqn>`. Surface
2908
- # that as a `next:` hint whenever the root is an interface (helpful even
2909
- # when a few sub-interfaces exist, and essential when results are empty).
2910
- extra_hints: list[str] | None = None
2911
- if (node.symbol_kind or "").lower() == "interface":
2912
- extra_hints = [f"jrag implementations {node.fqn}"]
2913
- return _emit_traversal(
2914
- args, root_id=root_id, nodes=nodes, edges=edges,
2915
- noun="subclasses", truncated=truncated, extra_hints=extra_hints,
2916
- )
2917
-
2918
-
2919
- def _cmd_overrides(args: argparse.Namespace) -> int:
2920
- from java_codebase_rag.mcp import mcp_v2
2921
-
2922
- cfg, graph, rc = _load_graph_or_error(args)
2923
- if rc:
2924
- return rc
2925
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
2926
- if rrc or node is None:
2927
- return rrc
2928
- limit = _clamped_limit(args)
2929
-
2930
- from java_codebase_rag.jrag_envelope import Envelope
2931
- from java_codebase_rag.jrag_render import render
2932
-
2933
- guard = _require_kind(
2934
- node, expected="overrides expects a method Symbol root", kinds=("symbol",),
2935
- java_kinds=("method",), args=args,
2936
- )
2937
- if guard is not None:
2938
- return guard
2939
-
2940
- warnings = _warn_unapplied_scope(
2941
- args, reason="OVERRIDES is a structural method-to-method edge with no microservice predicate"
2942
- )
2943
-
2944
- root_id = node.id
2945
- # OVERRIDES edge runs overrider -> declaration (subtype -> supertype method).
2946
- # direction="out" dispatches UP (the declarations this method overrides).
2947
- out = mcp_v2.neighbors_v2(
2948
- [root_id], direction="out", edge_types=["OVERRIDES"],
2949
- limit=limit + 1, graph=graph,
2950
- )
2951
- if not out.success:
2952
- print(render(Envelope(status="error", message=out.message or "neighbors_v2 failed"), fmt=args.format, detail=args.detail))
2953
- return 2
2954
-
2955
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
2956
- edges: list[dict] = []
2957
- for e in out.results:
2958
- nodes[e.other.id] = _noderef_to_node_dict(e.other)
2959
- # No `direction` key: overrides is a flat list, not a tree. Setting
2960
- # direction="up" would trip the renderer's has_direction guard and
2961
- # mis-label these rows as `↑ supertypes:` (hierarchy). Flat is correct.
2962
- edges.append({"other_id": e.other.id, "edge_type": "OVERRIDES"})
2963
- truncated = bool(out.has_more_results) or len(edges) > limit
2964
- if len(edges) > limit:
2965
- edges = edges[:limit]
2966
- return _emit_traversal(
2967
- args, root_id=root_id, nodes=nodes, edges=edges,
2968
- noun="overrides", warnings=warnings, truncated=truncated,
2969
- )
2970
-
2971
-
2972
- def _cmd_overridden_by(args: argparse.Namespace) -> int:
2973
- from java_codebase_rag.mcp import mcp_v2
2974
-
2975
- cfg, graph, rc = _load_graph_or_error(args)
2976
- if rc:
2977
- return rc
2978
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
2979
- if rrc or node is None:
2980
- return rrc
2981
- limit = _clamped_limit(args)
2982
-
2983
- from java_codebase_rag.jrag_envelope import Envelope
2984
- from java_codebase_rag.jrag_render import render
2985
-
2986
- guard = _require_kind(
2987
- node, expected="overridden-by expects a method Symbol root", kinds=("symbol",),
2988
- java_kinds=("method",), args=args,
2989
- )
2990
- if guard is not None:
2991
- return guard
2992
-
2993
- warnings = _warn_unapplied_scope(
2994
- args, reason="OVERRIDES is a structural method-to-method edge with no microservice predicate"
2995
- )
2996
-
2997
- root_id = node.id
2998
- # direction="in" on OVERRIDES = virtual OVERRIDDEN_BY out (dispatch DOWN:
2999
- # from declaration to its overriders).
3000
- out = mcp_v2.neighbors_v2(
3001
- [root_id], direction="in", edge_types=["OVERRIDES"],
3002
- limit=limit + 1, graph=graph,
3003
- )
3004
- if not out.success:
3005
- print(render(Envelope(status="error", message=out.message or "neighbors_v2 failed"), fmt=args.format, detail=args.detail))
3006
- return 2
3007
-
3008
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
3009
- edges: list[dict] = []
3010
- for e in out.results:
3011
- nodes[e.other.id] = _noderef_to_node_dict(e.other)
3012
- # No `direction` key — see _cmd_overrides: a `direction` value would
3013
- # route these into the hierarchy renderer (`↓ subtypes:`), mis-labeling
3014
- # a flat overridden-by list.
3015
- edges.append({"other_id": e.other.id, "edge_type": "OVERRIDES"})
3016
- truncated = bool(out.has_more_results) or len(edges) > limit
3017
- if len(edges) > limit:
3018
- edges = edges[:limit]
3019
- return _emit_traversal(
3020
- args, root_id=root_id, nodes=nodes, edges=edges,
3021
- noun="overridden-by", warnings=warnings, truncated=truncated,
3022
- )
3023
-
3024
-
3025
- def _cmd_dependents(args: argparse.Namespace) -> int:
3026
- cfg, graph, rc = _load_graph_or_error(args)
3027
- if rc:
3028
- return rc
3029
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
3030
- if rrc or node is None:
3031
- return rrc
3032
- limit = _clamped_limit(args)
3033
-
3034
- guard = _require_kind(
3035
- node, expected="dependents expects a type Symbol root", kinds=("symbol",), args=args,
3036
- )
3037
- if guard is not None:
3038
- return guard
3039
-
3040
- from java_codebase_rag.jrag_envelope import mark_truncated
3041
-
3042
- inj = graph.find_injectors(
3043
- node.fqn,
3044
- microservice=args.service,
3045
- module=args.module,
3046
- limit=limit + 1,
3047
- )
3048
- display, truncated = mark_truncated(inj, limit)
3049
- root_id = node.id
3050
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
3051
- edges: list[dict] = []
3052
- for eh in display:
3053
- nodes[eh.src.id] = _symbol_hit_to_dict(eh.src)
3054
- edges.append(
3055
- {
3056
- "other_id": eh.src.id,
3057
- "edge_type": "INJECTS",
3058
- "mechanism": eh.mechanism,
3059
- "annotation": eh.annotation,
3060
- "field_or_param": eh.field_or_param,
3061
- }
3062
- )
3063
- return _emit_traversal(
3064
- args, root_id=root_id, nodes=nodes, edges=edges,
3065
- noun="dependents", truncated=truncated,
3066
- )
3067
-
3068
-
3069
- def _cmd_impact(args: argparse.Namespace) -> int:
3070
- cfg, graph, rc = _load_graph_or_error(args)
3071
- if rc:
3072
- return rc
3073
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
3074
- if rrc or node is None:
3075
- return rrc
3076
- limit = _clamped_limit(args)
3077
- depth = getattr(args, "depth", 2)
3078
-
3079
- from java_codebase_rag.jrag_envelope import mark_truncated
3080
-
3081
- impacts = graph.impact_analysis(node.fqn, depth=depth, limit=limit + 1)
3082
- warnings: list[str] = []
3083
- if args.service:
3084
- # Filter client-side (impact_analysis has no microservice param). The
3085
- # explanatory warning fires only when the caller EXPLICITLY passed
3086
- # --service: under cwd-derived auto-scope the filter still applies
3087
- # (that's the point — keep the blast-radius inside the working
3088
- # service) but the "post-filter" caveat would be noise the agent
3089
- # didn't ask for, so it's gated on ``_service_user``.
3090
- impacts = [h for h in impacts if (h.microservice or "") == args.service]
3091
- if getattr(args, "_service_user", False):
3092
- warnings.append(
3093
- "--service is a post-filter on impact (impact_analysis has no microservice param)"
3094
- )
3095
- if getattr(args, "module", None):
3096
- # impact_analysis has no module param either; warn rather than drop silently.
3097
- warnings.append(
3098
- "--module is not applied on impact (impact_analysis has no module param)"
3099
- )
3100
- display, truncated = mark_truncated(impacts, limit)
3101
- root_id = node.id
3102
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
3103
- edges: list[dict] = []
3104
- for hit in display:
3105
- nodes[hit.id] = _symbol_hit_to_dict(hit)
3106
- edges.append({"other_id": hit.id, "edge_type": "IMPACTS"})
3107
- return _emit_traversal(
3108
- args, root_id=root_id, nodes=nodes, edges=edges,
3109
- noun="impact", warnings=warnings, truncated=truncated,
3110
- )
3111
-
3112
-
3113
- def _cmd_decompose(args: argparse.Namespace) -> int:
3114
- cfg, graph, rc = _load_graph_or_error(args)
3115
- if rc:
3116
- return rc
3117
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
3118
- if rrc or node is None:
3119
- return rrc
3120
-
3121
- guard = _require_kind(
3122
- node, expected="decompose expects an entrypoint Symbol root", kinds=("symbol",), args=args,
3123
- )
3124
- if guard is not None:
3125
- return guard
3126
-
3127
- # trace_flow clamps depth internally to 1..3; mirror here for the help text.
3128
- depth = max(1, min(3, getattr(args, "depth", 2)))
3129
- # decompose walks a TYPE role-waterfall (CONTROLLER -> SERVICE/COMPONENT ->
3130
- # CLIENT/REPOSITORY/MAPPER) via INJECTS/EXTENDS/IMPLEMENTS, which are
3131
- # type-to-type edges. A METHOD seed has no such edges, so trace_flow would
3132
- # return only stage 0 (the seed itself). Promote a method seed to its owning
3133
- # type so the waterfall is meaningful; point the agent at `callees` for the
3134
- # method's direct call chain. (root stays the resolved method node.)
3135
- seed_fqn = node.fqn
3136
- warnings: list[str] = []
3137
- if seed_fqn and "#" in seed_fqn:
3138
- owning_type = seed_fqn.split("#", 1)[0]
3139
- warnings.append(
3140
- f"decompose is a type role-waterfall; promoted method seed "
3141
- f"'{seed_fqn}' to its owning type '{owning_type}'. "
3142
- f"Use `jrag callees {seed_fqn}` for the method's direct call chain."
3143
- )
3144
- seed_fqn = owning_type
3145
- stages = graph.trace_flow(
3146
- seed_fqns=[seed_fqn],
3147
- depth=depth,
3148
- follow_calls=getattr(args, "follow_calls", True),
3149
- stage_limit=getattr(args, "per_stage_limit", 20),
3150
- min_call_confidence=getattr(args, "min_confidence", 0.0),
3151
- exclude_external=not getattr(args, "include_external", False),
3152
- microservice=args.service,
3153
- module=args.module,
3154
- )
3155
- root_id = node.id
3156
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
3157
- edges: list[dict] = []
3158
- for stage_idx, stage in enumerate(stages):
3159
- for ss in stage:
3160
- nodes[ss.symbol.id] = _symbol_hit_to_dict(ss.symbol)
3161
- via = ss.via[0] if ss.via else None
3162
- edge_type = via.edge_type if via else ("SEED" if stage_idx == 0 else "STAGE")
3163
- edge_row = {
3164
- "other_id": ss.symbol.id,
3165
- "edge_type": edge_type,
3166
- "stage": stage_idx,
3167
- # Role carries through to the renderer so the waterfall can
3168
- # label each stage with the role allow-list it matched.
3169
- "role": ss.symbol.role or "",
3170
- }
3171
- if via and via.from_fqn:
3172
- edge_row["from_fqn"] = via.from_fqn
3173
- edges.append(edge_row)
3174
- # --limit is inherited from common but does not cap decompose (trace_flow
3175
- # is stage-limited via --per-stage-limit, not a total edge count). Warn when the
3176
- # user explicitly set --limit away from the default so they get a signal
3177
- # rather than a silent multi-stage dump (Fix 4).
3178
- if args.limit is not None and args.limit != 20:
3179
- warnings.append(
3180
- "--limit does not apply to decompose; use --per-stage-limit to cap per-stage breadth"
3181
- )
3182
- return _emit_traversal(
3183
- args, root_id=root_id, nodes=nodes, edges=edges,
3184
- noun="decompose", warnings=warnings,
3185
- )
3186
-
3187
-
3188
- def _cmd_flow(args: argparse.Namespace) -> int:
3189
- cfg, graph, rc = _load_graph_or_error(args)
3190
- if rc:
3191
- return rc
3192
- from java_codebase_rag.read_payloads import PayloadError, flow_payload
3193
- from java_codebase_rag.watch.client import get_payload
3194
-
3195
- try:
3196
- payload = get_payload("flow", vars(args), cfg, cold_core=flow_payload)
3197
- except PayloadError as pe:
3198
- # Resolve-miss: route through _emit so --exists/--count shape it
3199
- # (flow Missing --exists -> false, rc 2), mirroring master's
3200
- # _resolve_traversal_node resolve-miss path.
3201
- return _emit(pe.env, args)
3202
- return _emit_traversal(
3203
- args, root_id=payload["root_id"], nodes=payload["nodes"], edges=payload["edges"],
3204
- noun=payload["noun"], warnings=payload["warnings"], truncated=payload["truncated"],
3205
- is_external_entrypoint=payload["is_external_entrypoint"],
3206
- )
3207
-
3208
-
3209
-
3210
- def _cmd_dependencies(args: argparse.Namespace) -> int:
3211
- from java_codebase_rag.mcp import mcp_v2
3212
-
3213
- cfg, graph, rc = _load_graph_or_error(args)
3214
- if rc:
3215
- return rc
3216
- node, _renv, rrc = _resolve_traversal_node(args, cfg=cfg, graph=graph, hint_kind=args.kind)
3217
- if rrc or node is None:
3218
- return rrc
3219
- limit = _clamped_limit(args)
3220
-
3221
- from java_codebase_rag.jrag_envelope import Envelope
3222
- from java_codebase_rag.jrag_render import render
3223
-
3224
- # INJECTS is Symbol -> Symbol; Client/Producer/Route roots have no
3225
- # injection edges (the edge type only fires on type Symbols).
3226
- guard = _require_kind(
3227
- node, expected="dependencies expects a Symbol root (INJECTS is Symbol -> Symbol)",
3228
- kinds=("symbol",), args=args,
3229
- )
3230
- if guard is not None:
3231
- return guard
3232
-
3233
- warnings = _warn_unapplied_scope(
3234
- args, reason="neighbors_v2 walks structural INJECTS edges with no microservice predicate"
3235
- )
3236
- # --include-external is accepted for surface symmetry with callers/callees
3237
- # but is a warned no-op here (INJECTS has no external-exclusion analog at
3238
- # the neighbors_v2 layer; the edge is structural Symbol -> Symbol).
3239
- if getattr(args, "include_external", False):
3240
- warnings.append(
3241
- "--include-external does not apply to dependencies "
3242
- "(INJECTS is structural Symbol -> Symbol with no external-exclusion analog)"
3243
- )
3244
-
3245
- root_id = node.id
3246
- out = mcp_v2.neighbors_v2(
3247
- [root_id], direction="out", edge_types=["INJECTS"],
3248
- limit=limit + 1, graph=graph,
3249
- )
3250
- if not out.success:
3251
- print(render(Envelope(status="error", message=out.message or "neighbors_v2 failed"), fmt=args.format, detail=args.detail))
3252
- return 2
3253
-
3254
- nodes: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
3255
- edges: list[dict] = []
3256
- for e in out.results:
3257
- nodes[e.other.id] = _noderef_to_node_dict(e.other)
3258
- # Carry the injection metadata from the edge attrs (mechanism/annotation/
3259
- # field_or_param) so the renderer and JSON consumers see how the dep is
3260
- # injected.
3261
- edge_row = {"other_id": e.other.id, "edge_type": "INJECTS"}
3262
- for k in ("mechanism", "annotation", "field_or_param", "dst_fqn", "resolved"):
3263
- if k in e.attrs:
3264
- edge_row[k] = e.attrs[k]
3265
- edges.append(edge_row)
3266
- truncated = bool(out.has_more_results) or len(edges) > limit
3267
- if len(edges) > limit:
3268
- edges = edges[:limit]
3269
- return _emit_traversal(
3270
- args, root_id=root_id, nodes=nodes, edges=edges,
3271
- noun="dependencies", warnings=warnings, truncated=truncated,
3272
- )
3273
-
3274
-
3275
- def _client_dict_to_node(c: dict) -> dict:
3276
- """list_clients dict -> envelope node dict (kind=client)."""
3277
- return {
3278
- "id": str(c.get("id") or ""),
3279
- "kind": "client",
3280
- "fqn": str(c.get("member_fqn") or c.get("path") or ""),
3281
- "name": str(c.get("path") or ""),
3282
- "client_kind": str(c.get("client_kind") or ""),
3283
- "target_service": str(c.get("target_service") or ""),
3284
- "method": str(c.get("method") or ""),
3285
- "path": str(c.get("path") or ""),
3286
- "microservice": str(c.get("microservice") or ""),
3287
- "module": str(c.get("module") or ""),
3288
- }
3289
-
3290
-
3291
- def _producer_dict_to_node(p: dict) -> dict:
3292
- """list_producers dict -> envelope node dict (kind=producer)."""
3293
- return {
3294
- "id": str(p.get("id") or ""),
3295
- "kind": "producer",
3296
- "fqn": str(p.get("member_fqn") or p.get("topic") or ""),
3297
- "name": str(p.get("topic") or ""),
3298
- "producer_kind": str(p.get("producer_kind") or ""),
3299
- "topic": str(p.get("topic") or ""),
3300
- "broker": str(p.get("broker") or ""),
3301
- "microservice": str(p.get("microservice") or ""),
3302
- "module": str(p.get("module") or ""),
3303
- }
3304
-
3305
-
3306
- def _cmd_connection(args: argparse.Namespace) -> int:
3307
- """connection <microservice> — multi-section inbound:/outbound: view.
3308
-
3309
- RESOLVE-FIRST EXCEPTION: the first positional is a microservice NAME (used
3310
- literally for list_clients / list_producers / find_route_callers); resolve_v2
3311
- is NEVER run on it (the agent spec calls this out loudly in --help).
3312
- """
3313
- cfg, graph, rc = _load_graph_or_error(args)
3314
- if rc:
3315
- return rc
3316
- limit = _clamped_limit(args)
3317
-
3318
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
3319
-
3320
- # Validate the microservice against the known set so a bogus name surfaces a
3321
- # clear error instead of an empty inbound:/outbound: view (silent wrong
3322
- # answer). Done AFTER graph load so `jrag connection X --format json` on a
3323
- # missing index still reports the index error, not the microservice error.
3324
- rc_ms = _validate_known_microservice(graph, args.microservice, args)
3325
- if rc_ms is not None:
3326
- return rc_ms
3327
-
3328
- microservice = args.microservice
3329
- # argparse stores --inbound/--outbound/--both into `direction` via
3330
- # action="store_const"; default is None when no flag is given (-> inbound,
3331
- # per the brief: --inbound is the default direction).
3332
- direction = getattr(args, "direction", None) or "both"
3333
- http_method = (args.http_method or "").upper() or None
3334
- calls_service = args.calls_service
3335
-
3336
- show_inbound = direction in ("inbound", "both")
3337
- show_outbound = direction in ("outbound", "both")
3338
-
3339
- nodes: dict[str, dict] = {}
3340
- edges: list[dict] = []
3341
- warnings: list[str] = []
3342
-
3343
- # Filter predicates (applied client-side; --module is the only structural
3344
- # common flag that's a bit meaningful here, but list_clients/list_producers
3345
- # already take microservice; --module has no analog and is warned).
3346
- if args.module:
3347
- warnings.append("--module is not applied on connection (use --calls-service to narrow)")
3348
-
3349
- # --calls-service on outbound: clients are filtered STRICTLY (target_service
3350
- # == calls_service); producers have no service target (they target topics),
3351
- # so they bypass the filter and we emit a single warning so the agent knows
3352
- # the async channel wasn't narrowed. The previous `or not target_service`
3353
- # escape hatch matched unresolved clients (empty target_service, e.g.
3354
- # AuditLogClient#logAssignment) — that was silent-wrong-results.
3355
- producers_bypass_calls_service = bool(calls_service) and show_outbound
3356
-
3357
- def _http_method_match(row: dict) -> bool:
3358
- if not http_method:
3359
- return True
3360
- return (str(row.get("method") or "").upper()) == http_method
3361
-
3362
- def _calls_service_match_out_client(row: dict) -> bool:
3363
- # STRICT: a client is kept iff target_service == calls_service exactly.
3364
- # Unresolved clients (empty target_service) are EXCLUDED — they did not
3365
- # resolve to a specific target service, so we cannot confirm they call
3366
- # --calls-service and must not surface them as a match.
3367
- if not calls_service:
3368
- return True
3369
- return str(row.get("target_service") or "") == calls_service
3370
-
3371
- def _calls_service_match_in(caller_microservice: str) -> bool:
3372
- if not calls_service:
3373
- return True
3374
- return caller_microservice == calls_service
3375
-
3376
- # --- Inbound: clients/producers in OTHER services targeting <microservice> ---
3377
- if show_inbound:
3378
- # HTTP: list_clients(target_service=microservice) gives every client
3379
- # declaring a call into this service. Filter out clients IN this
3380
- # microservice (those are intra-service, not inbound).
3381
- http_in = graph.list_clients(target_service=microservice, limit=limit + 1)
3382
- http_in = [c for c in http_in if (c.get("microservice") or "") != microservice]
3383
- http_in = [c for c in http_in if _http_method_match(c) and _calls_service_match_in(c.get("microservice") or "")]
3384
- for c in http_in[:limit + 1]:
3385
- cid = c["id"]
3386
- nodes[cid] = _client_dict_to_node(c)
3387
- edges.append({"other_id": cid, "edge_type": "HTTP_CALLS", "section": "inbound"})
3388
-
3389
- # Async: topic Routes consumed by this microservice's listeners are
3390
- # reached by producers in OTHER services via ASYNC_CALLS. The path is
3391
- # listener_method -[:EXPOSES]-> Route(topic) <-[:ASYNC_CALLS]- Producer
3392
- # find_route_callers gives both client and producer callers for a route,
3393
- # so we (a) enumerate this service's listener classes, (b) for each,
3394
- # resolve the Route(s) it EXPOSES, (c) call find_route_callers on each
3395
- # topic Route, (d) keep producer callers from other services.
3396
- try:
3397
- listener_hits = graph.list_by_capability(
3398
- capability="MESSAGE_LISTENER",
3399
- microservice=microservice,
3400
- limit=_CONSUMER_FETCH_LIMIT,
3401
- )
3402
- except Exception as e: # noqa: BLE001 - best-effort multi-section view
3403
- # Don't swallow silently: surface the failure so an empty async
3404
- # inbound section is distinguishable from "no listeners". HTTP
3405
- # inbound above is unaffected; the command still returns its other
3406
- # sections. (The bare `except: listener_hits = []` this replaces
3407
- # produced silent wrong-results — status:ok with no async + no clue.)
3408
- warnings.append(f"listener lookup failed; async inbound section skipped: {e}")
3409
- listener_hits = []
3410
- topic_route_ids: set[str] = set()
3411
- for h in listener_hits:
3412
- # listener method -> EXPOSES -> Route(topic). Resolve via a focused
3413
- # Cypher lookup (Route.id for the EXPOSES target).
3414
- rows = graph._rows( # noqa: SLF001 - focused lookup, same pattern as _node_file_location
3415
- "MATCH (mth:Symbol)-[:EXPOSES]->(r:Route) WHERE mth.id = $mid RETURN r.id AS rid",
3416
- {"mid": h.id},
3417
- )
3418
- for r in rows:
3419
- rid = str(r.get("rid") or "")
3420
- if rid:
3421
- topic_route_ids.add(rid)
3422
- # Cache list_producers() per caller_microservice so the inbound-async
3423
- # loop issues ONE fetch per external service (not one per producer id).
3424
- producer_cache: dict[str, list[dict]] = {}
3425
- for rid in topic_route_ids:
3426
- callers = graph.find_route_callers(route_id=rid)
3427
- for c in callers:
3428
- if c.caller_node_kind != "producer":
3429
- continue
3430
- if (c.caller_microservice or "") == microservice:
3431
- continue # intra-service
3432
- if not _calls_service_match_in(c.caller_microservice or ""):
3433
- continue
3434
- pid = c.caller_node_id
3435
- if pid in nodes:
3436
- # Already rendered (e.g. duplicated via multiple topic routes)
3437
- edges.append({"other_id": pid, "edge_type": "ASYNC_CALLS", "section": "inbound", "confidence": c.confidence})
3438
- continue
3439
- # Fetch producer dict for richer node data (cached per service).
3440
- caller_ms = c.caller_microservice or ""
3441
- if caller_ms not in producer_cache:
3442
- producer_cache[caller_ms] = graph.list_producers(
3443
- microservice=caller_ms or None, limit=_CONSUMER_FETCH_LIMIT,
3444
- )
3445
- prod_dict = next((p for p in producer_cache[caller_ms] if p.get("id") == pid), None)
3446
- if prod_dict:
3447
- nodes[pid] = _producer_dict_to_node(prod_dict)
3448
- else:
3449
- nodes[pid] = {
3450
- "id": pid,
3451
- "kind": "producer",
3452
- "fqn": c.topic or "",
3453
- "name": c.topic or "",
3454
- "topic": c.topic or "",
3455
- "broker": c.broker or "",
3456
- "microservice": c.caller_microservice or "",
3457
- }
3458
- edges.append({"other_id": pid, "edge_type": "ASYNC_CALLS", "section": "inbound", "confidence": c.confidence})
3459
-
3460
- # --- Outbound: clients/producers IN this microservice (calling out) ---
3461
- if show_outbound:
3462
- clients_out = graph.list_clients(microservice=microservice, limit=limit + 1)
3463
- # Clients: apply --http-method AND --calls-service strictly (no empty-
3464
- # target escape; unresolved clients are EXCLUDED under --calls-service).
3465
- clients_out = [c for c in clients_out if _http_method_match(c) and _calls_service_match_out_client(c)]
3466
- for c in clients_out[:limit + 1]:
3467
- cid = c["id"]
3468
- nodes[cid] = _client_dict_to_node(c)
3469
- edges.append({"other_id": cid, "edge_type": "HTTP_CALLS", "section": "outbound"})
3470
-
3471
- producers_out = graph.list_producers(microservice=microservice, limit=limit + 1)
3472
- # Producers bypass --calls-service (no service target on ASYNC channels);
3473
- # emit ONE warning so the agent knows the async channel wasn't narrowed.
3474
- if producers_bypass_calls_service and producers_out:
3475
- warnings.append(
3476
- f"--calls-service does not filter producers (no target_service on "
3477
- f"ASYNC channels); {len(producers_out)} producer(s) kept visible"
3478
- )
3479
- for p in producers_out[:limit + 1]:
3480
- pid = p["id"]
3481
- nodes[pid] = _producer_dict_to_node(p)
3482
- edges.append({"other_id": pid, "edge_type": "ASYNC_CALLS", "section": "outbound"})
3483
-
3484
- # Synthesize a microservice "root" node so the renderer uses the traversal
3485
- # shape (root + edges) and the section-grouped rendering fires. The synthetic
3486
- # id is namespaced to avoid colliding with real node ids.
3487
- root_id = f"microservice:{microservice}"
3488
- nodes[root_id] = {
3489
- "id": root_id,
3490
- "kind": "microservice",
3491
- "fqn": microservice,
3492
- "name": microservice,
3493
- "microservice": microservice,
3494
- }
3495
-
3496
- # Per-section truncation: cap each section at `limit` (drop overflow rows
3497
- # and flag truncation if either side overflowed). We collected limit+1
3498
- # rows above; slice here.
3499
- inbound_edges = [e for e in edges if e.get("section") == "inbound"]
3500
- outbound_edges = [e for e in edges if e.get("section") == "outbound"]
3501
- truncated = len(inbound_edges) > limit or len(outbound_edges) > limit
3502
- inbound_edges = inbound_edges[:limit]
3503
- outbound_edges = outbound_edges[:limit]
3504
- display_edges = inbound_edges + outbound_edges
3505
- # Drop unreferenced node ids (keep the synthetic root).
3506
- referenced = {root_id} | {e["other_id"] for e in display_edges}
3507
- nodes = {nid: nd for nid, nd in nodes.items() if nid in referenced}
3508
-
3509
- env = Envelope(
3510
- status="ok",
3511
- nodes=nodes,
3512
- edges=display_edges,
3513
- root=root_id,
3514
- warnings=warnings,
3515
- truncated=truncated,
3516
- )
3517
- next_actions_hook(env, root=root_id, result_edges=display_edges)
3518
- return _emit(env, args, noun="connection")
3519
-
3520
-
3521
- def _resolve_source_path(cfg, file_arg: str) -> Path | None:
3522
- """Resolve <file> to an existing path: absolute, else cfg.source_root/<file>.
3523
-
3524
- Returns None when neither exists (callers render a graceful envelope).
3525
- """
3526
- p = Path(file_arg)
3527
- if p.is_absolute() and p.is_file():
3528
- return p
3529
- src = Path(cfg.source_root) if cfg.source_root else Path.cwd()
3530
- candidate = src / file_arg
3531
- if candidate.is_file():
3532
- return candidate
3533
- return None
3534
-
3535
-
3536
- def _cmd_outline(args: argparse.Namespace) -> int:
3537
- """outline <file> — list every Symbol whose declared location is in <file>.
3538
-
3539
- Calls find_symbols_in_file_range(graph, filename=<file>, start_line=1,
3540
- end_line=2**31-1). start_line MUST be >=1 (the backend returns [] for
3541
- start_line<1). ``--limit`` caps the entry count (the file's symbol table
3542
- is otherwise unbounded); ``truncated`` is set when more entries exist.
3543
- """
3544
- from java_codebase_rag.graph.ladybug_queries import find_symbols_in_file_range
3545
-
3546
- from java_codebase_rag.jrag_envelope import Envelope, mark_truncated, next_actions_hook
3547
- from java_codebase_rag.jrag_render import render
3548
-
3549
- cfg, graph, rc = _load_graph_or_error(args)
3550
- if rc:
3551
- return rc
3552
-
3553
- # PARITY with `imports`: resolve <file> via _resolve_source_path so a bare
3554
- # class name or non-existent path yields the SAME "file not found" error
3555
- # instead of a silent empty success. The graph stores filenames as
3556
- # POSIX-relative paths from source root, so once the path resolves on disk
3557
- # we re-derive that relative form for the exact-match query.
3558
- file_path = _resolve_source_path(cfg, args.file)
3559
- if file_path is None:
3560
- env = Envelope(
3561
- status="error",
3562
- message=(
3563
- f"file not found: {args.file!r} (looked at the literal path and at "
3564
- f"<source_root>/{args.file})"
3565
- ),
3566
- )
3567
- print(render(env, fmt=args.format, detail=args.detail))
3568
- return 2
3569
- filename = args.file
3570
- src_root = Path(cfg.source_root) if cfg.source_root else None
3571
- if src_root is not None:
3572
- try:
3573
- filename = file_path.resolve().relative_to(src_root.resolve()).as_posix()
3574
- except ValueError:
3575
- # File lives outside source_root (e.g. an absolute path elsewhere);
3576
- # fall back to the user's literal input — the graph may still match.
3577
- filename = args.file
3578
- try:
3579
- hits = find_symbols_in_file_range(
3580
- graph,
3581
- filename=filename,
3582
- start_line=1,
3583
- end_line=2**31 - 1,
3584
- )
3585
- except Exception as exc:
3586
- env = Envelope(status="error", message=f"outline failed: {exc}")
3587
- print(render(env, fmt=args.format, detail=args.detail))
3588
- return 2
3589
-
3590
- rows = [_symbol_hit_to_dict(h) for h in hits]
3591
- limit = _clamped_limit(args)
3592
- display, truncated = mark_truncated(rows, limit)
3593
- nodes = {n["id"]: n for n in display}
3594
-
3595
- env = Envelope(status="ok", nodes=nodes, truncated=truncated)
3596
- next_actions_hook(env)
3597
- # Drill-down: the first declared symbol (class/interface) is the natural
3598
- # thing to inspect from an outline. Per-row inspect hints for the leading
3599
- # entries give the agent a concrete next step.
3600
- env.agent_next_actions = _inspect_hints_for_rows(display, limit=2)
3601
- return _emit(env, args, noun="symbol")
3602
-
3603
-
3604
- def _cmd_imports(args: argparse.Namespace) -> int:
3605
- """imports <file> — tree-sitter parse + resolve_v2 per imported FQN.
3606
-
3607
- Reads <file> from disk (cfg.source_root / <file> for relative paths),
3608
- parses via the language backend (backend_for(...).parse — parse_java for
3609
- .java, parse_kotlin for .kt), walks explicit_imports (dict: simple_name
3610
- -> FQN), then resolves each FQN via resolve_v2 against the graph. Returns
3611
- a node per import: resolved graph Symbol when resolve_v2 hits (status=one),
3612
- or an unresolved placeholder carrying the raw FQN otherwise.
3613
- """
3614
- from java_codebase_rag.ast.language import backend_for
3615
- from java_codebase_rag.analysis.resolve_service import resolve_v2
3616
-
3617
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
3618
- from java_codebase_rag.jrag_render import render
3619
-
3620
- cfg, graph, rc = _load_graph_or_error(args)
3621
- if rc:
3622
- return rc
3623
-
3624
- file_path = _resolve_source_path(cfg, args.file)
3625
- if file_path is None:
3626
- env = Envelope(
3627
- status="error",
3628
- message=(
3629
- f"file not found: {args.file!r} (looked at the literal path and at "
3630
- f"<source_root>/{args.file})"
3631
- ),
3632
- )
3633
- print(render(env, fmt=args.format, detail=args.detail))
3634
- return 2
3635
-
3636
- try:
3637
- src = file_path.read_bytes()
3638
- except OSError as exc:
3639
- env = Envelope(status="error", message=f"could not read {file_path}: {exc}")
3640
- print(render(env, fmt=args.format, detail=args.detail))
3641
- return 2
3642
-
3643
- # The backend parse (backend_for(...).parse — parse_java / parse_kotlin)
3644
- # is robust to invalid source (returns an empty JavaFileAst on parse
3645
- # errors, never raises). It builds imports from the `import_declaration`
3646
- # tree-sitter nodes (Java path: `_import_declaration_is_static` at
3647
- # ast_java.py:905 and the scoped_identifier child walk at ast_java.py:2658).
3648
- # explicit_imports: dict[str, str] = simple_name -> FQN (non-wildcard,
3649
- # non-static); we also surface wildcard/static imports as unresolved rows so
3650
- # the agent sees the full import block.
3651
- backend = backend_for(args.file)
3652
- if backend is None:
3653
- env = Envelope(
3654
- status="error",
3655
- message=(
3656
- f"no language backend registered for {args.file!r} "
3657
- f"(suffix {Path(args.file).suffix!r} not in registry)"
3658
- ),
3659
- )
3660
- print(render(env, fmt=args.format, detail=args.detail))
3661
- return 2
3662
- ast = backend.parse(src, filename=args.file)
3663
- nodes: dict[str, dict] = {}
3664
- edges: list[dict] = []
3665
- warnings: list[str] = []
3666
- # Mirror outline: --limit is accepted (common flag) but imports returns the
3667
- # full import block; surface a warning when the user explicitly set --limit
3668
- # away from the default so they know it has no effect.
3669
- if args.limit is not None and args.limit != 20:
3670
- warnings.append("--limit does not apply to imports (the full import block is returned)")
3671
-
3672
- # Static + wildcard imports: rendered as unresolved rows (resolve_v2 only
3673
- # matches type Symbols, not methods or wildcards).
3674
- unresolved_imports: list[dict] = []
3675
- for ident in ast.wildcard_imports:
3676
- unresolved_imports.append({"fqn": f"{ident}.*", "kind": "wildcard"})
3677
- for simple, fqn in ast.file_imports.static_methods.items():
3678
- unresolved_imports.append({"fqn": fqn, "kind": "static_method", "name": simple})
3679
- for prefix in ast.file_imports.static_wildcards:
3680
- unresolved_imports.append({"fqn": f"{prefix}.*", "kind": "static_wildcard"})
3681
-
3682
- # Explicit type imports: resolve each via resolve_v2.
3683
- resolved_count = 0
3684
- unresolved_count = 0
3685
- for simple, fqn in ast.explicit_imports.items():
3686
- out = resolve_v2(fqn, hint_kind="symbol", graph=graph)
3687
- if out.status == "one" and out.node is not None:
3688
- ref = out.node
3689
- node_dict = _noderef_to_node_dict(ref)
3690
- node_dict["import_fqn"] = fqn
3691
- node_dict["import_simple"] = simple
3692
- nodes[ref.id] = node_dict
3693
- edges.append({"other_id": ref.id, "edge_type": "IMPORTS", "resolved": True})
3694
- resolved_count += 1
3695
- else:
3696
- # Use a stable synthetic id so unresolved imports round-trip JSON.
3697
- synthetic_id = f"import:{fqn}"
3698
- nodes[synthetic_id] = {
3699
- "id": synthetic_id,
3700
- "kind": "unresolved_import",
3701
- "fqn": fqn,
3702
- "name": simple,
3703
- "import_simple": simple,
3704
- "import_fqn": fqn,
3705
- }
3706
- edges.append({"other_id": synthetic_id, "edge_type": "IMPORTS", "resolved": False})
3707
- unresolved_count += 1
3708
-
3709
- # Append unresolved static/wildcard imports as additional rows.
3710
- for entry in unresolved_imports:
3711
- fqn = entry["fqn"]
3712
- synthetic_id = f"import:{fqn}"
3713
- nodes[synthetic_id] = {
3714
- "id": synthetic_id,
3715
- "kind": "unresolved_import",
3716
- "fqn": fqn,
3717
- "name": fqn.rsplit(".", 1)[-1],
3718
- "import_kind": entry.get("kind", ""),
3719
- }
3720
- edges.append({"other_id": synthetic_id, "edge_type": "IMPORTS", "resolved": False})
3721
-
3722
- if ast.parse_error:
3723
- warnings.append("tree-sitter reported a parse_error for this file (imports extracted best-effort)")
3724
-
3725
- env = Envelope(status="ok", nodes=nodes, edges=edges, warnings=warnings)
3726
- next_actions_hook(env, result_edges=edges)
3727
- return _emit(env, args, noun="import")
3728
-
3729
-
3730
- # ============================================================================
3731
- # PR-JRAG-4: orientation commands (microservices / map / conventions / overview)
3732
- # + semantic search.
3733
- #
3734
- # Orientation commands compose counts and listings from LadybugGraph methods
3735
- # and focused Cypher lookups (graph._rows). They render as inspect-shape
3736
- # (kv-block + nested dict sections) so the agent sees compact structured data.
3737
- #
3738
- # Search dispatches to search_v2 (mcp_v2.search_v2) after building a NodeFilter
3739
- # from flags. --fuzzy is registered on the parser and accepted as a silent
3740
- # no-op (search is inherently semantic; --fuzzy is implicit).
3741
- # ============================================================================
3742
-
3743
-
3744
- def _cmd_microservices(args: argparse.Namespace) -> int:
3745
- """microservices — list every microservice with its resolved type count."""
3746
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
3747
- from java_codebase_rag.jrag_render import render
3748
-
3749
- _, graph, rc = _load_graph_or_error(args)
3750
- if rc:
3751
- return rc
3752
-
3753
- counts = graph.microservice_counts()
3754
- # --service / --module / --limit are rejected at the argparse layer
3755
- # (microservices uses _core_parser), so no no-op warning is needed here.
3756
- env = Envelope(
3757
- status="ok",
3758
- nodes={"microservices": {"counts": dict(counts)}},
3759
- )
3760
- next_actions_hook(env)
3761
- # Natural follow-ups: drill into one service's structure (map) or its
3762
- # conventions (role/framework distribution).
3763
- env.agent_next_actions = ["jrag map", "jrag conventions"][:5]
3764
- print(render(env, fmt=args.format, detail=args.detail, noun="microservices", shape="inspect"))
3765
- return 0
3766
-
3767
-
3768
- def _cmd_map(args: argparse.Namespace) -> int:
3769
- """map [--by microservice|module] [--service] [--module] — counts per kind.
3770
-
3771
- ``--by`` selects the grouping axis (default microservice). ``--service`` /
3772
- ``--module`` narrow the count to one service / module (filters, independent
3773
- of the axis). Previously ``--module`` was overloaded to also switch the
3774
- axis, which made "group by ALL modules" unreachable.
3775
- """
3776
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
3777
-
3778
- _, graph, rc = _load_graph_or_error(args)
3779
- if rc:
3780
- return rc
3781
-
3782
- # Grouping axis: explicit --by wins; otherwise --module implies module axis
3783
- # (the user's focus is the module they named), else default microservice.
3784
- # This keeps the `group_by` label honest about the actual grouping: before,
3785
- # `map --module X` labeled `group_by: microservice` while the user was
3786
- # asking about a module — the label now matches what they see.
3787
- group_col = args.by or ("module" if args.module else "microservice")
3788
- scope_clauses: list[str] = []
3789
- params: dict = {}
3790
- if args.service:
3791
- scope_clauses.append("s.microservice = $ms")
3792
- params["ms"] = args.service
3793
- if args.module:
3794
- scope_clauses.append("s.module = $mod")
3795
- params["mod"] = args.module
3796
- scope_clause = " AND " + " AND ".join(scope_clauses) if scope_clauses else ""
3797
-
3798
- rows = graph._rows( # noqa: SLF001 - counts compose query (same pattern as _scope_counts)
3799
- f"MATCH (s:Symbol) WHERE s.resolved "
3800
- f"AND s.kind IN ['class','interface','enum','record','annotation']"
3801
- f"{scope_clause} "
3802
- f"RETURN s.{group_col} AS scope, s.kind AS kind, count(*) AS n",
3803
- params,
3804
- )
3805
- grouped: dict[str, dict[str, int]] = {}
3806
- for r in rows:
3807
- scope = str(r.get("scope") or "(unscoped)")
3808
- kind = str(r.get("kind") or "(unknown)")
3809
- grouped.setdefault(scope, {})[kind] = int(r.get("n") or 0)
3810
-
3811
- # --service/--module are applied above (scope_clauses); --limit is not (this
3812
- # is an aggregate count, not a row fetch).
3813
- warnings = _warn_inapplicable_common(args, service=False, module=False, limit=True)
3814
- env = Envelope(
3815
- status="ok",
3816
- nodes={"map": {"group_by": group_col, "counts": grouped}},
3817
- warnings=warnings,
3818
- )
3819
- next_actions_hook(env)
3820
- # Drill-down: the agent's next step on a count is to inspect the structure
3821
- # of a specific scope. Suggest `jrag overview <first scope>` (or the explicit
3822
- # --service scope when present) so the agent has a concrete next command.
3823
- first_scope = next(iter(grouped), None) if grouped else None
3824
- drill_scope = args.service or (first_scope if group_col == "microservice" else None)
3825
- hints: list[str] = []
3826
- if drill_scope:
3827
- hints.append(f"jrag overview {drill_scope}")
3828
- hints.append("jrag conventions")
3829
- env.agent_next_actions = hints[:5]
3830
- return _emit(env, args, noun="map", shape="inspect")
3831
-
3832
-
3833
- def _cmd_conventions(args: argparse.Namespace) -> int:
3834
- """conventions [--service] — dominant roles + framework tallies."""
3835
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
3836
-
3837
- _, graph, rc = _load_graph_or_error(args)
3838
- if rc:
3839
- return rc
3840
-
3841
- scope_clause = ""
3842
- params: dict = {}
3843
- if args.service:
3844
- scope_clause = " AND s.microservice = $ms"
3845
- params["ms"] = args.service
3846
-
3847
- role_rows = graph._rows( # noqa: SLF001 - counts compose query
3848
- f"MATCH (s:Symbol) WHERE s.resolved AND s.role IS NOT NULL AND s.role <> ''"
3849
- f"{scope_clause} "
3850
- f"RETURN s.role AS role, count(*) AS n ORDER BY n DESC",
3851
- params,
3852
- )
3853
- role_counts: dict[str, int] = {}
3854
- for r in role_rows:
3855
- role = str(r.get("role") or "")
3856
- if role:
3857
- role_counts[role] = int(r.get("n") or 0)
3858
-
3859
- # Framework tallies: a direct count of route nodes by framework for
3860
- # accuracy. --service is forwarded here too (previously the route framework
3861
- # tally was global even when --service narrowed the role tally — half-scoped
3862
- # output). Frameworks are NOT hardcoded; they are derived from the data
3863
- # (r.framework on Route nodes).
3864
- fw_scope = " AND r.microservice = $ms" if args.service else ""
3865
- fw_rows = graph._rows( # noqa: SLF001 - counts compose query
3866
- f"MATCH (r:Route) WHERE r.framework IS NOT NULL AND r.framework <> ''"
3867
- f"{fw_scope} "
3868
- f"RETURN r.framework AS framework, count(*) AS n ORDER BY n DESC",
3869
- params,
3870
- )
3871
- framework_counts: dict[str, int] = {}
3872
- for r in fw_rows:
3873
- fw = str(r.get("framework") or "")
3874
- if fw:
3875
- framework_counts[fw] = int(r.get("n") or 0)
3876
-
3877
- # --service is applied above; --module/--limit are not (no module clause;
3878
- # aggregate count).
3879
- warnings = _warn_inapplicable_common(args, service=False, module=True, limit=True)
3880
- env = Envelope(
3881
- status="ok",
3882
- nodes={"conventions": {"roles": role_counts, "frameworks": framework_counts}},
3883
- warnings=warnings,
3884
- )
3885
- next_actions_hook(env)
3886
- # Drill-down: list the concrete symbols behind the dominant role so the
3887
- # agent can inspect one (e.g. the top role's instances).
3888
- hints: list[str] = []
3889
- top_role = next(iter(role_counts), None) if role_counts else None
3890
- drill_scope = args.service or ""
3891
- if top_role:
3892
- # Suggest finding symbols of the top role (scoped when --service set).
3893
- scope_suffix = f" --service {drill_scope}" if drill_scope else ""
3894
- hints.append(f"jrag find --role {top_role}{scope_suffix}")
3895
- hints.append("jrag map")
3896
- env.agent_next_actions = hints[:5]
3897
- return _emit(env, args, noun="conventions", shape="inspect")
3898
-
3899
-
3900
- def _overview_detect_type(subject: str, graph) -> str:
3901
- """Auto-detect the subject type for `overview`.
3902
-
3903
- Returns "route" | "microservice" | "topic". Heuristics:
3904
- * Starts with '/' → route.
3905
- * Matches a known microservice name (microservice_counts keys) → microservice.
3906
- * Else → topic (catch-all for messaging strings).
3907
- """
3908
- if subject.startswith("/"):
3909
- return "route"
3910
- try:
3911
- ms_counts = graph.microservice_counts()
3912
- except Exception:
3913
- ms_counts = {}
3914
- if subject in ms_counts:
3915
- return "microservice"
3916
- return "topic"
3917
-
3918
-
3919
- def _overview_microservice(args: argparse.Namespace, graph, microservice: str) -> int:
3920
- """overview microservice bundle: counts + routes + clients + producers.
3921
-
3922
- The node is built WITHOUT top-level identity (kind/fqn/name) on purpose:
3923
- that makes it a rollup to the envelope projector, which then keeps the
3924
- nested dict/list sections (``bundle`` + sample lists) at every detail
3925
- level. The command-side sample sizing below is what varies the output by
3926
- detail: brief = bundle counts only, normal = +3 samples, full = +5 samples.
3927
- Without both (rollup detection AND command-side sizing), brief/normal/full
3928
- would all render identically because the projection would either strip the
3929
- bundle to empty (subject node) or keep all samples equally (rollup node).
3930
- """
3931
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
3932
-
3933
- limit = _clamped_limit(args)
3934
- routes = graph.list_routes(microservice=microservice, limit=limit + 1)
3935
- clients = graph.list_clients(microservice=microservice, limit=limit + 1)
3936
- producers = graph.list_producers(microservice=microservice, limit=limit + 1)
3937
-
3938
- bundle = {
3939
- "microservice": microservice,
3940
- "routes": len(routes),
3941
- "clients": len(clients),
3942
- "producers": len(producers),
3943
- }
3944
- # Include sample entities (entities + listeners + jobs) for the service.
3945
- try:
3946
- entities = graph.list_by_role(
3947
- role="ENTITY", microservice=microservice, limit=limit + 1
3948
- )
3949
- bundle["entities"] = len(entities)
3950
- except Exception:
3951
- pass
3952
-
3953
- # Sample sizing by detail: brief drops samples entirely (counts only);
3954
- # normal caps at 3 (signal of what's there); full keeps 5 (richer picture).
3955
- detail = args.detail
3956
- sample_cap = 0 if detail == "brief" else (3 if detail == "normal" else 5)
3957
- # No fqn/name/path/topic/member_fqn → project_node treats this as a rollup
3958
- # and keeps the nested sections (bundle + sample lists) at every detail
3959
- # level. ``kind`` stays for self-identification (it's a type tag, not in
3960
- # the rollup-identity check).
3961
- node: dict = {
3962
- "kind": "microservice",
3963
- "microservice": microservice,
3964
- "bundle": bundle,
3965
- }
3966
- if sample_cap:
3967
- node["route_sample"] = [
3968
- {"path": r.get("path", ""), "framework": r.get("framework", "")}
3969
- for r in routes[:sample_cap]
3970
- ]
3971
- node["client_sample"] = [
3972
- {"fqn": c.get("member_fqn", ""), "target_service": c.get("target_service", "")}
3973
- for c in clients[:sample_cap]
3974
- ]
3975
- node["producer_sample"] = [
3976
- {"topic": p.get("topic", ""), "producer_kind": p.get("producer_kind", "")}
3977
- for p in producers[:sample_cap]
3978
- ]
3979
-
3980
- env = Envelope(
3981
- status="ok",
3982
- nodes={f"microservice:{microservice}": node},
3983
- )
3984
- next_actions_hook(env)
3985
- return _emit(env, args, noun="overview", shape="inspect")
3986
-
3987
-
3988
- def _overview_route(args: argparse.Namespace, cfg, graph, route_path: str) -> int:
3989
- """overview route: resolve + trace_request_flow (same as `flow`)."""
3990
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook, resolve_query
3991
- from java_codebase_rag.jrag_render import render
3992
-
3993
- limit = _clamped_limit(args)
3994
- node, renv = resolve_query(
3995
- route_path, hint_kind="route", java_kind=None, role=None, fqn_contains=None,
3996
- cfg=cfg, graph=graph,
3997
- )
3998
- if renv.status != "ok" or node is None:
3999
- return _emit(renv, args)
4000
-
4001
- if node.kind != "route":
4002
- env = Envelope(
4003
- status="error",
4004
- message=f"overview --as route expects a Route; resolved kind is {node.kind!r}.",
4005
- )
4006
- print(render(env, fmt=args.format, detail=args.detail))
4007
- return 2
4008
-
4009
- max_hops = max(1, min(8, 5))
4010
- flow_data = graph.trace_request_flow(entry_route_id=node.id, max_hops=max_hops)
4011
- root_id = node.id
4012
- nodes_dict: dict[str, dict] = {root_id: _noderef_to_node_dict(node)}
4013
- edges: list[dict] = []
4014
- for row in flow_data.get("inbound", []):
4015
- caller_id = str(row.get("caller_node_id") or "")
4016
- if not caller_id:
4017
- continue
4018
- kind = str(row.get("caller_node_kind") or "")
4019
- nodes_dict[caller_id] = {
4020
- "id": caller_id, "kind": kind,
4021
- "fqn": str(row.get("declaring_symbol_fqn") or ""),
4022
- "microservice": str(row.get("microservice") or ""),
4023
- }
4024
- edges.append({
4025
- "other_id": caller_id,
4026
- "edge_type": "HTTP_CALLS" if kind == "client" else "ASYNC_CALLS",
4027
- "confidence": float(row.get("confidence") or 0.0),
4028
- })
4029
- for row in flow_data.get("outbound", []):
4030
- next_id = str(row.get("next_symbol_id") or "")
4031
- if not next_id:
4032
- continue
4033
- nodes_dict[next_id] = {
4034
- "id": next_id, "kind": "symbol",
4035
- "fqn": str(row.get("next_fqn") or ""),
4036
- "microservice": str(row.get("next_microservice") or ""),
4037
- }
4038
- edges.append({"other_id": next_id, "edge_type": "CALLS"})
4039
- truncated = len(edges) > limit
4040
- if truncated:
4041
- edges = edges[:limit]
4042
- env = Envelope(status="ok", nodes=nodes_dict, edges=edges, root=root_id, truncated=truncated)
4043
- next_actions_hook(env, root=root_id, result_edges=edges)
4044
- return _emit(env, args, noun="overview")
4045
-
4046
-
4047
- def _overview_topic(args: argparse.Namespace, graph, topic: str) -> int:
4048
- """overview topic: producers + consumers for a topic string.
4049
-
4050
- Built without top-level identity (kind/fqn/name) so the projector treats
4051
- the node as a rollup and keeps the nested sections (``bundle`` +
4052
- producers/consumers lists) at every detail level. Command-side sample
4053
- sizing varies the output by detail: brief = counts only, normal = +3
4054
- samples, full = +limit samples.
4055
- """
4056
- from java_codebase_rag.jrag_envelope import Envelope, next_actions_hook
4057
-
4058
- limit = _clamped_limit(args)
4059
- # Producers: exact topic match first, then substring match as fallback.
4060
- producers = graph.list_producers(topic_contains=topic, limit=limit + 1)
4061
- if not producers and len(topic) >= 3:
4062
- # Try a shorter substring if the exact topic yields nothing.
4063
- producers = graph.list_producers(topic_contains=topic[:3], limit=limit + 1)
4064
- producers = [p for p in producers if topic in str(p.get("topic") or "")]
4065
-
4066
- # Consumers: listener classes consuming this topic via EXPOSES on Route.
4067
- consumers = _resolve_topic_consumers(graph, topic=topic, contains=False)
4068
- if not consumers:
4069
- consumers = _resolve_topic_consumers(graph, topic=topic, contains=True)
4070
-
4071
- detail = args.detail
4072
- sample_cap = 0 if detail == "brief" else (3 if detail == "normal" else limit)
4073
- # NOTE: no top-level ``topic``/fqn/name here — ``topic`` IS a rollup-
4074
- # identity key, so its presence would make project_node treat this as a
4075
- # subject and strip the bundle/producers/consumers sections at brief/
4076
- # normal. ``kind`` is fine (type tag, not in the rollup-identity check),
4077
- # so it stays for self-identification. The topic name travels in the dict
4078
- # key ("topic:<name>") and inside ``bundle.topic``.
4079
- topic_node: dict = {
4080
- "kind": "topic",
4081
- "bundle": {
4082
- "topic": topic,
4083
- "producers": len(producers),
4084
- "consumers": len(consumers),
4085
- },
4086
- }
4087
- if sample_cap:
4088
- topic_node["producers"] = [
4089
- {
4090
- "fqn": str(p.get("member_fqn") or ""),
4091
- "topic": str(p.get("topic") or ""),
4092
- "producer_kind": str(p.get("producer_kind") or ""),
4093
- "microservice": str(p.get("microservice") or ""),
4094
- }
4095
- for p in producers[:sample_cap]
4096
- ]
4097
- topic_node["consumers"] = [
4098
- {
4099
- "fqn": c.get("fqn", ""),
4100
- "kind": c.get("kind", "symbol"),
4101
- "microservice": c.get("microservice", ""),
4102
- }
4103
- for c in consumers[:sample_cap]
4104
- ]
4105
- env = Envelope(
4106
- status="ok",
4107
- nodes={f"topic:{topic}": topic_node},
4108
- )
4109
- next_actions_hook(env)
4110
- return _emit(env, args, noun="overview", shape="inspect")
4111
-
4112
-
4113
- def _cmd_overview(args: argparse.Namespace) -> int:
4114
- """overview <microservice|route-path|topic> [--as ...] — dispatch on type."""
4115
- cfg, graph, rc = _load_graph_or_error(args)
4116
- if rc:
4117
- return rc
4118
-
4119
- from java_codebase_rag.jrag_envelope import Envelope
4120
- from java_codebase_rag.jrag_render import render
4121
-
4122
- subject = args.subject
4123
- # --service is inherited from the common parser. Treat a provided --service
4124
- # as the subject when no positional was given (so `overview --service
4125
- # chat-assign` works like `overview chat-assign`), and ALWAYS validate it
4126
- # against the known set so a bogus name errors clearly instead of producing
4127
- # an empty bundle that reads as "service has no entries".
4128
- if args.service and not subject:
4129
- subject = args.service
4130
- if args.service:
4131
- rc_ms = _validate_known_microservice(graph, args.service, args)
4132
- if rc_ms is not None:
4133
- return rc_ms
4134
-
4135
- if not subject:
4136
- # Subject is optional on the parser (nargs='?') so we can emit a helpful
4137
- # explanation instead of argparse's opaque "the following arguments are
4138
- # required: subject". Prints to stderr (usage guidance) + a status:error
4139
- # envelope to stdout, exit 2.
4140
- msg = (
4141
- "overview requires a <subject>: a microservice name (e.g. 'chat-core'), "
4142
- "a route path (e.g. '/api/v1/chat/events'), or a topic string "
4143
- "(e.g. 'banking.chat.audit'). Use --as {microservice,route,topic} to "
4144
- "override auto-detection."
4145
- )
4146
- print(render(Envelope(status="error", message=msg), fmt=args.format, detail=args.detail))
4147
- return 2
4148
- as_type = getattr(args, "as_type", None)
4149
- if as_type is None:
4150
- as_type = _overview_detect_type(subject, graph)
4151
-
4152
- # NOTE: we do NOT validate `subject` against the known microservice set here.
4153
- # Auto-detect only returns "microservice" when the subject IS in
4154
- # microservice_counts, so that path is already known-good; and an explicit
4155
- # `--as microservice` is a deliberate force (e.g. on a route-shaped string)
4156
- # that must NOT be rejected. The bogus-microservice guard for overview is
4157
- # carried entirely by the --service flag validation above.
4158
- if as_type == "route":
4159
- return _overview_route(args, cfg, graph, subject)
4160
- if as_type == "microservice":
4161
- return _overview_microservice(args, graph, subject)
4162
- return _overview_topic(args, graph, subject)
4163
-
4164
-
4165
- # ============================================================================
4166
- # Search (PR-JRAG-4)
4167
- # ============================================================================
4168
-
4169
-
4170
- def _zero_result_guidance(args: argparse.Namespace, graph) -> str | None:
4171
- """Hint where matches live when a filtered search returns 0 results.
4172
-
4173
- Runs ONE cheap unfiltered probe (limit 10) and tallies the filtered
4174
- dimension across the probe hits, so an agent who filtered to e.g.
4175
- ``--role SERVICE`` and got nothing learns the matches are under
4176
- COMPONENT/OTHER instead of guessing. Returns None when no guidance
4177
- applies: no recognizable single-dimension filter set, the probe is
4178
- empty (truly no matches for this query), or the probe itself errored
4179
- (non-fatal — the empty result still renders).
4180
- """
4181
- from java_codebase_rag.mcp import mcp_v2
4182
- from collections import Counter
4183
-
4184
- from java_codebase_rag.jrag_envelope import normalize_enum
4185
-
4186
- # Only the common single-dimension filters get guidance; first set wins.
4187
- dims: list[tuple[str, str, str, str]] = []
4188
- if args.role:
4189
- dims.append(("role", "role", "roles", normalize_enum(args.role, kind="role")))
4190
- if args.service:
4191
- dims.append(("microservice", "service", "services", args.service))
4192
- if args.module:
4193
- dims.append(("module", "module", "modules", args.module))
4194
- if not dims:
4195
- return None
4196
- attr, flag, plural, value = dims[0]
4197
-
4198
- try:
4199
- probe = mcp_v2.search_v2(
4200
- args.query,
4201
- table=args.table,
4202
- hybrid=args.hybrid,
4203
- limit=10,
4204
- offset=0,
4205
- path_contains=args.path_contains,
4206
- filter=None,
4207
- explain=False,
4208
- graph=graph,
4209
- )
4210
- except Exception:
4211
- return None
4212
- if not probe.success or not probe.results:
4213
- return None
4214
-
4215
- counts: Counter = Counter(getattr(h, attr, None) for h in probe.results)
4216
- counts.pop(None, None)
4217
- if not counts:
4218
- return None
4219
- total = sum(counts.values())
4220
- top = counts.most_common(3)
4221
- alts = ", ".join(f"{v} ({c})" for v, c in top)
4222
- suggestion = top[0][0]
4223
- return (
4224
- f"0 results with --{flag} {value}; {total} matches exist under other {plural}: "
4225
- f"{alts} — try --{flag} {suggestion}"
4226
- )
4227
-
4228
-
4229
- def _cmd_search(args: argparse.Namespace) -> int:
4230
- """search <query> — semantic search via search_v2 over Lance tables.
4231
-
4232
- Builds a NodeFilter from flags, calls search_v2 with limit+1 for +1-fetch
4233
- truncation, and renders. --fuzzy is accepted as a silent no-op (search is
4234
- always semantic; --fuzzy is implicit).
4235
- """
4236
- from java_codebase_rag.jrag_envelope import Envelope, mark_truncated, next_actions_hook, normalize_enum
4237
- from java_codebase_rag.jrag_render import render
4238
-
4239
- # --fuzzy: accepted as a silent no-op. Search is inherently semantic
4240
- # (vector + lexical), so --fuzzy is implicit; the flag is kept registered
4241
- # so callers/agents that pass it don't hit an argparse or envelope error,
4242
- # and is simply ignored here.
4243
- _ = getattr(args, "fuzzy", False)
4244
-
4245
- cfg, graph, rc = _load_graph_or_error(args)
4246
- if rc:
4247
- return rc
4248
-
4249
- limit = min(args.limit if args.limit is not None else 20, 499)
4250
-
4251
- # --limit 0: short-circuit to a clean empty page. mark_truncated(rows, 0)
4252
- # would otherwise report truncated=True (a unit test pins the helper's
4253
- # current behavior, so we fix this in the handler, not the helper), and
4254
- # there is nothing to search — skip the embedding-model load entirely.
4255
- if limit == 0:
4256
- env = Envelope(
4257
- status="ok", nodes={}, truncated=False,
4258
- warnings=_auto_scope_notice(args),
4259
- )
4260
- next_actions_hook(env)
4261
- return _emit(env, args, noun="search")
4262
-
4263
- # Build NodeFilter from flags (same set as `find` filter mode).
4264
- filter_dict: dict = {}
4265
- if args.service:
4266
- filter_dict["microservice"] = args.service
4267
- if args.module:
4268
- filter_dict["module"] = args.module
4269
- if args.role:
4270
- filter_dict["role"] = normalize_enum(args.role, kind="role")
4271
- if args.exclude_role:
4272
- filter_dict["exclude_roles"] = [normalize_enum(args.exclude_role, kind="role")]
4273
- if args.annotation:
4274
- filter_dict["annotation"] = args.annotation
4275
- if args.capability:
4276
- filter_dict["capability"] = args.capability
4277
- if args.fqn_contains:
4278
- filter_dict["fqn_contains"] = args.fqn_contains
4279
- if args.java_kind:
4280
- filter_dict["symbol_kind"] = normalize_enum(args.java_kind, kind="java_kind")
4281
- # NOTE: --framework is intentionally NOT placed in the NodeFilter. The graph
4282
- # stores `framework` only on Route nodes (Route.framework), so the
4283
- # NodeFilter `framework` field is validated against the route-only Framework
4284
- # Literal AND rejected by the symbol-kind applicability guard. Applying it to
4285
- # a symbol result set requires mapping the framework tag back onto the
4286
- # declaring type via its annotations — done as a client-side POST-filter
4287
- # below (`_framework_post_filter`) after the search hits come back.
4288
- framework_want = normalize_enum(args.framework, kind="framework") if args.framework else None
4289
- if framework_want and framework_want not in _FRAMEWORK_ANNOTATIONS:
4290
- # Catch an unknown framework BEFORE the search runs (saves the embedding
4291
- # model load + Lance scan). The valid set is the same one NodeFilter
4292
- # validates against for routes — surfaced as a clean error envelope.
4293
- valid = ", ".join(sorted(_FRAMEWORK_ANNOTATIONS))
4294
- env = Envelope(
4295
- status="error",
4296
- message=(
4297
- f"invalid framework: {args.framework!r} (normalized to {framework_want!r}); "
4298
- f"expected one of: {valid}"
4299
- ),
4300
- )
4301
- print(render(env, fmt=args.format, detail=args.detail))
4302
- return 2
4303
- from java_codebase_rag.read_payloads import PayloadError, search_payload
4304
- from java_codebase_rag.watch.client import get_payload
4305
-
4306
- # search_payload builds the NodeFilter from args (same filter_dict set above)
4307
- # and calls search_v2 with limit+1. On filter-validation failure it raises
4308
- # PayloadError carrying the error Envelope (rendered identically to before).
4309
- # get_payload tries the watch daemon first (hot), cold-falling-back to the
4310
- # identical search_payload core when no daemon is alive (every non-watch jrag
4311
- # invocation). Reconstructs the SearchOutput object on the hot path so the
4312
- # downstream render is unchanged.
4313
- try:
4314
- out = get_payload("search", vars(args), cfg, cold_core=search_payload)
4315
- except PayloadError as pe:
4316
- print(render(pe.env, fmt=args.format, detail=args.detail))
4317
- return pe.rc
4318
-
4319
- if not out.success:
4320
- env = Envelope(status="error", message=out.message or "search failed")
4321
- print(render(env, fmt=args.format, detail=args.detail))
4322
- return 2
4323
-
4324
- # Convert SearchHit list to envelope node dicts.
4325
- # Score floor (default 0.0): drop negative-score noise — chunks farther than
4326
- # orthogonal to the query (l2_distance_to_score < 0) are never a real match.
4327
- # Applied BEFORE truncation so the floor tightens precision without the +1
4328
- # row leaking past it. SearchHit now carries filename/start_line; the
4329
- # envelope projector (_compose_file) folds those into the `file` display
4330
- # field so each rendered hit shows its file path (filename:start_line).
4331
- min_score = getattr(args, "min_score", 0.0) or 0.0
4332
- hit_dicts: list[dict] = []
4333
- for hit in out.results:
4334
- if float(getattr(hit, "score", 0.0)) < min_score:
4335
- continue
4336
- d = hit.model_dump() if hasattr(hit, "model_dump") else dict(hit)
4337
- # Ensure an `id` key for envelope nodes (SearchHit carries chunk_id +
4338
- # optional symbol_id; use chunk_id as the envelope node id).
4339
- if "id" not in d:
4340
- d["id"] = d.get("chunk_id") or d.get("symbol_id") or d.get("fqn") or ""
4341
- if "kind" not in d:
4342
- d["kind"] = "search_hit"
4343
- # Add explain token when --explain is set
4344
- if args.explain:
4345
- # search_lancedb is unimportable on graph-only (macOS Intel) installs —
4346
- # lancedb/sentence-transformers are excluded by the PEP 508 markers in
4347
- # pyproject.toml, and this module imports them at module top. Importing the
4348
- # explain renderer from there would crash `jrag search ... --explain` on the
4349
- # exact Intel install that runs the lexical path. search_scoring is
4350
- # dependency-free and always installed, so the explain import works everywhere.
4351
- from java_codebase_rag.search.search_scoring import explain_score_components
4352
- comps = d.get("score_components")
4353
- d["explain"] = explain_score_components(
4354
- comps,
4355
- role=d.get("role"),
4356
- hybrid=bool(args.hybrid),
4357
- graph_expanded=False,
4358
- lexical=bool(getattr(out, "lexical_mode", False)),
4359
- )
4360
- hit_dicts.append(d)
4361
-
4362
- # --framework POST-filter: the graph stores `framework` only on Route nodes,
4363
- # so we map the requested framework tag back onto the symbol's declaring
4364
- # type via its annotations (e.g. spring_mvc -> @RestController) and keep
4365
- # only hits whose primary type declares one of those annotations. Applied
4366
- # BEFORE truncation so the cap bounds the visible (filtered) page.
4367
- framework_dropped = 0
4368
- if framework_want and hit_dicts:
4369
- framework_fqns = _framework_type_fqns(graph, framework_want)
4370
- kept: list[dict] = []
4371
- for d in hit_dicts:
4372
- type_fqn = d.get("fqn") or ""
4373
- if type_fqn and type_fqn in framework_fqns:
4374
- kept.append(d)
4375
- else:
4376
- framework_dropped += 1
4377
- hit_dicts = kept
4378
-
4379
- display, truncated = mark_truncated(hit_dicts, limit)
4380
- nodes = {n["id"]: n for n in display} if display else {}
4381
-
4382
- warnings: list[str] = []
4383
- if framework_want and framework_dropped and not display:
4384
- warnings.append(
4385
- f"--framework {framework_want!r} filtered out all {framework_dropped} hit(s); "
4386
- f"no symbol's declaring type matched the framework's characteristic annotations"
4387
- )
4388
- # Zero-result guidance: when a structural filter emptied the page, run one
4389
- # cheap unfiltered probe and point at where matches actually live (e.g.
4390
- # "--role SERVICE" returned 0 but matches are under COMPONENT/OTHER).
4391
- if not hit_dicts and filter_dict:
4392
- guidance = _zero_result_guidance(args, graph)
4393
- if guidance:
4394
- warnings.append(guidance)
4395
- env = Envelope(
4396
- status="ok", nodes=nodes, truncated=truncated,
4397
- warnings=warnings + _auto_scope_notice(args),
4398
- )
4399
- next_actions_hook(env)
4400
- # Per-hit drill-down: the top search hit's primary type is the natural
4401
- # thing to inspect (signature, edges, callers). Two visible hints in text,
4402
- # up to 5 in JSON.
4403
- if display:
4404
- env.agent_next_actions = _inspect_hints_for_rows(display, limit=2)
4405
- next_offset = args.offset + limit if truncated else None
4406
- return _emit(env, args, noun="search", next_offset=next_offset)
4407
-
4408
-
4409
- def _suppress_runtime_stderr_noise() -> None:
4410
- """Silence known-benign stderr noise from the embedding/LanceDB stack.
4411
-
4412
- The CLI loads sentence_transformers + LanceDB per invocation; both emit
4413
- benign stderr noise that an agent-facing tool should not dump on the caller:
4414
-
4415
- * tqdm ``Loading weights`` progress bar (sentence_transformers model load)
4416
- * HuggingFace hub progress bars / telemetry
4417
- * torch multiprocessing ``leaked semaphore objects`` ``resource_tracker``
4418
- UserWarning emitted at shutdown
4419
-
4420
- Real diagnostics (the top-level handler's ``traceback.format_exc()``) still
4421
- go to stderr. Env vars are set with ``setdefault`` so an explicit caller
4422
- override wins. The ``resource_tracker`` warning is raised inside a spawned
4423
- child process; under the spawn start method (macOS default) the child
4424
- re-initializes ``warnings`` and does NOT inherit the parent's
4425
- ``warnings.filterwarnings``, so we route it through ``PYTHONWARNINGS`` (env
4426
- vars ARE inherited by spawned children) as well as the parent filter.
4427
- """
4428
- for key, val in (
4429
- ("TQDM_DISABLE", "1"),
4430
- ("TRANSFORMERS_VERBOSITY", "error"),
4431
- ("HF_HUB_DISABLE_PROGRESS_BARS", "1"),
4432
- ("HF_HUB_DISABLE_TELEMETRY", "1"),
4433
- # mcp_v2._log_fail_loud operator diagnostic — the CLI surfaces the same
4434
- # failure as a clean status:error envelope, so silence the stderr line.
4435
- ("JAVA_CODEBASE_RAG_FAIL_LOUD", "0"),
4436
- ):
4437
- os.environ.setdefault(key, val)
4438
- existing_pw = os.environ.get("PYTHONWARNINGS", "")
4439
- extra_pw = "ignore:resource_tracker:UserWarning"
4440
- if extra_pw not in existing_pw:
4441
- os.environ["PYTHONWARNINGS"] = f"{existing_pw},{extra_pw}" if existing_pw else extra_pw
4442
- import warnings
4443
-
4444
- warnings.filterwarnings("ignore", message=r"resource_tracker.*", category=UserWarning)
4445
-
4446
-
4447
- def main(argv: list[str] | None = None) -> int:
4448
- """Process-level entry. Returns the exit code.
4449
-
4450
- First line raises the FD soft limit (lancedb merge-insert opens many
4451
- handles; macOS IDE-launched soft limit is 256). Returns 0 on ok, 1 on
4452
- usage error (argparse rejects argv), 2 on handler exception. The top-level
4453
- exception handler emits a ``status: error`` envelope to stdout AND
4454
- ``traceback.format_exc()`` to stderr before returning 2 - this is a
4455
- deliberate divergence from the operator CLI which swallows tracebacks.
4456
- """
4457
- raise_fd_limit()
4458
- _suppress_runtime_stderr_noise()
4459
- parser = build_parser()
4460
- raw = list(argv if argv is not None else sys.argv[1:])
4461
- try:
4462
- args = parser.parse_args(raw)
4463
- except SystemExit as exc:
4464
- # argparse with exit_on_error=False raises SystemExit on -h/--help
4465
- # (code 0) and ArgumentError-propagated paths. Treat 0/None as ok and
4466
- # any other code as usage error (exit 1).
4467
- if exc.code in (0, None):
4468
- return 0
4469
- return 1
4470
- except argparse.ArgumentError as exc:
4471
- # exit_on_error=False + _EnvelopeArgumentParser routes argparse usage
4472
- # errors here (missing required positional, unrecognized flag, bad
4473
- # choices) WITHOUT dumping usage text. We emit a clean status:error
4474
- # envelope to STDOUT honoring --format so JSON consumers get a
4475
- # parseable result (parity with overview/find missing-arg paths), AND
4476
- # mirror a terse line to STDERR so shell users / `2>&1` pipelines and
4477
- # the existing "non-empty stderr on usage error" tests still see it.
4478
- # Exit non-zero: this is a usage error, distinct from a not_found
4479
- # envelope (exit 0, the resolve found nothing).
4480
- from java_codebase_rag.jrag_envelope import Envelope
4481
- from java_codebase_rag.jrag_render import render
4482
-
4483
- fmt, detail, leftover = _preparse_render_flags(raw)
4484
- fmt = fmt or "text"
4485
- detail = detail or "normal"
4486
- # The subcommand is the first non-dash token in the leftover (flag
4487
- # values already consumed by the pre-parser), so we don't mis-prefix
4488
- # with a value like ``json`` from ``--format json``.
4489
- cmd = next((t for t in leftover if not t.startswith("-")), None)
4490
- msg = str(exc).strip() or "usage error"
4491
- if cmd and not msg.startswith(cmd):
4492
- msg = f"{cmd}: {msg}"
4493
- env = Envelope(status="error", message=msg)
4494
- print(render(env, fmt=fmt, detail=detail))
4495
- print(f"jrag: error: {msg}", file=sys.stderr)
4496
- return 2
4497
- handler = getattr(args, "handler", None)
4498
- if handler is None:
4499
- # No subcommand: print help to stderr, return usage error.
4500
- parser.print_help(sys.stderr)
4501
- return 1
4502
- try:
4503
- return int(handler(args))
4504
- except Exception as exc:
4505
- from java_codebase_rag.jrag_envelope import Envelope
4506
- from java_codebase_rag.jrag_render import render
4507
-
4508
- env = Envelope(
4509
- status="error",
4510
- message=f"internal error: {exc}",
4511
- )
4512
- print(render(env, fmt=getattr(args, "format", "text")))
4513
- print(traceback.format_exc(), file=sys.stderr)
4514
- return 2
4515
-
4516
-
4517
- def _console_script_main() -> None:
4518
- """Real CLI entry: terminate without interpreter finalization.
4519
-
4520
- Mirrors ``java_codebase_rag.cli._console_script_main``: a pyarrow/lance
4521
- worker thread (loaded via lancedb in lifecycle commands) can outlive CPython
4522
- finalization in a one-shot CLI subprocess and trip ``PyGILState_Release``
4523
- (SIGABRT, exit -6). Flushing + ``os._exit`` skips that racy teardown - the
4524
- command has already done its work and emitted its result. ``main()`` stays
4525
- return-based so in-process test callers keep working.
4526
-
4527
- ``KeyboardInterrupt`` (Ctrl+C during a long indexing step) is caught here so
4528
- it routes through the same flush + ``os._exit`` path — clean, immediate exit
4529
- (code 130, no traceback) and no finalization-time SIGABRT — instead of
4530
- propagating past this function.
4531
- """
4532
- force_utf8_stdio()
4533
- try:
4534
- rc = main()
4535
- except KeyboardInterrupt:
4536
- sys.stderr.write("\nInterrupted.\n")
4537
- sys.stderr.flush()
4538
- rc = 130
4539
- sys.stdout.flush()
4540
- sys.stderr.flush()
4541
- os._exit(rc)
4542
-
4543
-
4544
- if __name__ == "__main__":
4545
- _console_script_main()