Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(overview): fold Do next on request and keep critical for live secrets (#3966)
Raghav Chamadiyaadaf956dd503
diff --git a/packages/core/src/repowise/core/analysis/actions/model.py b/packages/core/src/repowise/core/analysis/actions/model.pyindex 80b3d9a4d..a86125030 100644--- a/packages/core/src/repowise/core/analysis/actions/model.py+++ b/packages/core/src/repowise/core/analysis/actions/model.py@@ -15,7 +15,7 @@ from repowise.core.analysis.next_call import ActionCommand#: Bumped when a rule's output changes meaning or shape; stored views built#: under another version are rebuilt.-ACTIONS_MODEL_VERSION = 1+ACTIONS_MODEL_VERSION = 2ActionRule = Literal["live_secret",@@ -149,6 +149,9 @@ class Action:rule: ActionRuletier: ActionTierhorizons: tuple[Horizon, ...]+ #: Critical is for work that is both urgent and certain enough to drop+ #: other work for: a credential in the working tree. Code-health work tops+ #: out at high however many of its findings a detector tags critical.severity: str#: Verb first. Paths and symbols are wrapped in backticks, which every#: renderer sets in mono: "Raise test coverage on `a/b.py` from 62%".diff --git a/packages/core/src/repowise/core/analysis/actions/rules/code.py b/packages/core/src/repowise/core/analysis/actions/rules/code.pyindex 357fdd159..2a1a76ea4 100644--- a/packages/core/src/repowise/core/analysis/actions/rules/code.py+++ b/packages/core/src/repowise/core/analysis/actions/rules/code.py@@ -81,6 +81,18 @@ def fresh_regressions(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:)+def _regression_value(critical: int) -> int:+ """The value a regression ranks on: a week with critical findings still+ outranks one without, as it did when the action itself read critical.++ The action's severity tops out at high. Health detectors tag a long method+ critical, and a routine week of feature work leaves dozens of those, so a+ critical label here would read as an emergency most weeks. Critical on an+ action is kept for a live credential (``live_secret``).+ """+ return 4 if critical else 3++def _regression_file(path: str, found: list, ctx: RepoContext, weight: float) -> Action:symbols = sorted({f.symbol for f in found if f.symbol})critical = sum(f.severity == "critical" for f in found)@@ -97,7 +109,7 @@ def _regression_file(path: str, found: list, ctx: RepoContext, weight: float) ->rule="fresh_regressions",tier="act_now",horizons=("week",),- severity="critical" if critical else "high",+ severity="high",title=title,impact=(f"{plural(len(commits), 'commit')} in the last 7 days added or worsened "@@ -106,7 +118,7 @@ def _regression_file(path: str, found: list, ctx: RepoContext, weight: float) ->),why=(WhyFact("serious findings", str(len(found))),- WhyFact("critical", str(critical)),+ WhyFact("critical findings", str(critical)),WhyFact("latest commit", latest.subject[:72] or latest.sha[:7]),),target_kind="symbol" if len(symbols) == 1 else "file",@@ -118,6 +130,7 @@ def _regression_file(path: str, found: list, ctx: RepoContext, weight: float) ->done_when="The findings close on the next update.",marker=lead.biomarker,weight=weight,+ value=_regression_value(critical),evidence_ids=tuple(sorted(commits)),evidence_total=len(found),fingerprint=fingerprint(len(found), critical),@@ -176,7 +189,7 @@ def _regression_rollup(ranked: list[tuple[str, list]]) -> Action:rule="fresh_regressions",tier="act_now",horizons=("week",),- severity="critical" if critical else "high",+ severity="high",title=(f"Clean up what this week's commits left: {plural(len(found), 'serious finding')} "f"in {len(ranked):,} files"@@ -188,7 +201,7 @@ def _regression_rollup(ranked: list[tuple[str, list]]) -> Action:),why=(WhyFact("serious findings", str(len(found))),- WhyFact("critical", str(critical)),+ WhyFact("critical findings", str(critical)),WhyFact("files", str(len(ranked))),),target_kind="repo",@@ -198,6 +211,7 @@ def _regression_rollup(ranked: list[tuple[str, list]]) -> Action:confidence="high",done_when="The findings close on the next update.",weight=float(critical * 10 + len(found)),+ value=_regression_value(critical),evidence_ids=tuple(sorted(commits)),evidence_total=len(found),includes=tuple(path for path, _ in ranked[:10]),diff --git a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.pyindex 9ff5ab23d..6900ab6c7 100644--- a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py+++ b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py@@ -93,6 +93,8 @@ def live_secret(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:title = f"Rotate the {kind} in {code(path)}"impact = "A credential sits in the working tree; anyone who can read the repository can use it."done = "Rotate the credential with its provider, then remove it from the file."+ # The only critical action: a usable credential is exposed until it+ # is rotated, whatever else the week holds.tier, severity = "act_now", "critical"actions.append(Action(diff --git a/packages/ui/__tests__/overview/next-actions.test.tsx b/packages/ui/__tests__/overview/next-actions.test.tsxindex 6684d752a..abf5cb973 100644--- a/packages/ui/__tests__/overview/next-actions.test.tsx+++ b/packages/ui/__tests__/overview/next-actions.test.tsx@@ -153,6 +153,41 @@ describe("NextActions", () => {const { container } = render(<NextActions data={null} hrefFor={() => null} />);expect(container).toBeEmptyDOMElement();});++ it("renders open with the time frame in the header by default", () => {+ const { container } = render(<NextActions data={response([], [action()])} hrefFor={() => null} />);+ expect(container.querySelector("details")).toBeNull();+ expect(screen.getByRole("heading", { name: "Do next" })).toBeInTheDocument();+ expect(screen.getByRole("radio", { name: /This quarter/ })).toBeInTheDocument();+ expect(screen.queryByText(/suggested/)).toBeNull();+ });++ it("folds behind its heading with a count when defaultOpen is false", () => {+ const now = action({ id: "act_now", tier: "act_now", horizons: ["week"], title: "Clean up `b.ts`" });+ const { container } = render(+ <NextActions+ data={response([now], [action(), action({ id: "act_2" })])}+ hrefFor={() => null}+ defaultOpen={false}+ />,+ );+ const details = container.querySelector("details");+ expect(details).not.toBeNull();+ expect(details).not.toHaveAttribute("open");+ // The count is the default time frame's, the same one its chip shows.+ expect(within(details!.querySelector("summary")!).getByText("1 suggested")).toBeInTheDocument();++ details!.open = true;+ fireEvent.click(within(details!).getByRole("radio", { name: /This quarter/ }));+ expect(within(details!).getByRole("radio", { name: /This quarter/ })).toHaveAttribute(+ "aria-checked",+ "true",+ );+ expect(screen.getByText("2 suggested")).toBeInTheDocument();+ // React only writes `open` when the prop changes, so a rerender keeps a+ // section the user opened open.+ expect(details!.open).toBe(true);+ });});describe("the action drawer", () => {diff --git a/packages/ui/src/overview/next-actions.tsx b/packages/ui/src/overview/next-actions.tsxindex 1ec60a172..6c85b2ce4 100644--- a/packages/ui/src/overview/next-actions.tsx+++ b/packages/ui/src/overview/next-actions.tsx@@ -44,6 +44,11 @@ export interface NextActionsProps {unavailableHint?: ReactNode | null;/** Show each command's CLI line in the drawer. Set false for a host with no CLI. */showCliCommands?: boolean;+ /**+ * Set false to start folded behind its heading, for a page where the list+ * would push everything else below the fold. Defaults to open.+ */+ defaultOpen?: boolean;LinkComponent?: ElementType | undefined;}@@ -112,6 +117,7 @@ export function NextActions({loadPrompt,unavailableHint,showCliCommands,+ defaultOpen = true,LinkComponent,}: NextActionsProps) {// Open on the week unless it holds no work and the quarter does: a lone@@ -166,26 +172,34 @@ export function NextActions({);};+ const timeFrame = (+ <Segmented+ label="Time frame"+ value={horizon}+ options={[+ { value: "week", label: "This week", count: String(work("week")), hint: "What the last 7 days of commits changed" },+ { value: "quarter", label: "This quarter", count: String(work("quarter")), hint: "What the last 90 days say is worth planning" },+ ]}+ onChange={(v) => {+ setHorizon(v);+ setExpanded(false);+ }}+ />+ );return (<OverviewSectiontitle="Do next"description={data.summary?.[horizon] ?? fallbackSummary(data, horizon)}- action={- <Segmented- label="Time frame"- value={horizon}- options={[- { value: "week", label: "This week", count: String(work("week")), hint: "What the last 7 days of commits changed" },- { value: "quarter", label: "This quarter", count: String(work("quarter")), hint: "What the last 90 days say is worth planning" },- ]}- onChange={(v) => {- setHorizon(v);- setExpanded(false);- }}- />- }+ // A folded section has no header action slot, so the time frame sits+ // under the summary, above the list it filters, and the toggle carries+ // the count.+ action={defaultOpen ? timeFrame : undefined}+ collapsible={!defaultOpen}+ defaultOpen={defaultOpen}+ hint={defaultOpen ? undefined : `${work(horizon).toLocaleString("en-US")} suggested`}>+ {!defaultOpen && timeFrame}{shown.length === 0 && [...answered.values()].some((a) => a.horizons.includes(horizon)) ? (<p className="py-2 text-sm text-[var(--color-text-secondary)]">You have answered everything listed here. Answers are kept until the facts change.diff --git a/tests/unit/analysis/test_actions_rules.py b/tests/unit/analysis/test_actions_rules.pyindex 9eff3f038..6b06eaacc 100644--- a/tests/unit/analysis/test_actions_rules.py+++ b/tests/unit/analysis/test_actions_rules.py@@ -173,11 +173,58 @@ def test_regressions_over_three_files_roll_up() -> None:out = _run(code.fresh_regressions, _facts(recent_findings=found))(a,) = out.actionsassert a.target_kind == "repo"- assert a.severity == "critical"+ assert a.severity == "high"assert a.includes[0] == "src/worst.py"assert set(a.includes) == {"src/worst.py", *(f"src/f{i}.py" for i in range(4))}+def test_regressions_with_many_critical_findings_top_out_at_high() -> None:+ """heyputer/everything: 132 detector-critical findings in a week of commits+ read as a CRITICAL action. The count stays a fact; the label stays high."""+ found = tuple(+ _recent(f"src/f{i}.py", severity="critical", sha=f"s{i}") for i in range(40)+ )+ (rollup,) = _run(code.fresh_regressions, _facts(recent_findings=found)).actions+ (single,) = _run(code.fresh_regressions, _facts(recent_findings=found[:1])).actions+ for a in (rollup, single):+ assert a.severity == "high"+ assert dict((w.label, w.value) for w in a.why)["critical findings"] == (+ "40" if a is rollup else "1"+ )+++def test_a_week_with_critical_findings_still_outranks_one_without() -> None:+ critical = _run(+ code.fresh_regressions, _facts(recent_findings=(_recent("src/a.py", severity="critical"),))+ ).actions[0]+ high = _run(code.fresh_regressions, _facts(recent_findings=(_recent("src/a.py"),))).actions[0]+ assert critical.effective_value == SEVERITY_VALUE["critical"]+ assert high.effective_value == SEVERITY_VALUE["high"]+ assert critical.effective_priority > high.effective_priority+++def test_only_a_live_credential_is_critical() -> None:+ """Every rule over facts that would push it hardest: the one critical+ action is the credential in the working tree."""+ hot = _file(+ "src/hot.py", commits_90d=80, fix_commits_90d=40, dependents=50, lead=_LEAD,+ last_commit_at=ANCHOR - timedelta(days=1), line_coverage_pct=10.0,+ )+ facts = _facts(+ [hot],+ recent_findings=tuple(+ _recent(f"src/f{i}.py", severity="critical", sha=f"s{i}") for i in range(10)+ ),+ secrets=(SecretFacts("src/config.py", "hardcoded_secret", 4, 'API_KEY = "sk_live_abc1"'),),+ fix_first=_fix_items(),+ )+ view = compose_actions(facts, now=NOW)+ week = view["horizons"]["week"]["actions"]+ assert [a["rule"] for a in week if a["severity"] == "critical"] == ["live_secret"]+ # The secret still leads, and the week's regressions follow it in the same tier.+ assert [a["rule"] for a in week[:2]] == ["live_secret", "fresh_regressions"]++def test_regressions_unavailable_store() -> None:out = _run(code.fresh_regressions, _facts(unavailable={"commit_health": "missing"}))assert out.status == "unavailable"