java-codebase-rag 0.6.7__py3-none-any.whl → 0.8.0__py3-none-any.whl

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