Skip to content

Commit a771786

Browse files
fix: address review findings on billing, markup, and prompt fidelity
- free-tier: pass free_tier to commit telemetry so spend is not repriced at paid rates (bug 1) - ui: render preview, git output, and menus as literal text so [brackets] survive (bug 2) - prompt: label size-truncated and binary files by path in the prompt (bugs 3, 4) - config: honour ignore_globs in pr-summary and changelog extractors (bug 5) - cache: don't bill chunk summaries served from cache; track last_hit on CachedProvider (bug 6) - budget: check the monthly cap once per command via check_budget flag (bug 7) - fallback: say 'Token budgeting failed' instead of 'API unavailable' (bug 8)
1 parent fc744ec commit a771786

11 files changed

Lines changed: 219 additions & 34 deletions

File tree

‎src/gitmate/changelog.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def generate_changelog(
221221
extractor = (
222222
diff_extractor
223223
if diff_extractor is not None
224-
else DiffExtractor(repo=repo_path, runner=runner)
224+
else DiffExtractor(repo=repo_path, runner=runner, extra_ignores=active_cfg.ignore_globs)
225225
)
226226
diffs = []
227227
if include_diff:
@@ -253,6 +253,7 @@ def generate_changelog(
253253
console=con,
254254
secret_store=secret_store,
255255
bypass_cache=bypass_cache,
256+
check_budget=False, # already checked above
256257
)
257258

258259
if output_file is not None:

‎src/gitmate/chunking.py‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ def summarize_omitted_diffs(
4242
"""Summarize omitted diffs per file/chunk and return merged notes and token usage.
4343
4444
Consumes BudgetDecision.omitted_diffs (which preserves untruncated patches),
45-
prompts the provider for concise per-file summaries, and aggregates token usage.
45+
prompts the provider for concise per-file summaries, and aggregates billed token
46+
usage (responses served from a CachedProvider are excluded).
4647
"""
4748
summaries: list[str] = []
4849
total_in = 0
@@ -63,10 +64,12 @@ def summarize_omitted_diffs(
6364
f"{chunk}"
6465
)
6566
resp = provider.generate(prompt=prompt, model=model)
66-
if resp.input_tokens is not None:
67-
total_in += resp.input_tokens
68-
if resp.output_tokens is not None:
69-
total_out += resp.output_tokens
67+
# Cache hits consumed no API tokens this run; don't bill them.
68+
if not getattr(provider, "last_hit", False):
69+
if resp.input_tokens is not None:
70+
total_in += resp.input_tokens
71+
if resp.output_tokens is not None:
72+
total_out += resp.output_tokens
7073
text = resp.text.strip()
7174
if text:
7275
file_part_summaries.append(text)

‎src/gitmate/committer.py‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
from pathlib import Path
1414

1515
from rich.console import Console
16+
from rich.markup import escape
1617
from rich.panel import Panel
18+
from rich.text import Text
1719

1820
from gitmate import config as config_mod
1921
from gitmate.config import GitmateConfig
@@ -56,7 +58,7 @@ def _render_panel(console: Console, message: str, model: str, is_fallback: bool)
5658
else f"[green bold]{model}[/green bold]"
5759
)
5860
panel = Panel(
59-
message,
61+
Text(message),
6062
title=f"Proposed Commit Message [dim]({status_badge})[/dim]",
6163
border_style="yellow" if is_fallback else "green",
6264
padding=(1, 2),
@@ -88,12 +90,12 @@ def _execute_commit(message: str, console: Console | None = None, cwd: Path | No
8890
)
8991
if proc.returncode == 0:
9092
if console is not None and proc.stdout.strip():
91-
console.print(proc.stdout.strip())
93+
console.print(Text(proc.stdout.strip()))
9294
else:
9395
if console is not None:
9496
err_msg = proc.stderr.strip() or proc.stdout.strip()
9597
if err_msg:
96-
console.print(f"[red]{err_msg}[/red]")
98+
console.print(Text(err_msg, style="red"))
9799
return proc.returncode
98100
except FileNotFoundError:
99101
if console is not None:
@@ -236,6 +238,7 @@ def commit_flow(
236238
console=con,
237239
secret_store=secret_store,
238240
bypass_cache=False,
241+
check_budget=False,
239242
)
240243
latency_ms = int((time.perf_counter() - t0) * 1000)
241244

@@ -248,6 +251,7 @@ def commit_flow(
248251
latency_ms=latency_ms,
249252
fallback_used=gen_result.is_fallback,
250253
estimated_cost_usd=gen_result.estimated_cost_usd,
254+
free_tier=active_cfg.free_tier,
251255
)
252256

253257
current_message = gen_result.text
@@ -265,7 +269,7 @@ def commit_flow(
265269
while True:
266270
try:
267271
raw_input = con.input(
268-
"[bold cyan]?[/bold cyan] [bold][a]ccept / [e]dit / [r]egenerate / [c]ancel:[/bold] "
272+
"[bold cyan]?[/bold cyan] [bold]\\[a]ccept / \\[e]dit / \\[r]egenerate / \\[c]ancel:[/bold] "
269273
)
270274
except (EOFError, KeyboardInterrupt):
271275
con.print("\nCommit cancelled.")
@@ -274,7 +278,7 @@ def commit_flow(
274278
choice = raw_input.strip().lower()
275279
if not choice:
276280
con.print(
277-
"[yellow]Please select an option: [a]ccept, [e]dit, [r]egenerate, or [c]ancel.[/yellow]"
281+
"[yellow]Please select an option: \\[a]ccept, \\[e]dit, \\[r]egenerate, or \\[c]ancel.[/yellow]"
278282
)
279283
continue
280284

@@ -306,6 +310,7 @@ def commit_flow(
306310
console=con,
307311
secret_store=secret_store,
308312
bypass_cache=True,
313+
check_budget=False,
309314
)
310315
latency_ms = int((time.perf_counter() - t0) * 1000)
311316

@@ -318,6 +323,7 @@ def commit_flow(
318323
latency_ms=latency_ms,
319324
fallback_used=gen_result.is_fallback,
320325
estimated_cost_usd=gen_result.estimated_cost_usd,
326+
free_tier=active_cfg.free_tier,
321327
)
322328

323329
current_message = gen_result.text
@@ -331,6 +337,6 @@ def commit_flow(
331337

332338
else:
333339
con.print(
334-
f"[yellow]Invalid selection '{raw_input}'. "
335-
"Please choose [a]ccept, [e]dit, [r]egenerate, or [c]ancel.[/yellow]"
340+
f"[yellow]Invalid selection '{escape(raw_input)}'. "
341+
"Please choose \\[a]ccept, \\[e]dit, \\[r]egenerate, or \\[c]ancel.[/yellow]"
336342
)

‎src/gitmate/fallback.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,7 @@ def generate_commit_message(
264264
bypass_cache: bool = False,
265265
command: str | None = None,
266266
hook_mode: bool = False,
267+
check_budget: bool = True,
267268
) -> GenerationResult:
268269
"""Orchestrate commit message generation with graceful fallback on provider failure."""
269270
return run_generation_pipeline(
@@ -279,4 +280,5 @@ def generate_commit_message(
279280
console=console,
280281
secret_store=secret_store,
281282
bypass_cache=bypass_cache,
283+
check_budget=check_budget,
282284
)

‎src/gitmate/orchestrator.py‎

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@
1717
from gitmate.metrics import calculate_cost, get_monthly_spend, record_invocation
1818
from gitmate.prompt import load_template, render_prompt
1919
from gitmate.providers.base import LLMProvider, ProviderUnavailable
20-
from gitmate.providers.cache import CachedProvider, cache_key
20+
from gitmate.providers.cache import CachedProvider
2121
from gitmate.providers.gemini import GeminiProvider
2222
from gitmate.token_budget import (
23+
OMITTED_NOTE_PREFIX,
2324
BudgetStrategy,
2425
GeminiTokenCounter,
2526
HeuristicTokenCounter,
@@ -105,6 +106,23 @@ def check_budget_cap(cfg: GitmateConfig, console: Console | None = None) -> None
105106
)
106107

107108

109+
def _prompt_diff_text(diffs: list[FileDiff]) -> str:
110+
"""Join patches for the prompt, labelling files whose patch text lacks a header.
111+
112+
Binary files carry no patch and truncated files carry only a size note, so
113+
without a label the model would never learn which file they were.
114+
"""
115+
parts: list[str] = []
116+
for d in diffs:
117+
if d.is_binary:
118+
parts.append(f"Binary file {d.path} ({d.status})")
119+
elif d.patch_text.startswith(OMITTED_NOTE_PREFIX):
120+
parts.append(f"File {d.path} ({d.status}): {d.patch_text}")
121+
elif d.patch_text:
122+
parts.append(d.patch_text)
123+
return "\n".join(parts)
124+
125+
108126
def run_generation_pipeline(
109127
diffs: list[FileDiff],
110128
cfg: GitmateConfig,
@@ -119,16 +137,22 @@ def run_generation_pipeline(
119137
secret_store: SecretStore | None = None,
120138
bypass_cache: bool = False,
121139
hook_mode: bool = False,
140+
check_budget: bool = True,
122141
) -> GenerationResult:
123-
"""Execute unified generation: token budgeting, chunking, caching, LLM call, and fallback."""
142+
"""Execute unified generation: token budgeting, chunking, caching, LLM call, and fallback.
143+
144+
Pass check_budget=False only when the caller has already run check_budget_cap,
145+
so the 80% warning is not printed twice.
146+
"""
124147
if empty_diff_message is not None and not diffs:
125148
return GenerationResult(
126149
text=empty_diff_message,
127150
is_fallback=False,
128151
model=cfg.model,
129152
)
130153

131-
check_budget_cap(cfg, console=console)
154+
if check_budget:
155+
check_budget_cap(cfg, console=console)
132156

133157
store = secret_store if secret_store is not None else config_mod.KeyringSecretStore()
134158
api_key = store.get_secret(API_KEY_ACCOUNT) or os.environ.get("GEMINI_API_KEY")
@@ -170,7 +194,7 @@ def run_generation_pipeline(
170194
decision = budget_mgr.assess(diffs)
171195
except TokenBudgetError as exc:
172196
if console is not None:
173-
console.print("[yellow]⚠ API unavailable, using template fallback[/yellow]")
197+
console.print("[yellow]⚠ Token budgeting failed, using template fallback[/yellow]")
174198
gen_result = GenerationResult(
175199
text=fallback_generator(),
176200
is_fallback=True,
@@ -225,12 +249,9 @@ def run_generation_pipeline(
225249
summary_note = (
226250
f"{decision.summary_note}\n\nSummaries of large omitted files:\n{merged_summaries}"
227251
)
228-
patch_chunks = [d.patch_text for d in decision.included_diffs if d.patch_text]
229-
diff_text = "\n".join(patch_chunks)
230252
else:
231-
patch_chunks = [d.patch_text for d in decision.included_diffs if d.patch_text]
232-
diff_text = "\n".join(patch_chunks)
233253
summary_note = decision.summary_note
254+
diff_text = _prompt_diff_text(decision.included_diffs)
234255

235256
render_kwargs: dict[str, str] = {
236257
"diff": diff_text,
@@ -241,12 +262,8 @@ def run_generation_pipeline(
241262

242263
prompt_text, _ = render_prompt(template_name, **render_kwargs)
243264

244-
cache_hit = False
245-
if not bypass_cache and isinstance(active_provider, CachedProvider):
246-
key = cache_key(prompt_text, cfg.model, active_provider._template_version)
247-
cache_hit = active_provider._cache.get(key, default=None) is not None
248-
249265
resp = active_provider.generate(prompt=prompt_text, model=cfg.model)
266+
cache_hit = isinstance(active_provider, CachedProvider) and active_provider.last_hit
250267
if resp.input_tokens is not None:
251268
total_input_tokens += resp.input_tokens
252269
if resp.output_tokens is not None:

‎src/gitmate/pr_summary.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,11 @@ def generate_pr_summary(
9393

9494
check_budget_cap(active_cfg, console=con)
9595

96-
extractor = diff_extractor if diff_extractor is not None else DiffExtractor(repo=repo_dir)
96+
extractor = (
97+
diff_extractor
98+
if diff_extractor is not None
99+
else DiffExtractor(repo=repo_dir, extra_ignores=active_cfg.ignore_globs)
100+
)
97101
diffs = extractor.branch_comparison(base=base)
98102

99103
if not diffs:
@@ -115,6 +119,7 @@ def generate_pr_summary(
115119
console=con,
116120
secret_store=secret_store,
117121
bypass_cache=bypass_cache,
122+
check_budget=False, # already checked above
118123
)
119124

120125
if copy_to_cb:

‎src/gitmate/providers/cache.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ def __init__(
4646
self._cache = Cache(resolved)
4747
self._ttl = ttl
4848
self._template_version = template_version
49+
#: True when the most recent generate() was answered from the cache.
50+
self.last_hit = False
4951

5052
@property
5153
def underlying(self) -> LLMProvider:
@@ -56,6 +58,7 @@ def generate(self, prompt: str, model: str) -> LLMResponse:
5658
"""Return a cached response when present, else generate and store."""
5759
key = cache_key(prompt, model, self._template_version)
5860
cached: LLMResponse | None = self._cache.get(key, default=None)
61+
self.last_hit = cached is not None
5962
if cached is not None:
6063
return cached
6164
response = self._provider.generate(prompt, model)

‎src/gitmate/token_budget.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818
if TYPE_CHECKING:
1919
from google import genai
2020

21+
#: Start of the placeholder that replaces a patch dropped for size.
22+
OMITTED_NOTE_PREFIX = "[patch omitted for size:"
23+
2124

2225
class TokenBudgetError(Exception):
2326
"""Base exception for token budgeting and counting errors."""
@@ -264,7 +267,7 @@ def assess(
264267
current_tokens = total_tokens
265268

266269
for candidate in candidates:
267-
note = f"[patch omitted for size: +{candidate.additions}/-{candidate.deletions} lines]"
270+
note = f"{OMITTED_NOTE_PREFIX} +{candidate.additions}/-{candidate.deletions} lines]"
268271
if len(candidate.patch_text) <= len(note):
269272
continue
270273
omitted.append(candidate)

‎tests/test_committer.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -573,3 +573,50 @@ def test_commit_flow_budget_cap_warning_allows_commit(
573573
assert provider.call_count == 1
574574
messages = _get_git_log_messages(git_repo)
575575
assert messages[0] == "feat: allowed commit"
576+
577+
578+
# --- Regression: free-tier spend & Rich markup in the review UI ---
579+
580+
581+
def test_free_tier_commit_records_zero_spend(
582+
git_repo: Path, metrics_dir: Path, monkeypatch: pytest.MonkeyPatch
583+
) -> None:
584+
"""Free-tier commits must not be repriced at paid rates when read back."""
585+
from gitmate.metrics import get_monthly_spend
586+
587+
stage_file(git_repo, "file.txt", b"content\n")
588+
monkeypatch.setattr(sys.stdin, "isatty", lambda: False)
589+
cfg = GitmateConfig(allow_noninteractive_commit=True, free_tier=True)
590+
591+
assert commit_flow(yes=True, cfg=cfg, provider=FakeProvider()) == 0
592+
593+
invocations = get_invocations()
594+
assert invocations[0].free_tier is True
595+
assert get_monthly_spend() == 0.0
596+
597+
598+
def test_preview_and_git_output_render_brackets_literally(
599+
git_repo: Path, metrics_dir: Path, monkeypatch: pytest.MonkeyPatch
600+
) -> None:
601+
"""`[...]` in the message, menu, and git output must not be eaten as Rich markup."""
602+
stage_file(git_repo, "file.txt", b"content\n")
603+
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
604+
con = Console(record=True, width=200)
605+
prompts: list[str] = []
606+
inputs = iter(["[/oops]", "a"])
607+
608+
def _input(prompt: str = "") -> str:
609+
prompts.append(prompt)
610+
return next(inputs)
611+
612+
monkeypatch.setattr(con, "input", _input)
613+
message = "fix(cli): handle list[str] input [skip ci]"
614+
615+
assert commit_flow(console=con, provider=FakeProvider(message)) == 0
616+
617+
out = con.export_text()
618+
assert message in out # preview panel
619+
assert "Invalid selection '[/oops]'" in out # no MarkupError
620+
assert "[a]ccept, [e]dit, [r]egenerate, or [c]ancel" in out
621+
assert "[master " in out or "[main " in out # git's "[branch hash]" line
622+
assert _get_git_log_messages(git_repo)[0] == message

0 commit comments

Comments
 (0)