Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(health): ternary dispatch chains and JSX conditionals do not nest (#3278)

Raghav Chamadiya84f149948635
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index dedab112a..d35c9463f 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -511,6 +511,15 @@ dispatch and its heaviest arm: `nested_complexity` skips the two levels the
`switch` and its `case` open, and `complex_method`, `brain_method` and `bumpy_road`
read the CCN outside the dispatch plus the CCN of its most complex arm.
+In TypeScript and JavaScript (TSX / JSX included) a ternary opens no nesting level
+when it is an arm of a chain (`a ? x : b ? y : z`), sits inside JSX markup, or has a
+JSX branch: a view choosing one of ten panels is one decision per arm (each still
+counts toward CCN and adds a flat +1 to cognitive complexity, like an `else if`), not
+ten levels deep. A ternary inside another's `consequence` still nests, as does one in
+a call argument or object literal inside JSX (`{fmt(a ? b : c)}`) and one whose
+branch is not itself JSX (`cond ? c2 && <A/> : x`); so does every `if` / `for` /
+`try` in a handler written in JSX.
+
`biomarkers/registry.py` is an **explicit list**, not auto-discovery:
keeps the registration order deterministic and lets tests inject extras
via `registered_biomarkers(extra=...)`.
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.md
index 1b2cb268f..fecd9e47a 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md
+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md
@@ -28,6 +28,8 @@ Tree-sitter AST walker. Single AST pass per file computes:
(`if`, `for`, `while`, `case`, `catch`) plus boolean operators
(`&&`, `||`).
- **max nesting depth** — deepest nested control-flow block per function.
+ `else if` arms and, in TS/JS, ternary chain arms and ternaries choosing
+ JSX (`flat_ternary_kinds`) add CCN and a flat +1 cognitive but no level.
- **cognitive complexity** — SonarSource-style weighted nesting cost
(each level adds an incrementing penalty, plus +1 for each break in
control flow).
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
index a714d6b05..8720cdf53 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py
@@ -117,6 +117,48 @@ def _is_elif_continuation(node: Node) -> bool:
return prev is not None and prev.type in _ELSE_TOKEN_KINDS
+def is_markup(node: Node) -> bool:
+ """True for a JSX node: an element, attribute, expression slot or text."""
+ return node.type.startswith("jsx_")
+
+
+# Nodes inside JSX whose contents are values, not rendered choices:
+# ``{fmt(a ? b : c)}`` and ``style={{k: a ? b : c}}``.
+_MARKUP_VALUE_KINDS = frozenset({"arguments", "object"})
+
+
+def _unparen(node: Node | None) -> Node | None:
+ while node is not None and node.type == "parenthesized_expression" and node.named_children:
+ node = node.named_children[0]
+ return node
+
+
+def _is_flat_ternary(node: Node, lmap: LanguageNodeMap, in_markup: bool) -> bool:
+ """A ternary that chooses rather than nests (see ``flat_ternary_kinds``).
+
+ That is one rendered inside JSX, one with a JSX branch, or an arm of a
+ chain (the ``alternative`` of a ternary of its kind). A ternary in another's
+ ``consequence`` still nests: that is a decision inside a decision. Outside
+ markup a branch must itself be JSX, so ``cond ? c2 && <A/> : x`` nests.
+ Like an ``else if``, a flat ternary costs a flat +1 cognitive.
+ """
+ if node.type not in lmap.flat_ternary_kinds:
+ return False
+ if in_markup:
+ return True
+ parent = node.parent
+ while parent is not None and parent.type == "parenthesized_expression":
+ parent = parent.parent
+ if parent is not None and parent.type == node.type:
+ alternative = _unparen(parent.child_by_field_name("alternative"))
+ if alternative is not None and alternative.id == node.id:
+ return True
+ return any(
+ (branch := _unparen(node.child_by_field_name(field))) is not None and is_markup(branch)
+ for field in ("consequence", "alternative")
+ )
+
+
def _count_boolean_ops_in_condition(node: Node, lmap: LanguageNodeMap) -> int:
"""Count ``&&`` / ``||`` / ``and`` / ``or`` operators in a condition.
@@ -295,7 +337,7 @@ def _walk_function_body(
deepest_depth = 0
deepest_node: list[Node] = []
- def _recurse(node: Node, depth: int) -> None:
+ def _recurse(node: Node, depth: int, in_markup: bool = False) -> None:
nonlocal ccn, max_nesting, cognitive, deepest_depth
# Don't descend into nested function bodies — they're walked
@@ -339,11 +381,16 @@ def _walk_function_body(
or node.type in lmap.catch_kinds
):
ccn_increment = 1
- # An ``else if`` / ``elif`` chain arm and a comprehension /
- # case-guard filter are flat: charge the extra branch (ccn) but do
- # not open a new nesting level for them. This parallels the
- # flat-``switch``/``match`` special-case above.
- if node.type not in _FLAT_BRANCH_KINDS and not _is_elif_continuation(node):
+ # An ``else if`` / ``elif`` chain arm, a ternary chain arm or
+ # markup choice, and a comprehension / case-guard filter are flat:
+ # charge the extra branch (ccn) but do not open a new nesting
+ # level for them. This parallels the flat-``switch``/``match``
+ # special-case above.
+ if not (
+ node.type in _FLAT_BRANCH_KINDS
+ or _is_elif_continuation(node)
+ or _is_flat_ternary(node, lmap, in_markup)
+ ):
nesting_increment = 1
# Side-channel: count compound boolean ops in this
# construct's condition. Does not affect ccn/cognitive
@@ -390,8 +437,17 @@ def _walk_function_body(
deepest_depth = new_depth
deepest_node[:] = [node]
+ # Markup context ends at a callback (a handler inside JSX is logic) and
+ # at call arguments and object literals (a value, not a rendered
+ # choice). Only arrows need the reset: the walk never descends into
+ # other function kinds.
+ child_markup = (
+ (in_markup or is_markup(node))
+ and node.type not in lmap.lambda_kinds
+ and node.type not in _MARKUP_VALUE_KINDS
+ )
for child in node.children:
- _recurse(child, new_depth)
+ _recurse(child, new_depth, child_markup)
for child in body_node.children:
# Per-child peak depth: temporarily swap max_nesting out so we
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
index c6c0184fe..a5e3bfa0c 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py
@@ -65,6 +65,10 @@ class LanguageNodeMap:
# empty and we sniff operator text via this set of node types whose
# text content equals ``&&`` or ``||``.
boolean_operator_text_kinds: frozenset[str] = frozenset()
+ # Ternary node kind(s) that choose rather than nest: an arm of a chain
+ # (``a ? x : b ? y : z``, a dispatch) or a choice between markup (JSX).
+ # Still a CCN point; no nesting level. Empty keeps every ternary nesting.
+ flat_ternary_kinds: frozenset[str] = frozenset()
# ------------------------------------------------------------------
# Class-level analysis (LCOM4 / god-class). All three fields default
@@ -396,6 +400,7 @@ _TS = LanguageNodeMap(
),
lambda_kinds=frozenset({"arrow_function"}),
branch_kinds=frozenset({"if_statement", "ternary_expression"}),
+ flat_ternary_kinds=frozenset({"ternary_expression"}),
loop_kinds=frozenset(
{
"for_statement",
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
index ea120f74e..0a9b33138 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
@@ -72,7 +72,7 @@ from typing import TYPE_CHECKING, Any
from ..biomarkers.brain_method import BrainMethodDetector
from ..biomarkers.complex_method import ComplexMethodDetector
from ..biomarkers.large_method import LargeMethodDetector
-from ..complexity.cyclomatic import _is_boolean_operator
+from ..complexity.cyclomatic import _is_boolean_operator, is_markup
from ..complexity.languages import get_language_map
from ..complexity.nloc import is_string_stmt
from ..dataflow import find_extractions
@@ -413,7 +413,7 @@ def jsx_plumbing_dominates(fn_node: Any, lmap: LanguageNodeMap) -> bool:
node, inside = stack.pop()
if node.type in lmap.function_kinds:
continue
- in_jsx = node.type.startswith("jsx_")
+ in_jsx = is_markup(node)
has_jsx = has_jsx or in_jsx
if (node.is_named and node.type in kinds) or _is_boolean_operator(node, lmap):
total += 1
diff --git a/tests/unit/health/test_jsx_ternary_nesting.py b/tests/unit/health/test_jsx_ternary_nesting.py
new file mode 100644
index 000000000..006dcaf84
--- /dev/null
+++ b/tests/unit/health/test_jsx_ternary_nesting.py
@@ -0,0 +1,222 @@
+"""Markup and ternary dispatch are structure, not control-flow nesting.
+
+A view that picks one of ten panels with a ternary chain, or renders markup
+conditionally inside markup, read as "nests 10 levels deep". Those ternaries
+still count toward CCN; they open no nesting level. Real ``if`` / ``for`` /
+``try`` nesting, including inside a handler written in JSX, still does.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers.base import FileContext
+from repowise.core.analysis.health.biomarkers.nested_complexity import BIOMARKER
+from repowise.core.analysis.health.complexity import walk_file
+
+
+def _require(language: str) -> None:
+ from repowise.core.ingestion.parser import _get_language
+
+ if _get_language(language) is None:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+
+
+def _fn(src: str, name: str, language: str = "tsx", path: str = "/tmp/view.tsx"):
+ _require(language)
+ fns = {f.name: f for f in walk_file(path, language, src.encode()).functions}
+ assert name in fns, sorted(fns)
+ return fns[name]
+
+
+def _ctx(fn) -> FileContext:
+ return FileContext(
+ file_path="view.tsx", language="tsx", nloc=40, has_test_file=False, module=None,
+ all_functions=(fn,),
+ )
+
+
+# The shape of the dogfood example: one ternary chain choosing a panel, ten arms.
+SETTINGS_VIEW = """
+export function SettingsView({ view, onClose }: Props) {
+ return (
+ <Overlay onClose={onClose}>
+ <Main>
+ {view === 'appearance' ? (
+ <Appearance />
+ ) : view === 'about' ? (
+ <About />
+ ) : view === 'gateway' ? (
+ <Gateway />
+ ) : view === 'keybinds' ? (
+ <Keybinds />
+ ) : view.startsWith('config:') ? (
+ <Config section={view.slice(7)} />
+ ) : view === 'providers' ? (
+ <Providers />
+ ) : view === 'keys' ? (
+ <Keys />
+ ) : view === 'notifications' ? (
+ <Notifications />
+ ) : view === 'billing' ? (
+ <Billing />
+ ) : view === 'plugins' ? (
+ <Plugins />
+ ) : (
+ <Sessions />
+ )}
+ </Main>
+ </Overlay>
+ )
+}
+"""
+
+# Conditional rendering inside conditional rendering: markup, not logic.
+NESTED_RENDER = """
+export function Inspector({ entry, open, loading, error, rows }: Props) {
+ return entry ? (
+ <div>
+ {open ? (
+ loading ? (
+ <Spinner />
+ ) : error ? (
+ <Alert>{error.length > 0 ? <p>{error}</p> : null}</Alert>
+ ) : (
+ <List>{rows.map(r => (r.ok ? <Ok row={r} /> : <Bad row={r} />))}</List>
+ )
+ ) : null}
+ </div>
+ ) : null
+}
+"""
+
+# A real pyramid inside a handler written in JSX.
+HANDLER_PYRAMID = """
+export function Panel({ items, save }: Props) {
+ return (
+ <Button
+ onClick={() => {
+ for (const item of items) {
+ if (item.dirty) {
+ try {
+ if (item.remote) {
+ while (item.retries > 0) {
+ save(item)
+ }
+ }
+ } catch (err) {
+ console.error(err)
+ }
+ }
+ }
+ }}
+ />
+ )
+}
+"""
+
+
+def test_settings_view_ternary_dispatch_is_flat():
+ fn = _fn(SETTINGS_VIEW, "SettingsView")
+ assert fn.ccn == 11 # every arm is still a decision
+ assert fn.max_nesting == 0
+ assert fn.cognitive == 10 # a flat +1 per arm, like an ``else if``
+ assert BIOMARKER.detect(_ctx(fn)) == []
+
+
+def test_conditional_rendering_inside_markup_is_flat():
+ fn = _fn(NESTED_RENDER, "Inspector")
+ assert fn.ccn == 7
+ assert fn.max_nesting == 0
+ assert fn.cognitive == 6
+
+
+def test_real_pyramid_inside_a_jsx_handler_still_flagged():
+ fn = _fn(HANDLER_PYRAMID, "Panel")
+ # for > if > try > if > while: the arrow handler rolls into Panel.
+ assert fn.max_nesting == 5
+ [finding] = BIOMARKER.detect(_ctx(fn))
+ assert finding.severity.value == "high"
+
+
+def test_value_ternary_chain_is_flat_in_plain_typescript():
+ src = """
+function label(status: string, muted: boolean): string {
+ return status === 'speaking'
+ ? 'Speaking'
+ : status === 'transcribing'
+ ? 'Transcribing'
+ : (status === 'thinking' ? 'Thinking' : muted ? 'Muted' : 'Listening')
+}
+"""
+ fn = _fn(src, "label", "typescript", "/tmp/label.ts")
+ assert fn.ccn == 5
+ assert fn.max_nesting == 1 # the head opens one level, the arms none
+ assert fn.cognitive == 4 # head 1 + a flat 1 per arm
+
+
+def test_ternary_in_a_consequence_still_nests():
+ src = """
+function pick(err: unknown, active: boolean): string {
+ return err instanceof Error ? (active ? 'accept failed' : 'dismiss failed') : 'failed'
+}
+"""
+ assert _fn(src, "pick", "typescript", "/tmp/pick.ts").max_nesting == 2
+
+
+def test_pyramid_inside_a_map_arrow_in_jsx_still_nests():
+ src = """
+export function List({ items }: Props) {
+ return (
+ <ul>
+ {items.map(i => {
+ if (i.a) {
+ for (const x of i.xs) {
+ if (x.b) {
+ if (x.c) {
+ track(x)
+ }
+ }
+ }
+ }
+ return <li key={i.id} />
+ })}
+ </ul>
+ )
+}
+"""
+ assert _fn(src, "List").max_nesting == 4
+
+
+def test_value_ternary_in_a_call_argument_inside_jsx_still_nests():
+ src = """
+export function Label({ a, b }: Props) {
+ return <span>{fmt(a ? (b ? 1 : 2) : 3)}</span>
+}
+"""
+ assert _fn(src, "Label").max_nesting == 2
+
+
+def test_value_ternary_in_an_object_literal_inside_jsx_still_nests():
+ src = """
+export function Dot({ a, b }: Props) {
+ return <div style={{ color: a ? (b ? 'red' : 'green') : 'blue' }} />
+}
+"""
+ assert _fn(src, "Dot").max_nesting == 2
+
+
+def test_ternary_whose_branch_is_not_jsx_nests_outside_markup():
+ src = """
+export function Maybe({ a, b }: Props) {
+ const el = a ? b && <A /> : null
+ return el
+}
+"""
+ assert _fn(src, "Maybe").max_nesting == 1
+
+
+def test_python_conditional_expression_chain_unchanged():
+ src = "def f(a, b):\n return 1 if a else 2 if b else 3\n"
+ fn = _fn(src, "f", "python", "/tmp/f.py")
+ assert (fn.ccn, fn.max_nesting) == (3, 2)