Skip to content

Commit c72ba19

Browse files
fix: address PR #13 review feedback on hook retries, budget-cap fallback, and free-tier metrics
- Persist free_tier as a real metrics column; stop inferring it from zero-cost rows at read time so free-tier spend can't be inflated - Hook mode falls back to the Phase 4 template on BudgetCapExceededError instead of going silent; covered by a real-git-commit test - Bound hook-mode Gemini calls to 2 attempts, zero backoff, 900ms HTTP caps (worst case ~2.7s of the 4s hook budget); interactive commands keep full retry resilience - Remove --hook-mode/commit_msg_file from the user-facing commit command; hooks run only via the gitmate-hook entry point - Overwrite gitmate-marked hooks on reinstall so upgraded interpreter paths are refreshed - Prune stale .COMMIT_EDITMSG.* orphans left by SIGKILLed workers - Fall back to gemini*/claude* context-window family defaults for unrecognized models
1 parent 3cbbf5c commit c72ba19

12 files changed

Lines changed: 292 additions & 62 deletions

File tree

‎src/gitmate/cli.py‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -33,25 +33,8 @@ def _stub(name: str, milestone: str) -> None:
3333
@app.command()
3434
def commit(
3535
yes: bool = typer.Option(False, "--yes", "-y", help="Commit without interactive confirmation."),
36-
hook_mode: bool = typer.Option(
37-
False,
38-
"--hook-mode",
39-
help="Non-interactive hook mode (writes directly to commit message file).",
40-
),
41-
commit_msg_file: Path | None = typer.Argument( # noqa: B008
42-
None, help="Path to the commit message file in hook mode."
43-
),
4436
) -> None:
4537
"""Generate a commit message for the staged diff and review before committing."""
46-
if hook_mode:
47-
if commit_msg_file is None:
48-
err_console.print("[red]error:[/red] --hook-mode requires a commit message file path.")
49-
raise typer.Exit(1)
50-
from gitmate.hooks import _run_worker
51-
52-
_run_worker([str(commit_msg_file)])
53-
return
54-
5538
from gitmate.committer import commit_flow
5639

5740
code = commit_flow(yes=yes, console=console, secret_store=secret_store)

‎src/gitmate/config.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,11 @@ def get_context_window(cfg: GitmateConfig) -> int:
132132
return cfg.max_context_tokens
133133
if cfg.model in DEFAULT_MODEL_CONTEXT_WINDOWS:
134134
return DEFAULT_MODEL_CONTEXT_WINDOWS[cfg.model]
135+
model_name = cfg.model.lower()
136+
if model_name.startswith("gemini"):
137+
return 1_048_576
138+
if model_name.startswith("claude"):
139+
return 200_000
135140
raise UnknownModelError(
136141
f"unknown model {cfg.model!r} with no context window configured. "
137142
"Set 'max_context_tokens' in config.toml or use a known model."

‎src/gitmate/fallback.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,7 @@ def generate_commit_message(
263263
secret_store: config_mod.SecretStore | None = None,
264264
bypass_cache: bool = False,
265265
command: str | None = None,
266+
hook_mode: bool = False,
266267
) -> GenerationResult:
267268
"""Orchestrate commit message generation with graceful fallback on provider failure."""
268269
return run_generation_pipeline(
@@ -272,6 +273,7 @@ def generate_commit_message(
272273
fallback_generator=lambda: generate_fallback_message(diffs, style=cfg.commit_style),
273274
empty_diff_message="No changes staged for commit.",
274275
command=command,
276+
hook_mode=hook_mode,
275277
provider=provider,
276278
counter=counter,
277279
console=console,

‎src/gitmate/hooks.py‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import subprocess
88
import sys
99
import tempfile
10+
import time
1011
from pathlib import Path
1112

1213
HOOK_TIMEOUT_SECONDS = 4
@@ -68,10 +69,8 @@ def install_hook(cwd: Path | None = None) -> Path:
6869
path.parent.mkdir(parents=True, exist_ok=True)
6970
if path.exists():
7071
content = path.read_text(encoding="utf-8", errors="replace")
71-
if HOOK_MARKER in content:
72-
path.chmod(path.stat().st_mode | 0o111)
73-
return path
74-
raise HookError(f"{path} already exists; move or remove it before installing gitmate.")
72+
if HOOK_MARKER not in content:
73+
raise HookError(f"{path} already exists; move or remove it before installing gitmate.")
7574
path.write_text(HOOK_SCRIPT, encoding="utf-8")
7675
path.chmod(path.stat().st_mode | 0o111)
7776
return path
@@ -131,20 +130,37 @@ def _run_worker(args: list[str]) -> None:
131130

132131
from gitmate import config as config_mod
133132
from gitmate.diff_extractor import DiffExtractor
134-
from gitmate.fallback import generate_commit_message
133+
from gitmate.fallback import generate_commit_message, generate_fallback_message
134+
from gitmate.orchestrator import BudgetCapExceededError, safe_record_telemetry
135135

136136
cfg = config_mod.load_config()
137137
diffs = DiffExtractor(extra_ignores=cfg.ignore_globs).staged()
138138
if not diffs:
139139
return
140-
result = generate_commit_message(
141-
diffs=diffs,
142-
cfg=cfg,
143-
console=None,
144-
command="commit-hook",
145-
)
140+
started = time.perf_counter()
141+
try:
142+
result = generate_commit_message(
143+
diffs=diffs,
144+
cfg=cfg,
145+
console=None,
146+
command="commit-hook",
147+
hook_mode=True,
148+
)
149+
generated = result.text.rstrip()
150+
except BudgetCapExceededError:
151+
generated = generate_fallback_message(diffs, style=cfg.commit_style)
152+
safe_record_telemetry(
153+
command="commit-hook",
154+
model=cfg.model,
155+
tokens_in=None,
156+
tokens_out=None,
157+
cache_hit=False,
158+
latency_ms=int((time.perf_counter() - started) * 1000),
159+
fallback_used=True,
160+
estimated_cost_usd=0.0,
161+
free_tier=cfg.free_tier,
162+
)
146163
existing = message_file.read_text(encoding="utf-8", errors="replace")
147-
generated = result.text.rstrip()
148164
if existing.strip():
149165
new_message = f"{generated}\n\n{existing.lstrip()}"
150166
else:
@@ -154,6 +170,14 @@ def _run_worker(args: list[str]) -> None:
154170

155171
def _replace_message(message_file: Path, message: str) -> None:
156172
"""Atomically replace Git's message file so write failures preserve its contents."""
173+
cutoff = time.time() - HOOK_TIMEOUT_SECONDS
174+
for stale in message_file.parent.glob(f".{message_file.name}.*"):
175+
try:
176+
if stale.is_file() and stale.stat().st_mtime < cutoff:
177+
stale.unlink()
178+
except OSError:
179+
continue
180+
157181
mode = stat.S_IMODE(message_file.stat().st_mode)
158182
temp_path: Path | None = None
159183
try:

‎src/gitmate/metrics.py‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@
4242
cache_hit INTEGER NOT NULL,
4343
latency_ms INTEGER,
4444
fallback_used INTEGER NOT NULL,
45-
estimated_cost_usd REAL
45+
estimated_cost_usd REAL,
46+
free_tier INTEGER NOT NULL DEFAULT 0
4647
);
4748
CREATE INDEX IF NOT EXISTS idx_invocations_timestamp ON invocations(timestamp);
4849
CREATE INDEX IF NOT EXISTS idx_invocations_command ON invocations(command);
@@ -63,6 +64,7 @@ class InvocationRecord:
6364
latency_ms: int | None
6465
fallback_used: bool
6566
estimated_cost_usd: float = 0.0
67+
free_tier: bool | None = None
6668

6769

6870
@dataclass(frozen=True)
@@ -158,6 +160,9 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
158160
columns = {row[1] for row in cursor.fetchall()}
159161
if "estimated_cost_usd" not in columns:
160162
conn.execute("ALTER TABLE invocations ADD COLUMN estimated_cost_usd REAL")
163+
if "free_tier" not in columns:
164+
# Old rows are unknown: free-tier usage was not recorded, so don't guess.
165+
conn.execute("ALTER TABLE invocations ADD COLUMN free_tier INTEGER")
161166

162167

163168
def init_db(db_path: Path | str | None = None) -> Path:
@@ -213,8 +218,8 @@ def record_invocation(
213218
"""
214219
INSERT INTO invocations (
215220
timestamp, command, model, tokens_in, tokens_out,
216-
cache_hit, latency_ms, fallback_used, estimated_cost_usd
217-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
221+
cache_hit, latency_ms, fallback_used, estimated_cost_usd, free_tier
222+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
218223
""",
219224
(
220225
ts,
@@ -226,6 +231,7 @@ def record_invocation(
226231
latency_ms,
227232
1 if fallback_used else 0,
228233
cost,
234+
1 if free_tier else 0,
229235
),
230236
)
231237
except Exception as exc: # noqa: BLE001
@@ -248,7 +254,7 @@ def get_invocations(
248254
query = (
249255
"SELECT id, timestamp, command, model, tokens_in, tokens_out, "
250256
"cache_hit, latency_ms, fallback_used, "
251-
"COALESCE(estimated_cost_usd, 0.0) as estimated_cost_usd "
257+
"estimated_cost_usd, free_tier "
252258
"FROM invocations ORDER BY id ASC"
253259
)
254260
if limit is not None:
@@ -258,11 +264,13 @@ def get_invocations(
258264
rows = cursor.fetchall()
259265
records: list[InvocationRecord] = []
260266
for row in rows:
261-
raw_cost = float(row["estimated_cost_usd"])
262-
# If an older row had tokens but $0.00 was recorded (and not cache hit or fallback),
263-
# recalculate it at read-time against current pricing table:
267+
stored_cost = row["estimated_cost_usd"]
268+
raw_cost = float(stored_cost or 0.0)
269+
free_tier = None if row["free_tier"] is None else bool(row["free_tier"])
270+
# Reprice only known non-free rows, or rows predating cost persistence.
264271
if (
265272
raw_cost == 0.0
273+
and (free_tier is False or (free_tier is None and stored_cost is None))
266274
and not bool(row["cache_hit"])
267275
and not bool(row["fallback_used"])
268276
and ((row["tokens_in"] or 0) > 0 or (row["tokens_out"] or 0) > 0)
@@ -285,6 +293,7 @@ def get_invocations(
285293
latency_ms=row["latency_ms"],
286294
fallback_used=bool(row["fallback_used"]),
287295
estimated_cost_usd=raw_cost,
296+
free_tier=free_tier,
288297
)
289298
)
290299
return records

‎src/gitmate/orchestrator.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ def run_generation_pipeline(
118118
console: Console | None = None,
119119
secret_store: SecretStore | None = None,
120120
bypass_cache: bool = False,
121+
hook_mode: bool = False,
121122
) -> GenerationResult:
122123
"""Execute unified generation: token budgeting, chunking, caching, LLM call, and fallback."""
123124
if empty_diff_message is not None and not diffs:
@@ -142,7 +143,7 @@ def run_generation_pipeline(
142143
else:
143144
active_provider = provider
144145
else:
145-
base_provider = GeminiProvider(api_key=api_key)
146+
base_provider = GeminiProvider(api_key=api_key, hook_mode=hook_mode)
146147
if bypass_cache:
147148
active_provider = base_provider
148149
else:
@@ -158,7 +159,7 @@ def run_generation_pipeline(
158159
elif provider is not None:
159160
active_counter = HeuristicTokenCounter()
160161
else:
161-
active_counter = GeminiTokenCounter(api_key=api_key)
162+
active_counter = GeminiTokenCounter(api_key=api_key, hook_mode=hook_mode)
162163

163164
t0 = time.perf_counter()
164165
gen_result: GenerationResult
@@ -183,6 +184,14 @@ def run_generation_pipeline(
183184
chunk_cost = 0.0
184185

185186
if decision.strategy is BudgetStrategy.NEEDS_CHUNKING:
187+
if hook_mode:
188+
gen_result = GenerationResult(
189+
text=fallback_generator(),
190+
is_fallback=True,
191+
model=cfg.model,
192+
fallback_reason="Hook time budget does not allow chunked generation.",
193+
)
194+
return gen_result
186195
if not decision.omitted_diffs:
187196
if console is not None:
188197
console.print(

‎src/gitmate/providers/gemini.py‎

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,32 @@
44

55
from typing import TYPE_CHECKING
66

7-
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
7+
from tenacity import (
8+
retry,
9+
retry_if_exception_type,
10+
stop_after_attempt,
11+
wait_exponential,
12+
wait_fixed,
13+
)
814

915
from gitmate.providers.base import LLMResponse, ProviderUnavailable, RetryableProviderError
1016

1117
if TYPE_CHECKING:
1218
from google import genai
1319

20+
HOOK_REQUEST_TIMEOUT_MS = 900
21+
HOOK_GENERATION_ATTEMPTS = 2
22+
23+
24+
def hook_http_options() -> object:
25+
"""Limit each Gemini HTTP request and disable SDK-level retries for hooks."""
26+
from google.genai import types
27+
28+
return types.HttpOptions(
29+
timeout=HOOK_REQUEST_TIMEOUT_MS,
30+
retry_options=types.HttpRetryOptions(attempts=1),
31+
)
32+
1433

1534
def _is_transient(exc: BaseException) -> bool:
1635
"""True for failures worth retrying: 5xx, 429 rate limits, transport."""
@@ -28,9 +47,15 @@ def _is_transient(exc: BaseException) -> bool:
2847
class GeminiProvider:
2948
"""LLMProvider backed by Google's Gemini models via google-genai."""
3049

31-
def __init__(self, api_key: str | None = None, client: genai.Client | None = None) -> None:
50+
def __init__(
51+
self,
52+
api_key: str | None = None,
53+
client: genai.Client | None = None,
54+
hook_mode: bool = False,
55+
) -> None:
3256
self._client = client
3357
self._api_key = api_key
58+
self._hook_mode = hook_mode
3459

3560
def _get_client(self) -> genai.Client:
3661
if self._client is not None:
@@ -41,12 +66,20 @@ def _get_client(self) -> genai.Client:
4166
)
4267
from google import genai
4368

44-
self._client = genai.Client(api_key=self._api_key)
69+
if self._hook_mode:
70+
self._client = genai.Client(api_key=self._api_key, http_options=hook_http_options())
71+
else:
72+
self._client = genai.Client(api_key=self._api_key)
4573
return self._client
4674

4775
def generate(self, prompt: str, model: str) -> LLMResponse:
4876
"""Generate text for prompt, retrying transient failures then raising."""
4977
try:
78+
if self._hook_mode:
79+
return self._generate_with_retry.retry_with( # type: ignore[attr-defined]
80+
stop=stop_after_attempt(HOOK_GENERATION_ATTEMPTS),
81+
wait=wait_fixed(0),
82+
)(self._get_client(), prompt, model)
5083
return self._generate_with_retry(self._get_client(), prompt, model)
5184
except RetryableProviderError as exc:
5285
raise ProviderUnavailable(f"Gemini unavailable after retries: {exc}") from exc

‎src/gitmate/token_budget.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,11 @@ def __init__(
5151
self,
5252
api_key: str | None = None,
5353
client: genai.Client | None = None,
54+
hook_mode: bool = False,
5455
) -> None:
5556
self._client = client
5657
self._api_key = api_key
58+
self._hook_mode = hook_mode
5759

5860
def _get_client(self) -> genai.Client:
5961
if self._client is not None:
@@ -64,7 +66,15 @@ def _get_client(self) -> genai.Client:
6466
)
6567
from google import genai
6668

67-
self._client = genai.Client(api_key=self._api_key)
69+
if self._hook_mode:
70+
from gitmate.providers.gemini import hook_http_options
71+
72+
self._client = genai.Client(
73+
api_key=self._api_key,
74+
http_options=hook_http_options(),
75+
)
76+
else:
77+
self._client = genai.Client(api_key=self._api_key)
6878
return self._client
6979

7080
def count_tokens(self, text: str, model: str) -> int:

‎tests/test_config.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,14 @@ def test_get_context_window_unknown_model_raises() -> None:
142142
assert issubclass(UnknownModelError, ConfigError)
143143

144144

145+
@pytest.mark.parametrize(
146+
("model", "expected"),
147+
[("gemini-future-model", 1_048_576), ("claude-future-model", 200_000)],
148+
)
149+
def test_get_context_window_uses_family_default(model: str, expected: int) -> None:
150+
assert get_context_window(GitmateConfig(model=model)) == expected
151+
152+
145153
def test_get_context_window_unknown_model_with_override() -> None:
146154
cfg = GitmateConfig(model="unknown-model-xyz", max_context_tokens=32_000)
147155
assert get_context_window(cfg) == 32_000

0 commit comments

Comments
 (0)