Repository navigation
Expand file tree
/
Copy pathfc
More file actions
executable file
·2125 lines (1758 loc) · 76.1 KB
/
Copy pathfc
File metadata and controls
executable file
·2125 lines (1758 loc) · 76.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "requests",
# "truststore",
# ]
# ///
import argparse
import json
import os
import re
import subprocess
import sys
import threading
import time
import traceback
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from pathlib import Path
import truststore
# Verify TLS against the OS trust store. TLS-inspecting proxies install their
# root CA there, and certifi's bundle does not have it.
truststore.inject_into_ssl()
CONFIG_DIR = Path.home() / ".config" / "fast-commit"
CONFIG_PATH = CONFIG_DIR / ".env"
LOGS_DIR = CONFIG_DIR / "logs"
AUDIT_LOG = CONFIG_DIR / "audit.jsonl"
# Session log file - created once per run
_session_log = None
def get_session_log():
"""Get or create session log file for this execution."""
global _session_log
if _session_log is None:
LOGS_DIR.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
_session_log = LOGS_DIR / f"session_{timestamp}.log"
_session_log.write_text(f"=== fastc session started: {datetime.now().isoformat()} ===\n")
return _session_log
def log(level, message, context=None):
"""Log a message to the session log file."""
log_file = get_session_log()
timestamp = datetime.now().strftime("%H:%M:%S")
line = f"[{timestamp}] {level}: {message}"
if context:
context_str = ", ".join(f"{k}={v}" for k, v in context.items())
line += f" | {context_str}"
with open(log_file, "a") as f:
f.write(line + "\n")
def log_git_state():
"""Log current git state to session log."""
try:
branch_result = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
capture_output=True, timeout=5
)
branch = branch_result.stdout.decode().strip() if branch_result.returncode == 0 else "unknown"
log("INFO", "git branch", {"branch": branch})
status_result = subprocess.run(
["git", "status", "--short"],
capture_output=True, timeout=5
)
if status_result.returncode == 0:
status = status_result.stdout.decode().strip()
if status:
lines = status.splitlines()
log("INFO", "git status", {"files": len(lines)})
except Exception as e:
log("INFO", "git state capture failed", {"error": str(e)})
# ---------------------------------------------------------------------------
# Color + output helpers
# ---------------------------------------------------------------------------
_USE_COLOR = sys.stdout.isatty() and sys.stderr.isatty() and "NO_COLOR" not in os.environ
def _c(code, text):
"""Apply ANSI color if supported."""
if not _USE_COLOR:
return text
return f"\033[{code}m{text}\033[0m"
def _green(t): return _c("32", t)
def _red(t): return _c("31", t)
def _yellow(t): return _c("33", t)
def _dim(t): return _c("2", t)
def _cyan(t): return _c("36", t)
TICK = _green("✓")
CROSS = _red("✗")
WARN_SYM = _yellow("⚠")
SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
_output_lock = threading.Lock()
class Timings:
"""Track wall-clock time per phase and aggregate LLM request stats.
Used both for live progress (in-flight count, ETA) and for the end-of-run
breakdown so the user can see exactly where time went.
"""
def __init__(self):
self._lock = threading.Lock()
self._phases = {} # name -> accumulated wall seconds
self._phase_start = {} # name -> monotonic start
self._llm_total = 0.0 # sum of individual LLM durations (for parallel efficiency)
self._llm_count = 0
self._llm_inflight = 0
self._llm_durations = [] # rolling history for ETA
self._start = time.monotonic()
def phase_start(self, name):
with self._lock:
self._phase_start[name] = time.monotonic()
def phase_end(self, name):
with self._lock:
if name in self._phase_start:
self._phases[name] = self._phases.get(name, 0.0) + (
time.monotonic() - self._phase_start.pop(name)
)
def request_started(self):
with self._lock:
self._llm_inflight += 1
def request_finished(self, duration):
with self._lock:
self._llm_inflight = max(0, self._llm_inflight - 1)
self._llm_total += duration
self._llm_count += 1
self._llm_durations.append(duration)
def snapshot(self):
with self._lock:
return {
"inflight": self._llm_inflight,
"llm_total": self._llm_total,
"llm_count": self._llm_count,
"durations": list(self._llm_durations),
"elapsed": time.monotonic() - self._start,
}
def summary_line(self):
with self._lock:
# Deterministic ordering: phases in the order we started them.
parts = [f"{name} {t:.1f}s" for name, t in self._phases.items()]
total = time.monotonic() - self._start
parts.append(f"total {total:.1f}s")
if self._llm_count:
parts.append(
f"llm {self._llm_total:.1f}s/{self._llm_count} req"
)
return " · ".join(parts)
_timings = Timings()
class Spinner:
"""Thread-based terminal spinner. All output must go through this object
so that the spinner line is cleared before any print.
Supports a dynamic message callback so phase 2 can show live progress
(n/N, in-flight count, ETA) without polling from the main thread.
"""
def __init__(self):
self._msg = ""
self._dynamic = None
self._phase_start = time.monotonic()
self._last_line_len = 0
self._stop = threading.Event()
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def _render_text(self):
if self._dynamic is not None:
try:
return self._dynamic()
except Exception:
return self._msg
return self._msg
def _run(self):
i = 0
while not self._stop.wait(0.1):
with _output_lock:
frame = _cyan(SPINNER_FRAMES[i % len(SPINNER_FRAMES)])
elapsed = time.monotonic() - self._phase_start
body = self._render_text()
suffix = _dim(f" {elapsed:.1f}s")
line = f"{frame} {body}{suffix}"
# Pad over whatever we printed last frame so trailing
# characters from longer messages don't linger.
pad = max(0, self._last_line_len - len(line))
sys.stdout.write("\r" + line + (" " * pad))
sys.stdout.flush()
self._last_line_len = len(line)
i += 1
def set(self, message):
"""Update the spinner message and restart the per-phase elapsed timer."""
self._msg = message
self._dynamic = None
self._phase_start = time.monotonic()
def set_dynamic(self, fn):
"""Provide a callable whose return value is rendered every frame."""
self._dynamic = fn
self._phase_start = time.monotonic()
def _clear(self):
"""Clear spinner line. Must be called with _output_lock held."""
if self._last_line_len:
sys.stdout.write("\r" + " " * self._last_line_len + "\r")
sys.stdout.flush()
self._last_line_len = 0
def println(self, message, file=None):
"""Print a line, temporarily pausing the spinner."""
with _output_lock:
self._clear()
print(message, file=file or sys.stdout)
def ok(self, message):
self.println(f"{TICK} {message}")
def fail(self, message):
self.println(f"{CROSS} {message}", file=sys.stderr)
def warn(self, message):
self.println(f"{WARN_SYM} {message}", file=sys.stderr)
def stop(self):
if self._stop.is_set():
return
self._stop.set()
self._thread.join()
with _output_lock:
self._clear()
_spinner: "Spinner | None" = None
def sprint(message, file=None):
"""Print a message, clearing the spinner line first if one is active."""
if _spinner:
_spinner.println(message, file=file)
else:
print(message, file=file or sys.stdout)
# ---------------------------------------------------------------------------
# Error / warning helpers
# ---------------------------------------------------------------------------
def warn(message, context=None):
"""Print warning to user and log it."""
if _spinner:
_spinner.warn(message)
else:
print(f"{WARN_SYM} {message}", file=sys.stderr)
log("WARN", message, context)
def record_error(message, context=None):
"""Record error details to session log with full context."""
log("ERROR", message, context)
exc_info = traceback.format_exc()
if exc_info and exc_info.strip() != "NoneType: None":
log_file = get_session_log()
with open(log_file, "a") as f:
f.write(f"Stack trace:\n{exc_info}\n")
log_git_state()
sprint(f" session log: {get_session_log()}", file=sys.stderr)
_audit_repo = None
_audit_dir_created = False
def audit(event, data=None):
"""Append a structured entry to the persistent audit log."""
global _audit_repo, _audit_dir_created
if not _audit_dir_created:
AUDIT_LOG.parent.mkdir(parents=True, exist_ok=True)
_audit_dir_created = True
if _audit_repo is None:
repo_result = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
capture_output=True, timeout=5,
)
_audit_repo = repo_result.stdout.decode().strip() if repo_result.returncode == 0 else "unknown"
entry = {
"ts": datetime.now().isoformat(),
"repo": _audit_repo,
"event": event,
}
if data:
entry["data"] = data
with open(AUDIT_LOG, "a") as f:
f.write(json.dumps(entry) + "\n")
def exit_with_error(message, context=None):
"""Print error, record to disk, and exit."""
if _spinner:
_spinner.fail(f"error: {message}")
_spinner.stop()
else:
print(f"error: {message}", file=sys.stderr)
record_error(message, context)
audit("error", {"message": message})
sys.exit(1)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
# Files to exclude from diff analysis (don't help with commit messages)
EXCLUDED_PATTERNS = [
# JS/Node lockfiles
"pnpm-lock.yaml",
"package-lock.json",
"yarn.lock",
"bun.lockb",
# Other language lockfiles
"Cargo.lock",
"poetry.lock",
"Pipfile.lock",
"go.sum",
"composer.lock",
"Gemfile.lock",
# Minified/generated files
"*.min.js",
"*.min.css",
"*.map",
]
PROVIDER_OPENROUTER = "openrouter"
PROVIDER_CLAUDE = "claude"
PROVIDERS = (PROVIDER_OPENROUTER, PROVIDER_CLAUDE)
# Used when the config sets no CLAUDE_MODEL. Haiku is the cheapest model that
# handles this task, and the claude provider spends a seat's Agent SDK credit
# rather than metered API billing.
CLAUDE_DEFAULT_MODEL = "haiku"
SCOPE_GUIDANCE = (
"Scope MUST reflect the project or module, NOT the leaf filename. "
"Derive it from the file paths: in monorepos where top-level dirs are containers "
"(apps/, packages/, libs/, services/, crates/, cmd/, tools/), use the project name "
"(2nd path component) as scope. Otherwise use the first meaningful directory. "
"Examples: apps/grupeta/src/auth.ts -> (grupeta), packages/shared/utils.ts -> (shared), "
"src/api/handler.go -> (api), infra/terraform/main.tf -> (infra). "
"For mixed projects, pick the most specific common ancestor. "
"Always include a scope — omit only for truly root-level config files."
)
# The same rules without the worked examples, which produced identical scopes
# on a smaller prompt.
SCOPE_GUIDANCE_TERSE = (
"Scope is the project or module taken from the file path, never the filename. "
"Under a container dir (apps/ packages/ libs/ services/ crates/ cmd/ tools/) use the "
"2nd path component, otherwise the first directory. "
"Omit the scope only for truly root-level config files."
)
DESCRIPTION_GUIDANCE = (
"The description is the commit body. It must explain WHAT changed and WHY, not just restate the subject. "
"Cover: what behavior/logic changed, why the change was needed, and any non-obvious consequences. "
"Use 1-4 concise sentences. Never leave it empty or repeat the subject line."
)
PHASE1_PROMPT = """Group changed files into logical atomic commits by analyzing file paths and change types.
Output JSON array: [{"files":["path/to/file"],"hint":"what changed"}]
Use REAL file paths from the list below. Output ONLY valid JSON, no markdown."""
def _build_prompts(scope_guidance, description_guidance):
return {
"system": f"""Group git diff into atomic commits. Every file MUST appear in exactly one commit.
Output JSON array: [{{"files":["path/to/file"],"message":"type(scope): subject","description":"commit body"}}]
Types: feat|fix|refactor|chore|docs|style|test|perf. Subject: imperative, <=50 chars, no period.
{scope_guidance}
{description_guidance}
Use REAL file paths from the diff and REAL commit messages. Output ONLY valid JSON, no markdown.""",
"phase2": f"""Generate ONE commit message for this diff.
Output JSON object: {{"message":"type(scope): subject","description":"commit body"}}
Types: feat|fix|refactor|chore|docs|style|test|perf. Subject: imperative, <=50 chars, no period.
{scope_guidance}
{description_guidance}
Output ONLY valid JSON, no markdown.""",
# No description field at all. Used where the phase 1 hint already
# describes the group, so there is nothing to pay a model to write.
"phase2_subject": f"""Generate ONE commit subject for this diff.
Output JSON object: {{"message":"type(scope): subject"}}
Types: feat|fix|refactor|chore|docs|style|test|perf. Subject: imperative, <=50 chars, no period.
{scope_guidance}
Output ONLY valid JSON, no markdown.""",
"retry": f"""Previous output was rejected. Use REAL file paths from the diff and REAL commit messages.
Every file MUST appear in exactly one commit.
{scope_guidance}
{description_guidance}
Output ONLY valid JSON array:
[{{"files":["real/path.go"],"message":"feat(scope): real subject","description":"what changed and why"}}]""",
}
PROMPTS = {
PROVIDER_OPENROUTER: _build_prompts(SCOPE_GUIDANCE, DESCRIPTION_GUIDANCE),
PROVIDER_CLAUDE: _build_prompts(SCOPE_GUIDANCE_TERSE, DESCRIPTION_GUIDANCE),
}
# Directories that are monorepo containers — scope should be the child (project name)
CONTAINER_DIRS = {"apps", "packages", "libs", "services", "crates", "cmd", "tools"}
def _dir_scope(path):
"""Extract monorepo-aware scope from a file path.
In monorepos where the first directory is a container (apps/, packages/, etc.),
the scope is the project name (2nd component). Otherwise it's the first directory.
"""
parts = path.split("/")
if len(parts) > 2 and parts[0] in CONTAINER_DIRS:
return parts[1]
if len(parts) > 1:
return parts[0]
return ""
def _smart_path_label(path):
"""Return a grounded label for a file path, suitable for commit messages.
Instead of just the leaf filename, includes enough path context to be meaningful.
"""
parts = path.split("/")
if len(parts) <= 2:
return path
if parts[0] in CONTAINER_DIRS and len(parts) > 2:
return f"{parts[1]}/{parts[-1]}"
return f"{parts[0]}/{parts[-1]}"
def compute_path_context(file_paths):
"""Compute a path context hint for the LLM from staged file paths.
Returns a string like:
PATH CONTEXT: All files under "apps/grupeta/". Projects: grupeta.
or for multi-project changes:
PATH CONTEXT: Projects: grupeta, shared. Dirs: apps/grupeta/, packages/shared/.
"""
if not file_paths:
return ""
paths = list(file_paths)
scopes = defaultdict(set)
for p in paths:
parts = p.split("/")
if len(parts) > 2 and parts[0] in CONTAINER_DIRS:
scopes[parts[1]].add("/".join(parts[:2]))
elif len(parts) > 1:
scopes[parts[0]].add(parts[0])
if not scopes:
return ""
projects = sorted(scopes.keys())
if len(projects) == 1:
proj = projects[0]
dirs = sorted(scopes[proj])
return f"PATH CONTEXT: All files under \"{dirs[0]}/\". Project: {proj}.\n"
all_dirs = sorted(d for ds in scopes.values() for d in ds)
return f"PATH CONTEXT: Projects: {', '.join(projects)}. Dirs: {', '.join(d + '/' for d in all_dirs)}.\n"
# ---------------------------------------------------------------------------
# Config + git helpers
# ---------------------------------------------------------------------------
def resolve_provider(requested, config):
"""Force the claude provider in repos whose remotes match CLAUDE_ONLY_REMOTES."""
patterns = [p.strip() for p in config.get("CLAUDE_ONLY_REMOTES", "").split(",") if p.strip()]
remotes, _, _ = run(["git", "remote", "-v"])
match = next((p for p in patterns if p in remotes), None)
if match is None:
return requested or PROVIDER_OPENROUTER
if requested == PROVIDER_OPENROUTER:
exit_with_error(
f"remote matches CLAUDE_ONLY_REMOTES ({match}): only --provider claude is allowed",
{"pattern": match}
)
return PROVIDER_CLAUDE
def load_config(requested):
if not CONFIG_PATH.exists():
exit_with_error(
f"config not found at {CONFIG_PATH}. Create it with OPENROUTER_API_KEY and MODEL",
{"config_path": str(CONFIG_PATH)}
)
config = {}
for line in CONFIG_PATH.read_text().splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
key, _, value = line.partition("=")
config[key.strip()] = value.strip().strip("\"'")
provider = resolve_provider(requested, config)
config["PROVIDER"] = provider
if provider == PROVIDER_OPENROUTER:
if "OPENROUTER_API_KEY" not in config:
exit_with_error("OPENROUTER_API_KEY not set in config", {"config_path": str(CONFIG_PATH)})
if "MODEL" not in config:
exit_with_error("MODEL not set in config", {"config_path": str(CONFIG_PATH)})
else:
# MODEL is the one field the rest of the script reads for the model
# name, so the claude model lands there too.
config["MODEL"] = config.get("CLAUDE_MODEL", CLAUDE_DEFAULT_MODEL)
return config
def run(cmd, check=False, timeout=60):
try:
result = subprocess.run(cmd, capture_output=True, timeout=timeout)
except subprocess.TimeoutExpired:
exit_with_error(
f"command timed out after {timeout}s: {' '.join(cmd)}",
{"command": " ".join(cmd), "timeout": timeout}
)
stdout = result.stdout.decode("utf-8", errors="replace")
stderr = result.stderr.decode("utf-8", errors="replace")
if check and result.returncode != 0:
exit_with_error(
f"command failed: {' '.join(cmd)}",
{"command": " ".join(cmd), "stderr": stderr.strip(), "returncode": result.returncode}
)
return stdout, stderr, result.returncode
_PATHSPEC_EXCLUDES = [":(exclude)**/" + p for p in EXCLUDED_PATTERNS]
def build_pathspec_excludes():
"""Build git pathspec exclude args for lockfiles etc."""
return _PATHSPEC_EXCLUDES
def _top(path):
"""Wrap a repo-root-relative path with :(top) so git resolves it from
the repo root regardless of CWD."""
return f":(top){path}"
_DIFF_NOISE_PREFIXES = ("index ", "similarity index ", "dissimilarity index ")
def strip_diff_noise(diff):
"""Remove noise lines from diff to save tokens."""
return "\n".join(
line for line in diff.splitlines()
if not line.startswith(_DIFF_NOISE_PREFIXES)
)
_DIFF_META_PREFIXES = ("rename ", "new file", "deleted file", "old mode", "new mode")
def strip_diff_context(diff):
"""Drop unified-diff context lines and the redundant ---/+++ header pair.
Keeps the `diff --git` line, so file identity survives, plus hunk headers,
every changed line and the rename/create/delete metadata. Only the copy
sent to a model goes through this; everything that parses a diff for file
paths or operations reads the original.
Header and hunk body are tracked separately because a removed line can
itself start with `---`, which is common in YAML and markdown. Inside a
hunk every line is content, so there is nothing to disambiguate.
"""
kept = []
in_hunk = False
for line in diff.splitlines():
if line.startswith("diff --git"):
in_hunk = False
kept.append(line)
elif line.startswith("@@"):
in_hunk = True
kept.append(line)
elif not in_hunk:
if line.startswith(_DIFF_META_PREFIXES):
kept.append(line)
elif line.startswith(("+", "-")):
kept.append(line)
return "\n".join(kept)
def get_diff():
"""Get diff for analysis, excluding lockfiles from LLM context.
Only considers files in the current working directory and below.
"""
excludes = build_pathspec_excludes()
staged, _, _ = run(["git", "diff", "--cached", "--name-only", "--", "."])
if staged.strip():
diff, _, _ = run(["git", "diff", "--cached", "--minimal", "--", "."] + excludes)
diff = strip_diff_noise(diff)
if diff:
return diff, "staged"
# Staged files were all lockfiles/excluded — fall through to check unstaged
diff, _, _ = run(["git", "diff", "--minimal", "--", "."])
if not diff.strip():
untracked, _, _ = run(["git", "ls-files", "--others", "--exclude-standard", "."])
if not untracked.strip():
return "", "none"
run(["git", "add", "-A", "."], check=True)
diff, _, _ = run(["git", "diff", "--cached", "--minimal", "--", "."] + excludes)
return strip_diff_noise(diff), "all"
MAX_DIFF_CHARS = 20000
MAX_LINES_PER_HUNK = 15
MAX_HUNKS_PER_FILE = 5
# Below this many files, use the single-shot fast path (one LLM call) instead
# of the two-phase grouping pipeline. Single-shot is dramatically faster because
# it avoids a full round-trip before any parallel work can start.
LARGE_DIFF_FILES = 60
MAX_OUTPUT_TOKENS = 8192
# Cap on concurrent phase-2 LLM requests. Over HTTP these are pure I/O, so the
# cap exists only to protect OpenRouter from a single user hammering it. Each
# claude call is instead a CLI process holding ~450MB, so that cap is a memory
# budget and has to be far lower.
PHASE2_MAX_PARALLEL = {
PROVIDER_OPENROUTER: 32,
PROVIDER_CLAUDE: 4,
}
# Warn the user if a single LLM request takes longer than this many seconds.
SLOW_LLM_THRESHOLD_S = 15.0
# Beyond this many files, skip LLM entirely and use bulk commit
BULK_FILE_THRESHOLD = 200
# Maximum characters for phase 1 file summary before fallback
MAX_PHASE1_CHARS = 50000
# LLM retry attempts when files are missed
MAX_LLM_RETRIES = 3
BINARY_EXTENSIONS = {
'.zip', '.tar', '.gz', '.bz2', '.xz', '.7z', '.rar',
'.png', '.jpg', '.jpeg', '.gif', '.bmp', '.ico', '.webp', '.avif',
'.woff', '.woff2', '.ttf', '.eot', '.otf',
'.pdf', '.doc', '.docx', '.xls', '.xlsx',
'.exe', '.dll', '.so', '.dylib', '.o', '.a',
'.pyc', '.class', '.jar',
'.db', '.sqlite', '.sqlite3', '.bin', '.dat',
'.mp3', '.mp4', '.avi', '.mov', '.wav',
'.lockb',
}
# Budget for compressed diff (chars). ~100K tokens at ~4 chars/token.
MAX_COMPRESSED_CHARS = 400000
def is_binary_path(path):
"""Check if path has a known binary extension."""
dot = path.rfind(".")
return dot >= 0 and path[dot:].lower() in BINARY_EXTENSIONS
def extract_diff_path(header):
"""Extract file path from 'diff --git a/X b/Y' header."""
if " b/" in header:
return header.split(" b/", 1)[1]
return ""
_LOCKFILE_SUFFIXES = tuple(p[1:] for p in EXCLUDED_PATTERNS if p.startswith("*"))
_LOCKFILE_NAMES = frozenset(p for p in EXCLUDED_PATTERNS if not p.startswith("*"))
def is_lockfile(path):
"""Check if a file path matches any lockfile pattern."""
basename = path.rsplit("/", 1)[-1]
if basename in _LOCKFILE_NAMES:
return True
return path.endswith(_LOCKFILE_SUFFIXES)
_GIT_ESCAPE_MAP = {
'\\': ord('\\'), '"': ord('"'), 'n': ord('\n'), 't': ord('\t'),
'a': ord('\a'), 'b': ord('\b'), 'f': ord('\f'), 'v': ord('\v'),
'r': ord('\r'),
}
def git_unquote(path):
"""Decode git's C-style quoted path."""
if not (path.startswith('"') and path.endswith('"')):
return path
inner = path[1:-1]
result = bytearray()
i = 0
while i < len(inner):
if inner[i] == '\\' and i + 1 < len(inner):
c = inner[i + 1]
if c in '01234567' and i + 3 < len(inner):
result.append(int(inner[i + 1:i + 4], 8))
i += 4
elif c in _GIT_ESCAPE_MAP:
result.append(_GIT_ESCAPE_MAP[c])
i += 2
else:
result.extend(inner[i].encode('utf-8'))
i += 1
else:
result.extend(inner[i].encode('utf-8'))
i += 1
return result.decode('utf-8')
def get_staged_files_for_commit():
"""Get actual staged files that can be committed (excluding lockfiles).
Only includes files in the current working directory and below.
Returns dict mapping path -> {old_path, is_deleted}
"""
name_status, _, _ = run(["git", "diff", "--cached", "--name-status", "-M", "--", "."])
files = {}
for line in name_status.strip().splitlines():
if not line:
continue
parts = line.split("\t")
if len(parts) < 2:
continue
status = parts[0]
if status.startswith("R") and len(parts) >= 3: # Rename: R100\told\tnew
old_path = git_unquote(parts[1])
new_path = git_unquote(parts[2])
if not is_lockfile(new_path):
files[new_path] = {"old": old_path, "deleted": False}
elif status == "D": # Deleted
path = git_unquote(parts[1])
if not is_lockfile(path):
files[path] = {"old": path, "deleted": True}
else: # Added, Modified, etc
path = git_unquote(parts[1])
if not is_lockfile(path):
files[path] = {"old": path, "deleted": False}
return files
def normalize_llm_files(llm_files, staged_files):
"""Map LLM file paths to actual staged paths."""
if not isinstance(llm_files, list):
return []
old_to_new = {info["old"]: path for path, info in staged_files.items()}
normalized = set()
dropped = []
for f in llm_files:
if not isinstance(f, str):
continue
f = f.lstrip("/")
if f.startswith("a/") or f.startswith("b/"):
f = f[2:]
if f in staged_files:
normalized.add(f)
elif f in old_to_new:
normalized.add(old_to_new[f])
else:
dropped.append(f)
if dropped:
log("INFO", "LLM referenced unknown files", {"dropped": dropped})
return list(normalized)
def is_file_deleted(path, staged_files):
"""Check if a file is marked as deleted in staged files."""
info = staged_files.get(path)
return info.get("deleted", False) if info else False
def is_echoing_keys(commit):
"""Check if commit has literal key strings instead of real values."""
if not isinstance(commit, dict):
return True
files = commit.get("files")
message = commit.get("message")
description = commit.get("description")
if files is None:
return True
if isinstance(files, str) and files in ("files", "[]", "", "file"):
return True
if isinstance(files, list) and len(files) == 0:
return True
if message is None:
return True
if isinstance(message, str) and message.lower() in ("message", "", "commit message", "msg"):
return True
if isinstance(description, str) and description.lower() == "description":
return True
return False
_VALID_TYPES = {"feat", "fix", "refactor", "chore", "docs", "style", "test", "perf"}
def _clean_commit_message(message):
"""Clean up LLM-generated commit message for quality."""
message = message.strip().rstrip(".")
# Truncate to 72 chars (git convention for subject line)
if len(message) > 72:
message = message[:69] + "..."
return message
_SCOPE_RE = re.compile(r'^(\w+)(?:\(([^)]*)\))?:\s*(.*)')
def _ensure_grounded_scope(commit):
"""If the LLM produced a message with no scope, derive one from file paths."""
msg = commit.get("message", "")
m = _SCOPE_RE.match(msg)
if not m:
return commit
type_, scope, subject = m.groups()
if scope:
return commit
files = commit.get("files", [])
if not files:
return commit
scopes = set()
for f in files:
s = _dir_scope(f)
if s:
scopes.add(s)
if len(scopes) == 1:
scope = scopes.pop()
commit["message"] = f"{type_}({scope}): {subject}"
return commit
def validate_and_fix_commits(commits, staged_files):
"""Validate LLM output and fix issues.
Returns (fixed_commits, missing_files_set).
missing_files_set is empty when all staged files are covered.
"""
# Detect key-echoing pattern (model failure)
echo_count = sum(1 for c in commits if is_echoing_keys(c))
if echo_count > 0 and echo_count == len(commits):
exit_with_error(
f"LLM returned malformed commits (echoing keys: {echo_count}/{len(commits)})",
{"commits_sample": commits[:3]}
)
all_staged = set(staged_files.keys())
covered_files = set()
fixed_commits = []
for commit in commits:
if not isinstance(commit, dict):
warn(f"skipping non-dict commit: {commit}")
continue
if "files" not in commit or "message" not in commit:
warn(f"skipping malformed commit: {commit}")
continue
normalized = normalize_llm_files(commit["files"], staged_files)
if not normalized:
warn(f"skipping commit with no valid files: {commit.get('message', '<missing>')}")
continue
covered_files.update(normalized)
fixed = {
"files": normalized,
"message": _clean_commit_message(commit["message"]),
"description": commit.get("description", ""),
}
fixed_commits.append(_ensure_grounded_scope(fixed))
if not fixed_commits:
# No valid commits at all - create a fallback single commit
warn("LLM failed to group files, creating single commit")
return [{
"files": list(all_staged),
"message": "chore: update files",
"description": "",
}], set()
missing_files = all_staged - covered_files
return fixed_commits, missing_files
def get_diff_for_files(files):
"""Get the diff for specific files only (fresh from git).
Kept for callers that don't have a parsed diff cache to hand. The
hot path in phase 2 uses ``slice_diff_by_file`` against an in-memory
cache built via ``parse_diff_by_file``.
"""
diff, _, _ = run(["git", "diff", "--cached", "--minimal", "--"] + [_top(f) for f in files])
return strip_diff_noise(diff)
def parse_diff_by_file(diff):
"""Split a unified diff into a dict of {file_path: section_text}.
Each section includes its ``diff --git`` header so downstream code can
treat it as a self-contained mini-diff.
"""
sections = {}
current_path = None
current_lines = []
for line in diff.splitlines():
if line.startswith("diff --git"):
if current_path is not None:
sections[current_path] = "\n".join(current_lines)
current_path = extract_diff_path(line)
current_lines = [line]
elif current_path is not None:
current_lines.append(line)
if current_path is not None:
sections[current_path] = "\n".join(current_lines)
return sections
def slice_diff_by_file(diff_by_file, files):
"""Return a concatenated diff for ``files`` from the parsed cache."""
return "\n".join(diff_by_file[f] for f in files if f in diff_by_file)
def compress_diff(diff, max_chars=None):
"""Compress diff while preserving semantic information.
Respects a total character budget, skips binary files, and enforces
per-file limits so the result fits within LLM context windows.
"""
if max_chars is None:
max_chars = MAX_COMPRESSED_CHARS
excludes = build_pathspec_excludes()
stat, _, _ = run(["git", "diff", "--cached", "--stat", "--", "."] + excludes)
parts = [f"DIFF STAT:\n{stat}"]
header_chars = sum(len(p) for p in parts) + 50
remaining = max_chars - header_chars
if remaining <= 0:
return "\n".join(parts)
# Parse diff into per-file sections
file_sections = []
current_header = None
current_lines = []
for line in diff.splitlines():
if line.startswith("diff --git"):
if current_header:
file_sections.append((current_header, current_lines))
current_header = line
current_lines = []
elif current_header:
current_lines.append(line)
if current_header:
file_sections.append((current_header, current_lines))
if not file_sections:
return "\n".join(parts)
parts.append("COMPRESSED PATCHES:")
total_chars = 0
files_truncated = 0