lgit-cli 5.1.1__py3-none-any.whl → 5.3.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,8 @@ 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
440
+ config.fast_model = resolved_model
439
441
  if args.sign:
440
442
  config.gpg_sign = True
441
443
  if args.signoff:
@@ -545,7 +547,7 @@ async def _generate_fast_workflow(
545
547
  scope_candidates, _wide = (
546
548
  extract_scope_candidates(numstat, args.target, args.dir, config) if numstat.strip() else ("(none)", False)
547
549
  )
548
- style.status(f"{style.dim('›')} {style.dim('fast mode:')} {style.model(_resolve_fast_mode_model(args, config))}")
550
+ style.status(f"{style.dim('›')} {style.dim('fast mode:')} {style.model(config.effective_fast_model)}")
549
551
  style.status(f"{style.info('›')} Analyzing {style.bold(mode.value)} changes...")
550
552
  if changelog_runner is not None:
551
553
  changelog_runner.start_with_diff()
@@ -573,8 +575,14 @@ async def _generate_standard_workflow(
573
575
  )
574
576
  with profile.section("create_token_counter", collector):
575
577
  token_counter = create_token_counter(config)
576
- if config.analysis_model == config.summary_model:
578
+ if config.analysis_model == config.summary_model == config.effective_map_model:
577
579
  style.status(f"{style.dim('›')} {style.dim('model:')} {style.model(config.analysis_model)}")
580
+ elif config.effective_map_model != config.summary_model:
581
+ style.status(
582
+ f"{style.dim('›')} {style.dim('models:')} {style.dim('map')} "
583
+ f"{style.model(config.effective_map_model)} {style.dim('analysis')} "
584
+ f"{style.model(config.analysis_model)} {style.dim('summary')} {style.model(config.summary_model)}"
585
+ )
578
586
  else:
579
587
  style.status(
580
588
  f"{style.dim('›')} {style.dim('models:')} {style.dim('analysis')} "
@@ -603,10 +611,6 @@ async def _generate_standard_workflow(
603
611
  return await _message_from_analysis(analysis, config, stat, user_context, args, collector)
604
612
 
605
613
 
606
- def _resolve_fast_mode_model(args: argparse.Namespace, config: CommitConfig) -> str:
607
- return str(config.analysis_model if args.model or config.legacy_model else resolve_model_name("haiku"))
608
-
609
-
610
614
  async def _generate_fast_message(
611
615
  config: CommitConfig,
612
616
  stat: str,
@@ -616,7 +620,7 @@ async def _generate_fast_message(
616
620
  args: argparse.Namespace,
617
621
  collector: profile.TimingCollector | None = None,
618
622
  ) -> ConventionalCommit:
619
- fast_config = replace(config, analysis_model=_resolve_fast_mode_model(args, config))
623
+ fast_config = replace(config, analysis_model=config.effective_fast_model)
620
624
  try:
621
625
  async with profile.section("generate_fast_commit", collector):
622
626
  message = await generate_fast_commit(
lgit/compose.py CHANGED
@@ -51,11 +51,13 @@ class _ComposeArgs(Protocol):
51
51
  debug_output: str | None
52
52
 
53
53
 
54
- COMPOSE_PLAN_SCHEMA_VERSION = "v3"
54
+ COMPOSE_PLAN_SCHEMA_VERSION = "v4"
55
55
  COMPOSE_MESSAGE_PARALLELISM = 8
56
56
  # Compose planning intentionally switches representation as snapshots grow:
57
57
  # small/medium snapshots preserve per-file detail, while large snapshots plan by
58
58
  # path area to keep prompts bounded and avoid monolithic LLM output.
59
+ # Large snapshots stop subdividing once they expose enough workstream-level areas;
60
+ # repositories with only a few workstreams keep splitting for useful granularity.
59
61
  MAX_OBSERVATIONS_PER_FILE = 3
60
62
  COMPOSE_SUMMARY_MEDIUM_FILE_THRESHOLD = 60
61
63
  COMPOSE_SUMMARY_MEDIUM_HUNK_THRESHOLD = 200
@@ -64,8 +66,11 @@ COMPOSE_SUMMARY_LARGE_HUNK_THRESHOLD = 500
64
66
  COMPOSE_AREA_TARGET_MAX_FILES = 60
65
67
  COMPOSE_AREA_TARGET_MAX_HUNKS = 140
66
68
  COMPOSE_AREA_TARGET_MAX_DEPTH = 6
67
- COMPOSE_MONOLITH_FALLBACK_TARGET_THRESHOLD = 8
69
+ COMPOSE_AREA_TARGET_MAX_COUNT = 48
70
+ COMPOSE_AREA_TARGET_MIN_COUNT = 24
71
+ COMPOSE_MONOLITH_FALLBACK_TARGET_THRESHOLD = 3
68
72
  COMPOSE_MONOLITH_FALLBACK_WORKSTREAM_THRESHOLD = 3
73
+ COMPOSE_GRAB_BAG_WORKSTREAM_THRESHOLD = 5
69
74
  MAX_BIND_FILES_PER_REQUEST = 18
70
75
  MAX_BIND_HUNKS_PER_REQUEST = 120
71
76
  _DEPENDENCY_MANIFESTS = {
@@ -352,7 +357,9 @@ async def run_compose_round(
352
357
  observations = []
353
358
  planning_diff = diffing.scrub_diff_for_prompt(snapshot.diff)
354
359
  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)
360
+ observations = await map_reduce.observe_diff_files(
361
+ planning_diff, config.effective_map_model, config, token_counter
362
+ )
356
363
  if observations:
357
364
  _save_debug_artifact(
358
365
  args,
@@ -360,7 +367,7 @@ async def run_compose_round(
360
367
  [_observation_to_jsonable(item) for item in observations],
361
368
  )
362
369
 
363
- max_commits = args.compose_max_commits or 20
370
+ max_commits = args.compose_max_commits or 32
364
371
  model = config.analysis_model
365
372
  plan = _load_cached_plan(repo_dir, snapshot, max_commits, model)
366
373
  if plan is None:
@@ -464,7 +471,8 @@ def _analyze_compose_intent_from_mapping(
464
471
  raw_groups = data.get("groups", ())
465
472
  groups = [_intent_group_from_mapping(item, idx) for idx, item in enumerate(raw_groups, start=1)]
466
473
  planning_index = _build_planning_index(snapshot)
467
- return _normalize_intent_plan(snapshot, planning_index, groups, config, max_commits)
474
+ normalized = _normalize_intent_plan(snapshot, planning_index, groups, config, max_commits)
475
+ return _split_grab_bag_groups(snapshot, normalized, max_commits)
468
476
 
469
477
 
470
478
  async def _analyze_compose_intent(
@@ -743,6 +751,11 @@ def _build_planning_index(snapshot: ComposeSnapshot) -> PlanningIndex:
743
751
  aliases[target.target_id] = target.target_id
744
752
  aliases[target.target_id.upper()] = target.target_id
745
753
  aliases[_normalize_file_reference(target.label)] = target.target_id
754
+ for file_id in target.file_ids:
755
+ file = snapshot.file_by_id(file_id)
756
+ if file is not None:
757
+ aliases[file.file_id] = target.target_id
758
+ aliases[_normalize_file_reference(file.path)] = target.target_id
746
759
  return PlanningIndex(mode=mode, targets=targets, aliases=aliases)
747
760
 
748
761
 
@@ -775,24 +788,41 @@ def _build_area_planning_targets(snapshot: ComposeSnapshot) -> list[PlanningTarg
775
788
  def _collect_planning_buckets(
776
789
  snapshot: ComposeSnapshot, file_ids: Sequence[str], depth: int
777
790
  ) -> list[tuple[str, tuple[str, ...]]]:
778
- files = [file for file_id in file_ids for file in [snapshot.file_by_id(file_id)] if file is not None]
779
- hunk_count = sum(len(file.hunk_ids) for file in files)
780
- max_depth = max((len(file.path.split("/")) for file in files), default=depth)
781
- if (
782
- (len(files) <= COMPOSE_AREA_TARGET_MAX_FILES and hunk_count <= COMPOSE_AREA_TARGET_MAX_HUNKS)
783
- or depth >= COMPOSE_AREA_TARGET_MAX_DEPTH
784
- or depth >= max_depth
785
- ):
786
- return [(_planning_bucket_label(snapshot, file_ids), tuple(file_ids))]
787
- groups: dict[str, list[str]] = defaultdict(list)
788
- for file in files:
789
- groups[_prefix_at_depth(file.path, depth + 1)].append(file.file_id)
790
- if len(groups) <= 1:
791
- return _collect_planning_buckets(snapshot, file_ids, depth + 1)
792
- out: list[tuple[str, tuple[str, ...]]] = []
793
- for group_file_ids in groups.values():
794
- out.extend(_collect_planning_buckets(snapshot, group_file_ids, depth + 1))
795
- return out
791
+ buckets: list[tuple[int, tuple[str, ...]]] = [(depth, tuple(file_ids))]
792
+ while len(buckets) < COMPOSE_AREA_TARGET_MIN_COUNT:
793
+ chosen: tuple[tuple[int, int, int, int], int, int, list[list[str]]] | None = None
794
+ for idx, (bucket_depth, bucket_file_ids) in enumerate(buckets):
795
+ files = [file for file_id in bucket_file_ids for file in [snapshot.file_by_id(file_id)] if file is not None]
796
+ hunk_count = sum(len(file.hunk_ids) for file in files)
797
+ max_depth = max((len(file.path.split("/")) for file in files), default=bucket_depth)
798
+ if (
799
+ (len(files) <= COMPOSE_AREA_TARGET_MAX_FILES and hunk_count <= COMPOSE_AREA_TARGET_MAX_HUNKS)
800
+ or bucket_depth >= COMPOSE_AREA_TARGET_MAX_DEPTH
801
+ or bucket_depth >= max_depth
802
+ ):
803
+ continue
804
+
805
+ groups: dict[str, list[str]] = defaultdict(list)
806
+ for file in files:
807
+ groups[_prefix_at_depth(file.path, bucket_depth + 1)].append(file.file_id)
808
+ children = list(groups.values())
809
+ if len(children) > 1 and len(buckets) - 1 + len(children) > COMPOSE_AREA_TARGET_MAX_COUNT:
810
+ continue
811
+
812
+ pressure = max(
813
+ -(-len(files) // COMPOSE_AREA_TARGET_MAX_FILES),
814
+ -(-hunk_count // COMPOSE_AREA_TARGET_MAX_HUNKS),
815
+ )
816
+ score = (pressure, hunk_count, len(files), -idx)
817
+ if chosen is None or score > chosen[0]:
818
+ chosen = (score, idx, bucket_depth, children)
819
+
820
+ if chosen is None:
821
+ break
822
+ _, idx, bucket_depth, children = chosen
823
+ buckets[idx : idx + 1] = [(bucket_depth + 1, tuple(child)) for child in children]
824
+
825
+ return [(_planning_bucket_label(snapshot, ids), ids) for _, ids in buckets]
796
826
 
797
827
 
798
828
  def _prefix_at_depth(path: str, depth: int) -> str:
@@ -912,8 +942,8 @@ def _render_planning_notes(index: PlanningIndex) -> str:
912
942
 
913
943
  def _render_split_bias(index: PlanningIndex) -> str:
914
944
  if index.mode is PlanningMode.FILE:
915
- return "Prefer fewer groups when the split is uncertain."
916
- return "Prefer splitting unrelated areas into separate groups. Only return one broad group if nearly every area clearly belongs to the same atomic change."
945
+ return "Prefer fewer groups when the split is uncertain. Keep test files in the same group as the implementation they cover."
946
+ return "Prefer splitting unrelated areas into separate groups. Only return one broad group if nearly every area clearly belongs to the same atomic change. Keep a tests-only area in the same group as the implementation area it covers."
917
947
 
918
948
 
919
949
  def _normalize_file_reference(raw_file_ref: str) -> str:
@@ -1108,6 +1138,118 @@ def _normalize_intent_plan(
1108
1138
  return tuple(finalized)
1109
1139
 
1110
1140
 
1141
+ def _split_grab_bag_groups(
1142
+ snapshot: ComposeSnapshot,
1143
+ groups: Sequence[ComposeIntentGroup],
1144
+ max_commits: int,
1145
+ ) -> tuple[ComposeIntentGroup, ...]:
1146
+ partitions_by_index: dict[int, list[tuple[str, tuple[str, ...]]]] = {}
1147
+ for idx, group in enumerate(groups):
1148
+ partition_files: dict[str, list[str]] = {}
1149
+ for file_id in group.file_ids:
1150
+ file = snapshot.file_by_id(file_id)
1151
+ if file is None:
1152
+ continue
1153
+ key = "repo" if "/" not in file.path else _workstream_key_for_label(file.path)
1154
+ partition_files.setdefault(key, []).append(file_id)
1155
+ if len(partition_files) >= COMPOSE_GRAB_BAG_WORKSTREAM_THRESHOLD:
1156
+ partitions_by_index[idx] = [(key, tuple(file_ids)) for key, file_ids in partition_files.items()]
1157
+
1158
+ available_slots = max(0, max_commits - len(groups))
1159
+ split_indices: set[int] = set()
1160
+ for idx, partitions in sorted(partitions_by_index.items(), key=lambda item: (-len(item[1]), item[0])):
1161
+ extra_groups = len(partitions) - 1
1162
+ if extra_groups <= available_slots:
1163
+ split_indices.add(idx)
1164
+ available_slots -= extra_groups
1165
+ if not split_indices:
1166
+ return tuple(groups)
1167
+
1168
+ used_group_ids = {group.group_id for group in groups}
1169
+ next_group_number = 1
1170
+ for group_id in used_group_ids:
1171
+ candidate = _extract_group_id_candidate(group_id)
1172
+ if candidate is not None:
1173
+ next_group_number = max(next_group_number, int(candidate[1:]) + 1)
1174
+
1175
+ def allocate_group_id() -> str:
1176
+ nonlocal next_group_number
1177
+ while f"G{next_group_number}" in used_group_ids:
1178
+ next_group_number += 1
1179
+ group_id = f"G{next_group_number}"
1180
+ used_group_ids.add(group_id)
1181
+ next_group_number += 1
1182
+ return group_id
1183
+
1184
+ split_ids: dict[str, tuple[str, ...]] = {}
1185
+ expanded_groups: list[ComposeIntentGroup] = []
1186
+ for idx, group in enumerate(groups):
1187
+ if idx not in split_indices:
1188
+ expanded_groups.append(group)
1189
+ continue
1190
+
1191
+ partitions = partitions_by_index[idx]
1192
+ group_text = " ".join(
1193
+ (
1194
+ group.rationale,
1195
+ group.scope.as_str() if group.scope is not None else "",
1196
+ )
1197
+ )
1198
+ group_tokens = set(_planning_text_tokens(group_text))
1199
+ ranked_partitions: list[tuple[int, int, int]] = []
1200
+ for position, (key, file_ids) in enumerate(partitions):
1201
+ paths = [file.path for file_id in file_ids for file in [snapshot.file_by_id(file_id)] if file is not None]
1202
+ tokens = set(_planning_text_tokens(" ".join((key, *paths))))
1203
+ ranked_partitions.append((len(group_tokens & tokens), len(file_ids), -position))
1204
+ _, _, negative_primary = max(ranked_partitions)
1205
+ primary = -negative_primary
1206
+ ordered_positions = [primary, *(position for position in range(len(partitions)) if position != primary)]
1207
+ generated: list[ComposeIntentGroup] = []
1208
+ for position in ordered_positions:
1209
+ key, file_ids = partitions[position]
1210
+ if position == primary:
1211
+ split_group = ComposeIntentGroup(
1212
+ group.group_id,
1213
+ group.commit_type,
1214
+ group.scope,
1215
+ file_ids,
1216
+ group.rationale,
1217
+ group.dependencies,
1218
+ )
1219
+ else:
1220
+ split_group = ComposeIntentGroup(
1221
+ allocate_group_id(),
1222
+ _fallback_commit_type_for_group(snapshot, (key,), file_ids),
1223
+ _fallback_scope_for_label(key),
1224
+ file_ids,
1225
+ _fallback_rationale_for_labels((key,)),
1226
+ group.dependencies,
1227
+ )
1228
+ generated.append(split_group)
1229
+ expanded_groups.extend(generated)
1230
+ split_ids[group.group_id] = tuple(item.group_id for item in generated)
1231
+
1232
+ rewritten: list[ComposeIntentGroup] = []
1233
+ for group in expanded_groups:
1234
+ dependencies: list[str] = []
1235
+ for dependency in group.dependencies:
1236
+ for expanded_dependency in split_ids.get(dependency, (dependency,)):
1237
+ if expanded_dependency != group.group_id and expanded_dependency not in dependencies:
1238
+ dependencies.append(expanded_dependency)
1239
+ rewritten.append(
1240
+ ComposeIntentGroup(
1241
+ group.group_id,
1242
+ group.commit_type,
1243
+ group.scope,
1244
+ group.file_ids,
1245
+ group.rationale,
1246
+ tuple(dependencies),
1247
+ )
1248
+ )
1249
+ compute_dependency_order(rewritten)
1250
+ return tuple(rewritten)
1251
+
1252
+
1111
1253
  def _seed_group_target(group: ComposeIntentGroup, planning_index: PlanningIndex, claimed: set[str]) -> list[str]:
1112
1254
  if not planning_index.targets:
1113
1255
  return []
@@ -1307,6 +1449,8 @@ def _fallback_commit_type_for_group(
1307
1449
  return CommitType.from_raw("build")
1308
1450
  if files and all(_compose_file_category(file) in {"config", "dependency"} for file in files):
1309
1451
  return CommitType.from_raw("chore")
1452
+ if files and all("new file mode" in file.patch_header for file in files):
1453
+ return CommitType.from_raw("feat")
1310
1454
  return CommitType.from_raw("refactor")
1311
1455
 
1312
1456
 
lgit/config.py CHANGED
@@ -93,6 +93,8 @@ 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 = ""
97
+ fast_model: str = ""
96
98
  legacy_model: str | None = None
97
99
  excluded_files: list[str] = field(default_factory=lambda: list(DEFAULT_EXCLUDED_FILES))
98
100
  low_priority_extensions: list[str] = field(default_factory=lambda: list(DEFAULT_LOW_PRIORITY_EXTENSIONS))
@@ -160,6 +162,16 @@ class CommitConfig:
160
162
  kwargs[key] = _FIELD_COERCERS[key](value)
161
163
  return cls(**kwargs)
162
164
 
165
+ @property
166
+ def effective_map_model(self) -> str:
167
+ """Return the model for map-phase calls: ``map_model``, falling back to ``summary_model``."""
168
+ return self.map_model or self.summary_model
169
+
170
+ @property
171
+ def effective_fast_model(self) -> str:
172
+ """Return the model for fast-mode single calls: ``fast_model``, falling back to ``summary_model``."""
173
+ return self.fast_model or self.summary_model
174
+
163
175
  @property
164
176
  def resolved_api_mode(self) -> ResolvedApiMode:
165
177
  """Return the concrete API protocol selected for this configuration."""
@@ -400,6 +412,8 @@ _FIELD_COERCERS = {
400
412
  "wide_change_threshold": _to_float,
401
413
  "analysis_model": _to_str,
402
414
  "summary_model": _to_str,
415
+ "map_model": _to_str,
416
+ "fast_model": _to_str,
403
417
  "legacy_model": _to_optional_str,
404
418
  "excluded_files": _to_str_list,
405
419
  "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,6 +196,33 @@ 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
 
@@ -228,7 +257,7 @@ def parse_diff(diff: str) -> list[FileDiff]:
228
257
  if line.startswith("Binary files"):
229
258
  current.is_binary = True
230
259
  header_lines.append(line)
231
- elif line.startswith(
260
+ elif in_diff_header and line.startswith(
232
261
  (
233
262
  "index ",
234
263
  "new file",
@@ -244,9 +273,15 @@ def parse_diff(diff: str) -> list[FileDiff]:
244
273
  )
245
274
  ):
246
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"
247
282
  elif line.startswith("@@"):
248
283
  in_diff_header = False
249
- header_lines.append(line)
284
+ content_lines.append(line)
250
285
  elif not in_diff_header:
251
286
  content_lines.append(line)
252
287
  if line.startswith("+") and not line.startswith("+++"):
@@ -287,7 +322,7 @@ def scrub_diff_for_prompt(diff: str, max_file_bytes: int = MAX_PROMPT_FILE_BYTES
287
322
  """
288
323
 
289
324
  diff = collapse_blob_lines(diff)
290
- if len(diff) <= max_file_bytes:
325
+ if _byte_len(diff) <= max_file_bytes:
291
326
  return diff
292
327
  files = parse_diff(diff)
293
328
  if not any(file.size > max_file_bytes for file in files):
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
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)
@@ -177,6 +183,7 @@ async def _map_phase(
177
183
  config,
178
184
  counter,
179
185
  f"map batch {batch_idx + 1}/{len(batches)} ({len(batch_files)} files)",
186
+ budget,
180
187
  )
181
188
  return list(zip(batch_indices, observations, strict=True))
182
189
 
@@ -199,8 +206,9 @@ async def _map_file_batch(
199
206
  config: CommitConfig,
200
207
  counter: Any,
201
208
  progress_label: str,
209
+ budget: int,
202
210
  ) -> list[FileObservation]:
203
- rendered = [_render_file_diff_for_batch(file, counter) for file in files]
211
+ rendered = [_render_file_diff_for_batch(file, counter, budget) for file in files]
204
212
  prompt_files = [{"path": file.filename, "diff": diff} for file, diff in zip(files, rendered, strict=True)]
205
213
  system_prompt, user_prompt = _render_map_prompt(prompt_files, context_header)
206
214
  response = await run_oneshot(
@@ -241,7 +249,9 @@ def _map_batch_response_to_observations(
241
249
  raw_observations = _parse_observations(entry.get("observations", []))
242
250
  if not raw_observations and stopped_at_max_tokens:
243
251
  raw_observations = [_fallback_observation_text(file.filename)]
244
- observations.append(FileObservation(file.filename, tuple(raw_observations), file.additions, file.deletions))
252
+ observations.append(
253
+ FileObservation(file.filename, tuple(raw_observations), file.additions, file.deletions, file.status)
254
+ )
245
255
  return observations
246
256
 
247
257
 
@@ -288,28 +298,51 @@ def _parse_observations(value: Any) -> list[str]:
288
298
  return []
289
299
 
290
300
 
301
+ def _effective_map_budget(total_tokens: int, cap: int) -> int:
302
+ """Return the map batch budget that fills every concurrency lane in one wave.
303
+
304
+ Map wall time is the slowest batch, and batch latency is decode-dominated,
305
+ so the budget shrinks with the diff until all ``MAP_PHASE_CONCURRENCY``
306
+ lanes are used — bounded below by ``MIN_MAP_BATCH_TOKENS`` (per-call
307
+ overhead floor) and above by the configured ``map_batch_token_budget`` cap
308
+ (prompt-size guard for very large diffs).
309
+ """
310
+
311
+ # 25% slack absorbs greedy-packing overflow so batch count stays at or
312
+ # under the lane count; without it a few batches spill into a second wave.
313
+ ideal = -(-max(0, total_tokens) * 5 // (MAP_PHASE_CONCURRENCY * 4))
314
+ return min(max(1, cap), max(MIN_MAP_BATCH_TOKENS, ideal))
315
+
316
+
291
317
  def _build_file_batches_for_indices(
292
318
  files: Sequence[FileDiff], indices: Iterable[int], counter: Any, budget: int
293
319
  ) -> list[list[int]]:
294
320
  token_budget = max(1, int(budget))
321
+ byte_budget = token_budget * 4
295
322
  batches: list[list[int]] = []
296
323
  current: list[int] = []
297
324
  current_tokens = 0
325
+ current_bytes = 0
298
326
  for idx in indices:
299
- file_tokens = files[idx].token_estimate(counter)
300
- if file_tokens > token_budget:
327
+ file = files[idx]
328
+ file_tokens = file.token_estimate(counter)
329
+ file_bytes = file.size + (1 if file.content else 0)
330
+ if file_tokens > token_budget or file_bytes > byte_budget:
301
331
  if current:
302
332
  batches.append(current)
303
333
  current = []
304
334
  current_tokens = 0
335
+ current_bytes = 0
305
336
  batches.append([idx])
306
337
  continue
307
- if current and current_tokens + file_tokens > token_budget:
338
+ if current and (current_tokens + file_tokens > token_budget or current_bytes + file_bytes > byte_budget):
308
339
  batches.append(current)
309
340
  current = []
310
341
  current_tokens = 0
342
+ current_bytes = 0
311
343
  current.append(idx)
312
344
  current_tokens += file_tokens
345
+ current_bytes += file_bytes
313
346
  if current:
314
347
  batches.append(current)
315
348
  return batches
@@ -320,12 +353,16 @@ def _included_files(files: Sequence[FileDiff], config: CommitConfig) -> list[Fil
320
353
  return [file for file in files if not any(file.filename.endswith(pattern) for pattern in excluded)]
321
354
 
322
355
 
323
- def _render_file_diff_for_batch(file: FileDiff, counter: Any) -> str:
324
- if file.token_estimate(counter) <= MAX_FILE_TOKENS:
356
+ def _render_file_diff_for_batch(file: FileDiff, counter: Any, budget: int) -> str:
357
+ max_bytes = max(1, budget * 4)
358
+ rendered_bytes = file.size + (1 if file.content else 0)
359
+ if file.token_estimate(counter) <= budget and rendered_bytes <= max_bytes:
325
360
  return _reconstruct_single_file_diff(file)
326
- clone = FileDiff(file.filename, file.header, file.content, file.additions, file.deletions, file.is_binary)
327
- clone.truncate(MAX_FILE_TOKENS * 4)
328
- return reconstruct_diff([clone])
361
+ clone = FileDiff(
362
+ file.filename, file.header, file.content, file.additions, file.deletions, file.is_binary, file.status
363
+ )
364
+ clone.truncate(max(1, max_bytes - 1))
365
+ return _reconstruct_single_file_diff(clone)
329
366
 
330
367
 
331
368
  def _reconstruct_single_file_diff(file: FileDiff) -> str:
@@ -333,7 +370,9 @@ def _reconstruct_single_file_diff(file: FileDiff) -> str:
333
370
 
334
371
 
335
372
  def _fallback_file_observation(file: FileDiff) -> FileObservation:
336
- return FileObservation(file.filename, (_fallback_observation_text(file.filename),), file.additions, file.deletions)
373
+ return FileObservation(
374
+ file.filename, (_fallback_observation_text(file.filename),), file.additions, file.deletions, file.status
375
+ )
337
376
 
338
377
 
339
378
  def _fallback_observation_text(filename: str) -> str:
@@ -388,13 +427,22 @@ def _render_reduce_prompt(
388
427
  )
389
428
 
390
429
 
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
- }
430
+ def render_observations_markdown(observations: Sequence[FileObservation]) -> str:
431
+ """Render observations as per-file markdown sections.
432
+
433
+ Headings carry the file status (when not ``modified``) and nonzero change
434
+ counts, e.g. ``# src/ulid.rs (added, +120/-0)``.
435
+ """
436
+
437
+ sections = []
438
+ for item in observations:
439
+ annotations = [] if item.status == "modified" else [item.status]
440
+ if item.additions or item.deletions:
441
+ annotations.append(f"+{item.additions}/-{item.deletions}")
442
+ suffix = f" ({', '.join(annotations)})" if annotations else ""
443
+ bullets = "\n".join(f"- {text}" for text in item.observations)
444
+ sections.append(f"# {item.file}{suffix}\n{bullets}")
445
+ return "\n\n".join(sections)
398
446
 
399
447
 
400
448
  def _path_basename(path: str) -> str:
@@ -473,6 +521,7 @@ __all__ = [
473
521
  "build_llm_file_batches",
474
522
  "observe_diff_files",
475
523
  "reduce_phase",
524
+ "render_observations_markdown",
476
525
  "run_map_reduce",
477
526
  "should_use_map_reduce",
478
527
  ]
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>
@@ -8,30 +8,32 @@ Return your groups in a markdown-like format where each group defines a standalo
8
8
  1. Each group is identified by a group ID (G1, G2, G3, etc.)
9
9
  2. Each group has one commit type (from the `<commit_types>` list) and optional scope
10
10
  3. Groups are independent when possible; use dependencies for strict ordering
11
- 4. Return 1–5 groups (or the requested maximum)
12
- 5. Every provided file ID must appear in at least one group
11
+ 4. Return no more than the requested maximum; use fewer only when the changes are genuinely atomic
12
+ 5. Assign every provided file or area ID to exactly one group
13
+ 7. Never split tests from the implementation they cover: put both in one group, and only emit a test-only group when the code under test is not part of this change
14
+ 8. Keep documentation, generated artifacts, and dependency manifests with the implementation they belong to unless they are an independent change
15
+ 9. Group by intent, not by file type, path adjacency, or broad labels such as "core", "tools", or "tests"
16
+ 7. Keep tests, documentation, generated artifacts, and dependency manifests with the implementation they belong to unless they are an independent change
17
+ 8. Group by intent, not by file type, path adjacency, or broad labels such as "core", "tools", or "tests"
13
18
 
14
19
  Format rules:
15
20
  - `G1 := type(scope): rationale` — group definition
16
21
  - `G2 <- G1` — G2 depends on G1
17
- - `Files:` section lists file assignments
18
- - `- GN: file1, file2, file3` — files in group GN
22
+ - `Files:` must list only the provided `F...` or `A...` target IDs, never paths or hunk IDs
23
+ - `- GN: F001, F002, F003` — target IDs assigned to group GN
19
24
  </instructions>
20
25
 
21
26
  <output_format>
22
27
  You MUST return the result in this format WITHOUT the fences:
23
28
  ```
24
29
  G1 := feat(api): add authentication endpoints
25
- G2 := test(api): add comprehensive tests
26
- G3 := docs(api): document new endpoints
30
+ G2 := feat(client): consume authentication endpoints
27
31
 
28
32
  G2 <- G1
29
- G3 <- G1
30
33
 
31
34
  Files:
32
- - G1: src/auth.rs, src/models.rs
33
- - G2: tests/auth.test.ts
34
- - G3: docs/API.md
35
+ - G1: F001, F002
36
+ - G2: F003, F004
35
37
  ```
36
38
  </output_format>
37
39
 
@@ -44,6 +46,11 @@ max_commits: {{ max_commits }}
44
46
  {{ planning_targets }}
45
47
  </planning_targets>
46
48
 
49
+ <planning_guidance>
50
+ {{ planning_notes }}
51
+ {{ split_bias }}
52
+ </planning_guidance>
53
+
47
54
  {% if types_description %}
48
55
  <commit_types>
49
56
  {{ types_description }}
@@ -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
1
  Metadata-Version: 2.5
2
2
  Name: lgit-cli
3
- Version: 5.1.1
3
+ Version: 5.3.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=DRwie4rxNKha7A3TmsZEEgoVlwVHWyBKyHZd5QX5Y9Q,16071
6
+ lgit/changelog.py,sha256=HGuz2qeM_2m8uV2x36X79OP5SL9Wn0JxFhfvk4oCG_o,37264
7
+ lgit/cli.py,sha256=nqvrJZfLxkYwjHSPNqaajZKe_PCPRcpDkfING3crhto,52778
8
+ lgit/compose.py,sha256=g4HW7NDNR9ynFtDk9TtPBuHvTnhHOUUrG3NAX7N4HC0,83243
9
+ lgit/config.py,sha256=GkldpfMAX8T7Vzkl5RVY3eTgNM8Dalqntf2IuUmFnrg,14749
10
+ lgit/diffing.py,sha256=USk8qws0kXEfTlphvf7-hMyBdqdOD9H7i7UOimm99SY,17595
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=Tk11z9FT9Ox2pFZEy7Ns-eruyWo62jZokQuUWWCFyqE,20188
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
- lgit/resources/prompts/compose-intent.md,sha256=OCUwji8cuf7LD351yryevIJ8Kyyh-4t6tBGjyplwtVo,1485
35
- lgit/resources/prompts/fast.md,sha256=OLrJqaTjS7-F4jeXa5LI4I1g-wh0EDKxA-D4Vfxeqek,2209
34
+ lgit/resources/prompts/compose-intent.md,sha256=1A3FXApZe_2ERiqodyzhNrJ12WddEydty-5Zb9FroaM,2273
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.1.dist-info/METADATA,sha256=JSnMlZkXRyQ2sXmAFpWuWsbwoWaq7dBSxzvoJWjL5jw,9565
45
- lgit_cli-5.1.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
46
- lgit_cli-5.1.1.dist-info/entry_points.txt,sha256=CUSsokc0V3oVHQ2Z1ocL09wV7Krhm0SSfLZpnRMBdA0,39
47
- lgit_cli-5.1.1.dist-info/licenses/LICENSE,sha256=6dqVzjngLuIcUMd4wWLXPLpv-Pi8gySZAEE3hSN5iKw,1076
48
- lgit_cli-5.1.1.dist-info/RECORD,,
45
+ lgit_cli-5.3.0.dist-info/METADATA,sha256=07djXpV_LJpdd8TU6Vz-RFYpBgGwiWAuAl4gqgJ6DQI,9565
46
+ lgit_cli-5.3.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
47
+ lgit_cli-5.3.0.dist-info/entry_points.txt,sha256=CUSsokc0V3oVHQ2Z1ocL09wV7Krhm0SSfLZpnRMBdA0,39
48
+ lgit_cli-5.3.0.dist-info/licenses/LICENSE,sha256=6dqVzjngLuIcUMd4wWLXPLpv-Pi8gySZAEE3hSN5iKw,1076
49
+ lgit_cli-5.3.0.dist-info/RECORD,,