Skip to content

Commit 2cda9ef

Browse files
fix: address PR #12 review feedback on exit codes, stderr routing, and orchestrator consolidation
- #1 (Blocker): Fail loud with exit code 1 on git errors, budget cap breaches, and gh CLI errors across pr-summary and changelog CLI commands. - #2: Prevent duplicate printing when no changes/commits exist by early returning None. - #3: Route diagnostic warnings, budget alerts, and error messages to stderr console (err_console) to keep stdout clean for Unix piping. - #4: Correctly parse and surface breaking changes (exclamation mark and BREAKING CHANGE: footers) in conventional commits and templates. - #5: Bump changelog template to version 2, including from_ref..to_ref range and explicit release headers. - #6: Support --title (-t) flag in pr-summary and propagate gh pr create failures. - #7: Remove dead head argument from fallback PR summary. - #8: Consolidate duplicate budget checking, safe telemetry recording, and heuristic token counters into orchestrator.py. - #9: Enforce strict type hints with CommitLogEntry in fallback.py.
1 parent ed44b47 commit 2cda9ef

12 files changed

Lines changed: 436 additions & 319 deletions

File tree

‎src/gitmate/changelog.py‎

Lines changed: 15 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import logging
66
import re
7-
import time
87
from dataclasses import dataclass
98
from pathlib import Path
109

@@ -14,8 +13,7 @@
1413
from gitmate.config import GitmateConfig, SecretStore
1514
from gitmate.diff_extractor import DiffExtractor, GitCommandError, GitRunner, SubprocessGitRunner
1615
from gitmate.fallback import generate_fallback_changelog
17-
from gitmate.metrics import get_monthly_spend, record_invocation
18-
from gitmate.orchestrator import GenerationResult, run_generation_pipeline
16+
from gitmate.orchestrator import GenerationResult, check_budget_cap, run_generation_pipeline
1917
from gitmate.providers.base import LLMProvider
2018
from gitmate.token_budget import TokenCounter
2119

@@ -60,6 +58,7 @@ class CommitLogEntry:
6058
commit_type: str | None = None
6159
scope: str | None = None
6260
description: str | None = None
61+
is_breaking: bool = False
6362

6463

6564
def parse_commit_message(
@@ -75,6 +74,9 @@ def parse_commit_message(
7574
c_type = match.group("type").lower()
7675
scope = match.group("scope")
7776
desc = match.group("desc").strip()
77+
is_breaking = bool(match.group("breaking")) or (
78+
"BREAKING CHANGE:" in body or "BREAKING-CHANGE:" in body
79+
)
7880
return CommitLogEntry(
7981
commit_hash=commit_hash,
8082
subject=subject.strip(),
@@ -84,8 +86,10 @@ def parse_commit_message(
8486
commit_type=c_type,
8587
scope=scope,
8688
description=desc,
89+
is_breaking=is_breaking,
8790
)
8891

92+
is_breaking = "BREAKING CHANGE:" in body or "BREAKING-CHANGE:" in body
8993
return CommitLogEntry(
9094
commit_hash=commit_hash,
9195
subject=subject.strip(),
@@ -95,6 +99,7 @@ def parse_commit_message(
9599
commit_type=None,
96100
scope=None,
97101
description=subject.strip(),
102+
is_breaking=is_breaking,
98103
)
99104

100105

@@ -173,41 +178,14 @@ def format_commits_for_prompt(grouped: dict[str, list[CommitLogEntry]]) -> str:
173178
for item in items:
174179
scope_prefix = f"({item.scope}): " if item.scope else ": "
175180
t = item.commit_type or "other"
181+
breaking_marker = "!" if item.is_breaking else ""
176182
desc = item.description or item.subject
177-
sections.append(f"- [{item.commit_hash[:7]}] {t}{scope_prefix}{desc}")
183+
sections.append(f"- [{item.commit_hash[:7]}] {t}{breaking_marker}{scope_prefix}{desc}")
178184
sections.append("")
179185

180186
return "\n".join(sections).strip()
181187

182188

183-
def _safe_record_telemetry(
184-
command: str,
185-
model: str,
186-
tokens_in: int | None,
187-
tokens_out: int | None,
188-
cache_hit: bool,
189-
latency_ms: int | None,
190-
fallback_used: bool,
191-
estimated_cost_usd: float | None = None,
192-
free_tier: bool = False,
193-
) -> None:
194-
"""Record invocation to metrics database without propagating errors."""
195-
try:
196-
record_invocation(
197-
command=command,
198-
model=model,
199-
tokens_in=tokens_in,
200-
tokens_out=tokens_out,
201-
cache_hit=cache_hit,
202-
latency_ms=latency_ms,
203-
fallback_used=fallback_used,
204-
estimated_cost_usd=estimated_cost_usd,
205-
free_tier=free_tier,
206-
)
207-
except Exception as exc: # noqa: BLE001
208-
logger.warning("Failed to record telemetry: %s", exc)
209-
210-
211189
def generate_changelog(
212190
from_ref: str,
213191
to_ref: str = "HEAD",
@@ -227,46 +205,15 @@ def generate_changelog(
227205
con = console if console is not None else Console()
228206
active_cfg = cfg if cfg is not None else config_mod.load_config()
229207

230-
# Budget cap check
231-
if active_cfg.budget_cap_usd is not None:
232-
monthly_spend = get_monthly_spend()
233-
if monthly_spend >= active_cfg.budget_cap_usd:
234-
con.print(
235-
f"[red]error:[/red] Monthly budget cap exceeded "
236-
f"(${monthly_spend:.2f} >= ${active_cfg.budget_cap_usd:.2f}). "
237-
"Aborting to prevent further LLM spend."
238-
)
239-
return GenerationResult(
240-
text="Monthly budget cap exceeded. Generation aborted.",
241-
is_fallback=True,
242-
model=active_cfg.model,
243-
fallback_reason="Monthly budget cap exceeded",
244-
)
245-
if monthly_spend >= 0.8 * active_cfg.budget_cap_usd:
246-
con.print(
247-
f"[yellow]warning: Monthly spend has reached {int(monthly_spend / active_cfg.budget_cap_usd * 100)}% "
248-
f"of budget cap (${monthly_spend:.2f} / ${active_cfg.budget_cap_usd:.2f}).[/yellow]"
249-
)
208+
check_budget_cap(active_cfg, console=con)
250209

251210
repo_path = repo_dir if repo_dir is not None else Path.cwd()
252211
runner = git_runner if git_runner is not None else SubprocessGitRunner()
253212

254-
try:
255-
commits = extract_commits_between(from_ref, to_ref, runner=runner, repo=repo_path)
256-
except GitCommandError as exc:
257-
con.print(f"[red]git error:[/red] {exc}")
258-
return GenerationResult(
259-
text=f"Git error: {exc}",
260-
is_fallback=True,
261-
model=active_cfg.model,
262-
fallback_reason=str(exc),
263-
)
264-
213+
commits = extract_commits_between(from_ref, to_ref, runner=runner, repo=repo_path)
265214
if not commits:
266-
empty_msg = f"No commits found between '{from_ref}' and '{to_ref}'."
267-
con.print(f"[dim]{empty_msg}[/dim]")
268215
return GenerationResult(
269-
text=empty_msg,
216+
text=f"No commits found between '{from_ref}' and '{to_ref}'.",
270217
is_fallback=False,
271218
model=active_cfg.model,
272219
)
@@ -288,16 +235,6 @@ def generate_changelog(
288235
grouped = group_commits(commits)
289236
formatted_commits = format_commits_for_prompt(grouped)
290237

291-
active_counter = counter
292-
if active_counter is None and provider is not None:
293-
294-
class _SimpleCounter(TokenCounter):
295-
def count_tokens(self, text: str, model: str) -> int:
296-
return max(1, len(text) // 4)
297-
298-
active_counter = _SimpleCounter()
299-
300-
t0 = time.perf_counter()
301238
gen_result = run_generation_pipeline(
302239
diffs=diffs,
303240
cfg=active_cfg,
@@ -310,25 +247,13 @@ def count_tokens(self, text: str, model: str) -> int:
310247
"from_ref": from_ref,
311248
"to_ref": to_ref,
312249
},
250+
command="changelog",
313251
provider=provider,
314-
counter=active_counter,
252+
counter=counter,
315253
console=con,
316254
secret_store=secret_store,
317255
bypass_cache=bypass_cache,
318256
)
319-
latency_ms = int((time.perf_counter() - t0) * 1000)
320-
321-
_safe_record_telemetry(
322-
command="changelog",
323-
model=gen_result.model,
324-
tokens_in=gen_result.input_tokens,
325-
tokens_out=gen_result.output_tokens,
326-
cache_hit=gen_result.cache_hit,
327-
latency_ms=latency_ms,
328-
fallback_used=gen_result.is_fallback,
329-
estimated_cost_usd=gen_result.estimated_cost_usd,
330-
free_tier=active_cfg.free_tier,
331-
)
332257

333258
if output_file is not None:
334259
try:

‎src/gitmate/cli.py‎

Lines changed: 43 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
app.add_typer(config_app, name="config")
2222

2323
console = Console()
24+
err_console = Console(stderr=True)
2425
secret_store: config_mod.SecretStore = config_mod.KeyringSecretStore()
2526

2627

@@ -121,6 +122,7 @@ def stats(
121122
@app.command("pr-summary")
122123
def pr_summary(
123124
base: str = typer.Option("main", "--base", "-b", help="Base branch to compare against."),
125+
title: str | None = typer.Option(None, "--title", "-t", help="PR title for gh pr create."),
124126
copy: bool = typer.Option(True, "--copy/--no-copy", help="Copy summary to clipboard."),
125127
create_pr: bool = typer.Option(
126128
False, "--create-pr", help="Open GitHub PR create flow with gh CLI."
@@ -131,16 +133,28 @@ def pr_summary(
131133
from rich.markdown import Markdown
132134
from rich.panel import Panel
133135

134-
from gitmate.pr_summary import generate_pr_summary
136+
from gitmate.diff_extractor import GitCommandError
137+
from gitmate.orchestrator import BudgetCapExceededError
138+
from gitmate.pr_summary import GitHubCliError, generate_pr_summary
139+
140+
try:
141+
res = generate_pr_summary(
142+
base=base,
143+
title=title,
144+
console=err_console,
145+
secret_store=secret_store,
146+
bypass_cache=bypass_cache,
147+
copy_to_cb=copy,
148+
create_pr=create_pr,
149+
)
150+
except (GitCommandError, BudgetCapExceededError, GitHubCliError) as exc:
151+
err_console.print(f"[red]error:[/red] {exc}")
152+
raise typer.Exit(1) from None
153+
154+
if res.text.startswith("No changes between"):
155+
err_console.print(f"[dim]{res.text}[/dim]")
156+
return
135157

136-
res = generate_pr_summary(
137-
base=base,
138-
console=console,
139-
secret_store=secret_store,
140-
bypass_cache=bypass_cache,
141-
copy_to_cb=copy,
142-
create_pr=create_pr,
143-
)
144158
status_badge = (
145159
"[yellow bold]⚠ FALLBACK TEMPLATE[/yellow bold]"
146160
if res.is_fallback
@@ -173,16 +187,27 @@ def changelog(
173187
) -> None:
174188
"""Generate a changelog section between two git tags or revisions."""
175189
from gitmate.changelog import generate_changelog
190+
from gitmate.diff_extractor import GitCommandError
191+
from gitmate.orchestrator import BudgetCapExceededError
192+
193+
try:
194+
res = generate_changelog(
195+
from_ref=from_ref,
196+
to_ref=to_ref,
197+
include_diff=include_diff,
198+
output_file=output,
199+
console=err_console,
200+
secret_store=secret_store,
201+
bypass_cache=bypass_cache,
202+
)
203+
except (GitCommandError, BudgetCapExceededError) as exc:
204+
err_console.print(f"[red]error:[/red] {exc}")
205+
raise typer.Exit(1) from None
206+
207+
if res.text.startswith("No commits found"):
208+
err_console.print(f"[dim]{res.text}[/dim]")
209+
return
176210

177-
res = generate_changelog(
178-
from_ref=from_ref,
179-
to_ref=to_ref,
180-
include_diff=include_diff,
181-
output_file=output,
182-
console=console,
183-
secret_store=secret_store,
184-
bypass_cache=bypass_cache,
185-
)
186211
if output is None:
187212
typer.echo(res.text)
188213

‎src/gitmate/committer.py‎

Lines changed: 20 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,13 @@
1919
from gitmate.config import GitmateConfig
2020
from gitmate.diff_extractor import DiffExtractor, GitCommandError
2121
from gitmate.fallback import generate_commit_message
22-
from gitmate.metrics import get_monthly_spend, record_invocation
22+
from gitmate.orchestrator import (
23+
BudgetCapExceededError,
24+
check_budget_cap,
25+
safe_record_telemetry,
26+
)
2327
from gitmate.providers.base import LLMProvider
24-
from gitmate.token_budget import TokenCounter
28+
from gitmate.token_budget import HeuristicTokenCounter, TokenCounter
2529

2630
logger = logging.getLogger("gitmate.committer")
2731

@@ -30,31 +34,7 @@
3034
"# with '#' will be ignored, and an empty message aborts the commit.\n"
3135
)
3236

33-
34-
def _safe_record_telemetry(
35-
command: str,
36-
model: str,
37-
tokens_in: int | None,
38-
tokens_out: int | None,
39-
cache_hit: bool,
40-
latency_ms: int | None,
41-
fallback_used: bool,
42-
estimated_cost_usd: float | None = None,
43-
) -> None:
44-
"""Record invocation to metrics database without propagating errors."""
45-
try:
46-
record_invocation(
47-
command=command,
48-
model=model,
49-
tokens_in=tokens_in,
50-
tokens_out=tokens_out,
51-
cache_hit=cache_hit,
52-
latency_ms=latency_ms,
53-
fallback_used=fallback_used,
54-
estimated_cost_usd=estimated_cost_usd,
55-
)
56-
except Exception as exc: # noqa: BLE001
57-
logger.warning("Failed to record telemetry: %s", exc)
37+
_safe_record_telemetry = safe_record_telemetry
5838

5939

6040
def _resolve_editor() -> str:
@@ -235,30 +215,16 @@ def commit_flow(
235215
return 1
236216

237217
# 3. Monthly budget cap enforcement
238-
if active_cfg.budget_cap_usd is not None:
239-
monthly_spend = get_monthly_spend()
240-
if monthly_spend >= active_cfg.budget_cap_usd:
241-
con.print(
242-
f"[red]error:[/red] Monthly budget cap exceeded "
243-
f"(${monthly_spend:.2f} >= ${active_cfg.budget_cap_usd:.2f}). "
244-
"Aborting to prevent further LLM spend.\n"
245-
"To adjust or remove the cap, run: gitmate config set budget_cap_usd <new_limit_or_none>"
246-
)
247-
return 1
248-
if monthly_spend >= 0.8 * active_cfg.budget_cap_usd:
249-
con.print(
250-
f"[yellow]warning: Monthly spend has reached {int(monthly_spend / active_cfg.budget_cap_usd * 100)}% "
251-
f"of budget cap (${monthly_spend:.2f} / ${active_cfg.budget_cap_usd:.2f}).[/yellow]"
252-
)
253-
254-
active_counter = counter
255-
if active_counter is None and provider is not None:
256-
257-
class _SimpleCounter(TokenCounter):
258-
def count_tokens(self, text: str, model: str) -> int:
259-
return max(1, len(text) // 4)
218+
try:
219+
check_budget_cap(active_cfg, console=con)
220+
except BudgetCapExceededError:
221+
return 1
260222

261-
active_counter = _SimpleCounter()
223+
active_counter = (
224+
counter
225+
if counter is not None
226+
else (HeuristicTokenCounter() if provider is not None else None)
227+
)
262228

263229
# 4. Initial generation & telemetry recording
264230
t0 = time.perf_counter()
@@ -325,21 +291,10 @@ def count_tokens(self, text: str, model: str) -> int:
325291
_render_panel(con, current_message, current_model, current_is_fallback)
326292

327293
elif choice in ("r", "regenerate"):
328-
if active_cfg.budget_cap_usd is not None:
329-
monthly_spend = get_monthly_spend()
330-
if monthly_spend >= active_cfg.budget_cap_usd:
331-
con.print(
332-
f"[red]error:[/red] Monthly budget cap exceeded "
333-
f"(${monthly_spend:.2f} >= ${active_cfg.budget_cap_usd:.2f}). "
334-
"Aborting to prevent further LLM spend.\n"
335-
"To adjust or remove the cap, run: gitmate config set budget_cap_usd <new_limit_or_none>"
336-
)
337-
continue
338-
if monthly_spend >= 0.8 * active_cfg.budget_cap_usd:
339-
con.print(
340-
f"[yellow]warning: Monthly spend has reached {int(monthly_spend / active_cfg.budget_cap_usd * 100)}% "
341-
f"of budget cap (${monthly_spend:.2f} / ${active_cfg.budget_cap_usd:.2f}).[/yellow]"
342-
)
294+
try:
295+
check_budget_cap(active_cfg, console=con)
296+
except BudgetCapExceededError:
297+
continue
343298

344299
con.print("Regenerating commit message with fresh API call...")
345300
t0 = time.perf_counter()

0 commit comments

Comments
 (0)