lgit-cli 5.1.0__py3-none-any.whl → 5.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lgit/api.py CHANGED
@@ -19,6 +19,7 @@ from jinja2 import Template
19
19
 
20
20
  from . import cache as llm_cache
21
21
  from . import pricing, profile
22
+ from .diffing import condense_stat
22
23
  from .errors import ApiContextLengthExceeded, ApiError, LgitError
23
24
  from .markdown_output import (
24
25
  analysis_from_mapping,
@@ -35,7 +36,7 @@ from .markdown_output import (
35
36
  )
36
37
  from .models import CommitSummary, ConventionalAnalysis, ConventionalCommit, ResolvedApiMode, resolve_model_name
37
38
  from .normalization import post_process_commit_message
38
- from .validation import is_past_tense_first_word, validate_summary_quality
39
+ from .validation import is_past_tense_first_word, repair_summary_tense, validate_summary_quality
39
40
 
40
41
  if TYPE_CHECKING:
41
42
  from .config import CommitConfig
@@ -238,7 +239,7 @@ async def generate_summary_from_analysis(
238
239
  "chars": chars,
239
240
  "user_context": user_context or "",
240
241
  "details": details,
241
- "stat": stat,
242
+ "stat": condense_stat(stat, max_files=30),
242
243
  },
243
244
  )
244
245
  spec = OneShotSpec(
@@ -257,14 +258,24 @@ async def generate_summary_from_analysis(
257
258
  summary = _summary_from_output(response.output, response.text_content)
258
259
  except Exception:
259
260
  summary = ""
260
- summary = strip_type_prefix(
261
- summary
262
- or analysis.summary
263
- or fallback_summary(stat, analysis.body_texts(), limit=config.summary_hard_limit, commit_type=commit_type)
264
- )
265
- if not validate_summary_quality(summary, commit_type, stat).ok:
266
- summary = _fallback_summary_for_commit(stat, analysis.body_texts(), commit_type, config.summary_hard_limit)
267
- return summary[: config.summary_hard_limit].rstrip(" .")
261
+ chosen = ""
262
+ draft = ""
263
+ draft_rejection = ""
264
+ for raw in (summary, "" if analysis.summary is None else str(analysis.summary)):
265
+ candidate = strip_type_prefix(raw).strip()
266
+ if not candidate:
267
+ continue
268
+ accepted, rejection = _accept_summary(candidate, commit_type, stat)
269
+ if accepted:
270
+ chosen = accepted
271
+ break
272
+ if not draft:
273
+ draft, draft_rejection = candidate, rejection or ""
274
+ if not chosen and draft:
275
+ chosen = await _rewrite_summary_for_compliance(config, spec, draft, draft_rejection, commit_type, chars, stat)
276
+ if not chosen:
277
+ chosen = _fallback_summary_for_commit(stat, analysis.body_texts(), commit_type, config.summary_hard_limit)
278
+ return chosen[: config.summary_hard_limit].rstrip(" .")
268
279
 
269
280
 
270
281
  async def generate_analysis_with_map_reduce(
@@ -372,6 +383,59 @@ def _fallback_summary_for_commit(stat: str, details: Iterable[str], commit_type:
372
383
  return fallback_summary("", details_list, limit=limit, commit_type=commit_type)
373
384
 
374
385
 
386
+ def _accept_summary(candidate: str, commit_type: str, stat: str) -> tuple[str | None, str | None]:
387
+ """Validate a summary candidate, mechanically repairing a leading present-tense verb first.
388
+
389
+ Returns ``(accepted_summary, None)`` on success, else ``(None, rejection_reason)``.
390
+ """
391
+
392
+ report = validate_summary_quality(candidate, commit_type, stat)
393
+ if report.ok:
394
+ return candidate, None
395
+ repaired = repair_summary_tense(candidate)
396
+ if repaired is not None and validate_summary_quality(repaired, commit_type, stat).ok:
397
+ return repaired, None
398
+ return None, "; ".join(issue.message for issue in report.errors)
399
+
400
+
401
+ async def _rewrite_summary_for_compliance(
402
+ config: CommitConfig,
403
+ spec: OneShotSpec,
404
+ draft: str,
405
+ rejection: str,
406
+ commit_type: str,
407
+ chars: int,
408
+ stat: str,
409
+ ) -> str:
410
+ """Ask the summary model to minimally rewrite a rejected draft into a compliant summary.
411
+
412
+ A pure text-editing task with no diff, details, or stat context — much easier for a small
413
+ model than regenerating the summary from scratch.
414
+ """
415
+
416
+ system_prompt, user_prompt = render_prompt(
417
+ "summary-rewrite",
418
+ {"commit_type": commit_type, "chars": chars, "draft": draft, "rejection": rejection},
419
+ )
420
+ retry_spec = replace(
421
+ spec,
422
+ operation="summary-rewrite",
423
+ prompt_family="summary-rewrite",
424
+ system_prompt=system_prompt,
425
+ user_prompt=user_prompt,
426
+ progress_label="summary rewrite",
427
+ )
428
+ try:
429
+ response = await _run_oneshot_response(config, retry_spec)
430
+ candidate = strip_type_prefix(_summary_from_output(response.output, response.text_content)).strip()
431
+ except Exception:
432
+ return ""
433
+ if not candidate:
434
+ return ""
435
+ accepted, _ = _accept_summary(candidate, commit_type, stat)
436
+ return accepted or ""
437
+
438
+
375
439
  def render_prompt(family: str, context: Mapping[str, Any]) -> tuple[str, str]:
376
440
  """Render a prompt through ``lgit.templates`` with resource fallback."""
377
441
 
@@ -831,6 +895,13 @@ def _render_with_template_helper(templates: Any, family: str, context: Mapping[s
831
895
  str(context.get("stat", "")),
832
896
  context.get("user_context"),
833
897
  )
898
+ case "summary-rewrite":
899
+ parts = helper(
900
+ str(context.get("commit_type", "")),
901
+ str(context.get("chars", "")),
902
+ str(context.get("draft", "")),
903
+ str(context.get("rejection", "")),
904
+ )
834
905
  case "map":
835
906
  parts = helper(context.get("files", ()), str(context.get("context_header", "")))
836
907
  case "reduce":
lgit/changelog.py CHANGED
@@ -15,6 +15,7 @@ from . import style
15
15
  from .diffing import scrub_diff_for_prompt, smart_truncate_diff
16
16
  from .errors import GitError, ValidationFailure
17
17
  from .git import run_git
18
+ from .map_reduce import render_observations_markdown
18
19
  from .markdown_output import parse_changelog_response
19
20
  from .models import ChangelogCategory, resolve_model_name
20
21
  from .templates import render_changelog_prompt
@@ -252,12 +253,8 @@ def _observations_markdown(observations: Sequence[FileObservation] | None, files
252
253
  if observations is None:
253
254
  return None
254
255
  wanted = set(files)
255
- sections = [
256
- "# {}\n{}".format(item.file, "\n".join(f"- {text}" for text in item.observations))
257
- for item in observations
258
- if item.file in wanted and item.observations
259
- ]
260
- return "\n\n".join(sections) if sections else None
256
+ covered = [item for item in observations if item.file in wanted and item.observations]
257
+ return render_observations_markdown(covered) if covered else None
261
258
 
262
259
 
263
260
  @dataclass(slots=True)
lgit/cli.py CHANGED
@@ -436,6 +436,7 @@ def _load_config(args: argparse.Namespace) -> CommitConfig:
436
436
  resolved_model = resolve_model_name(args.model)
437
437
  config.analysis_model = resolved_model
438
438
  config.summary_model = resolved_model
439
+ config.map_model = resolved_model
439
440
  if args.sign:
440
441
  config.gpg_sign = True
441
442
  if args.signoff:
@@ -573,8 +574,14 @@ async def _generate_standard_workflow(
573
574
  )
574
575
  with profile.section("create_token_counter", collector):
575
576
  token_counter = create_token_counter(config)
576
- if config.analysis_model == config.summary_model:
577
+ if config.analysis_model == config.summary_model == config.effective_map_model:
577
578
  style.status(f"{style.dim('›')} {style.dim('model:')} {style.model(config.analysis_model)}")
579
+ elif config.effective_map_model != config.summary_model:
580
+ style.status(
581
+ f"{style.dim('›')} {style.dim('models:')} {style.dim('map')} "
582
+ f"{style.model(config.effective_map_model)} {style.dim('analysis')} "
583
+ f"{style.model(config.analysis_model)} {style.dim('summary')} {style.model(config.summary_model)}"
584
+ )
578
585
  else:
579
586
  style.status(
580
587
  f"{style.dim('›')} {style.dim('models:')} {style.dim('analysis')} "
lgit/compose.py CHANGED
@@ -352,7 +352,9 @@ async def run_compose_round(
352
352
  observations = []
353
353
  planning_diff = diffing.scrub_diff_for_prompt(snapshot.diff)
354
354
  if not _is_large_compose_snapshot(snapshot) and _should_use_map_reduce(planning_diff, config, token_counter):
355
- observations = await map_reduce.observe_diff_files(planning_diff, config.summary_model, config, token_counter)
355
+ observations = await map_reduce.observe_diff_files(
356
+ planning_diff, config.effective_map_model, config, token_counter
357
+ )
356
358
  if observations:
357
359
  _save_debug_artifact(
358
360
  args,
lgit/config.py CHANGED
@@ -93,6 +93,7 @@ class CommitConfig:
93
93
  wide_change_threshold: float = 0.50
94
94
  analysis_model: str = DEFAULT_ANALYSIS_MODEL
95
95
  summary_model: str = DEFAULT_SUMMARY_MODEL
96
+ map_model: str = ""
96
97
  legacy_model: str | None = None
97
98
  excluded_files: list[str] = field(default_factory=lambda: list(DEFAULT_EXCLUDED_FILES))
98
99
  low_priority_extensions: list[str] = field(default_factory=lambda: list(DEFAULT_LOW_PRIORITY_EXTENSIONS))
@@ -160,6 +161,11 @@ class CommitConfig:
160
161
  kwargs[key] = _FIELD_COERCERS[key](value)
161
162
  return cls(**kwargs)
162
163
 
164
+ @property
165
+ def effective_map_model(self) -> str:
166
+ """Return the model for map-phase calls: ``map_model``, falling back to ``summary_model``."""
167
+ return self.map_model or self.summary_model
168
+
163
169
  @property
164
170
  def resolved_api_mode(self) -> ResolvedApiMode:
165
171
  """Return the concrete API protocol selected for this configuration."""
@@ -400,6 +406,7 @@ _FIELD_COERCERS = {
400
406
  "wide_change_threshold": _to_float,
401
407
  "analysis_model": _to_str,
402
408
  "summary_model": _to_str,
409
+ "map_model": _to_str,
403
410
  "legacy_model": _to_optional_str,
404
411
  "excluded_files": _to_str_list,
405
412
  "low_priority_extensions": _to_str_list,
lgit/diffing.py CHANGED
@@ -49,6 +49,8 @@ class FileDiff:
49
49
  deletions: int = 0
50
50
  is_binary: bool = False
51
51
 
52
+ status: str = "modified" # added | deleted | renamed | modified
53
+
52
54
  @property
53
55
  def size(self) -> int:
54
56
  """Return the UTF-8 byte size used for budgeting."""
@@ -194,20 +196,58 @@ class WhitespaceReport:
194
196
  return self.all_whitespace
195
197
 
196
198
 
199
+ def condense_stat(stat: str, max_files: int = 0) -> str:
200
+ """Condense a ``git diff --stat`` block to its ``max_files`` largest per-file lines plus the totals line.
201
+
202
+ ``max_files=0`` keeps only the totals line. Small stats (at or under the
203
+ budget) are returned unchanged. Used to shrink LLM prompts whose per-file
204
+ data is supplied elsewhere (map-reduce observations).
205
+ """
206
+
207
+ lines = [line for line in stat.splitlines() if line.strip()]
208
+ file_lines = [line for line in lines if "|" in line]
209
+ if len(file_lines) <= max_files:
210
+ return stat
211
+ other_lines = [line for line in lines if "|" not in line]
212
+
213
+ def change_count(line: str) -> int:
214
+ tail = line.rsplit("|", 1)[1].strip()
215
+ digits = tail.split(None, 1)[0] if tail else ""
216
+ return int(digits) if digits.isdigit() else 0
217
+
218
+ kept = set(sorted(file_lines, key=change_count, reverse=True)[:max_files])
219
+ condensed = [line for line in file_lines if line in kept]
220
+ omitted = len(file_lines) - len(condensed)
221
+ if omitted and condensed:
222
+ condensed.append(f" ... {omitted} more files omitted ...")
223
+ return "\n".join(condensed + other_lines)
224
+
225
+
197
226
  def parse_diff(diff: str) -> list[FileDiff]:
198
227
  """Parse a unified git diff into file-level sections."""
199
228
 
200
229
  file_diffs: list[FileDiff] = []
201
230
  current: FileDiff | None = None
231
+ header_lines: list[str] = []
232
+ content_lines: list[str] = []
202
233
  in_diff_header = False
203
234
 
235
+ def flush_current() -> None:
236
+ nonlocal current, header_lines, content_lines
237
+ if current is not None:
238
+ current.header = "\n".join(header_lines)
239
+ current.content = "\n".join(content_lines)
240
+ file_diffs.append(current)
241
+ header_lines = []
242
+ content_lines = []
243
+
204
244
  for line in diff.splitlines():
205
245
  if line.startswith("diff --git"):
206
- if current is not None:
207
- file_diffs.append(current)
246
+ flush_current()
208
247
  parts = line.split()
209
248
  filename = parts[3].removeprefix("b/") if len(parts) > 3 else "unknown"
210
- current = FileDiff(filename=filename, header=line)
249
+ current = FileDiff(filename=filename, header="")
250
+ header_lines.append(line)
211
251
  in_diff_header = True
212
252
  continue
213
253
 
@@ -216,7 +256,7 @@ def parse_diff(diff: str) -> list[FileDiff]:
216
256
 
217
257
  if line.startswith("Binary files"):
218
258
  current.is_binary = True
219
- current.header += "\n" + line
259
+ header_lines.append(line)
220
260
  elif line.startswith(
221
261
  (
222
262
  "index ",
@@ -232,23 +272,26 @@ def parse_diff(diff: str) -> list[FileDiff]:
232
272
  "---",
233
273
  )
234
274
  ):
235
- current.header += "\n" + line
275
+ header_lines.append(line)
276
+ if line.startswith("new file"):
277
+ current.status = "added"
278
+ elif line.startswith("deleted file"):
279
+ current.status = "deleted"
280
+ elif line.startswith("rename "):
281
+ current.status = "renamed"
236
282
  elif line.startswith("@@"):
237
283
  in_diff_header = False
238
- current.header += "\n" + line
284
+ header_lines.append(line)
239
285
  elif not in_diff_header:
240
- if current.content:
241
- current.content += "\n"
242
- current.content += line
286
+ content_lines.append(line)
243
287
  if line.startswith("+") and not line.startswith("+++"):
244
288
  current.additions += 1
245
289
  elif line.startswith("-") and not line.startswith("---"):
246
290
  current.deletions += 1
247
291
  else:
248
- current.header += "\n" + line
292
+ header_lines.append(line)
249
293
 
250
- if current is not None:
251
- file_diffs.append(current)
294
+ flush_current()
252
295
  return file_diffs
253
296
 
254
297
 
lgit/map_reduce.py CHANGED
@@ -15,7 +15,7 @@ from .api import (
15
15
  render_prompt,
16
16
  run_oneshot,
17
17
  )
18
- from .diffing import FileDiff, parse_diff, reconstruct_diff
18
+ from .diffing import FileDiff, condense_stat, parse_diff, reconstruct_diff
19
19
  from .markdown_output import analysis_from_mapping, fallback_summary, parse_conventional_analysis_markdown
20
20
  from .models import AnalysisDetail, ConventionalAnalysis, resolve_model_name
21
21
  from .tokens import create_token_counter
@@ -25,6 +25,7 @@ if TYPE_CHECKING:
25
25
 
26
26
  MAX_FILE_TOKENS = 50_000
27
27
  MAP_PHASE_CONCURRENCY = 16
28
+ MIN_MAP_BATCH_TOKENS = 4_000
28
29
  MAX_CONTEXT_FILES = 20
29
30
 
30
31
 
@@ -36,6 +37,7 @@ class FileObservation:
36
37
  observations: tuple[str, ...]
37
38
  additions: int = 0
38
39
  deletions: int = 0
40
+ status: str = "modified" # added | deleted | renamed | modified
39
41
 
40
42
 
41
43
  def should_use_map_reduce(diff: str, config: CommitConfig, counter: Any | None = None) -> bool:
@@ -85,15 +87,17 @@ async def observe_diff_files(
85
87
  async def reduce_phase(
86
88
  observations: Sequence[FileObservation], stat: str, scope_candidates: str, model_name: str, config: CommitConfig
87
89
  ) -> ConventionalAnalysis:
88
- """Synthesize map observations into final conventional analysis."""
90
+ """Synthesize map observations into final conventional analysis.
91
+
92
+ Observations are rendered as per-file markdown and the stat is condensed to
93
+ its totals line: every path and change count already appears in the
94
+ observations, so the prompt stays roughly half the size of the raw inputs.
95
+ """
89
96
 
90
97
  type_enum = list(config.types) or ["chore"]
91
- observations_json = json.dumps(
92
- [_observation_to_mapping(item) for item in observations], ensure_ascii=False, indent=2
93
- )
94
98
  system_prompt, user_prompt = _render_reduce_prompt(
95
- observations_json,
96
- stat,
99
+ render_observations_markdown(observations),
100
+ condense_stat(stat),
97
101
  scope_candidates,
98
102
  format_types_description(config),
99
103
  )
@@ -144,7 +148,7 @@ async def run_map_reduce(
144
148
 
145
149
  counter = counter or create_token_counter(config)
146
150
  reduce_model = resolve_model_name(model_name or config.analysis_model)
147
- map_model = resolve_model_name(config.summary_model)
151
+ map_model = resolve_model_name(config.effective_map_model)
148
152
  observations = await observe_diff_files(diff, map_model, config, counter)
149
153
  if on_observations is not None:
150
154
  on_observations(observations)
@@ -155,12 +159,14 @@ async def _map_phase(
155
159
  files: Sequence[FileDiff], map_model_name: str, config: CommitConfig, counter: Any
156
160
  ) -> list[FileObservation]:
157
161
  context_headers = _ContextHeaders(files)
158
- batches = build_llm_file_batches(files, counter, config.map_batch_token_budget)
162
+ total_tokens = sum(file.token_estimate(counter) for file in files if not file.is_binary)
163
+ budget = _effective_map_budget(total_tokens, config.map_batch_token_budget)
164
+ batches = build_llm_file_batches(files, counter, budget)
159
165
  observations_by_index: list[FileObservation | None] = [None] * len(files)
160
166
  for idx, file in enumerate(files):
161
167
  if file.is_binary:
162
168
  observations_by_index[idx] = FileObservation(
163
- file.filename, ("Binary file changed.",), file.additions, file.deletions
169
+ file.filename, ("Binary file changed.",), file.additions, file.deletions, file.status
164
170
  )
165
171
 
166
172
  semaphore = asyncio.Semaphore(MAP_PHASE_CONCURRENCY)
@@ -241,7 +247,9 @@ def _map_batch_response_to_observations(
241
247
  raw_observations = _parse_observations(entry.get("observations", []))
242
248
  if not raw_observations and stopped_at_max_tokens:
243
249
  raw_observations = [_fallback_observation_text(file.filename)]
244
- observations.append(FileObservation(file.filename, tuple(raw_observations), file.additions, file.deletions))
250
+ observations.append(
251
+ FileObservation(file.filename, tuple(raw_observations), file.additions, file.deletions, file.status)
252
+ )
245
253
  return observations
246
254
 
247
255
 
@@ -288,6 +296,22 @@ def _parse_observations(value: Any) -> list[str]:
288
296
  return []
289
297
 
290
298
 
299
+ def _effective_map_budget(total_tokens: int, cap: int) -> int:
300
+ """Return the map batch budget that fills every concurrency lane in one wave.
301
+
302
+ Map wall time is the slowest batch, and batch latency is decode-dominated,
303
+ so the budget shrinks with the diff until all ``MAP_PHASE_CONCURRENCY``
304
+ lanes are used — bounded below by ``MIN_MAP_BATCH_TOKENS`` (per-call
305
+ overhead floor) and above by the configured ``map_batch_token_budget`` cap
306
+ (prompt-size guard for very large diffs).
307
+ """
308
+
309
+ # 25% slack absorbs greedy-packing overflow so batch count stays at or
310
+ # under the lane count; without it a few batches spill into a second wave.
311
+ ideal = -(-max(0, total_tokens) * 5 // (MAP_PHASE_CONCURRENCY * 4))
312
+ return min(max(1, cap), max(MIN_MAP_BATCH_TOKENS, ideal))
313
+
314
+
291
315
  def _build_file_batches_for_indices(
292
316
  files: Sequence[FileDiff], indices: Iterable[int], counter: Any, budget: int
293
317
  ) -> list[list[int]]:
@@ -323,7 +347,9 @@ def _included_files(files: Sequence[FileDiff], config: CommitConfig) -> list[Fil
323
347
  def _render_file_diff_for_batch(file: FileDiff, counter: Any) -> str:
324
348
  if file.token_estimate(counter) <= MAX_FILE_TOKENS:
325
349
  return _reconstruct_single_file_diff(file)
326
- clone = FileDiff(file.filename, file.header, file.content, file.additions, file.deletions, file.is_binary)
350
+ clone = FileDiff(
351
+ file.filename, file.header, file.content, file.additions, file.deletions, file.is_binary, file.status
352
+ )
327
353
  clone.truncate(MAX_FILE_TOKENS * 4)
328
354
  return reconstruct_diff([clone])
329
355
 
@@ -333,7 +359,9 @@ def _reconstruct_single_file_diff(file: FileDiff) -> str:
333
359
 
334
360
 
335
361
  def _fallback_file_observation(file: FileDiff) -> FileObservation:
336
- return FileObservation(file.filename, (_fallback_observation_text(file.filename),), file.additions, file.deletions)
362
+ return FileObservation(
363
+ file.filename, (_fallback_observation_text(file.filename),), file.additions, file.deletions, file.status
364
+ )
337
365
 
338
366
 
339
367
  def _fallback_observation_text(filename: str) -> str:
@@ -388,13 +416,22 @@ def _render_reduce_prompt(
388
416
  )
389
417
 
390
418
 
391
- def _observation_to_mapping(item: FileObservation) -> dict[str, Any]:
392
- return {
393
- "file": item.file,
394
- "observations": list(item.observations),
395
- "additions": item.additions,
396
- "deletions": item.deletions,
397
- }
419
+ def render_observations_markdown(observations: Sequence[FileObservation]) -> str:
420
+ """Render observations as per-file markdown sections.
421
+
422
+ Headings carry the file status (when not ``modified``) and nonzero change
423
+ counts, e.g. ``# src/ulid.rs (added, +120/-0)``.
424
+ """
425
+
426
+ sections = []
427
+ for item in observations:
428
+ annotations = [] if item.status == "modified" else [item.status]
429
+ if item.additions or item.deletions:
430
+ annotations.append(f"+{item.additions}/-{item.deletions}")
431
+ suffix = f" ({', '.join(annotations)})" if annotations else ""
432
+ bullets = "\n".join(f"- {text}" for text in item.observations)
433
+ sections.append(f"# {item.file}{suffix}\n{bullets}")
434
+ return "\n\n".join(sections)
398
435
 
399
436
 
400
437
  def _path_basename(path: str) -> str:
@@ -473,6 +510,7 @@ __all__ = [
473
510
  "build_llm_file_batches",
474
511
  "observe_diff_files",
475
512
  "reduce_phase",
513
+ "render_observations_markdown",
476
514
  "run_map_reduce",
477
515
  "should_use_map_reduce",
478
516
  ]
lgit/markdown_output.py CHANGED
@@ -86,7 +86,7 @@ def fallback_summary(
86
86
  candidate = "Updated files"
87
87
  if needs_verb and not _starts_with_past_tense(candidate):
88
88
  candidate = f"{_summary_verb(normalized_type)} {candidate}"
89
- cap = max(1, min(limit, 50))
89
+ cap = max(1, limit)
90
90
  candidate = _truncate_summary(candidate, cap).rstrip(".")
91
91
  first_word = candidate.split(maxsplit=1)[0] if candidate else ""
92
92
  if first_word.lower() == normalized_type.lower():
@@ -1,51 +1,47 @@
1
1
  <context>
2
- You are a senior release engineer who writes precise, changelog-ready commit classifications. Return your response in markdown format for easier parsing.
2
+ Senior release engineer; precise, changelog-ready commit classifications. Respond in markdown for easier parsing.
3
3
  </context>
4
4
 
5
5
  <instructions>
6
- Classify this git diff into conventional commit format. Ground every choice in the diff, stats, and supplied context only. Prefer conservative classifications over speculation.
6
+ Classify the git diff into conventional commit format. Ground every choice in diff, stats, and supplied context only; conservative over speculative.
7
7
 
8
- ## 1. Determine Scope
8
+ ## 1. Scope
9
9
 
10
- Apply scope only when one component clearly dominates the semantic change or roughly 60%+ of line changes:
10
+ Apply only when one component clearly dominates the semantic change or roughly 60%+ of line changes:
11
11
  - 150 lines in src/api/, 30 in src/lib.rs -> `api`
12
12
  - 50 lines in src/api/, 50 in src/types/ -> (none)
13
13
 
14
- Use no scope for cross-cutting changes, evenly split changes, project-wide refactoring, or any case where the best scope would be vague.
14
+ Cross-cutting, evenly split, project-wide, or vague best scope → no scope.
15
15
 
16
- Prefer scopes from `<common_scopes>` and `<scope_candidates>` over inventing new ones. Only invent a scope if no candidate fits.
16
+ Prefer `<common_scopes>` and `<scope_candidates>`; invent only when no candidate fits.
17
17
 
18
- Scope MUST be short — ideally one word, max two words joined by `-`. If a candidate is long (e.g. `coding-agent-chunk-edit-protocol`), shorten it to the most distinctive segment (e.g. `chunk-edit`). Never use 3+ hyphenated words.
18
+ Scope MUST be short — ideally one word, max two joined by `-`. Long candidate (e.g. `coding-agent-chunk-edit-protocol`) → most distinctive segment (`chunk-edit`). Never 3+ hyphenated words.
19
19
 
20
20
  Forbidden scopes: `src`, `lib`, `include`, `tests`, `benches`, `examples`, `docs`, project name, `app`, `main`, `entire`, `all`, `misc`.
21
21
 
22
- If unsure, omit scope rather than a weak or misleading one.
22
+ Unsure → omit rather than weak or misleading.
23
23
 
24
- ## 2. Generate Summary
24
+ ## 2. Summary
25
25
 
26
- The summary is the description part after `type(scope):`.
26
+ Description after `type(scope):`:
27
+ 1. lowercase past-tense verb first
28
+ 2. umbrella headline for the whole changeset
29
+ 3. synthesizes shared behavior/outcome across diff and details
30
+ 4. never copies detail #1 or one narrow file unless it dominates
31
+ 5. no `type(scope):` prefix, no trailing period, no markdown
32
+ 6. fits the configured guideline (normally ≤72 characters including prefix)
27
33
 
28
- The summary:
29
- 1. Starts with a lowercase past-tense verb
30
- 2. Is an umbrella headline for the whole changeset
31
- 3. Synthesizes the shared behavior or outcome across the diff and details
32
- 4. Does not copy detail #1 or focus on one narrow file unless it dominates
33
- 5. Has no `type(scope):` prefix, no trailing period, and no markdown
34
- 6. Fits the configured summary guideline (normally ≤72 characters including prefix)
34
+ ## 3. Details (0-6)
35
35
 
36
- ## 3. Generate Details (0-6 items)
36
+ Highest-signal 0-6 only. Each:
37
+ 1. past-tense verb, ends with period
38
+ 2. impact/rationale (skip trivial what-changed)
39
+ 3. precise names (modules, APIs, files)
40
+ 4. under 120 characters
37
41
 
38
- Return only the highest-signal 0-6 details.
42
+ 3+ similar changes → one detail. Exclude: import changes, whitespace, formatting, trivial renames, debug prints, comment-only changes, file moves without meaningful modification.
39
43
 
40
- Each detail:
41
- 1. Past-tense verb, ends with period
42
- 2. Explains impact/rationale (skip trivial what-changed)
43
- 3. Uses precise names (modules, APIs, files)
44
- 4. Under 120 characters
45
-
46
- Group 3+ similar changes into one detail. Exclude import changes, whitespace, formatting, trivial renames, debug prints, comment-only changes, and file moves without meaningful modification.
47
-
48
- ## 4. Assign Changelog Metadata (when user-visible)
44
+ ## 4. Changelog Metadata (user-visible only)
49
45
 
50
46
  - New public API, feature, capability → Added
51
47
  - Modified existing behavior → Changed
@@ -54,14 +50,13 @@ Group 3+ similar changes into one detail. Exclude import changes, whitespace, fo
54
50
  - Feature/API removed → Removed
55
51
  - Security fix or improvement → Security
56
52
 
57
- ## 5. Verify Before Finalizing
53
+ ## 5. Verify
58
54
 
59
- Before responding, check that:
60
- - `type` matches the dominant change and is one of the allowed commit types.
61
- - `scope` is either a valid short scope or omitted.
62
- - `summary` is an umbrella headline, starts with a past-tense verb, and has no prefix or period.
63
- - `details` are complete, grounded, and within the 0-6 limit.
64
- - `issue_refs` only contains references supported by the diff/context.
55
+ - `type`: dominant change; allowed commit type
56
+ - `scope`: valid short scope or omitted
57
+ - `summary`: umbrella headline, past-tense verb, no prefix or period
58
+ - `details`: complete, grounded, ≤6
59
+ - `issue_refs`: only supported by diff/context
65
60
  </instructions>
66
61
 
67
62
  <output_format>
@@ -1,20 +1,20 @@
1
- You are a senior engineer writing a conventional commit message. Return your response in markdown format for easier parsing.
1
+ Senior engineer writing a conventional commit message. Respond in markdown for easier parsing.
2
2
 
3
3
  Rules:
4
- - Use the supplied `stat`, `scope_candidates`, `user_context`, and `diff`. Treat `diff` as the source of truth; use the other inputs only as hints.
5
- - `type`: choose the best conventional commit type for the dominant change. When `<commit_types>` guidance is provided, follow its descriptions, notes, and disambiguation rules — they override your priors (e.g. prompt/template files under `prompts/` are functional changes, not `docs`).
6
- - `scope`: use a narrow lowercase module/component only when the diff clearly supports it. Prefer `scope_candidates` when helpful. Omit the `(scope)` if unclear, cross-cutting, repo-wide, or if no single scope covers most of the change.
7
- - `summary`: specific past-tense phrase, no type prefix, no trailing period, and at most 72 characters.
8
- - `details`: 0-3 past-tense sentences, each ending with a period. Include only material changes that matter to a reader; skip renames, imports, formatting, and incidental churn.
9
- - If the diff is mixed or noisy, summarize the main cohesive change and keep the scope conservative rather than guessing.
10
- - Do not invent behavior, file contents, or reasons that are not visible in the diff.
11
-
12
- Before finalizing, self-check:
13
- - Does the summary fit the length and tense rules?
14
- - Does the type match the actual change?
15
- - Is the scope justified, or should it be omitted?
16
- - Are the details within 0-3 and limited to meaningful changes?
17
- - Are all claims grounded in the provided diff?
4
+ - Inputs: `stat`, `scope_candidates`, `user_context`, `diff`. `diff` is the source of truth; the rest are hints only.
5
+ - `type`: best conventional commit type for the dominant change. `<commit_types>` guidance, when provided, overrides your priors — follow its descriptions, notes, and disambiguation rules (e.g. prompt/template files under `prompts/` are functional changes, not `docs`).
6
+ - `scope`: narrow lowercase module/component only when the diff clearly supports it. Prefer `scope_candidates`. Omit `(scope)` if unclear, cross-cutting, repo-wide, or no single scope covers most of the change.
7
+ - `summary`: specific past-tense phrase, no type prefix, no trailing period, ≤72 characters.
8
+ - `details`: 0-3 past-tense sentences, each ending with a period. Only material changes; skip renames, imports, formatting, incidental churn.
9
+ - Mixed or noisy diff → summarize the main cohesive change; conservative scope over guessing.
10
+ - Never invent behavior, file contents, or reasons not visible in the diff.
11
+
12
+ Self-check before finalizing:
13
+ - summary fits length and tense rules
14
+ - type matches the actual change
15
+ - scope justified, or omitted
16
+ - details within 0-3, meaningful only
17
+ - all claims grounded in the provided diff
18
18
 
19
19
  <output_format>
20
20
  You MUST return the result in this format WITHOUT the fences:
@@ -25,6 +25,7 @@ Base the answer only on the provided observations, stat, and scope candidates. D
25
25
 
26
26
  <synthesis_rules>
27
27
  - Produce 3-4 strong grouped details when possible; use the 6-item limit only for genuinely distinct outcomes.
28
+ - Each `# file` heading may be annotated with a status (`added`, `deleted`, `renamed`; unannotated files were modified) and its `+added/-deleted` line counts. Only describe a crate, module, package, or component as introduced/created when its own files are `added`; `added` files inside an existing component extend that component, they do not introduce it.
28
29
  - Synthesize repeated file observations into the shared behavior, abstraction, or user-visible outcome they support.
29
30
  - Prefer broader, evidence-backed details over enumerating files, hunks, or one observation per file.
30
31
  - If observations conflict, reconcile them conservatively using the most specific and repeated evidence.
@@ -0,0 +1,30 @@
1
+ You are a copy editor for one-line commit summaries. Rewrite the draft so it satisfies every constraint while preserving its meaning. This is a pure text edit: you do not need to understand the underlying code change.
2
+
3
+ <constraints>
4
+ 1. Start with a lowercase past-tense verb (added, replaced, migrated, restructured, ...); never the commit type token itself.
5
+ 2. Stay at or under the character limit from the user message.
6
+ 3. No type/scope prefix, no trailing period, no quotes, no markdown.
7
+ 4. Change as little wording as possible; never add information that is not in the draft.
8
+ 5. Fix exactly the reported problems and nothing else.
9
+ </constraints>
10
+
11
+ <output_format>
12
+ You MUST return the result in this format WITHOUT the fences:
13
+ ```
14
+ <summary>rewritten text only</summary>
15
+ ```
16
+ </output_format>
17
+
18
+ <!-- USER -->
19
+ <commit_metadata>
20
+ commit_type: {{ commit_type }}
21
+ max_summary_chars: {{ chars }}
22
+ </commit_metadata>
23
+
24
+ <draft_summary>
25
+ {{ draft }}
26
+ </draft_summary>
27
+
28
+ <rejection_reason>
29
+ {{ rejection }}
30
+ </rejection_reason>
lgit/templates.py CHANGED
@@ -20,6 +20,7 @@ PROMPT_CATEGORIES = (
20
20
  "map",
21
21
  "reduce",
22
22
  "fast",
23
+ "summary-rewrite",
23
24
  "compose-intent",
24
25
  "compose-bind",
25
26
  )
@@ -161,6 +162,13 @@ def render_summary_prompt(
161
162
  return render_prompt_parts("summary.md", template_content, context)
162
163
 
163
164
 
165
+ def render_summary_rewrite_prompt(commit_type: str, chars: str, draft: str, rejection: str) -> PromptParts:
166
+ """Render the summary-rewrite prompt that minimally edits a rejected draft into compliance."""
167
+ template_content = load_template_file("summary-rewrite")
168
+ context = {"commit_type": commit_type, "chars": chars, "draft": draft, "rejection": rejection}
169
+ return render_prompt_parts("summary-rewrite.md", template_content, context)
170
+
171
+
164
172
  def render_changelog_prompt(
165
173
  changelog_path: str,
166
174
  is_package_changelog: bool,
@@ -348,6 +356,7 @@ __all__ = [
348
356
  "load_template_file",
349
357
  "render_analysis_prompt",
350
358
  "render_summary_prompt",
359
+ "render_summary_rewrite_prompt",
351
360
  "render_changelog_prompt",
352
361
  "render_map_prompt",
353
362
  "render_reduce_prompt",
lgit/validation.py CHANGED
@@ -159,6 +159,18 @@ def present_to_past(present: str) -> str | None:
159
159
  return _load_validation_data().past_tense.get(present.lower())
160
160
 
161
161
 
162
+ def repair_summary_tense(summary: str) -> str | None:
163
+ """Rewrite a leading present-tense verb to its past form, or ``None`` when no repair applies."""
164
+
165
+ words = summary.split(maxsplit=1)
166
+ if not words:
167
+ return None
168
+ past = present_to_past(words[0])
169
+ if past is None:
170
+ return None
171
+ return past if len(words) == 1 else f"{past} {words[1]}"
172
+
173
+
162
174
  def split_verb_token(token: str) -> tuple[str, str] | None:
163
175
  """Split a first token into its leading ASCII verb segment and suffix."""
164
176
 
@@ -541,6 +553,7 @@ __all__ = [
541
553
  "is_past_tense_first_word",
542
554
  "is_past_tense_verb",
543
555
  "present_to_past",
556
+ "repair_summary_tense",
544
557
  "split_verb_token",
545
558
  "validate_commit_message",
546
559
  "validate_summary_quality",
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: lgit-cli
3
- Version: 5.1.0
3
+ Version: 5.2.0
4
4
  Summary: AI-powered git commit message generator using Claude and other LLMs via OpenAI-compatible APIs
5
5
  Project-URL: Homepage, https://github.com/can1357/llm-git
6
6
  Project-URL: Repository, https://github.com/can1357/llm-git
@@ -1,17 +1,17 @@
1
1
  lgit/__init__.py,sha256=y37z3-HahOME0CKTU7Gg3UHxN57G4ovK1mogGUs0iTc,1767
2
2
  lgit/__main__.py,sha256=VbaRO8-0ehWv7zA27BpyHYWTQVvt5M-aG5HnWr7ws0U,165
3
3
  lgit/analysis.py,sha256=j8bduuV6pqvMuza-r_RNJDe5SMQGKTtU6gwktaAeSS4,10671
4
- lgit/api.py,sha256=34jBaT8X_qH62weNCSmpI4JtTqmmVmOpwxlEthPpxi4,35543
4
+ lgit/api.py,sha256=Ypo6-6Y3fHKT_zJvzyZMClg5NUi6uCv6NK4paEYWrxo,38129
5
5
  lgit/cache.py,sha256=mrF5g74HMP9FR9kCJgwBcT4l34DuAuBaAkC1pCV7x6M,12477
6
- lgit/changelog.py,sha256=UL48dCYLre4I1X-8HW1JRTy4NgU2TANyMOOEIoVPvT0,37305
7
- lgit/cli.py,sha256=2svPdaTKspreB6gTv8dH_VGLeae34mOx4VI9YLRTWn4,52517
8
- lgit/compose.py,sha256=S4cSJ5CtFjM7_U_jbqr22vmIJg1ZjYudqpmUPbzfoTM,76747
9
- lgit/config.py,sha256=VI5zJtsr2WHRH6WbI-KKsaLUEtoyEZx-xayCbrTaMZ4,14215
10
- lgit/diffing.py,sha256=9z1gQdRYQg6Wsujt9tqgM7mfyXj2AkT0lfnaM6cKaj0,15819
6
+ lgit/changelog.py,sha256=HGuz2qeM_2m8uV2x36X79OP5SL9Wn0JxFhfvk4oCG_o,37264
7
+ lgit/cli.py,sha256=TMffDvL1ZHczRBbJhEn5WsyvPLaWGdA9MTuZBAnS0zw,52952
8
+ lgit/compose.py,sha256=HmuLK13I8rf7tSE6JDnpkkHBTX3gv-UHXr64GUACgF8,76775
9
+ lgit/config.py,sha256=rfFwD-bzpRwbGkRMzLWcgTptocK1hoOLzkwB7QiWWlY,14476
10
+ lgit/diffing.py,sha256=By2I7aH8tYTAwff7KqKWQw61b0Y5JqQgLlcU18dv8vY,17569
11
11
  lgit/errors.py,sha256=DkPJKA2ag5KbBoyuRk1d8zKgz9Mp1qRoLVBGRudlqkg,3457
12
12
  lgit/git.py,sha256=_wavbMwewf0lP1fZrrhgW5yD36jwWUC87Y7jfIikIEk,31543
13
- lgit/map_reduce.py,sha256=4I1kRlMCuK86_pbU1e_ZsnyfudCwscGDLS05GVNeH60,17840
14
- lgit/markdown_output.py,sha256=GPWxr5l_E0vhLDI-uwviJzqtyOei0F4rTV8eV2i6m1E,26364
13
+ lgit/map_reduce.py,sha256=ak4HPpHmbBKTFThdIBJcKqTVwS8zSTWWZNsdxIq01c4,19702
14
+ lgit/markdown_output.py,sha256=mgRLhpa9TBr3AVCoFaMYktXPYfxh6NqM75xpcudYexA,26355
15
15
  lgit/models.py,sha256=hc3AJ37YXoLBGgSbdLQN5EEnDNViXf-wywlkUW92_Z8,28942
16
16
  lgit/normalization.py,sha256=Kj_xqLw_fLDkN7wTFtAbwlEAD8t_s8v8JEGcLWLG8DM,11889
17
17
  lgit/patch.py,sha256=6Nx66t8pFZf4iNJS8nxxdtbSjiYk737EZVPpZscW4G0,30579
@@ -21,28 +21,29 @@ lgit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
21
21
  lgit/repo.py,sha256=eflCUY_XvTx8NY-KES5_BsyxpQczFEiT46eV2Fi4itQ,8926
22
22
  lgit/rewrite.py,sha256=PX6Pf7fS9ySU5DFdsvR2apecX_A6tZ8u5jTbnOERm5U,8771
23
23
  lgit/style.py,sha256=gfQYsUU-6nZFVhFkDBw6kWpsC3y7cGjOyUCJTV9ModY,7504
24
- lgit/templates.py,sha256=T9J2k3Tk-uAriD43BzguSBR30GFEId1tiVg7Oo49__4,11789
24
+ lgit/templates.py,sha256=8wjtsSE9hfr3zYa4yHCxbg0YlUU2b7urQM1jD-uuuKY,12298
25
25
  lgit/tokens.py,sha256=BbAhjIUtCXVBStPXzq4ZeuZa8H5r9ZqZJUnA1XHD_MI,3123
26
- lgit/validation.py,sha256=hMTD6wCw1MRqAqo6fYoep5BzKsVimvgDm8AbO2ZeLQ8,18813
26
+ lgit/validation.py,sha256=l1BMjyscypImLUHxA6f_igyHNkGEZF0-MTAR3qKCxdk,19214
27
27
  lgit/resources/__init__.py,sha256=w6eXZjQeAp_h24IJu_GhNIZelcSMuM3qk8GOmWLQPaQ,53
28
28
  lgit/resources/commit_types.json,sha256=IPtUig1U8UAIFnfMVaszQFI_LOZIiaZ2yyE20J1FG1E,11900
29
29
  lgit/resources/model_pricing.json,sha256=sAH7cr70wQpKZmbJU9Pnp8lNozbf_MpUsN0mYvhXQh0,932
30
30
  lgit/resources/validation_data.json,sha256=PJ1Iocq2qPKvh-zC1V_WyPrlDFFsXyTdnIxa2bokK5I,14634
31
- lgit/resources/prompts/analysis.md,sha256=3JsJ4C3pXaJW_93uZMdYUmMMZ-5j8-f7aIjrXXqOwIs,3685
31
+ lgit/resources/prompts/analysis.md,sha256=0CTqrvoeSTac9DSGzpV1pRrtOoxYfdh5PqtN3glVdYI,3111
32
32
  lgit/resources/prompts/changelog.md,sha256=6B7AsOMieF35VQvXRZaDBF4uNmXQzTFYGqUF4CnxZYA,5677
33
33
  lgit/resources/prompts/compose-bind.md,sha256=PEEeq9J2dWgXF3tL7uT2mpuws-u1rw_5m4IOSta4Oi4,832
34
34
  lgit/resources/prompts/compose-intent.md,sha256=OCUwji8cuf7LD351yryevIJ8Kyyh-4t6tBGjyplwtVo,1485
35
- lgit/resources/prompts/fast.md,sha256=OLrJqaTjS7-F4jeXa5LI4I1g-wh0EDKxA-D4Vfxeqek,2209
35
+ lgit/resources/prompts/fast.md,sha256=hM0z84pc4f8kGbcLDz2ZJNTN8Nj45lHH1Nrggv3YSLg,1951
36
36
  lgit/resources/prompts/map.md,sha256=f78-BUaEH1GPPBIB1rehkv012RcmPbD6mOHY9tWeyhM,2118
37
- lgit/resources/prompts/reduce.md,sha256=V3gpaIE5BAF67z_L41teembGoA4VM84if-kBpOib8EM,2564
37
+ lgit/resources/prompts/reduce.md,sha256=emZwrBXr9QzrzgGa2iImwNIVCTKk607w41UzBjQp9D4,2922
38
+ lgit/resources/prompts/summary-rewrite.md,sha256=Z96z6Cf5sNOUk12cQqC8nH4y0mywKYLbte5abGtrjAs,1009
38
39
  lgit/resources/prompts/summary.md,sha256=fM2RpQtwz7wFOYoS96cl5lQnakmKTsLuW4X-PT3CfFE,3138
39
40
  lgit/testing/__init__.py,sha256=_NQxrUIOQIQLKUP6Zerh2oNoJ7GVLAiWKFj9K2Vkhls,1373
40
41
  lgit/testing/compare.py,sha256=jRY98uLclVPyQ7e1TMqFVz2cjUi6kwwn2dkQyR_xsgY,1834
41
42
  lgit/testing/fixture.py,sha256=VXk02ZzFTBHHhYax6bsoGowdyz06nmrJm3ylenyfGbU,13654
42
43
  lgit/testing/report.py,sha256=wb7YnP_lsYwsg5OIFtsIC1bMHtK42Mttul_zQcwRNpk,9036
43
44
  lgit/testing/runner.py,sha256=5Sr4QvEOTdE7CAxB-CKcNJClEZARQGqB-t_6P6-UA2c,9514
44
- lgit_cli-5.1.0.dist-info/METADATA,sha256=haooGGBss1jxE2HNOk9I50aFj3Tycg9OKgpOKPhJN1o,9565
45
- lgit_cli-5.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
46
- lgit_cli-5.1.0.dist-info/entry_points.txt,sha256=CUSsokc0V3oVHQ2Z1ocL09wV7Krhm0SSfLZpnRMBdA0,39
47
- lgit_cli-5.1.0.dist-info/licenses/LICENSE,sha256=6dqVzjngLuIcUMd4wWLXPLpv-Pi8gySZAEE3hSN5iKw,1076
48
- lgit_cli-5.1.0.dist-info/RECORD,,
45
+ lgit_cli-5.2.0.dist-info/METADATA,sha256=1LqIE55ptncofGo62Tm4yilSGdllI2YSuckqyQveXyo,9565
46
+ lgit_cli-5.2.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
47
+ lgit_cli-5.2.0.dist-info/entry_points.txt,sha256=CUSsokc0V3oVHQ2Z1ocL09wV7Krhm0SSfLZpnRMBdA0,39
48
+ lgit_cli-5.2.0.dist-info/licenses/LICENSE,sha256=6dqVzjngLuIcUMd4wWLXPLpv-Pi8gySZAEE3hSN5iKw,1076
49
+ lgit_cli-5.2.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.31.0
2
+ Generator: hatchling 1.32.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any