-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfc
More file actions
executable file
·1546 lines (1273 loc) · 53.6 KB
/
fc
File metadata and controls
executable file
·1546 lines (1273 loc) · 53.6 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",
# ]
# ///
import argparse
import json
import subprocess
import sys
import threading
import time
import traceback
from collections import defaultdict
from datetime import datetime
from pathlib import Path
CONFIG_PATH = Path.home() / ".config" / "fast-commit" / ".env"
LOGS_DIR = Path.home() / ".fastc" / "logs"
AUDIT_LOG = Path.home() / ".fastc" / "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")
MAX_STATUS_LINES_IN_LOG = 100
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", f"git 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()
if len(lines) > MAX_STATUS_LINES_IN_LOG:
truncated = "\n".join(lines[:MAX_STATUS_LINES_IN_LOG])
log("INFO", f"git status (truncated, {len(lines)} files total):\n{truncated}\n... and {len(lines) - MAX_STATUS_LINES_IN_LOG} more")
else:
log("INFO", f"git status:\n{status}")
except Exception as e:
log("INFO", f"failed to capture git state: {e}")
# ---------------------------------------------------------------------------
# Spinner + output helpers
# ---------------------------------------------------------------------------
TICK = "✓"
CROSS = "✗"
WARN_SYM = "⚠"
SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
_output_lock = threading.Lock()
class Spinner:
"""Thread-based terminal spinner. All output must go through this object
so that the spinner line is cleared before any print."""
def __init__(self):
self._msg = ""
self._stop = threading.Event()
self._thread = threading.Thread(target=self._run, daemon=True)
self._thread.start()
def _run(self):
i = 0
while not self._stop.wait(0.08):
with _output_lock:
frame = SPINNER_FRAMES[i % len(SPINNER_FRAMES)]
sys.stdout.write(f"\r{frame} {self._msg}")
sys.stdout.flush()
i += 1
def set(self, message):
"""Update the spinner message."""
self._msg = message
def _clear(self):
"""Clear spinner line. Must be called with _output_lock held."""
sys.stdout.write("\r" + " " * (len(self._msg) + 4) + "\r")
sys.stdout.flush()
def println(self, message, file=sys.stdout):
"""Print a line, temporarily pausing the spinner."""
with _output_lock:
self._clear()
print(message, file=file)
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):
self._stop.set()
self._thread.join()
with _output_lock:
self._clear()
_spinner: "Spinner | None" = None
def sprint(message, file=sys.stdout):
"""Print a message, clearing the spinner line first if one is active."""
if _spinner:
_spinner.println(message, file=file)
else:
print(message, file=file)
# ---------------------------------------------------------------------------
# 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("INFO", 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
def audit(event, data=None):
"""Append a structured entry to the persistent audit log."""
global _audit_repo
AUDIT_LOG.parent.mkdir(parents=True, exist_ok=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",
]
SYSTEM_PROMPT = """You are a git commit message generator. Given a git diff, analyse the changes and group them into logical atomic commits.
CRITICAL REQUIREMENTS:
- "files" MUST be actual file paths from the diff (e.g., "src/auth.go", "tests/auth_test.go")
- "message" MUST be a real commit message, NOT the word "message"
- "description" MUST be a real description, NOT the word "description"
- Every file in the diff MUST appear in exactly one commit's files array
Rules:
- Each commit should represent one logical change
- Use conventional commit format: <type>(<scope>): <subject>
- Types: feat, fix, refactor, chore, docs, style, test, perf
- Subject: imperative mood, max 50 chars, no period
- Description: 1-3 sentences explaining WHY the change was made, not what changed
- Group files that belong to the same logical change together
- If all changes are one logical unit, return a single commit
BAD OUTPUT (will be rejected):
[
{"files": "files", "message": "message", "description": "description"}
]
GOOD OUTPUT:
[
{
"files": ["src/auth.go", "tests/auth_test.go"],
"message": "feat(auth): add login endpoint",
"description": "Users need to authenticate before accessing protected resources."
}
]
Respond with ONLY a valid JSON array (no markdown, no explanation):"""
PHASE1_PROMPT = """You are a git commit analyzer. Given a summary of changed files (name-status and stats), group them into logical atomic commits.
CRITICAL REQUIREMENT:
- "files" MUST be actual file paths from the FILE CHANGES list below
Rules:
- Each group should represent one logical change
- Group files that belong to the same logical change together
- If all changes are one logical unit, return a single group
- Use the file paths and change types (A=added, M=modified, D=deleted, R=renamed) to understand the changes
BAD OUTPUT (will be rejected):
[{"files": "files", "hint": "hint"}]
GOOD OUTPUT:
[{"files": ["src/auth.go", "tests/auth_test.go"], "hint": "authentication logic changes"}]
Respond with ONLY a valid JSON array of file groups (no markdown, no explanation):"""
PHASE2_PROMPT = """You are a git commit message generator. Given a diff for a specific group of related files, generate ONE commit message.
CRITICAL REQUIREMENTS:
- "message" MUST be a real commit message, NOT the word "message"
- "description" MUST be a real description, NOT the word "description"
Rules:
- Use conventional commit format: <type>(<scope>): <subject>
- Types: feat, fix, refactor, chore, docs, style, test, perf
- Subject: imperative mood, max 50 chars, no period
- Description: 1-3 sentences explaining WHY the change was made, not what changed
BAD OUTPUT (will be rejected):
{"message": "message", "description": "description"}
GOOD OUTPUT:
{"message": "feat(auth): add login endpoint", "description": "Users need to authenticate before accessing protected resources."}
Respond with ONLY a valid JSON object (no markdown, no explanation):"""
# ---------------------------------------------------------------------------
# Config + git helpers
# ---------------------------------------------------------------------------
def load_config():
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("\"'")
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)})
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
def build_pathspec_excludes():
"""Build git pathspec exclude args for lockfiles etc."""
excludes = []
for pattern in EXCLUDED_PATTERNS:
excludes.append(":(exclude)**/" + pattern)
return 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}"
def strip_diff_noise(diff):
"""Remove noise lines from diff to save tokens."""
lines = []
for line in diff.splitlines():
if line.startswith("index "):
continue
if line.startswith("similarity index "):
continue
if line.startswith("dissimilarity index "):
continue
lines.append(line)
return "\n".join(lines)
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"
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
LARGE_DIFF_FILES = 15
MAX_OUTPUT_TOKENS = 4096
# 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', '.svg', '.webp',
'.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 ""
def is_lockfile(path):
"""Check if a file path matches any lockfile pattern."""
for pattern in EXCLUDED_PATTERNS:
if pattern.startswith("*"):
if path.endswith(pattern[1:]):
return True
elif path.endswith("/" + pattern) or path == pattern:
return True
return False
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 == '\\':
result.append(ord('\\'))
i += 2
elif c == '"':
result.append(ord('"'))
i += 2
elif c == 'n':
result.append(ord('\n'))
i += 2
elif c == 't':
result.append(ord('\t'))
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")
status = parts[0]
if status.startswith("R"): # 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()
for f in llm_files:
if not isinstance(f, str):
continue
if f in staged_files:
normalized.add(f)
elif f in old_to_new:
normalized.add(old_to_new[f])
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["deleted"] 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() in ("description", "desc"):
return True
return False
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_commits.append({
"files": normalized,
"message": commit["message"],
"description": commit.get("description", ""),
})
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."""
diff, _, _ = run(["git", "diff", "--cached", "--minimal", "--"] + [_top(f) for f in files])
return strip_diff_noise(diff)
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)
dirstat, _, _ = run(["git", "diff", "--cached", "--dirstat", "--", "."] + excludes)
parts = [f"DIFF STAT:\n{stat}"]
if dirstat.strip():
parts.append(f"DIRECTORY CHANGES:\n{dirstat}")
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
for file_header, lines in file_sections:
if total_chars >= remaining:
files_truncated += 1
continue
path = extract_diff_path(file_header)
# Skip binary files
is_binary = any("Binary files" in l for l in lines[:5])
if is_binary or is_binary_path(path):
summary = f"{file_header}\n[binary file]"
parts.append(summary)
total_chars += len(summary)
continue
# Compress this file's diff with per-file budget
per_file_budget = min(
remaining - total_chars,
remaining // max(len(file_sections), 1),
)
file_parts = [file_header]
file_chars = len(file_header)
hunk_count = 0
hunk_lines = 0
hunk_truncated = False
for line in lines:
if file_chars >= per_file_budget:
file_parts.append("[... file truncated]")
break
if line.startswith("@@") and " @@" in line:
hunk_count += 1
hunk_lines = 0
hunk_truncated = False
if hunk_count <= MAX_HUNKS_PER_FILE:
file_parts.append(line)
file_chars += len(line)
elif hunk_count <= MAX_HUNKS_PER_FILE:
if line.startswith("---") or line.startswith("+++"):
file_parts.append(line)
file_chars += len(line)
elif line.startswith("rename ") or line.startswith("new file") or line.startswith("deleted file"):
file_parts.append(line)
file_chars += len(line)
elif hunk_lines < MAX_LINES_PER_HUNK:
if line.startswith("+") or line.startswith("-"):
file_parts.append(line)
file_chars += len(line)
hunk_lines += 1
elif line.startswith(" ") and hunk_lines < MAX_LINES_PER_HUNK // 2:
file_parts.append(line)
file_chars += len(line)
hunk_lines += 1
elif not hunk_truncated:
file_parts.append("[... hunk truncated]")
hunk_truncated = True
if hunk_count > MAX_HUNKS_PER_FILE:
file_parts.append(f"[... {hunk_count - MAX_HUNKS_PER_FILE} more hunks truncated]")
parts.extend(file_parts)
total_chars += file_chars
if files_truncated > 0:
parts.append(f"[... {files_truncated} more files truncated]")
return "\n".join(parts)
RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504}
MAX_RETRIES = 3
class ContextLengthExceeded(Exception):
"""Raised when LLM context length is exceeded."""
pass
def try_repair_json(content):
"""Attempt to repair truncated or malformed JSON arrays/objects."""
content = content.strip()
# Strip leading garbage - find first [ or {
start_idx = -1
for i, c in enumerate(content):
if c in '[{':
start_idx = i
break
if start_idx > 0:
content = content[start_idx:]
# Strip trailing garbage - find last ] or }
end_idx = -1
for i in range(len(content) - 1, -1, -1):
if content[i] in ']}':
end_idx = i
break
if end_idx >= 0 and end_idx < len(content) - 1:
content = content[:end_idx + 1]
try:
return json.loads(content)
except json.JSONDecodeError:
pass
repairs = [
'"}]',
'"]}}]',
'"}]}]',
'"]',
'"}',
'}]',
']',
'}',
'"]}',
'"],"hint":""}]',
]
for repair in repairs:
try:
result = json.loads(content + repair)
warn(f"repaired truncated JSON (appended: {repair})")
return result
except json.JSONDecodeError:
continue
for end_char in ['},', '],', '}', ']', '",']:
idx = content.rfind(end_char)
if idx > 0:
truncated = content[:idx + len(end_char)]
for close in [']', ']}', '}]', ']}]', '"]}', '"],"hint":""}]']:
try:
result = json.loads(truncated + close)
warn("repaired truncated JSON by removing incomplete element")
return result
except json.JSONDecodeError:
continue
return None
class _LLMWallClockTimeout(Exception):
pass
def call_llm_raw(config, system_prompt, user_content):
"""Make a raw LLM API call and return parsed JSON."""
import signal
import requests
def _alarm_handler(signum, frame):
raise _LLMWallClockTimeout()
use_structured = config.get("STRUCTURED_OUTPUT", "true").lower() == "true"
request_body = {
"model": config["MODEL"],
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_content},
],
"temperature": 0,
"max_tokens": MAX_OUTPUT_TOKENS,
}
if use_structured:
request_body["response_format"] = {"type": "json_object"}
wall_clock_timeout = 90 # total seconds per attempt, kills chunked-transfer hangs
old_alarm_handler = signal.signal(signal.SIGALRM, _alarm_handler)
for attempt in range(MAX_RETRIES):
try:
signal.alarm(wall_clock_timeout)
resp = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {config['OPENROUTER_API_KEY']}",
"Content-Type": "application/json",
},
json=request_body,
timeout=60,
)
signal.alarm(0)
if resp.status_code == 200:
break
if resp.status_code == 400 and "context length" in resp.text.lower():
log("INFO", "LLM context length exceeded", {"response": resp.text[:300]})
raise ContextLengthExceeded(resp.text[:500])
if resp.status_code in RETRYABLE_STATUS_CODES and attempt < MAX_RETRIES - 1:
wait_time = 2**attempt
warn(f"LLM API returned {resp.status_code}, retrying in {wait_time}s (attempt {attempt + 1}/{MAX_RETRIES})")
time.sleep(wait_time)
continue
exit_with_error(
f"LLM API returned {resp.status_code}",
{"status_code": resp.status_code, "response": resp.text[:500], "model": config["MODEL"]}
)
except _LLMWallClockTimeout:
signal.alarm(0)
if attempt < MAX_RETRIES - 1:
wait_time = 2**attempt
warn(f"LLM request exceeded {wall_clock_timeout}s wall-clock timeout, retrying in {wait_time}s (attempt {attempt + 1}/{MAX_RETRIES})")
time.sleep(wait_time)
continue
exit_with_error(
f"LLM API request timed out after {MAX_RETRIES} attempts",
{"model": config["MODEL"], "attempts": MAX_RETRIES}
)
except requests.exceptions.Timeout:
signal.alarm(0)
if attempt < MAX_RETRIES - 1:
wait_time = 2**attempt
warn(f"LLM request timed out, retrying in {wait_time}s (attempt {attempt + 1}/{MAX_RETRIES})")
time.sleep(wait_time)
continue
exit_with_error(
f"LLM API request timed out after {MAX_RETRIES} attempts",
{"model": config["MODEL"], "attempts": MAX_RETRIES}
)
except requests.exceptions.RequestException as e:
signal.alarm(0)
if attempt < MAX_RETRIES - 1:
wait_time = 2**attempt
warn(f"LLM request failed: {e}, retrying in {wait_time}s (attempt {attempt + 1}/{MAX_RETRIES})")
time.sleep(wait_time)
continue
exit_with_error(
f"LLM API request failed after {MAX_RETRIES} attempts: {e}",
{"model": config["MODEL"], "attempts": MAX_RETRIES}
)
signal.alarm(0)
signal.signal(signal.SIGALRM, old_alarm_handler)
try:
resp_json = resp.json()
except json.JSONDecodeError as e:
exit_with_error(
f"failed to parse API response as JSON: {e}",
{"response_text": resp.text[:1000], "model": config["MODEL"]}
)
try:
content = resp_json["choices"][0]["message"]["content"]
except (KeyError, IndexError) as e:
exit_with_error(
f"unexpected API response structure: {e}",
{"response_json": str(resp_json)[:1000], "model": config["MODEL"]}
)
content = content.strip()
if content.startswith("```"):
content = "\n".join(content.split("\n")[1:])
if content.endswith("```"):
content = "\n".join(content.split("\n")[:-1])
content = content.strip()
finish_reason = resp_json.get("choices", [{}])[0].get("finish_reason", "")
if finish_reason == "length":
warn("LLM response was truncated due to length limit")
if not content:
record_error("LLM returned empty response", {"model": config["MODEL"]})
return []
try:
return json.loads(content)
except json.JSONDecodeError:
pass
repaired = try_repair_json(content)
if repaired is not None:
return repaired
record_error(
"LLM returned unparseable JSON",
{"content": content[:1000], "model": config["MODEL"]}
)
return []
RETRY_PROMPT = """You MUST output REAL file paths and REAL commit messages.
Example of what NOT to do (will be rejected):
[{"files": "files", "message": "message", "description": "description"}]
Example of what you MUST do:
[{"files": ["src/main.go", "src/config.go"], "message": "feat(config): add app settings", "description": "Add runtime configuration support"}]
CRITICAL: Every file in the diff below must appear in the files array.
Output ONLY valid JSON array with no markdown fences:"""
def is_malformed_response(result):
"""Check if response is clearly malformed (key echoing or invalid structure)."""
if not isinstance(result, list):
return True
if not result:
return True
echo_count = sum(1 for r in result if is_echoing_keys(r))
return echo_count > len(result) // 2
def normalize_llm_result(result):
"""Normalize LLM result to a list of commits."""
if isinstance(result, list):
return result
if isinstance(result, dict):
if "commits" in result:
return result["commits"]
if "groups" in result:
return result["groups"]
if "files" in result and "message" in result:
return [result]
return []
def call_llm(config, diff, missing_hint=None):
"""Single-phase: send diff and get commits.
missing_hint: set of file paths the LLM missed on a previous attempt.
"""
content = diff if len(diff) <= MAX_DIFF_CHARS else compress_diff(diff)
if missing_hint:
hint_line = "IMPORTANT: You previously missed these files — they MUST be included: " + ", ".join(sorted(missing_hint))
content = hint_line + "\n\n" + content
log("INFO", "sending diff to LLM", {"chars": len(content), "compressed": len(diff) > MAX_DIFF_CHARS})
result = call_llm_raw(config, SYSTEM_PROMPT, content)
result = normalize_llm_result(result)