-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathcommit.sh
More file actions
executable file
·1281 lines (1160 loc) · 60.7 KB
/
Copy pathcommit.sh
File metadata and controls
executable file
·1281 lines (1160 loc) · 60.7 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 bash
# commit.sh — Génère un message de commit à partir des modifications Git
# Analyse le code modifié, résume les tâches réalisées, copie dans le presse-papier.
set -euo pipefail
MY_PATH="`dirname \"$0\"`"
MY_PATH="`( cd \"$MY_PATH\" && pwd )`"
ME="${0##*/}"
[[ ! -L ~/.local/bin/${ME} ]] && ln -sf "${MY_PATH}/${ME}" ~/.local/bin/${ME} && echo "Auto Install into ~/.local/bin/${ME}"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'
# RTK (Rust Token Killer) — proxy compact si disponible
RTK=$(command -v rtk 2>/dev/null || echo "")
_git() { ${RTK:+rtk} git "$@"; }
# Recherche question.py : repo courant, install standard ~/.zen, répertoire du script
QUESTION_PY=""
for _candidate in \
"$HOME/.zen/Astroport.ONE/IA/question.py" \
"${MY_PATH}/IA/question.py" \
"$(dirname "${MY_PATH}")/IA/question.py"; do
if [[ -f "$_candidate" ]]; then
QUESTION_PY="$_candidate"
break
fi
done
# ── Paramètres par défaut ─────────────────────────────────────────────────────
MODE="commit" # commit | staged | day | week | month | period
SINCE_COMMIT="HEAD" # référence git de base pour le diff
SINCE_LABEL="dernier commit"
PERIOD_DAYS="" # pour --period N
AI_MODEL="qwen2.5-coder:14b"
AI_BACKEND="ollama" # ollama | claude | gemini
VERBOSE=false
PR_MODE=false
AI_ENHANCED=false
REVIEW_HAD_WARNINGS=false
dbg() { [[ "$VERBOSE" == "true" ]] && echo -e "\033[2m[verbose] $*\033[0m" >&2 || true; }
# ── Aide ──────────────────────────────────────────────────────────────────────
show_help() {
echo -e "${GREEN}commit.sh${NC} — Résumé des tâches réalisées + message de commit"
echo ""
echo -e "${YELLOW}USAGE:${NC} $0 [OPTIONS]"
echo ""
echo -e "${YELLOW}OPTIONS:${NC}"
echo -e " ${GREEN}--commit, -c${NC} Depuis le dernier commit (défaut)"
echo -e " ${GREEN}--staged, -s${NC} Uniquement les fichiers stagés (git add)"
echo -e " ${GREEN}--day, -d${NC} Rapport d'activité des 24 dernières heures (presse-papier)"
echo -e " ${GREEN}--week, -w${NC} Rapport d'activité des 7 derniers jours"
echo -e " ${GREEN}--month, -m${NC} Rapport d'activité des 30 derniers jours"
echo -e " ${GREEN}--period N, -P N${NC} Rapport d'activité des N derniers jours"
echo -e " ${GREEN}--branch, -b${NC} Basculer sur cette branche avant d'analyser"
echo -e " ${GREEN}--pr, -p${NC} Proposer une Pull Request après push (assistance IA)"
echo -e " ${GREEN}--ai [BACKEND],-a${NC} Revue de code IA. BACKEND: ollama (défaut) | claude | gemini"
echo -e " claude → correction directe des bugs par Claude"
echo -e " gemini → GEMINI_API_KEY requis"
echo -e " ${GREEN}--model MODEL, -M${NC} Modèle LLM (défaut Ollama: qwen2.5-coder:14b | Claude: haiku)"
echo -e " ${GREEN}--verbose, -v${NC} Mode verbeux : affiche diff, prompt et réponse brute"
echo -e " ${GREEN}--help, -h${NC} Afficher cette aide"
echo ""
echo -e "${YELLOW}EXEMPLES:${NC}"
echo " $0 # diff depuis le dernier commit (avec sélection branche)"
echo " $0 --staged # staging interactif par date → commit IA en boucle"
echo " $0 --staged --ai claude # revue claude CLI → correction directe des bugs"
echo " $0 --staged --pr # idem + propose une PR après push (IA)"
echo " $0 --day # rapport d'activité 24h → presse-papier"
echo " $0 --week --ai claude # rapport 7 jours via Claude"
echo " $0 --period 3 # rapport des 3 derniers jours"
echo " $0 --branch fix/issue-7 --staged # basculer fix/issue-7 puis staging interactif"
echo " $0 --staged --verbose # mode verbeux pour diagnostiquer"
echo ""
echo -e "${YELLOW}SORTIE:${NC} Le rapport/message généré est affiché et copié dans le presse-papier."
exit 0
}
# ── Staging interactif par temporalité ───────────────────────────────────────
interactive_stage() {
local -a unstaged untracked all_files
local -A _fmap _fstats
local _idx=1 _total _today _sel entry mtime fname ftype dt statinfo
mapfile -t unstaged < <(git diff --name-only 2>/dev/null)
mapfile -t untracked < <(git ls-files --others --exclude-standard 2>/dev/null)
all_files=("${unstaged[@]:-}" "${untracked[@]:-}")
if [[ ${#all_files[@]} -eq 0 ]]; then
echo -e "${YELLOW}⚠️ Aucun fichier modifié ou non-tracké.${NC}"
return 1
fi
_today=$(date "+%Y-%m-%d")
# ── Stats de lignes modifiées par fichier ─────────────────────────────────
while IFS=$'\t' read -r added removed fnm; do
if [[ "$added" == "-" ]]; then
_fstats["$fnm"]="binaire"
else
_fstats["$fnm"]="+${added}/-${removed}"
fi
done < <(git diff --numstat 2>/dev/null)
for f in "${untracked[@]:-}"; do
[[ -f "$f" ]] && _fstats["$f"]="$(wc -l < "$f" 2>/dev/null || echo 0)L new"
done
echo -e "${YELLOW}📁 Fichiers disponibles (plus récent d'abord) :${NC}"
echo ""
while read -r entry; do
mtime="${entry%% *}"
fname="${entry#* }"
dt=$(date -d "@$mtime" "+%Y-%m-%d %H:%M" 2>/dev/null || echo "?")
ftype="M"
printf '%s\n' "${untracked[@]:-}" | grep -qx "$fname" 2>/dev/null && ftype="?"
local color="${GREEN}"; [[ "$ftype" == "?" ]] && color="${CYAN}"
statinfo="${_fstats[$fname]:-}"
printf " [%2d] ${BLUE}%s${NC} %b%-48s%b %-14s ${YELLOW}%s${NC}\n" \
"$_idx" "$dt" "$color" "$fname" "${NC}" "$statinfo" "($ftype)"
_fmap[$_idx]="$fname"
_idx=$(( _idx + 1 ))
done < <(
for f in "${all_files[@]:-}"; do
[[ -n "$f" && -e "$f" ]] || continue
printf '%s %s\n' "$(stat -c '%Y' "$f" 2>/dev/null || echo 0)" "$f"
done | sort -rn
)
_total=$(( _idx - 1 ))
if [[ $_total -eq 0 ]]; then
echo -e "${YELLOW}⚠️ Aucun fichier trouvé.${NC}"
return 1
fi
# ── Suggestion IA de regroupement sémantique (si --ai, >1 fichier) ─────────
if [[ "${AI_ENHANCED:-false}" == "true" ]] && [[ -f "${QUESTION_PY:-}" ]] && [[ $_total -gt 1 ]]; then
echo ""
local _gp_list=""
for i in $(seq 1 "$_total"); do
_gp_list+=" [$i] ${_fmap[$i]} (${_fstats[${_fmap[$i]}]:-})\n"
done
local _gp_file
_gp_file=$(mktemp /tmp/group_prompt_XXXXXX.txt)
cat > "$_gp_file" <<GPROMPT
Regroupe ces fichiers git modifiés en commits logiques et cohérents.
RÉPONSE ULTRA-COURTE (max 10 lignes). FORMAT STRICT, FRANÇAIS :
Groupe A [numéros]: <type>(<scope>): <description>
Groupe B [numéros]: <type>(<scope>): <description>
...
Fichiers :
$(printf '%b' "$_gp_list")
GPROMPT
local _groups
_groups=$(timeout 25 python3 "$QUESTION_PY" --model "$AI_MODEL" --ctx 2048 \
--prompt-file "$_gp_file" --temperature 0.1 2>/dev/null) || true
rm -f "$_gp_file"
# Nettoyer les artefacts IA (chiffres parasites en début de ligne)
_groups=$(echo "$_groups" | sed 's/^[0-9]\+─/─/g' | sed '/^[[:space:]]*$/d')
if [[ -n "$_groups" ]]; then
echo -e "${CYAN}── Groupes suggérés ────────────────────────────────────────────${NC}"
echo -e "\033[2m$_groups\033[0m"
echo -e "${CYAN}────────────────────────────────────────────────────────────────${NC}"
fi
fi
echo ""
echo -ne "${CYAN}Sélection [Entrée=tout / N,M / N-M / aujourd'hui / Ctrl+C=annuler] :${NC} "
read -r _sel
# Entrée vide = tout sélectionner
[[ -z "$_sel" ]] && _sel="tout"
local -a selected=()
case "$_sel" in
tout|all|ALL|TOUT)
for i in $(seq 1 "$_total"); do selected+=("${_fmap[$i]}"); done ;;
aujourd*|today|TODAY)
for i in $(seq 1 "$_total"); do
local f="${_fmap[$i]}"
local mt fdt
mt=$(stat -c '%Y' "$f" 2>/dev/null || echo 0)
fdt=$(date -d "@$mt" "+%Y-%m-%d" 2>/dev/null || echo "")
[[ "$fdt" == "$_today" ]] && selected+=("$f")
done ;;
*-*)
if [[ "$_sel" =~ ^[0-9]+-[0-9]+$ ]]; then
local s="${_sel%-*}" e="${_sel#*-}"
for i in $(seq "$s" "$e"); do
[[ -n "${_fmap[$i]:-}" ]] && selected+=("${_fmap[$i]}")
done
fi ;;
*)
IFS=',' read -ra idxs <<< "$_sel"
for i in "${idxs[@]}"; do
i="${i//[[:space:]]/}" # trim espaces (ex: "1, 4, 5" → "1","4","5")
[[ "$i" =~ ^[0-9]+$ ]] && [[ -n "${_fmap[$i]:-}" ]] && selected+=("${_fmap[$i]}")
done ;;
esac
if [[ ${#selected[@]} -eq 0 ]]; then
echo -e "${YELLOW}⚠️ Aucun fichier sélectionné.${NC}"
return 1
fi
echo ""
echo -e "${GREEN}📦 Staging :${NC}"
for f in "${selected[@]}"; do
git add -- "$f" 2>/dev/null \
&& echo -e " ${GREEN}✓${NC} $f" \
|| echo -e " ${RED}✗${NC} $f"
done
echo ""
return 0
}
# ── Sélection d'un compte Claude alternatif (quota épuisé) ───────────────────
# Usage : _claude_pick_alternate "$current_cfg_path" → écrit nouveau cfg sur stdout
_claude_pick_alternate() {
local _cur="$1"
local _claude_bin; _claude_bin=$(command -v claude 2>/dev/null || echo "")
[[ -z "$_claude_bin" ]] && return 1
local _alts=()
for _d in "${HOME}"/.claude-*/; do
[[ -d "$_d" ]] || continue
[[ "$_d" == "${_cur%/}/" || "$_d" == "${_cur}/" ]] && continue
_alts+=("$_d")
done
if [[ ${#_alts[@]} -eq 0 ]]; then
echo -e "${YELLOW}[INFO]${NC} Aucun autre compte Claude disponible." >&2
return 1
fi
echo -e "${CYAN}Comptes Claude disponibles :${NC}" >&2
local _i=1
for _d in "${_alts[@]}"; do
local _slug; _slug=$(basename "$_d" | sed 's/^\.claude-//')
local _mk=""; [[ "$_d" == "$(readlink "${HOME}/.claude" 2>/dev/null)/" ]] && _mk=" ✦"
# Lire le quota depuis ~/.claude-slug/settings.json ou ~/.claude-slug/quota.json si dispo
local _quota_info=""
local _hist_file="${_d}history.jsonl"
if [[ -f "$_hist_file" ]]; then
_quota_info=$(python3 -c "
import json
from datetime import datetime
try:
lines=[l for l in open('$_hist_file').readlines() if l.strip()]
if lines:
d=json.loads(lines[-1])
ts=d.get('timestamp',0)
dt=datetime.fromtimestamp(ts/1000).strftime('%Y-%m-%d')
print(f'dernière util.: {dt} ({len(lines)} req.)')
except: pass
" 2>/dev/null || true)
fi
printf " [%d] %s%s%s\n" "$_i" "$_slug" "$_mk" "${_quota_info:+ — ${_quota_info}}" >&2
(( _i++ ))
done
read -r -p "Utiliser ce compte ? [numéro/Entrée=Defaut] : " _choice </dev/tty
if [[ "$_choice" =~ ^[0-9]+$ ]] && (( _choice >= 1 && _choice < _i )); then
echo "${_alts[$((_choice-1))]}"
fi
}
# ── Revue de code IA avant commit (si --ai) ───────────────────────────────────
ai_code_review() {
[[ "${AI_ENHANCED:-false}" != "true" ]] && return
# En mode claude, QUESTION_PY n'est pas requis
[[ "${AI_BACKEND:-ollama}" != "claude" ]] && [[ ! -f "${QUESTION_PY:-}" ]] && return
local diff_content="${1:-}"
[[ -z "$diff_content" ]] && return
echo -e "${BLUE}🔍 Revue de code IA (--ai)...${NC}"
local _rv_file
_rv_file=$(mktemp /tmp/review_prompt_XXXXXX.txt)
cat > "$_rv_file" <<RVPROMPT
Tu es un reviewer de code senior. Analyse ce diff git.
RÉPONSE COURTE (max 8 lignes). EN FRANÇAIS. PAS D'INTRODUCTION.
Cherche uniquement ce qui est clairement problématique :
• Bugs évidents ou régressions (comportement cassé)
• TODOs oubliés, code mort laissé en place
• Failles de sécurité ou données sensibles exposées
• Incohérences majeures (ex: fonction modifiée mais appelants non mis à jour)
Si tout va bien → une seule ligne : "✅ Aucun problème détecté."
Si problème → "⚠️ \`chemin/fichier.sh:42\` description courte" (chemin du fichier visible dans le diff header, jamais un nom de fonction)
DIFF :
\`\`\`
${diff_content:0:14000}
\`\`\`
RVPROMPT
local _review
case "${AI_BACKEND:-ollama}" in
claude)
local _claude_bin; _claude_bin=$(command -v claude 2>/dev/null || echo "")
if [[ -z "$_claude_bin" ]]; then
echo -e "${YELLOW}⚠️ claude CLI introuvable — fallback Ollama${NC}" >&2
_review=$(timeout 35 python3 "$QUESTION_PY" --model "$AI_MODEL" --ctx 16384 \
--prompt-file "$_rv_file" --temperature 0.1 2>/dev/null) || true
else
# Hérite du compte sélectionné pour le résumé (CLAUDE_CONFIG_DIR exporté)
local _claude_cfg="${CLAUDE_CONFIG_DIR:-${HOME}/.claude}"
_review=$(CLAUDE_CONFIG_DIR="$_claude_cfg" \
"$_claude_bin" --print < "$_rv_file" 2>/dev/null) || true
# Détection quota
if echo "$_review" | grep -qi "weekly limit\|rate.limit\|You've hit\|quota\|resets.*am"; then
echo -e "${YELLOW}⚠️ Quota Claude (${_claude_cfg##*-}) atteint.${NC}" >&2
_review=""
local _alt_cfg; _alt_cfg=$(_claude_pick_alternate "$_claude_cfg")
if [[ -n "$_alt_cfg" ]]; then
export CLAUDE_CONFIG_DIR="$_alt_cfg"
_claude_cfg="$_alt_cfg"
_review=$(CLAUDE_CONFIG_DIR="$_claude_cfg" \
"$_claude_bin" --print < "$_rv_file" 2>/dev/null) || true
fi
fi
fi ;;
gemini)
local _api_key="${GEMINI_API_KEY:-}"
if [[ -z "$_api_key" ]]; then
echo -e "${YELLOW}⚠️ GEMINI_API_KEY absent — fallback Ollama${NC}" >&2
_review=$(timeout 35 python3 "$QUESTION_PY" --model "$AI_MODEL" --ctx 16384 \
--prompt-file "$_rv_file" --temperature 0.1 2>/dev/null) || true
else
local _pj; _pj=$(python3 -c "import json,sys; print(json.dumps(sys.stdin.read()))" < "$_rv_file")
local _gm="${AI_MODEL:-gemini-2.0-flash}"
_review=$(curl -sf "https://generativelanguage.googleapis.com/v1beta/models/${_gm}:generateContent?key=${_api_key}" \
-H "content-type: application/json" \
-d "{\"contents\":[{\"parts\":[{\"text\":${_pj}}]}]}" \
| jq -r '.candidates[0].content.parts[0].text // .error.message // empty' 2>/dev/null) || true
fi ;;
*)
_review=$(timeout 35 python3 "$QUESTION_PY" --model "$AI_MODEL" --ctx 16384 \
--prompt-file "$_rv_file" --temperature 0.1 2>/dev/null) || true ;;
esac
rm -f "$_rv_file"
if [[ -n "$_review" ]]; then
echo -e "${CYAN}── Revue de code ────────────────────────────────────────────────${NC}"
echo -e "$_review"
echo -e "${CYAN}─────────────────────────────────────────────────────────────────${NC}"
echo ""
# ── Cycle de correction si problèmes détectés ────────────────────
if echo "$_review" | grep -q '⚠'; then
REVIEW_HAD_WARNINGS=true
echo -e "${YELLOW}🔧 Des problèmes ont été détectés par la revue.${NC}"
# ── Numérotation des problèmes (strip backticks + :ligne) ──────────
local -a _warns=() # "filepath|message" indexé par numéro (1-based)
while IFS= read -r _wl; do
echo "$_wl" | grep -q '⚠' || continue
local _wraw; _wraw=$(echo "$_wl" | sed 's/^[^a-zA-Z_./`-]*//' | tr -d '`')
local _wf="${_wraw%% *}"
_wf="${_wf%%:*}" # strip :140,230 → HOWTO.md
local _wmsg="${_wraw#* }"
[[ "$_wmsg" == "$_wf" ]] && _wmsg=""
[[ -z "$_wf" ]] && continue
local _wpath="$_wf"
if [[ ! -f "$_wpath" ]]; then
# Cherche dans le repo git courant (fichier sans chemin complet)
local _git_root; _git_root=$(git rev-parse --show-toplevel 2>/dev/null || echo "")
if [[ -n "$_git_root" ]]; then
local _fname; _fname=$(basename "$_wf")
local _gfound; _gfound=$(git -C "$_git_root" ls-files "*${_fname}" 2>/dev/null | head -1)
[[ -n "$_gfound" ]] && _wpath="${_git_root}/${_gfound}"
fi
[[ ! -f "$_wpath" && -f "${MY_PATH}/$_wf" ]] && _wpath="${MY_PATH}/$_wf"
fi
# Fallback : si _wf est un nom de fonction (ex: npub_to_hex()), chercher le symbole dans les fichiers stagés
if [[ ! -f "$_wpath" ]]; then
local _sym; _sym="${_wf%%(*}"
if [[ -n "$_sym" ]]; then
while IFS= read -r _sf; do
[[ -n "$_sf" && -f "$_sf" ]] && grep -qF "$_sym" "$_sf" 2>/dev/null && {
_wpath="$_sf"; break
}
done < <(git diff --cached --name-only 2>/dev/null)
fi
fi
_warns+=("${_wpath}|${_wmsg}")
done <<< "$_review"
# _warn_map initial (tous warnings, sans exclusion) — utilisé par le mode Ollama
local -A _warn_map=()
for _w in "${_warns[@]}"; do
local _wp="${_w%%|*}"
local _wm="${_w#*|}"
[[ -f "$_wp" ]] && _warn_map["$_wp"]+="${_wm}; "
done
if [[ "${AI_BACKEND:-ollama}" == "claude" ]]; then
# ── Mode Claude : correction directe, sélection par numéro ──
local _claude_bin; _claude_bin=$(command -v claude 2>/dev/null || echo "")
if [[ -z "$_claude_bin" ]]; then
echo -e "${YELLOW}💡 claude CLI introuvable — correction manuelle nécessaire.${NC}"
else
# Afficher la liste numérotée
local _ni=1
local _has_local=false
for _w in "${_warns[@]}"; do
local _wp="${_w%%|*}"
local _wm="${_w#*|}"
local _found_mark=""
[[ ! -f "$_wp" ]] && _found_mark=" ${YELLOW}(fichier introuvable)${NC}"
[[ -f "$_wp" ]] && _has_local=true
printf " ${YELLOW}[%d]${NC} %-30s %s%b\n" \
"$_ni" "$(basename "$_wp")" "${_wm:0:55}" "$_found_mark"
(( _ni++ )) || true
done
echo -ne "${CYAN} Corriger [Entrée=tous / ex:3,4=exclure / n=ignorer] : ${NC}"
read -r _fix_choice </dev/tty
# Reconstruire _warn_map en appliquant les exclusions choisies
_warn_map=()
if [[ ! "${_fix_choice:-}" =~ ^[nNqQ]$ ]]; then
local -a _excl=()
IFS=', ' read -ra _excl <<< "${_fix_choice:-}"
_ni=1
for _w in "${_warns[@]}"; do
local _skip=false
for _ex in "${_excl[@]}"; do
[[ "$_ex" == "$_ni" ]] && _skip=true && break
done
if [[ "$_skip" == "false" ]]; then
local _wp="${_w%%|*}"
local _wm="${_w#*|}"
[[ -f "$_wp" ]] && _warn_map["$_wp"]+="${_wm}; "
fi
(( _ni++ )) || true
done
fi
if [[ ${#_warn_map[@]} -eq 0 ]]; then
echo -e "${YELLOW} Aucun fichier à corriger (exclus ou introuvables).${NC}"
else
local _claude_cfg="${CLAUDE_CONFIG_DIR:-${HOME}/.claude}"
local _any_fix=false
for _wpath in "${!_warn_map[@]}"; do
local _issues="${_warn_map[$_wpath]%; }"
[[ ! -f "$_wpath" ]] && continue
echo -e "${BLUE} 🔧 $(basename "$_wpath")...${NC}"
local _fdiff
_fdiff=$(git diff HEAD -- "$_wpath" 2>/dev/null \
|| git diff --cached -- "$_wpath" 2>/dev/null || true)
local _fix_pf; _fix_pf=$(mktemp /tmp/fix_prompt_XXXXXX.txt)
local _fix_out; _fix_out=$(mktemp /tmp/fix_output_XXXXXX.txt)
cat > "$_fix_pf" <<FIXPROMPT
Fichier : ${_wpath}
Problème(s) : ${_issues}
Diff git (contexte des modifications) :
\`\`\`diff
${_fdiff:0:4000}
\`\`\`
Contenu actuel du fichier :
\`\`\`
$(head -c 10000 "$_wpath")
\`\`\`
Corrige UNIQUEMENT les problèmes listés. Format de réponse STRICT :
===FIND===
<texte exact à remplacer — assez unique dans le fichier>
===REPLACE===
<texte corrigé>
===END===
Un bloc par correction. Aucune explication, uniquement les blocs.
FIXPROMPT
CLAUDE_CONFIG_DIR="$_claude_cfg" \
"$_claude_bin" --print < "$_fix_pf" > "$_fix_out" 2>/dev/null || true
rm -f "$_fix_pf"
if grep -q '===FIND===' "$_fix_out" 2>/dev/null; then
local _py_apply; _py_apply=$(mktemp /tmp/apply_fix_XXXXXX.py)
cat > "$_py_apply" <<'PYEOF'
import sys, re
with open(sys.argv[1]) as f:
raw = f.read()
blocks = re.findall(r'===FIND===\n(.*?)\n===REPLACE===\n(.*?)\n===END===', raw, re.DOTALL)
if not blocks:
print("NO_BLOCKS"); sys.exit(1)
with open(sys.argv[2]) as f:
content = f.read()
applied = 0
for find, replace in blocks:
find = find.strip('\n'); replace = replace.strip('\n')
if find in content:
content = content.replace(find, replace, 1); applied += 1
else:
print(f"NOT_FOUND: {find[:60]!r}", file=sys.stderr)
if applied > 0:
with open(sys.argv[2], 'w') as f:
f.write(content)
print(f"APPLIED:{applied}")
else:
print("NOTHING_APPLIED"); sys.exit(1)
PYEOF
local _result
_result=$(python3 "$_py_apply" "$_fix_out" "$_wpath" 2>/dev/null) || true
rm -f "$_py_apply"
if echo "$_result" | grep -q "^APPLIED:"; then
local _n; _n=$(echo "$_result" | grep -oE '[0-9]+$')
echo -e "${GREEN} ✅ ${_n} correction(s) dans $(basename "$_wpath")${NC}"
git diff "$_wpath" 2>/dev/null | head -35 || true
_any_fix=true
else
echo -e "${YELLOW} ⚠️ Correspondance introuvable — correction manuelle : ${_issues}${NC}"
fi
else
echo -e "${YELLOW} ⚠️ Pas de corrections retournées — correction manuelle : ${_issues}${NC}"
fi
rm -f "$_fix_out"
done
if [[ "$_any_fix" == "true" ]]; then
echo ""
echo -ne "${CYAN}Relancer revue+commit ? [Entrée=oui / n=commiter quand même] : ${NC}"
read -r _rerun </dev/tty
if [[ ! "${_rerun:-}" =~ ^[nN]$ ]]; then
git reset HEAD 2>/dev/null || true
exec "$0" --staged${_cur_branch:+ --branch "$_cur_branch"}${PR_MODE:+ --pr}${AI_ENHANCED:+ --ai claude}
fi
fi
fi
fi
else
# ── Mode Ollama : code_assistant (comportement classique) ───────
local _ca="${MY_PATH}/code_assistant"
[[ ! -x "$_ca" ]] && _ca=$(command -v code_assistant 2>/dev/null || echo "")
if [[ -n "$_ca" && -x "$_ca" ]]; then
echo -ne "${CYAN} Corriger avec code_assistant (analyse → correction → patch) ? [o/N] : ${NC}"
read -r _ca_confirm
if [[ "$_ca_confirm" =~ ^[oOyY]$ ]]; then
if [[ ${#_warn_map[@]} -gt 0 ]]; then
for _wpath in "${!_warn_map[@]}"; do
local _issues="${_warn_map[$_wpath]%; }"
local _session
_session="ca-$(basename "$_wpath" | sed 's/\.[^.]*$//')-$(date +%Y%m%d)"
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════════════════╗${NC}"
printf "${GREEN}║ 🤖 code_assistant : %-38s║${NC}\n" "$(basename "$_wpath")"
echo -e "${GREEN}╚══════════════════════════════════════════════════════════╝${NC}"
echo -e "${YELLOW} Session : $_session${NC}"
echo -e "${YELLOW} Problèmes : ${_issues}${NC}"
echo ""
"$_ca" "$_wpath" \
--kvbasename "$_session" \
--supplement "REVUE DE COMMIT : ${_issues}" || true
done
echo ""
echo -e "${GREEN}✅ code_assistant terminé — relance du cycle de commit...${NC}"
git reset HEAD 2>/dev/null || true
exec "$0" --staged${_cur_branch:+ --branch "$_cur_branch"}${PR_MODE:+ --pr}${AI_ENHANCED:+ --ai "$AI_BACKEND"}
else
echo -e "${YELLOW}💡 Fichiers non localisés — lance manuellement :${NC}"
echo -e "${YELLOW} code_assistant <fichier> --kvbasename session${NC}"
fi
fi
else
echo -e "${YELLOW}💡 code_assistant disponible dans ${MY_PATH}/ — correction manuelle :${NC}"
echo -e "${YELLOW} code_assistant <fichier> --kvbasename session --supplement \"<problème>\"${NC}"
fi
fi
fi
fi
}
# ── Parsing des arguments ─────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
case "$1" in
--help|-h) show_help ;;
--commit|-c) MODE="commit"; SINCE_LABEL="dernier commit" ; shift ;;
--staged|-s) MODE="staged"; SINCE_LABEL="fichiers stagés" ; shift ;;
--day|-d) MODE="day"; SINCE_LABEL="24 dernières heures" ; shift ;;
--week|-w) MODE="week"; SINCE_LABEL="7 derniers jours" ; shift ;;
--month|-m) MODE="month"; SINCE_LABEL="30 derniers jours" ; shift ;;
--period|-P)
shift
PERIOD_DAYS="${1:?'--period requiert un nombre de jours (ex: --period 3)'}"
MODE="period"; SINCE_LABEL="${PERIOD_DAYS} derniers jours"
shift ;;
--model|-M)
shift
AI_MODEL="${1:?'--model requiert un nom de modèle'}"
shift ;;
--branch|-b)
shift
TARGET_BRANCH="${1:?'--branch requiert un nom de branche'}"
shift ;;
--pr|-p) PR_MODE=true ; shift ;;
--ai|-a)
AI_ENHANCED=true
case "${2:-}" in
claude|gemini|ollama) AI_BACKEND="${2}"; shift ;;
*)
# Auto-détection : Claude si disponible, sinon Ollama
if command -v claude &>/dev/null && \
{ [[ -L "${HOME}/.claude" ]] || ls "${HOME}"/.claude-*/ &>/dev/null 2>&1; }; then
AI_BACKEND="claude"
fi
;;
esac
shift ;;
--verbose|-v) VERBOSE=true ; shift ;;
*)
echo -e "${RED}Option inconnue: $1${NC}"
echo "Utilisez --help pour l'aide."
exit 1 ;;
esac
done
# Backend d'origine : mémorisé avant qu'un fix ne le remplace par claude
ORIG_AI_BACKEND="${COMMIT_ORIG_AI_BACKEND:-$AI_BACKEND}"
export COMMIT_ORIG_AI_BACKEND="$ORIG_AI_BACKEND"
# ── Vérification dépôt Git ────────────────────────────────────────────────────
if ! git rev-parse --git-dir > /dev/null 2>&1; then
echo -e "${RED}❌ Ce répertoire n'est pas un dépôt Git.${NC}"
exit 1
fi
# ── Sélection de branche ──────────────────────────────────────────────────────
_cur_branch=$(git branch --show-current 2>/dev/null || echo "?")
# Si --branch est passé en argument, basculer directement
if [[ -n "${TARGET_BRANCH:-}" ]] && [[ "$TARGET_BRANCH" != "$_cur_branch" ]]; then
git checkout "$TARGET_BRANCH" 2>/dev/null \
&& echo -e "${GREEN}✓ Basculé sur '${TARGET_BRANCH}'${NC}" \
|| echo -e "${RED}[ERREUR]${NC} Impossible de basculer sur '${TARGET_BRANCH}'" >&2
_cur_branch=$(git branch --show-current 2>/dev/null || echo "?")
fi
echo -e "${BLUE}🌿 Branche courante :${NC} ${GREEN}${_cur_branch}${NC}"
# Lister les branches fix/issue-* (workflow issue.sh) + toutes les branches locales
mapfile -t _fix_branches < <(git branch --list "fix/issue-*" 2>/dev/null | sed 's/^[* ]*//' | grep -v "^$")
mapfile -t _all_branches < <(git branch 2>/dev/null | sed 's/^[* ]*//' | grep -v "^$")
if [[ ${#_all_branches[@]} -gt 1 ]] && [[ -z "${TARGET_BRANCH:-}" ]]; then
echo ""
if [[ ${#_fix_branches[@]} -gt 0 ]]; then
echo -e "${YELLOW}🔧 Branches de correctif (fix/issue-*) :${NC}"
_i=1
for _b in "${_fix_branches[@]}"; do
_star=""; [[ "$_b" == "$_cur_branch" ]] && _star=" ${GREEN}← courante${NC}"
printf " [%d] %b%s%b\n" "$_i" "${GREEN}" "$_b" "${NC}${_star}"
(( _i++ ))
done
echo ""
echo -e "${YELLOW}📋 Autres branches :${NC}"
else
echo -e "${YELLOW}📋 Branches disponibles :${NC}"
fi
_j=1
for _b in "${_all_branches[@]}"; do
# Ne pas relister les fix branches déjà affichées si elles existent
[[ ${#_fix_branches[@]} -gt 0 ]] && printf '%s\n' "${_fix_branches[@]}" | grep -qx "$_b" && continue
_star=""; [[ "$_b" == "$_cur_branch" ]] && _star=" ${GREEN}← courante${NC}"
printf " [%s] %s%b\n" "$(( ${#_fix_branches[@]} + _j ))" "$_b" "${NC}${_star}"
(( _j++ ))
done
echo ""
echo -ne "${CYAN}Basculer sur une branche ? (numéro ou nom, Entrée pour garder '${_cur_branch}') : ${NC}"
read -r _branch_choice
if [[ -n "$_branch_choice" ]]; then
# Sélection par numéro
if [[ "$_branch_choice" =~ ^[0-9]+$ ]]; then
_all_combined=("${_fix_branches[@]}" "${_all_branches[@]}")
# Reconstruire la liste combinée unique en excluant doublons fix dans all
mapfile -t _combined_unique < <(printf '%s\n' "${_fix_branches[@]}" \
$(printf '%s\n' "${_all_branches[@]}" | grep -vxF -f <(printf '%s\n' "${_fix_branches[@]}")) \
| grep -v "^$")
_idx=$(( _branch_choice - 1 ))
if (( _idx >= 0 && _idx < ${#_combined_unique[@]} )); then
_target="${_combined_unique[$_idx]}"
if [[ "$_target" != "$_cur_branch" ]]; then
git checkout "$_target" 2>/dev/null \
&& echo -e "${GREEN}✓ Basculé sur '${_target}'${NC}" \
|| echo -e "${RED}[ERREUR]${NC} Impossible de basculer sur '${_target}'" >&2
_cur_branch=$(git branch --show-current 2>/dev/null || echo "?")
fi
fi
else
# Sélection par nom
if [[ "$_branch_choice" != "$_cur_branch" ]]; then
git checkout "$_branch_choice" 2>/dev/null \
&& echo -e "${GREEN}✓ Basculé sur '${_branch_choice}'${NC}" \
|| echo -e "${RED}[ERREUR]${NC} Branche '${_branch_choice}' introuvable" >&2
_cur_branch=$(git branch --show-current 2>/dev/null || echo "?")
fi
fi
fi
fi
dbg "Dépôt Git : $(git rev-parse --show-toplevel)"
dbg "Branche : $_cur_branch"
dbg "Mode : $MODE"
dbg "Modèle IA : $AI_MODEL"
dbg "question.py : $QUESTION_PY ($([ -f "$QUESTION_PY" ] && echo 'trouvé' || echo 'ABSENT'))"
# ── Pull avant analyse ────────────────────────────────────────────────────────
if git remote get-url origin &>/dev/null; then
echo -e "${BLUE}⬇️ git pull...${NC}"
git pull --ff-only 2>&1 | grep -v '^$' || \
echo -e "${YELLOW}⚠️ pull non fast-forward — continuez manuellement si nécessaire.${NC}"
fi
# ── Collecte du diff ──────────────────────────────────────────────────────────
dbg "Collecte des modifications ($SINCE_LABEL)"
DIFF_CONTENT=""
DIFF_RAW=""
FILES_CHANGED=""
COMMITS_INFO=""
DIFF_STAT=""
case "$MODE" in
staged)
# Staging interactif si rien n'est encore stagé
if [[ -z "$(git diff --cached --name-only 2>/dev/null)" ]]; then
echo -e "${YELLOW}⚠️ Aucun fichier stagé.${NC}"
interactive_stage || exit 0
fi
DIFF_RAW=$(git diff --cached -U0 -- . ':(exclude)*.lock' ':(exclude)*.min.js' ':(exclude)dist/*' ':(exclude)node_modules/*' ':(exclude)*-core.js' ':(exclude)*.wasm' ':(exclude)earth/ffmpeg/*' 2>/dev/null | tr -d '\0' | iconv -c -f UTF-8 -t UTF-8 || true)
FILES_CHANGED=$(git diff --cached -- . ':(exclude)*.lock' ':(exclude)*.min.js' ':(exclude)dist/*' ':(exclude)node_modules/*' ':(exclude)*-core.js' ':(exclude)*.wasm' ':(exclude)earth/ffmpeg/*' --name-status 2>/dev/null || true)
DIFF_STAT=$(_git diff --cached --stat 2>/dev/null || true)
if [[ -z "$DIFF_RAW" ]]; then
echo -e "${YELLOW}⚠️ Aucun fichier stagé (git add).${NC}"
exit 0
fi
;;
commit)
DIFF_RAW=$(git diff HEAD -U0 -- . ':(exclude)*.lock' ':(exclude)*.min.js' ':(exclude)dist/*' ':(exclude)node_modules/*' ':(exclude)*-core.js' ':(exclude)*.wasm' ':(exclude)earth/ffmpeg/*' 2>/dev/null | tr -d '\0' | iconv -c -f UTF-8 -t UTF-8 || true)
DIFF_RAW+=$'\n'$(git diff --cached -U0 -- . ':(exclude)*.lock' ':(exclude)*.min.js' ':(exclude)dist/*' ':(exclude)node_modules/*' ':(exclude)*-core.js' ':(exclude)*.wasm' ':(exclude)earth/ffmpeg/*' 2>/dev/null | tr -d '\0' | iconv -c -f UTF-8 -t UTF-8 || true)
FILES_CHANGED=$(git diff HEAD -- . ':(exclude)*.lock' ':(exclude)*.min.js' ':(exclude)dist/*' ':(exclude)node_modules/*' ':(exclude)*-core.js' ':(exclude)*.wasm' ':(exclude)earth/ffmpeg/*' --name-status 2>/dev/null || true)
FILES_CHANGED+=$'\n'$(git diff --cached -- . ':(exclude)*.lock' ':(exclude)*.min.js' ':(exclude)dist/*' ':(exclude)node_modules/*' ':(exclude)*-core.js' ':(exclude)*.wasm' ':(exclude)earth/ffmpeg/*' --name-status 2>/dev/null || true)
DIFF_STAT=$(_git diff HEAD --stat 2>/dev/null || true)
COMMITS_INFO=$(_git log -1 --pretty=format:"[%h] %s (%an, %ar)" 2>/dev/null || true)
if [[ -z "$DIFF_RAW" || "$DIFF_RAW" =~ ^[[:space:]]*$ ]]; then
echo -e "${YELLOW}⚠️ Aucune modification non commitée détectée.${NC}"
echo -e "${BLUE}💡 Le dernier commit:${NC} $COMMITS_INFO"
echo -e "${BLUE} Utilisez --staged pour les fichiers en attente, ou --day pour les commits récents.${NC}"
exit 0
fi
;;
day)
SINCE_DATE=$(date -d "24 hours ago" -Iseconds 2>/dev/null || date -u -v-24H +"%Y-%m-%dT%H:%M:%S")
COMMITS_INFO=$(_git log --since="$SINCE_DATE" --pretty=format:"[%h] %s (%an, %ar)" 2>/dev/null || true)
FILES_CHANGED=$(git log --since="$SINCE_DATE" --name-status --pretty=format: 2>/dev/null | grep -v '^$' | sort -u || true)
DIFF_CONTENT=$(git diff "HEAD@{24.hours.ago}" HEAD 2>/dev/null || git log --since="$SINCE_DATE" -p 2>/dev/null || true)
if [[ -z "$COMMITS_INFO" ]]; then
echo -e "${YELLOW}⚠️ Aucun commit dans les dernières 24 heures.${NC}"
exit 0
fi
;;
week)
SINCE_DATE=$(date -d "7 days ago" -Iseconds 2>/dev/null || date -u -v-7d +"%Y-%m-%dT%H:%M:%S")
COMMITS_INFO=$(_git log --since="$SINCE_DATE" --pretty=format:"[%h] %s (%an, %ar)" 2>/dev/null || true)
FILES_CHANGED=$(git log --since="$SINCE_DATE" --name-status --pretty=format: 2>/dev/null | grep -v '^$' | sort -u || true)
DIFF_CONTENT=$(git diff "HEAD@{7.days.ago}" HEAD 2>/dev/null || git log --since="$SINCE_DATE" -p 2>/dev/null || true)
if [[ -z "$COMMITS_INFO" ]]; then
echo -e "${YELLOW}⚠️ Aucun commit dans les 7 derniers jours.${NC}"
exit 0
fi
;;
month)
SINCE_DATE=$(date -d "30 days ago" -Iseconds 2>/dev/null || date -u -v-30d +"%Y-%m-%dT%H:%M:%S")
COMMITS_INFO=$(_git log --since="$SINCE_DATE" --pretty=format:"[%h] %s (%an, %ar)" 2>/dev/null || true)
FILES_CHANGED=$(git log --since="$SINCE_DATE" --name-status --pretty=format: 2>/dev/null | grep -v '^$' | sort -u || true)
DIFF_CONTENT=$(git diff "HEAD@{30.days.ago}" HEAD 2>/dev/null || git log --since="$SINCE_DATE" -p 2>/dev/null || true)
if [[ -z "$COMMITS_INFO" ]]; then
echo -e "${YELLOW}⚠️ Aucun commit dans les 30 derniers jours.${NC}"
exit 0
fi
;;
period)
SINCE_DATE=$(date -d "${PERIOD_DAYS} days ago" -Iseconds 2>/dev/null \
|| date -u -v-"${PERIOD_DAYS}d" +"%Y-%m-%dT%H:%M:%S")
COMMITS_INFO=$(_git log --since="$SINCE_DATE" --pretty=format:"[%h] %s (%an, %ar)" 2>/dev/null || true)
FILES_CHANGED=$(git log --since="$SINCE_DATE" --name-status --pretty=format: 2>/dev/null | grep -v '^$' | sort -u || true)
DIFF_CONTENT=$(git log --since="$SINCE_DATE" -p 2>/dev/null || true)
if [[ -z "$COMMITS_INFO" ]]; then
echo -e "${YELLOW}⚠️ Aucun commit dans les ${PERIOD_DAYS} derniers jours.${NC}"
exit 0
fi
;;
esac
dbg "Commits trouvés :"
dbg "$COMMITS_INFO"
dbg "---"
dbg "Fichiers modifiés :"
dbg "$FILES_CHANGED"
# ── Troncature head+tail (staged/commit) ou simple (day/week/month) ──────────
if [[ -n "$DIFF_RAW" ]]; then
DIFF_ORIGINAL_LEN=${#DIFF_RAW}
if [[ $DIFF_ORIGINAL_LEN -gt 25000 ]]; then
DIFF_CONTENT="${DIFF_RAW:0:15000}"
DIFF_CONTENT+=$'\n... [TRONCATURE CENTRALE] ...\n'
DIFF_CONTENT+="${DIFF_RAW: -10000}"
dbg "Diff tronqué head+tail : $DIFF_ORIGINAL_LEN → ~25000 caractères"
else
DIFF_CONTENT="$DIFF_RAW"
dbg "Diff complet : $DIFF_ORIGINAL_LEN caractères"
fi
else
DIFF_ORIGINAL_LEN=${#DIFF_CONTENT}
if [[ $DIFF_ORIGINAL_LEN -gt 24000 ]]; then
DIFF_CONTENT="${DIFF_CONTENT:0:24000}"$'\n...[tronqué]'
dbg "Diff tronqué : $DIFF_ORIGINAL_LEN → 24000 caractères"
else
dbg "Diff complet : $DIFF_ORIGINAL_LEN caractères"
fi
fi
if [[ "$VERBOSE" == "true" ]]; then
echo -e "\033[2m[VERBOSE] ── Diff complet envoyé à l'IA ──────────────────────────\033[0m" >&2
echo -e "\033[2m$DIFF_CONTENT\033[0m" >&2
echo -e "\033[2m[VERBOSE] ────────────────────────────────────────────────────────\033[0m" >&2
fi
dbg "Modifications collectées"
# ── Résumé basic sans IA ──────────────────────────────────────────────────────
basic_summary() {
local summary="## Résumé des modifications — $(date +"%Y-%m-%d")\n\n"
summary+="**Période :** $SINCE_LABEL\n\n"
if [[ -n "$COMMITS_INFO" ]]; then
summary+="### Commits\n"
while IFS= read -r line; do
[[ -n "$line" ]] && summary+="- $line\n"
done <<< "$COMMITS_INFO"
summary+="\n"
fi
if [[ -n "$FILES_CHANGED" ]]; then
summary+="### Fichiers modifiés\n"
local count=0
while IFS= read -r line; do
if [[ -n "$line" && $count -lt 20 ]]; then
summary+="- $line\n"
((count++))
fi
done <<< "$FILES_CHANGED"
summary+="\n"
fi
echo -e "$summary"
}
# ── Rapport d'activité (--day / --week / --month / --period) ─────────────────
generate_activity_report() {
local prompt
prompt=$(cat <<RPROMPT
Tu rédiges un rapport d'activité pour un développeur. EN FRANÇAIS. CONCIS.
Période : ${SINCE_LABEL} (au ${SINCE_DATE:-maintenant})
Projet : $(basename "$(git rev-parse --show-toplevel 2>/dev/null || echo .)")
Branche : ${_cur_branch}
Commits de la période :
${COMMITS_INFO}
Fichiers modifiés :
${FILES_CHANGED:0:3000}
FORMAT DE RÉPONSE (commence directement, aucune introduction) :
## Activité — ${SINCE_LABEL}
### Ce qui a été fait
- … (liste des réalisations, orienté valeur/usage, max 8 points)
### Impact
- … (ce que ça change concrètement pour les utilisateurs ou le projet, 2-4 points)
### Fichiers principaux
- \`fichier\` — explication sur une ligne
---
*Rapport généré le $(date +"%Y-%m-%d %H:%M")*
RPROMPT
)
local _rf; _rf=$(mktemp /tmp/report_prompt_XXXXXX.txt)
echo "$prompt" > "$_rf"
local result=""
if [[ "${AI_BACKEND:-ollama}" == "claude" ]] && command -v claude &>/dev/null; then
local _rcfg="${CLAUDE_CONFIG_DIR:-${HOME}/.claude}"
result=$(CLAUDE_CONFIG_DIR="$_rcfg" claude --print < "$_rf" 2>/dev/null) || true
if echo "$result" | grep -qi "weekly limit\|rate.limit\|You've hit\|quota\|resets.*am"; then
result=""
_rcfg=$(_claude_pick_alternate "$_rcfg")
[[ -n "$_rcfg" ]] && result=$(CLAUDE_CONFIG_DIR="$_rcfg" claude --print < "$_rf" 2>/dev/null) || true
fi
elif [[ -f "${QUESTION_PY:-}" ]]; then
result=$(python3 "$QUESTION_PY" --model "$AI_MODEL" --ctx 16384 \
--prompt-file "$_rf" --temperature 0.2 2>/dev/null) || true
fi
rm -f "$_rf"
if [[ -z "$result" ]]; then
# Rapport basique sans IA
result="## Activité — ${SINCE_LABEL}\n\n"
result+="### Commits\n"
while IFS= read -r _cl; do [[ -n "$_cl" ]] && result+="- ${_cl}\n"; done <<< "$COMMITS_INFO"
result+="\n### Fichiers modifiés\n"
while IFS= read -r _fl; do [[ -n "$_fl" ]] && result+="- ${_fl}\n"; done <<< "$(echo "$FILES_CHANGED" | head -20)"
result+="\n---\n*Rapport généré le $(date +"%Y-%m-%d %H:%M")*"
fi
echo "$result"
}
# ── Appel IA via question.py ──────────────────────────────────────────────────
generate_ai_summary() {
local prompt
prompt=$(cat <<PROMPT
Tu es un automate d'analyse Git pour UPlanet/Astroport.ONE.
INTERDICTION de faire une introduction ou des commentaires.
NE FAIS AUCUNE INTRODUCTION NI CONCLUSION. Commence directement par # COMMIT.
RÉPONSE STRICTEMENT AU FORMAT DEMANDÉ.
RÉPONDS UNIQUEMENT EN FRANÇAIS.
**ANALYSE :**
1. **MESSAGE DE COMMIT :** Format <type>(<scope>): <description>
- Scope : dossier principal des fichiers changés (ex: earth, tools, RUNTIME, tests, docs, install).
Si plusieurs dossiers → scope = sous-projet le plus significatif (earth > tools > RUNTIME).
Si fichier à la racine → scope = basename sans extension.
- Description : impératif présent, pas de majuscule, pas de point final, max 72 chars.
- Types : feat (nouvelle fonctionnalité), fix (correction), refactor, docs, chore, test
2. **SCAN DE PATTERNS TECHNIQUES :** Cherche EXACTEMENT ces chaînes dans le diff :
- "kind.*30311" ou "NIP-53" → "Live Streaming NIP-53"
- "kind.*1311" → "chat live NIP-53"
- "kind.*22\b" → "publication vidéo Kind 22"
- "kind.*30504" ou "uDRIVE" → "formation WoTx2 (Kind 30504)"
- "kind.*30500" → "permis WoTx2 (Kind 30500)"
- "app_switch" ou "FAB" → "navigation FAB circulaire"
- "cidirect" → "accès CID direct IPFS"
- "NIP-42" → "auth NIP-42"
- "MULTIPASS" → "MULTIPASS UPlanet"
- "keygen.*nostr" → "dérivation clé NOSTR"
- "rtk" → "intégration RTK (économie tokens)"
3. **RÈGLE FICHIERS :** Ne cite QUE les fichiers présents dans les Stats globales. Pas d'invention.
4. **STYLE :** Technique et précis. "corrige accès CID direct" plutôt que "corrige le code".
**CONTEXTE :**
- Branche : $_cur_branch\n- Contexte : ${ISSUE_REF:-}
- Période : $SINCE_LABEL
- Commits : $COMMITS_INFO
**Stats globales (seuls ces fichiers existent) :**
$DIFF_STAT
**DIFF (compact -U0, head+tail si tronqué) :**
\`\`\`
$DIFF_CONTENT
\`\`\`
**FORMAT EXACT DE RÉPONSE (ne rien ajouter avant # COMMIT) :**
# COMMIT
<type>(<scope>): <description>
## Tâches réalisées
- …
## Fichiers clés
- …
PROMPT
)
local prompt_file
prompt_file=$(mktemp /tmp/commit_prompt_XXXXXX.txt)
echo "$prompt" > "$prompt_file"
if [[ "$VERBOSE" == "true" ]]; then
echo -e "\033[2m[VERBOSE] ── Prompt ($(wc -c < "$prompt_file") bytes) → ${AI_BACKEND} ──\033[0m" >&2
cat "$prompt_file" >&2
echo -e "\033[2m[VERBOSE] ──────────────────────────────────────────────────────────\033[0m" >&2
fi