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
refactor(cli): one outcome recorder and finalize step for init and update (#3986)
Raghav Chamadiyadf02c49d8641
diff --git a/packages/cli/src/repowise/cli/commands/_index_outcome.py b/packages/cli/src/repowise/cli/commands/_index_outcome.pynew file mode 100644index 000000000..9c79d55e0--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/_index_outcome.py@@ -0,0 +1,95 @@+"""Steps every outcome of ``repowise init`` and ``repowise update`` shares.++The telemetry outcome both commands attach to ``command_run``, and the stored+read views both refresh once every store is final.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import structlog++from repowise.cli.helpers import console, run_async++log = structlog.get_logger(__name__)+++def record_index_outcome(+ *,+ index_only: bool,+ provider: Any,+ docs_mode: str,+ pages: list | None,+ buckets: dict[str, int] | None = None,+ fields: dict[str, Any] | None = None,+) -> None:+ """Attach an anonymous index-shape outcome to the ``command_run`` event.++ Coarse buckets + enums only: each ``buckets`` count is reported as+ ``<name>_bucket``, ``fields`` as given. Provider and model are named only+ for a docs run. No repo names, paths, or exact counts. Best-effort: never+ let telemetry break the command's happy path.+ """+ try:+ from repowise.cli.platform import telemetry++ outcome: dict[str, Any] = {+ "outcome": "success",+ "index_only": bool(index_only),+ "docs_mode": docs_mode,+ **(fields or {}),+ }+ for name, count in (buckets or {}).items():+ outcome[f"{name}_bucket"] = telemetry.bucket_count(count)+ if not index_only and provider is not None:+ outcome["provider"] = getattr(provider, "provider_name", None)+ outcome["model"] = getattr(provider, "model_name", None)+ if pages:+ outcome["pages_bucket"] = telemetry.bucket_count(len(pages))+ telemetry.add_command_outcome(**{k: v for k, v in outcome.items() if v is not None})+ except Exception:+ return+++def refresh_read_snapshots(repo_path: Any) -> None:+ """Store the Fix first queue and the next-actions view for the next reader.++ A named step at every outcome of ``repowise update`` and at the end of+ ``repowise init``, once every store is final, so ``repowise next``, the+ overview and the dashboard read one row instead of rebuilding in each new+ process. A view no write has invalidated since is left as it is, so the+ "already up to date" path costs one primary-key read per view.+ Best-effort: without a snapshot a reader builds live, as before. A+ snapshot that is not written is named with its error, here rather than in+ the core log, which an update keeps at ERROR.+ """+ from repowise.cli.helpers import repo_index_session+ from repowise.core.persistence.crud.analysis.actions import write_read_snapshots++ async def _run() -> list[tuple[str, Exception]]:+ async with repo_index_session(Path(repo_path)) as opened:+ return [] if opened is None else await write_read_snapshots(*opened)++ try:+ try:+ failed = run_async(_run())+ except Exception as exc:+ failed = [("read snapshots", exc)]+ for name, exc in failed:+ log.debug("read_snapshot_not_written", snapshot=name, error=repr(exc))+ console.print(f"[yellow]Snapshot not written: {_short_error(name, exc)}[/yellow]")+ except Exception: # reporting must never fail the update+ log.debug("read_snapshot_report_failed", exc_info=True)+++def _short_error(name: str, exc: BaseException) -> str:+ """``<snapshot>: <ErrorType>: <first line>``, cut to one line and escaped+ for Rich: an error text can hold markup brackets or a whole traceback."""+ from rich.markup import escape++ first = (str(exc).strip().splitlines() or [""])[0]+ if len(first) > 160:+ first = first[:159] + "…"+ return escape(f"{name}: {type(exc).__name__}" + (f": {first}" if first else ""))diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/command.py b/packages/cli/src/repowise/cli/commands/init_cmd/command.pyindex c0ed63514..ab7fdc79f 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/command.py@@ -19,6 +19,7 @@ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElfrom rich.table import Tablefrom repowise.cli._setup import configure_cli_logging+from repowise.cli.commands._index_outcome import record_index_outcome, refresh_read_snapshotsfrom repowise.cli.editor_integrations.defaults import (get_default_disabled_project_files,get_default_integration_overrides,@@ -142,48 +143,47 @@ def _record_init_outcome() -> None:"""Attach an anonymous shape-of-the-index outcome to the ``command_run`` event.- Coarse buckets + enums only (file-count bucket, docs mode, run mode, top- language, provider/embedder names) — no repo names, paths, or exact counts.- Best-effort: never let telemetry break the command's happy path.+ File and symbol buckets, run mode, top language and embedder on top of the+ shared index shape. Best-effort: never let telemetry break the command."""try:- from repowise.cli.platform import telemetry-- outcome: dict[str, Any] = {- "outcome": "success",- "index_only": bool(effective_index_only),- "run_mode": run_mode,- "file_count_bucket": telemetry.bucket_count(getattr(result, "file_count", 0) or 0),- "symbol_count_bucket": telemetry.bucket_count(getattr(result, "symbol_count", 0) or 0),- }-lang_dist = getattr(getattr(result, "repo_structure", None), "root_language_distribution", None)+ top_language = Noneif isinstance(lang_dist, dict) and lang_dist:- outcome["top_language"] = max(lang_dist.items(), key=lambda kv: kv[1])[0]+ top_language = max(lang_dist.items(), key=lambda kv: kv[1])[0]# docs_mode carries the same three values as the state field of that# name. It used to be a bool, which collapsed "template wiki" and "no# wiki" into one number, and template runs are the ones worth counting.pages = getattr(result, "generated_pages", None) or []- det = sum(1 for p in pages if getattr(p, "provider_name", "") == "template")if not effective_index_only and provider is not None:- outcome["docs_mode"] = "llm"- outcome["provider"] = getattr(provider, "provider_name", None)- outcome["model"] = getattr(provider, "model_name", None)+ docs_mode = "llm"else:- outcome["docs_mode"] = "deterministic" if pages else "none"+ docs_mode = "deterministic" if pages else "none"+ buckets = {+ "file_count": getattr(result, "file_count", 0) or 0,+ "symbol_count": getattr(result, "symbol_count", 0) or 0,+ }if pages:- outcome["pages_bucket"] = telemetry.bucket_count(len(pages))- outcome["deterministic_pages_bucket"] = telemetry.bucket_count(det)-- if embedder_name_resolved:- outcome["embedder"] = embedder_name_resolved-- telemetry.add_command_outcome(**{k: v for k, v in outcome.items() if v is not None})+ buckets["deterministic_pages"] = sum(+ 1 for p in pages if getattr(p, "provider_name", "") == "template"+ )except Exception:return+ record_index_outcome(+ index_only=effective_index_only,+ provider=provider,+ docs_mode=docs_mode,+ pages=pages,+ buckets=buckets,+ fields={+ "run_mode": run_mode,+ "top_language": top_language,+ "embedder": embedder_name_resolved or None,+ },+ )def _print_structural_plan(@@ -1988,8 +1988,6 @@ def init_command(# Every store is final: store the views ``repowise next`` and the# dashboard read, before the editor files quote Fix first from them.- from repowise.cli.commands.update_cmd.persistence import refresh_read_snapshots-refresh_read_snapshots(repo_path)files_written = write_editor_project_files(console,diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex ad82188e6..74336f31e 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -21,6 +21,7 @@ import clickimport structlogfrom repowise.cli._setup import configure_cli_logging+from repowise.cli.commands._index_outcome import record_index_outcome, refresh_read_snapshotsfrom repowise.cli.helpers import (clear_update_queued,console,@@ -69,7 +70,6 @@ from .persistence import (heal_commit_offsets,health_analyzer_changed,parser_changed,- refresh_read_snapshots,rescan_security_if_changed,security_scanner_changed,stamp_head_commit,@@ -160,35 +160,23 @@ def _record_update_outcome() -> None:"""Attach an anonymous update-shape outcome to the ``command_run`` event.- Coarse buckets + enums only (changed-files bucket, docs mode, provider,- pages bucket). Best-effort; never breaks the command.+ Changed-files bucket on top of the shared index shape."""- try:- from repowise.cli.platform import telemetry-- # docs_mode carries the same three values as the state field of that- # name; it was a bool until an index-only update started re-rendering- # template pages, which that shape could not express. It comes from the- # repo's persisted mode, not from this run's page count: a commit that- # touched no source file re-renders nothing, and that is not the same- # as the repo having no wiki.- pages = generated_pages or []- if docs_mode is None:- docs_mode = "llm" if (not index_only and provider is not None) else "none"- outcome: dict[str, Any] = {- "outcome": "success",- "index_only": bool(index_only),- "docs_mode": docs_mode,- "changed_files_bucket": telemetry.bucket_count(changed_count),- }- if not index_only and provider is not None:- outcome["provider"] = getattr(provider, "provider_name", None)- outcome["model"] = getattr(provider, "model_name", None)- if pages:- outcome["pages_bucket"] = telemetry.bucket_count(len(pages))- telemetry.add_command_outcome(**{k: v for k, v in outcome.items() if v is not None})- except Exception:- return+ # docs_mode carries the same three values as the state field of that+ # name; it was a bool until an index-only update started re-rendering+ # template pages, which that shape could not express. It comes from the+ # repo's persisted mode, not from this run's page count: a commit that+ # touched no source file re-renders nothing, and that is not the same+ # as the repo having no wiki.+ if docs_mode is None:+ docs_mode = "llm" if (not index_only and provider is not None) else "none"+ record_index_outcome(+ index_only=index_only,+ provider=provider,+ docs_mode=docs_mode,+ pages=generated_pages,+ buckets={"changed_files": changed_count},+ )def _finish_outcome(diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 232e4f894..3d4fb1b2e 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -18,6 +18,7 @@ from typing import Anyimport structlog+from repowise.cli.commands._index_outcome import refresh_read_snapshots # noqa: F401 (re-export)from repowise.cli.helpers import (as_commit_id,console,@@ -284,48 +285,6 @@ def heal_commit_offsets(repo_path: Any) -> None:run_async(_run())-def refresh_read_snapshots(repo_path: Any) -> None:- """Store the Fix first queue and the next-actions view for the next reader.-- A named step at every outcome of ``repowise update`` and at the end of- ``repowise init``, once every store is final, so ``repowise next``, the- overview and the dashboard read one row instead of rebuilding in each new- process. A view no write has invalidated since is left as it is, so the- "already up to date" path costs one primary-key read per view.- Best-effort: without a snapshot a reader builds live, as before. A- snapshot that is not written is named with its error, here rather than in- the core log, which an update keeps at ERROR.- """- from repowise.cli.helpers import repo_index_session- from repowise.core.persistence.crud.analysis.actions import write_read_snapshots-- async def _run() -> list[tuple[str, Exception]]:- async with repo_index_session(Path(repo_path)) as opened:- return [] if opened is None else await write_read_snapshots(*opened)-- try:- try:- failed = run_async(_run())- except Exception as exc:- failed = [("read snapshots", exc)]- for name, exc in failed:- log.debug("read_snapshot_not_written", snapshot=name, error=repr(exc))- console.print(f"[yellow]Snapshot not written: {_short_error(name, exc)}[/yellow]")- except Exception: # reporting must never fail the update- log.debug("read_snapshot_report_failed", exc_info=True)---def _short_error(name: str, exc: BaseException) -> str:- """``<snapshot>: <ErrorType>: <first line>``, cut to one line and escaped- for Rich: an error text can hold markup brackets or a whole traceback."""- from rich.markup import escape-- first = (str(exc).strip().splitlines() or [""])[0]- if len(first) > 160:- first = first[:159] + "…"- return escape(f"{name}: {type(exc).__name__}" + (f": {first}" if first else ""))--# A repair window that has grown past this many commits stopped being a repair# and became a re-index: the diff it forces every update to walk is no longer# change-sized. Bounding it is what stops a step that fails on every run fromdiff --git a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.pyindex 89aca9fcb..da1c0d275 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/workspace.py@@ -587,11 +587,10 @@ def _refresh_workspace_editor_project_files(who never passed ``--agents-md`` (the default), making the index look stalelong after it was current. Mirrors the single-repo update path."""+ from repowise.cli.commands._index_outcome import refresh_read_snapshotsfrom repowise.cli.editor_integrations.defaults import get_default_project_file_overridesfrom repowise.cli.editor_setup import EditorSetupOptions, refresh_editor_project_files- from .persistence import refresh_read_snapshots-options: EditorSetupOptions | None = Noneif agents_md is not None:options = EditorSetupOptions(