Repository navigation
Expand file tree
/
Copy pathai-code-discussion.el
More file actions
911 lines (834 loc) · 42.8 KB
/
Copy pathai-code-discussion.el
File metadata and controls
911 lines (834 loc) · 42.8 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
;;; ai-code-discussion.el --- AI code discussion operations -*- lexical-binding: t; -*-
;; Author: Kang Tu <tninja@gmail.com>
;; SPDX-License-Identifier: Apache-2.0
;;; Commentary:
;; This file provides code discussion functionality for the AI Code Interface package.
;;; Code:
(require 'which-func)
(require 'savehist)
(require 'subr-x)
(defvar ai-code--harness-loading)
(require 'ai-code-input)
(require 'ai-code-magit)
(require 'ai-code-prompt-mode)
(let ((ai-code--harness-loading t))
(require 'ai-code-change))
(declare-function ai-code--insert-prompt "ai-code-prompt-mode")
(declare-function ai-code--compose-question-brief
"ai-code-change" (&rest plist))
(declare-function ai-code--detect-todo-info
"ai-code-change" (region-active))
(declare-function ai-code--get-clipboard-text "ai-code-utils")
(declare-function ai-code--current-line-scope-context "ai-code-utils" ())
(declare-function ai-code--scope-context-for-region "ai-code-utils" (beg end))
(declare-function ai-code--format-scope-context "ai-code-utils" (context))
(declare-function ai-code-call-gptel-sync "ai-code-prompt-mode")
(declare-function ai-code--ensure-files-directory "ai-code-utils")
(declare-function ai-code--git-root "ai-code-utils" (&optional dir))
(declare-function ai-code--format-repo-context-info "ai-code-utils")
(declare-function ai-code--pull-or-review-action-choice "ai-code-github")
(declare-function ai-code--pull-or-review-source-instruction "ai-code-github"
(review-source &optional review-mode))
(declare-function org-current-level "org")
(declare-function org-roam-db-update-file "org-roam-db" (&optional file-path no-require))
(declare-function org-roam-db-sync "org-roam-db" (&optional force))
(declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
(declare-function dired-get-marked-files "dired"
(&optional localp arg filter distinguish-one-marked error-if-none-p))
(declare-function ai-code-implement-todo
"ai-code-change" (arg &optional default-action))
(defvar ai-code--repo-context-info)
(defvar org-roam-directory)
(defvar ai-code-note-request-history nil
"Minibuffer history for note requests.")
(defun ai-code--ensure-note-request-history ()
"Register persistent minibuffer history for note requests.
Only adds the variable to savehist tracking; does not enable
`savehist-mode'. Users should enable it in their Emacs configuration
to persist history."
(add-to-list 'savehist-additional-variables 'ai-code-note-request-history))
(ai-code--ensure-note-request-history)
(defconst ai-code-discussion--question-only-note
"Note: This is a question only - please do not modify the code."
"Prompt note for question-only requests.")
(defconst ai-code-discussion--selected-region-note
"Note: This is a question about the selected region - please do not modify the code."
"Prompt note for question-only requests about the selected region.")
(defconst ai-code-discussion--exception-investigation-boundaries
"Investigate first. Do not make code changes."
"Boundaries for exception investigation prompts.")
(defconst ai-code-discussion--exception-investigation-note
(concat
ai-code-discussion--question-only-note
"\n"
"Report root cause, relevant evidence, and candidate next steps. "
"Include at least one candidate next step that explains how to fix the issue.")
"Instruction for exception investigation prompts.")
(defconst ai-code-discussion--explain-selected-files-prefix
"Please explain the selected files or directories."
"Prompt prefix for explaining selected files or directories.")
(defconst ai-code-discussion--explain-file-at-path-prefix
"Please explain the file at path @"
"Prompt prefix for explaining a file selected from Dired.")
(defconst ai-code-discussion--explain-directory-at-path-prefix
"Please explain the directory at path @"
"Prompt prefix for explaining a directory selected from Dired.")
(defconst ai-code-discussion--explain-code-prefix
"Please explain the following code:"
"Prompt prefix for explaining a selected region.")
(defconst ai-code-discussion--explain-symbol-prefix
"Please explain the symbol '"
"Prompt prefix for explaining a symbol.")
(defconst ai-code-discussion--explain-line-prefix
"Please explain the following line of code:"
"Prompt prefix for explaining the current line.")
(defconst ai-code-discussion--explain-function-prefix
"Please explain the function '"
"Prompt prefix for explaining the current function.")
(defconst ai-code-discussion--explain-file-prefix
"Please explain the following file:"
"Prompt prefix for explaining the current file.")
(defconst ai-code-discussion--explain-files-prefix
"Please explain the following files:"
"Prompt prefix for explaining visible files.")
(defconst ai-code-discussion--explain-git-repo-prefix
"Please explain the current git repository:"
"Prompt prefix for explaining the current repository.")
(defconst ai-code-discussion--explain-code-change-pr-prefix
"Please explain the code change in pull request:"
"Prompt prefix for explaining a pull request code change.")
(defconst ai-code-discussion--explain-code-change-branch-range-prefix
"Please explain the code change between branches:"
"Prompt prefix for explaining a branch range code change.")
(defconst ai-code-discussion--explain-code-change-commit-prefix
"Please explain the code change introduced by commit:"
"Prompt prefix for explaining a commit code change.")
(defconst ai-code-discussion--explain-code-change-focus-note
"4. Focus on understanding the change. Do not make code changes."
"Shared final instruction for code change explanation prompts.")
(defconst ai-code-discussion--explain-prompt-prefixes
(list ai-code-discussion--explain-selected-files-prefix
ai-code-discussion--explain-file-at-path-prefix
ai-code-discussion--explain-directory-at-path-prefix
ai-code-discussion--explain-code-prefix
ai-code-discussion--explain-symbol-prefix
ai-code-discussion--explain-line-prefix
ai-code-discussion--explain-function-prefix
ai-code-discussion--explain-file-prefix
ai-code-discussion--explain-files-prefix
ai-code-discussion--explain-git-repo-prefix
ai-code-discussion--explain-code-change-pr-prefix
ai-code-discussion--explain-code-change-branch-range-prefix
ai-code-discussion--explain-code-change-commit-prefix)
"Known explain prompt prefixes generated by discussion commands.")
;;;###autoload
(defun ai-code-ask-question (arg)
"Generate prompt to ask questions about specific code.
In Magit, ask about selected textual hunks without changing code.
With a prefix argument \[universal-argument], append the clipboard
contents as context. If current buffer is a file, keep existing logic.
If current buffer is a Dired buffer:
- If there are files or directories marked, use them as context
\(use git repo relative path, start with @ character)
- If there are no files or dirs marked, but under cursor there is
file or dir, use it as context of prompt
If a region is selected, ask about that specific region.
If cursor is in a function, ask about that function.
Otherwise, ask a general question about the file.
Inserts the prompt into the AI prompt file and optionally sends to AI.
Argument ARG is the prefix argument."
(interactive "P")
;; DONE: similar to ai-code-code-change, when todo-info is available, call ai-code-implement-todo
(cond
((derived-mode-p 'magit-mode)
(ai-code-magit-prompt 'question arg))
((derived-mode-p 'dired-mode)
(let ((clipboard-context (when arg (ai-code--get-clipboard-text))))
(ai-code--ask-question-dired clipboard-context)))
(t
(let ((todo-info (when buffer-file-name
(ai-code--detect-todo-info (region-active-p)))))
(if todo-info
(ai-code-implement-todo arg "Ask question")
(let ((clipboard-context (when arg (ai-code--get-clipboard-text))))
(ai-code--ask-question-file clipboard-context)))))))
(defun ai-code--ask-question-dired (clipboard-context)
"Handle ask question for Dired buffer.
CLIPBOARD-CONTEXT is optional clipboard text to append as context."
(let* ((all-marked (dired-get-marked-files))
(file-at-point (dired-get-filename nil t))
(truly-marked (remove file-at-point all-marked))
(has-marks (> (length truly-marked) 0))
(context-files (cond
(has-marks truly-marked)
(file-at-point (list file-at-point))
(t nil)))
(git-relative-files (when context-files
(ai-code--get-git-relative-paths context-files)))
(scope-string
(if git-relative-files
(concat "Selected files/directories:\n"
(mapconcat (lambda (f) (concat "@" f))
git-relative-files "\n"))
(format "Current directory: %s" default-directory)))
(prompt-label (cond
((and clipboard-context
(string-match-p "\\S-" clipboard-context))
(if has-marks
"Question about marked files/directories (clipboard context): "
(if file-at-point
(format "Question about %s (clipboard context): " (file-name-nondirectory file-at-point))
"General question about directory (clipboard context): ")))
(has-marks "Question about marked files/directories: ")
(file-at-point (format "Question about %s: " (file-name-nondirectory file-at-point)))
(t "General question about directory: ")))
(question (ai-code-read-string prompt-label ""))
(repo-context-string (ai-code--format-repo-context-info))
(final-prompt
(ai-code--compose-question-brief
:goal question
:scope scope-string
:context repo-context-string
:clipboard-context (and clipboard-context
(string-match-p "\\S-" clipboard-context)
clipboard-context)
:instruction ai-code-discussion--question-only-note)))
(ai-code--insert-prompt final-prompt)))
(defun ai-code--ask-question-file (clipboard-context)
"Handle ask question for regular file buffer.
CLIPBOARD-CONTEXT is optional clipboard text to append as context."
(let* ((file-extension (when buffer-file-name
(file-name-extension buffer-file-name)))
(is-diff-or-patch (and file-extension
(member file-extension '("diff" "patch"))))
(region-active (region-active-p))
(scope-ctx (unless is-diff-or-patch
(if region-active
(ai-code--scope-context-for-region
(region-beginning) (region-end))
(ai-code--current-line-scope-context))))
(function-name (plist-get scope-ctx :function-name))
(semantic-scope (ai-code--format-scope-context scope-ctx))
(region-text (when region-active
(buffer-substring-no-properties (region-beginning) (region-end))))
(region-location-info (when region-active
(ai-code--get-region-location-info (region-beginning) (region-end))))
(prompt-label
(cond
((and clipboard-context
(string-match-p "\\S-" clipboard-context))
(cond
(region-active
(if function-name
(format "Question about selected code in function %s (clipboard context): " function-name)
"Question about selected code (clipboard context): "))
(function-name
(format "Question about function %s (clipboard context): " function-name))
(buffer-file-name
(format "General question about %s (clipboard context): " (file-name-nondirectory buffer-file-name)))
(t "General question (clipboard context): ")))
(region-active
(if function-name
(format "Question about selected code in function %s: " function-name)
"Question about selected code: "))
(function-name
(format "Question about function %s: " function-name))
(buffer-file-name
(format "General question about %s: " (file-name-nondirectory buffer-file-name)))
(t "General question: ")))
(question (ai-code-read-string prompt-label ""))
(files-context-string (ai-code--get-context-files-string))
(repo-context-string (ai-code--format-repo-context-info))
(scope-string
(concat
(if buffer-file-name
(format "Current file: %s" buffer-file-name)
(format "Current buffer: %s" (buffer-name)))
(when region-text
(concat "\nSelected region:\n"
(when region-location-info
(concat region-location-info "\n"))
region-text))
(unless (string-empty-p semantic-scope)
(concat "\n" semantic-scope))
files-context-string))
(final-prompt
(ai-code--compose-question-brief
:goal question
:scope scope-string
:context repo-context-string
:clipboard-context (and clipboard-context
(string-match-p "\\S-" clipboard-context)
clipboard-context)
:instruction (if region-text
ai-code-discussion--selected-region-note
ai-code-discussion--question-only-note))))
(ai-code--insert-prompt final-prompt)))
(defun ai-code--get-git-relative-paths (file-paths)
"Convert absolute FILE-PATHS to git repository relative paths.
Returns a list of relative paths from the git repository root."
(when file-paths
(let ((git-root (ai-code--git-root)))
(when git-root
(mapcar (lambda (file-path)
(file-relative-name file-path git-root))
file-paths)))))
(defun ai-code--get-region-location-info (region-beginning region-end)
"Compute region location information for the active region.
Returns region-location-info
REGION-BEGINNING and REGION-END are the region boundaries.
Returns nil if region is not active or required information is unavailable."
(when (and region-beginning region-end buffer-file-name)
(let* ((region-end-line (line-number-at-pos region-end))
(region-start-line (line-number-at-pos region-beginning))
(git-relative-path (car (ai-code--get-git-relative-paths (list buffer-file-name))))
(region-location-info (when (and git-relative-path region-start-line region-end-line)
(format "%s#L%d-L%d" git-relative-path region-start-line region-end-line))))
region-location-info)))
;;;###autoload
(defun ai-code-investigate-exception (arg)
"Generate prompt to investigate exceptions or errors in code.
With a prefix argument \[universal-argument], use context from clipboard
as the error to investigate. If a *compilation* buffer is visible in
the current window, use its full content as context. If a region is
selected, investigate that specific error or exception. If cursor is
in a function, investigate exceptions in that function. Otherwise,
investigate general exception handling in the file. Inserts the prompt
into the AI prompt file and optionally sends to AI.
Argument ARG is the prefix argument."
(interactive "P")
(let* ((clipboard-content (when arg
(condition-case nil
(current-kill 0)
(error nil))))
(compilation-buffer (get-buffer "*compilation*"))
(compilation-content (when (and compilation-buffer
(get-buffer-window compilation-buffer)
(not arg))
(with-current-buffer compilation-buffer
(buffer-substring-no-properties (point-min) (point-max)))))
(region-text (when (region-active-p)
(buffer-substring-no-properties (region-beginning) (region-end))))
(buffer-file buffer-file-name)
(full-buffer-context (when (and (not buffer-file) (not region-text))
(buffer-substring-no-properties (point-min) (point-max))))
(scope-context
(if region-text
(ai-code--scope-context-for-region
(region-beginning) (region-end))
(ai-code--current-line-scope-context)))
(function-name (plist-get scope-context :function-name))
(semantic-scope (ai-code--format-scope-context scope-context))
(files-context-string (ai-code--get-context-files-string))
(repo-context-string (ai-code--format-repo-context-info))
(diagnostic-context
(if full-buffer-context
full-buffer-context
(let ((context-blocks nil))
(when clipboard-content
(push (concat "Clipboard context (error/exception):\n" clipboard-content)
context-blocks))
(when compilation-content
(push (concat "Compilation output:\n" compilation-content)
context-blocks))
(when region-text
(push (concat "Selected code:\n" region-text)
context-blocks))
(when context-blocks
(mapconcat #'identity (nreverse context-blocks) "\n\n")))))
(default-question
(concat
"Investigate this error. Explain the likely root cause and suggest "
"candidate next steps, including how to fix it: "))
(prompt-label
(cond
(clipboard-content
"Investigate error from clipboard: ")
(compilation-content
"Investigate compilation error: ")
(full-buffer-context
"Investigate exception in current buffer: ")
(region-text
(if function-name
(format "Investigate exception in function %s: " function-name)
"Investigate selected exception: "))
(function-name
(format "Investigate exceptions in function %s: " function-name))
(t "Investigate exceptions in code: ")))
(initial-prompt (ai-code-read-string prompt-label default-question))
(scope-string
(concat
(if buffer-file
(format "Current file: %s" buffer-file)
(format "Current buffer: %s" (buffer-name)))
(unless (string-empty-p semantic-scope)
(concat "\n" semantic-scope))
files-context-string))
(context-string
(string-trim
(concat
(or diagnostic-context "")
(when (and diagnostic-context repo-context-string)
"\n\n")
repo-context-string)))
(final-prompt
(ai-code--compose-question-brief
:goal initial-prompt
:scope scope-string
:context context-string
:boundaries ai-code-discussion--exception-investigation-boundaries
:instruction ai-code-discussion--exception-investigation-note)))
(ai-code--insert-prompt final-prompt)))
;;;###autoload
(defun ai-code-explain ()
"Generate prompt to explain code at different levels.
In Magit, explain the behavior changes in selected textual hunks.
If current buffer is a Dired buffer and under cursor is a directory or
file, explain that directory or file using relative path as context
\(start with @ character). If a region is selected, explain that
specific region using function/file as context. Otherwise, prompt user
to select scope: symbol, line, function, file, repository, or code
change. Inserts the prompt into the AI prompt file and optionally
sends to AI."
(interactive)
(cond
((derived-mode-p 'magit-mode)
(ai-code-magit-prompt 'explain))
;; Handle dired buffer
((derived-mode-p 'dired-mode)
(ai-code--explain-dired))
;; Handle region selection
((region-active-p)
(ai-code--explain-region))
;; Handle regular file buffer
(t (ai-code--explain-with-scope-selection))))
(defun ai-code--explain-dired ()
"Handle explain for Dired buffer."
(let* ((file-at-point (dired-get-filename nil t))
(all-marked (dired-get-marked-files))
(has-marked-files (> (length all-marked) 1))
(context-files (if has-marked-files
all-marked
(when file-at-point
(list file-at-point))))
(git-relative-paths (when context-files
(ai-code--get-git-relative-paths context-files)))
(files-context-string (when git-relative-paths
(concat "\nFiles:\n"
(mapconcat (lambda (path) (concat "@" path))
git-relative-paths
"\n"))))
(file-type (if (and file-at-point (file-directory-p file-at-point))
"directory"
"file"))
(path-prefix (if (string-equal file-type "directory")
ai-code-discussion--explain-directory-at-path-prefix
ai-code-discussion--explain-file-at-path-prefix))
(initial-prompt (cond
(has-marked-files
(format "%s\n\nProvide a clear explanation of what these files or directories contain, their purpose, and their role in the project structure.%s"
ai-code-discussion--explain-selected-files-prefix
(or files-context-string "")))
((car git-relative-paths)
(format "%s%s.\n\nProvide a clear explanation of what this %s contains, its purpose, and its role in the project structure.%s"
path-prefix
(car git-relative-paths)
file-type
(or files-context-string "")))
(t "No file or directory found at cursor point."))))
(if git-relative-paths
(ai-code--confirm-and-send "Prompt: " initial-prompt)
(ai-code--insert-prompt initial-prompt))))
(defun ai-code--explain-region ()
"Explain the selected region with function/file context."
(let* ((region-text (buffer-substring-no-properties (region-beginning) (region-end)))
(scope-context
(ai-code--scope-context-for-region
(region-beginning) (region-end)))
(context-info (ai-code--format-scope-context scope-context))
(files-context-string (ai-code--get-context-files-string))
(initial-prompt (format "%s\n\n%s\n\n%s%s%s\n\nProvide a clear explanation of what this code does, how it works, and its purpose within the context."
ai-code-discussion--explain-code-prefix
region-text
context-info
(if (string-empty-p context-info) "" "\n")
files-context-string)))
(ai-code--confirm-and-send "Prompt: " initial-prompt)))
(defun ai-code--explain-with-scope-selection ()
"Prompt user to select explanation scope and explain accordingly."
(let* ((choices '("symbol" "line" "function" "file" "files visible"
"git repository" "code change"))
(scope (completing-read "Select scope to explain: " choices nil t)))
(pcase scope
("symbol" (ai-code--explain-symbol))
("line" (ai-code--explain-line))
("function" (ai-code--explain-function))
("file" (ai-code--explain-file))
("files visible" (ai-code--explain-files-visible))
("git repository" (ai-code--explain-git-repo))
("code change" (ai-code--explain-code-change)))))
(defun ai-code--explain-code-change-source-instruction (review-source)
"Return a PR explanation source instruction for REVIEW-SOURCE."
(if (fboundp 'ai-code--pull-or-review-source-instruction)
(ai-code--pull-or-review-source-instruction review-source 'explain-code-change)
"Inspect the pull request diff and relevant metadata to understand the change."))
(defun ai-code--ensure-explain-code-change-review-source (review-source)
"Return REVIEW-SOURCE or prompt for one when needed."
(or review-source
(progn
(require 'ai-code-git nil t)
(if (fboundp 'ai-code--pull-or-review-action-choice)
(ai-code--pull-or-review-action-choice)
(let* ((action-alist '(("Use GitHub MCP server" . github-mcp)
("Use gh CLI tool" . gh-cli)))
(choice (completing-read "Select review source: "
action-alist
nil t nil nil
"Use GitHub MCP server")))
(alist-get choice action-alist nil nil #'string=))))))
(defun ai-code--explain-code-change-insert-prompt (initial-prompt)
"Read and insert an explanation prompt starting from INITIAL-PROMPT."
(ai-code--confirm-and-send "Prompt: " initial-prompt))
(defun ai-code--format-code-change-explanation-outline (step-1 step-2 step-3)
"Return shared code-change explanation outline using STEP-1, STEP-2, and STEP-3."
(mapconcat #'identity
(list "Explanation Steps:"
(concat "1. " step-1)
(concat "2. " step-2)
(concat "3. " step-3)
ai-code-discussion--explain-code-change-focus-note)
"\n"))
(defun ai-code--explain-code-change (&optional review-source)
"Explain a code change from a PR, branch range, or commit.
When REVIEW-SOURCE is non-nil, use it for the GitHub PR flow."
(let* ((choices '(("GitHub PR" . github-pr)
("base..branch" . branch-range)
("commit" . commit)))
(selection (completing-read "Select code change source: " choices nil t))
(code-change-source (alist-get selection choices nil nil #'string=)))
(pcase code-change-source
('github-pr
(ai-code--explain-code-change-from-github-pr
(ai-code--ensure-explain-code-change-review-source review-source)))
('branch-range
(ai-code--explain-code-change-from-branch-range))
('commit
(ai-code--explain-code-change-from-commit))
(_
(user-error "Unknown code change source: %s" selection)))))
(defun ai-code--explain-code-change-from-github-pr (review-source)
"Build a prompt to explain a code change from a GitHub PR using REVIEW-SOURCE."
(let* ((pr-url (ai-code-read-string "Pull request URL: "))
(source-instruction
(ai-code--explain-code-change-source-instruction review-source))
(repo-context-string (ai-code--format-repo-context-info))
(initial-prompt
(format "%s %s
%s
%s%s"
ai-code-discussion--explain-code-change-pr-prefix
pr-url
source-instruction
(ai-code--format-code-change-explanation-outline
"Summarize the overall goal of the code change."
"Explain the main files, functions, and behavior changes in the PR."
"Highlight important design decisions, risks, and follow-up considerations.")
repo-context-string)))
(ai-code--explain-code-change-insert-prompt initial-prompt)))
(defun ai-code-explain-code-change (&optional review-source)
"Explain a code change using shared discussion helpers.
When REVIEW-SOURCE is non-nil, use it for the GitHub PR flow."
(interactive)
(ai-code--explain-code-change review-source))
(defun ai-code--explain-code-change-from-branch-range ()
"Build a prompt to explain a code change from BASE..BRANCH."
(let ((git-root (ai-code--git-root)))
(unless git-root
(user-error "Not in a git repository"))
(let* ((base-branch (ai-code-read-string "Base branch: "))
(branch-name (ai-code-read-string "Branch to explain: "))
(repo-context-string (ai-code--format-repo-context-info))
(explanation-outline
(ai-code--format-code-change-explanation-outline
"The overall purpose of this change set."
"The most important files, functions, and logic changes."
"The expected behavior impact, migration notes, and risks."))
(initial-prompt
(format "%s
Change range: %s..%s
Path: %s
In the current repository, inspect `git diff %s..%s` and explain:
%s%s"
ai-code-discussion--explain-code-change-branch-range-prefix
base-branch
branch-name
git-root
base-branch
branch-name
explanation-outline
repo-context-string)))
(ai-code--explain-code-change-insert-prompt initial-prompt))))
(defun ai-code--explain-code-change-from-commit ()
"Build a prompt to explain a code change from a specific commit."
(let ((git-root (ai-code--git-root)))
(unless git-root
(user-error "Not in a git repository"))
(let* ((commit-hash (ai-code-read-string "Commit hash: "))
(repo-context-string (ai-code--format-repo-context-info))
(explanation-outline
(ai-code--format-code-change-explanation-outline
"The problem this commit appears to address."
"The key code paths and behavior changes introduced by the commit."
"Any noteworthy implementation details, risks, or trade-offs."))
(initial-prompt
(format "%s %s
Path: %s
In the current repository, inspect `git show %s` and explain:
%s%s"
ai-code-discussion--explain-code-change-commit-prefix
commit-hash
git-root
commit-hash
explanation-outline
repo-context-string)))
(ai-code--explain-code-change-insert-prompt initial-prompt))))
(defun ai-code--explain-symbol ()
"Explain the symbol at point."
(let* ((symbol (thing-at-point 'symbol t))
(semantic-scope
(ai-code--format-scope-context
(ai-code--current-line-scope-context))))
(unless symbol
(user-error "No symbol at point"))
(let* ((initial-prompt (format "%s%s' in the context of:%s\nFile: %s\n\nExplain what this symbol represents, its type, purpose, and how it's used in this context."
ai-code-discussion--explain-symbol-prefix
symbol
(if (string-empty-p semantic-scope)
""
(concat "\n" semantic-scope))
(or buffer-file-name "current buffer"))))
(ai-code--confirm-and-send "Prompt: " initial-prompt))))
(defun ai-code--explain-line ()
"Explain the current line."
(let* ((line-text (string-trim (thing-at-point 'line t)))
(line-number (line-number-at-pos))
(semantic-scope
(ai-code--format-scope-context
(ai-code--current-line-scope-context))))
(let* ((initial-prompt (format "%s\n\nLine %d: %s\n\n%sFile: %s\n\nExplain what this line does, its purpose, and how it fits into the surrounding code."
ai-code-discussion--explain-line-prefix
line-number
line-text
(if (string-empty-p semantic-scope)
""
(concat semantic-scope "\n"))
(or buffer-file-name "current buffer"))))
(ai-code--confirm-and-send "Prompt: " initial-prompt))))
(defun ai-code--explain-function ()
"Explain the current function."
(let* ((scope-context (ai-code--current-line-scope-context))
(function-name (plist-get scope-context :function-name))
(semantic-scope (ai-code--format-scope-context scope-context)))
(unless function-name
(user-error "Not inside a function"))
(let* ((initial-prompt (format "%s%s':
%s
File: %s
Explain what this function does, its parameters, return value, algorithm, and its role in the overall codebase."
ai-code-discussion--explain-function-prefix
function-name
semantic-scope
(or buffer-file-name "current buffer"))))
(ai-code--confirm-and-send "Prompt: " initial-prompt))))
(defun ai-code--explain-file ()
"Explain the current file."
(let ((file-name (or buffer-file-name "current buffer")))
(let* ((initial-prompt (format "%s\nFile: %s\nProvide an overview of this file's purpose, its main components, key functions, and how it fits into the larger codebase architecture."
ai-code-discussion--explain-file-prefix
file-name)))
(ai-code--confirm-and-send "Prompt: " initial-prompt))))
(defun ai-code--explain-files-visible ()
"Explain all files visible in the current window."
(let ((files-context (ai-code--get-context-files-string)))
(if (string-empty-p files-context)
(user-error "No visible files with names found")
(let* ((initial-prompt (format "%s%s\n\nProvide an overview of these files, their relationships, and how they collectively contribute to the project's functionality."
ai-code-discussion--explain-files-prefix
files-context)))
(ai-code--confirm-and-send "Prompt: " initial-prompt)))))
(defun ai-code--explain-git-repo ()
"Explain the current git repository."
(let ((git-root (ai-code--git-root)))
(if (not git-root)
(user-error "Not in a git repository")
(let* ((repo-name (file-name-nondirectory (directory-file-name git-root)))
(initial-prompt (format "%s %s\nPath: %s\n\nProvide a comprehensive overview of this repository, its architecture, main technologies used, key modules, and how the different parts of the system interact."
ai-code-discussion--explain-git-repo-prefix
repo-name git-root)))
(ai-code--confirm-and-send "Prompt: " initial-prompt)))))
;;;###autoload
(defcustom ai-code-notes-file-name ".ai.code.notes.org"
"Default note file name relative to the project root.
This value is used by `ai-code-take-notes' when suggesting where to store notes."
:type 'string
:group 'ai-code)
(defconst ai-code-discussion--default-note-request
"Content of the most recent AI output"
"Default request text for `ai-code-take-notes'.")
(defun ai-code--get-note-candidates (default-note-file)
"Get a list of candidate note files.
DEFAULT-NOTE-FILE is included in the list. Visible org buffers are prioritized."
(let* ((default-note-file-truename (file-truename default-note-file))
;; Get all org-mode buffers with associated files
(org-buffers (seq-filter
(lambda (buf)
(with-current-buffer buf
(and (derived-mode-p 'org-mode)
(buffer-file-name))))
(buffer-list)))
(org-buffer-files (mapcar #'buffer-file-name org-buffers))
;; Get org buffers visible in the current frame
(visible-org-buffers (seq-filter (lambda (buf) (get-buffer-window buf 'visible))
org-buffers))
(visible-org-files (mapcar #'buffer-file-name visible-org-buffers)))
(delete-dups
(mapcar #'file-truename
(append visible-org-files
(list default-note-file-truename)
org-buffer-files)))))
(defun ai-code--append-org-note (file title content)
"Append a note with TITLE and CONTENT to FILE."
(let ((note-dir (file-name-directory file)))
(unless (file-exists-p note-dir)
(make-directory note-dir t)))
(with-current-buffer (find-file-noselect file)
(save-excursion
(goto-char (point-max))
(unless (bobp)
(insert "\n\n"))
(insert "* " title "\n")
(org-insert-time-stamp (current-time) t nil)
(insert "\n\n")
(insert content)
(insert "\n"))
(save-buffer)))
(defun ai-code--build-note-insert-prompt (file-path line-number note-request)
"Build an AI prompt to insert a note into FILE-PATH.
LINE-NUMBER and NOTE-REQUEST are included in the prompt context."
(format "Insert the note into the current Org file.\n\
Target file: %s\n\
Insert location: around line %d (current cursor position)\n\n\
Note request:\n%s\n\n\
Only update the requested insertion location. Do not change unrelated sections. Go ahead and start do the work."
file-path
line-number
note-request))
(defun ai-code--target-directory-under-org-roam-p (target-dir)
"Return non-nil when TARGET-DIR is under `org-roam-directory'.
Normalizes paths for robustness against symlinks and case sensitivity."
(and (ai-code--org-roam-ready-p)
(let ((target-expanded (expand-file-name target-dir))
(roam-expanded (expand-file-name org-roam-directory)))
(string-prefix-p (file-name-as-directory roam-expanded)
(file-name-as-directory target-expanded)))))
(defun ai-code--build-note-create-prompt (target-dir note-request)
"Build an AI prompt to create a note under TARGET-DIR.
NOTE-REQUEST is included in the prompt body."
(format "Create a new Org note file under directory: %s\n\
Automatically determine a concise filename from the note title/content you identified. \
Use lowercase letters, numbers, and underscores for the filename, with .org extension.\n\n\
Note request:\n%s\n\n\
%sDo not modify unrelated files. Go ahead and start the work."
target-dir
note-request
(if (ai-code--target-directory-under-org-roam-p target-dir)
"After creating the note file, run org-roam-db-sync so it is discoverable by org-roam commands.\n\n"
"")))
(defun ai-code--org-roam-ready-p ()
"Return non-nil when org-roam is available and configured."
(and (or (featurep 'org-roam) (require 'org-roam nil t))
(boundp 'org-roam-directory)
(stringp org-roam-directory)
(not (string-empty-p org-roam-directory))))
(defun ai-code--select-note-target-directory (default-note-directory)
"Select note target directory using DEFAULT-NOTE-DIRECTORY as fallback."
(let ((fallback-dir (file-name-as-directory default-note-directory)))
(if (and (ai-code--org-roam-ready-p)
(y-or-n-p (format "Create note under org-roam-directory (%s)? "
org-roam-directory)))
(file-name-as-directory (expand-file-name org-roam-directory))
(file-name-as-directory
(read-directory-name "Directory for new note: "
fallback-dir
fallback-dir
t)))))
(defun ai-code--insert-org-note-at-point (title content)
"Insert a note with TITLE and CONTENT at point in current Org buffer."
(let ((level (or (org-current-level) 1)))
(unless (bolp)
(insert "\n"))
(insert (make-string level ?*) " " title "\n")
(org-insert-time-stamp (current-time) t nil)
(insert "\n\n" content "\n")))
(defun ai-code--sync-org-roam-note-if-needed (note-file)
"Sync NOTE-FILE into org-roam DB when NOTE-FILE is under `org-roam-directory'."
(when (and (ai-code--org-roam-ready-p)
(file-in-directory-p (file-truename note-file)
(file-truename (expand-file-name org-roam-directory))))
(condition-case err
(progn
(when (fboundp 'org-roam-db-update-file)
(org-roam-db-update-file note-file t))
(when (fboundp 'org-roam-db-sync)
(org-roam-db-sync)))
(error
(message "Failed to sync org-roam note: %s" (error-message-string err))))))
(defun ai-code--read-note-request ()
"Prompt user for the note request and return a non-empty string."
(let ((note-request (string-trim
(or (read-string "Specification for the note? "
ai-code-discussion--default-note-request
'ai-code-note-request-history)
""))))
(when (string-empty-p note-request)
(user-error "Note request cannot be empty"))
note-request))
;;;###autoload
(defun ai-code-take-notes (&optional arg)
"Take notes by AI request and send prompt to the AI session.
When in an Org buffer with a saved file, generate a prompt to insert
note content.
Otherwise, generates a prompt to create a new note file.
With prefix ARG, open the default note file in other window instead."
(interactive "P")
(let ((files-dir (ai-code--ensure-files-directory)))
(if arg
(let ((note-file (expand-file-name ai-code-notes-file-name files-dir)))
(find-file-other-window note-file))
(let* ((default-note-dir (file-name-as-directory files-dir))
(note-request (ai-code--read-note-request)))
(if (derived-mode-p 'org-mode)
(if (not buffer-file-name)
(user-error "Org buffer must be saved to a file before taking notes")
(let* ((target-file buffer-file-name)
(line-number (line-number-at-pos))
(default-prompt (ai-code--build-note-insert-prompt
target-file
line-number
note-request)))
(when (ai-code--confirm-and-send "Prompt: " default-prompt)
(message "Generated AI prompt for note insertion in %s" target-file))))
(let* ((target-dir (ai-code--select-note-target-directory default-note-dir))
(default-prompt (ai-code--build-note-create-prompt
target-dir
note-request)))
(when (ai-code--confirm-and-send "Prompt: " default-prompt)
(when (ai-code--target-directory-under-org-roam-p target-dir)
(when (require 'org-roam nil t)
(org-roam-db-sync)))
(message "Generated AI prompt for note creation under %s" target-dir))))))))
(provide 'ai-code-discussion)
;; Load prompt harnesses after entry commands are defined.
(unless (bound-and-true-p ai-code--harness-loading)
(require 'ai-code-harness))
;;; ai-code-discussion.el ends here