-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopilot-workflows.el
More file actions
856 lines (801 loc) · 43.6 KB
/
Copy pathcopilot-workflows.el
File metadata and controls
856 lines (801 loc) · 43.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
;;; copilot-workflows.el --- Predefined agentic workflows -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Contributors
;;; Commentary:
;; Predefined multi-step agentic workflows that combine the Copilot agent
;; with Emacs capabilities. Each workflow orchestrates a sequence of
;; prompts and tool uses to accomplish a high-level task.
;;
;; Workflows include:
;; - Code review: analyze diff, review, suggest improvements
;; - Refactor: analyze code, plan refactoring, execute changes
;; - Test generation: analyze code, generate test cases
;; - Documentation: analyze code, generate documentation
;; - Explain: explain code in the current region or buffer
;;
;; Requires: copilot-sdk
;;; Code:
(require 'copilot-sdk)
(require 'cl-lib)
;;; ============================================================
;;; Org Write-Back Helpers
;;; ============================================================
(defun copilot-workflow--write-journal-entry (title body)
"Write an org-journal entry with TITLE and BODY, tagged as AI-generated.
Uses `org-journal-dir' if available, otherwise falls back to ~/org/journal/.
The entry is appended to today's daily file."
(let* ((dir (cond
((fboundp 'copilot-meta--journal-dir)
(copilot-meta--journal-dir))
((bound-and-true-p org-journal-dir)
(expand-file-name org-journal-dir))
(t (expand-file-name "~/org/journal/"))))
(file-fmt (cond
((fboundp 'copilot-meta--journal-file-format)
(copilot-meta--journal-file-format))
((bound-and-true-p org-journal-file-format)
org-journal-file-format)
(t "%Y-%m-%d.org")))
(today-file (expand-file-name
(format-time-string file-fmt)
dir)))
(unless (file-directory-p dir)
(make-directory dir t))
(when (file-writable-p (file-name-directory today-file))
(with-current-buffer (find-file-noselect today-file)
(goto-char (point-max))
(unless (bolp) (insert "\n"))
(insert (format "\n** %s %s\n:PROPERTIES:\n:AI_GENERATED: t\n:AI_TIMESTAMP: %s\n:END:\n%s\n"
(format-time-string "%H:%M")
title
(format-time-string "%Y-%m-%dT%H:%M:%S%z")
body))
(save-buffer)
(message "Journal entry written: %s" today-file)))))
(defun copilot-workflow--create-todos-from-plan (plan-text &optional target-file)
"Parse PLAN-TEXT and create org TODO entries in TARGET-FILE.
Extracts lines that look like action items (numbered lists, bullet points,
checklist items) and creates scheduled TODO headings for today.
Each TODO gets :AI_GENERATED: t and :AI_SESSION: properties."
(let* ((file (expand-file-name (or target-file "~/org/todo.org")))
(today (format-time-string "%Y-%m-%d %a"))
(session-id (format-time-string "%Y%m%d%H%M%S"))
(lines (split-string plan-text "\n"))
(created 0))
(when (file-writable-p (file-name-directory file))
(with-current-buffer (find-file-noselect file)
(goto-char (point-max))
(unless (bolp) (insert "\n"))
(dolist (line lines)
(let ((trimmed (string-trim line)))
;; Match numbered items, bullets, or checkbox lines that look like tasks
(when (and (not (string-empty-p trimmed))
(string-match
"^\\(?:[0-9]+[.):]\\|[-*•]\\|\\[[ x]\\]\\)\\s-+\\(.+\\)"
trimmed))
(let ((task-title (match-string 1 trimmed)))
;; Strip leading markdown-style formatting remnants
(setq task-title (replace-regexp-in-string
"^\\*\\*\\(.+?\\)\\*\\*" "\\1" task-title))
(setq task-title (string-trim task-title))
(unless (string-empty-p task-title)
(insert (format "* TODO [#B] %s\nSCHEDULED: <%s>\n:PROPERTIES:\n:AI_GENERATED: t\n:AI_SESSION: %s\n:CREATED: [%s]\n:END:\n"
task-title today session-id today))
(cl-incf created))))))
(when (> created 0)
(save-buffer)))
(message "Created %d TODO items in %s" created (file-name-nondirectory file))
created)))
(defun copilot-workflow--update-project-status (project status-text)
"Update PROJECT's roam node with STATUS-TEXT.
Looks for a project file in ~/org/roam/projects/<project>.org.
If found, appends a timestamped status update. If not found, creates
a minimal project node."
(let* ((project-slug (replace-regexp-in-string
"[^a-zA-Z0-9-]" "_" (downcase project)))
(project-dir (expand-file-name "~/org/roam/projects/"))
(project-file (expand-file-name
(concat project-slug ".org") project-dir)))
(unless (file-directory-p project-dir)
(make-directory project-dir t))
(when (file-writable-p project-dir)
(with-current-buffer (find-file-noselect project-file)
(when (= (buffer-size) 0)
;; New file — create minimal roam node header
(insert (format ":PROPERTIES:\n:ID: %s\n:END:\n#+title: %s\n#+filetags: :project:\n\n"
(if (fboundp 'org-id-new) (org-id-new) (format "%s-%s" project-slug (format-time-string "%Y%m%d")))
project)))
(goto-char (point-max))
(unless (bolp) (insert "\n"))
(insert (format "\n** Status Update — %s\n:PROPERTIES:\n:AI_GENERATED: t\n:AI_TIMESTAMP: %s\n:END:\n%s\n"
(format-time-string "%Y-%m-%d %H:%M")
(format-time-string "%Y-%m-%dT%H:%M:%S%z")
status-text))
(save-buffer)
(when (fboundp 'org-roam-db-update-file)
(org-roam-db-update-file project-file))
(message "Updated project status: %s" project)))))
;;; ============================================================
;;; Workflow Infrastructure
;;; ============================================================
(cl-defstruct (copilot-workflow (:constructor copilot-workflow--create))
"A multi-step agentic workflow."
(name nil :documentation "Workflow name.")
(description nil :documentation "What this workflow does.")
(steps nil :documentation "List of step plists.")
(session nil :documentation "Session used by this workflow.")
(current-step 0 :documentation "Index of the current step.")
(results nil :documentation "Accumulated results from each step."))
(defvar copilot-workflow--registry (make-hash-table :test 'equal)
"Registry of defined workflows by name.")
(defmacro copilot-defworkflow (name description &rest steps)
"Define a reusable agentic workflow.
NAME is a symbol identifying the workflow.
DESCRIPTION is a string.
STEPS are plists with :prompt and optional :context-fn.
The :prompt is a string template (use %s for context insertion).
The :context-fn is a function returning context string to insert.
Example:
(copilot-defworkflow code-review
\"Review code changes for bugs and improvements\"
(:prompt \"Here is the git diff of staged changes:\\n\\n```diff\\n%s\\n```\\n\\nReview for bugs, security issues, and improvements.\"
:context-fn (lambda () (shell-command-to-string \"git diff --staged\")))
(:prompt \"Now suggest concrete fixes for the issues you found. Be specific with file names and line numbers.\"))"
(declare (indent 2))
(let ((step-forms
(mapcar (lambda (step)
`(list ,@step))
steps)))
`(puthash ,(symbol-name name)
(list :name ,(symbol-name name)
:description ,description
:steps (list ,@step-forms))
copilot-workflow--registry)))
;;; ============================================================
;;; Workflow Execution
;;; ============================================================
(defun copilot-workflow-run (name &optional session)
"Run the workflow identified by NAME.
SESSION defaults to the current chat session or creates a new one."
(interactive
(list (completing-read "Workflow: "
(let (names)
(maphash (lambda (k _) (push k names))
copilot-workflow--registry)
names)
nil t)))
(let ((spec (gethash name copilot-workflow--registry)))
(unless spec
(user-error "Workflow not found: %s" name))
(let* ((session (or session
(copilot-sdk-create-session nil)))
(steps (plist-get spec :steps))
(results nil))
(message "Starting workflow: %s (%d steps)"
(plist-get spec :description) (length steps))
(dolist (step steps)
(let* ((prompt-template (plist-get step :prompt))
(context-fn (plist-get step :context-fn))
(context (when context-fn (funcall context-fn)))
(prompt (if context
(format prompt-template context)
prompt-template))
(result (copilot-sdk-send-and-wait session prompt 120)))
(push result results)
(message "Step complete: %s..."
(substring (or result "") 0 (min 60 (length (or result "")))))))
(nreverse results))))
;;; ============================================================
;;; Built-in Workflows
;;; ============================================================
;; -- Code Review --
(copilot-defworkflow code-review
"Review staged git changes for bugs and improvements"
(:prompt "Here is the git diff of staged changes:\n\n```diff\n%s\n```\n\nReview this diff carefully. Focus on:\n1. Bugs and logic errors\n2. Security vulnerabilities\n3. Performance issues\n4. Missing error handling\n\nBe specific with file names and line numbers."
:context-fn (lambda ()
(let ((diff (shell-command-to-string "git diff --staged")))
(if (string-empty-p (string-trim diff))
(shell-command-to-string "git diff")
diff))))
(:prompt "Now provide concrete fix suggestions for each issue. Show the exact code changes needed."))
;; -- Explain Region --
(copilot-defworkflow explain-region
"Explain the selected region or current buffer"
(:prompt "Explain this code in detail. What does it do? How does it work? Are there any subtle behaviors?\n\n```\n%s\n```"
:context-fn (lambda ()
(if (use-region-p)
(buffer-substring-no-properties (region-beginning) (region-end))
(buffer-substring-no-properties
(point-min)
(min (point-max) (+ (point-min) 10000)))))))
;; -- Generate Tests --
(copilot-defworkflow generate-tests
"Generate test cases for code in the current buffer"
(:prompt "Here is the code to test:\n\n```%s\n%s\n```\n\nFile: %s\n\nGenerate comprehensive test cases covering:\n1. Normal operation (happy path)\n2. Edge cases\n3. Error conditions\n4. Boundary values\n\nUse the appropriate testing framework for this language."
:context-fn (lambda ()
(let ((mode (symbol-name major-mode))
(content (buffer-substring-no-properties
(point-min)
(min (point-max) (+ (point-min) 10000))))
(file (or (buffer-file-name) "unknown")))
(format "%s\n%s\n%s" mode content file)))))
;; -- Generate Documentation --
(copilot-defworkflow generate-docs
"Generate documentation for code in the current buffer"
(:prompt "Here is the code to document:\n\n```\n%s\n```\n\nGenerate comprehensive documentation including:\n1. Module/function purpose\n2. Parameters and return values\n3. Usage examples\n4. Any important notes or caveats\n\nUse the documentation style appropriate for this language."
:context-fn (lambda ()
(buffer-substring-no-properties
(point-min)
(min (point-max) (+ (point-min) 10000))))))
;; -- Refactor --
(copilot-defworkflow refactor
"Analyze and refactor the current buffer"
(:prompt "Analyze this code for refactoring opportunities:\n\n```\n%s\n```\n\nIdentify:\n1. Code duplication\n2. Functions that are too long\n3. Poor naming\n4. Missing abstractions\n5. Coupling issues"
:context-fn (lambda ()
(buffer-substring-no-properties
(point-min)
(min (point-max) (+ (point-min) 10000)))))
(:prompt "Now provide the refactored code. Show the complete changed code, not just snippets."))
;; -- Debug --
(copilot-defworkflow debug
"Debug an error or unexpected behavior"
(:prompt "I'm experiencing an issue. Here's the context:\n\nFile: %s\nMode: %s\nError/Issue: %s\n\nPlease help me debug this. Analyze potential causes and suggest fixes."
:context-fn (lambda ()
(format "%s\n%s\n%s"
(or (buffer-file-name) "unknown")
(symbol-name major-mode)
(read-string "Describe the issue: ")))))
;;; ============================================================
;;; Convenience Commands
;;; ============================================================
;;;###autoload
(defun copilot-review ()
"Run the code-review workflow on staged/unstaged changes."
(interactive)
(copilot-workflow-run "code-review"))
;;;###autoload
(defun copilot-explain ()
"Explain the current region or buffer."
(interactive)
(copilot-workflow-run "explain-region"))
;;;###autoload
(defun copilot-generate-tests ()
"Generate tests for the current buffer."
(interactive)
(copilot-workflow-run "generate-tests"))
;;;###autoload
(defun copilot-generate-docs ()
"Generate documentation for the current buffer."
(interactive)
(copilot-workflow-run "generate-docs"))
;;;###autoload
(defun copilot-refactor ()
"Analyze and refactor the current buffer."
(interactive)
(copilot-workflow-run "refactor"))
;;;###autoload
(defun copilot-debug ()
"Debug an issue with agent assistance."
(interactive)
(copilot-workflow-run "debug"))
;;; ============================================================
;;; Morning Briefing & Evening Review
;;; ============================================================
(defvar copilot-briefing-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "q" #'quit-window)
(define-key map "n" #'forward-paragraph)
(define-key map "p" #'backward-paragraph)
(define-key map "g" #'copilot-morning-briefing)
map)
"Keymap for `copilot-briefing-mode'.")
(define-derived-mode copilot-briefing-mode special-mode "Briefing"
"Mode for displaying Copilot briefings."
(setq truncate-lines nil)
(setq word-wrap t)
(visual-line-mode 1))
(defun copilot-briefing--render-header (title)
"Render briefing TITLE header into current buffer."
(let ((date (format-time-string "%A, %B %d, %Y")))
(insert (propertize (format " %s — %s \n\n" title date)
'face '(:weight bold :height 1.3)))))
(defun copilot-briefing--render-section (emoji title content)
"Render a section with EMOJI, TITLE, and CONTENT."
(insert (propertize (format "%s %s\n" emoji title)
'face '(:weight bold :height 1.1)))
(insert (make-string 40 ?─) "\n")
(insert (or content "(not available)") "\n\n"))
(defun copilot-briefing--gather-data ()
"Gather all briefing data from Emacs subsystems.
Returns an alist of section data."
(let ((sections '()))
;; Agenda
(condition-case nil
(when (fboundp 'copilot-sdk-tool--org-agenda-today)
(push (cons 'agenda (funcall 'copilot-sdk-tool--org-agenda-today nil))
sections))
(error nil))
;; Habits
(condition-case nil
(when (fboundp 'copilot-sdk-tool--habits-due-today)
(push (cons 'habits (funcall 'copilot-sdk-tool--habits-due-today nil))
sections))
(error nil))
;; Elfeed
(condition-case nil
(when (fboundp 'copilot-sdk-tool--elfeed-unread)
(push (cons 'feeds (funcall 'copilot-sdk-tool--elfeed-unread
'((days . 1))))
sections))
(error nil))
;; Journal (yesterday)
(condition-case nil
(when (fboundp 'copilot-sdk-tool--journal-today)
(push (cons 'journal (funcall 'copilot-sdk-tool--journal-today nil))
sections))
(error nil))
;; .plan
(condition-case nil
(when (fboundp 'copilot-sdk--read-plan-file)
(let ((plan (copilot-sdk--read-plan-file)))
(when plan
(push (cons 'plan plan) sections))))
(error nil))
(nreverse sections)))
;;;###autoload
(defun copilot-morning-briefing ()
"Generate a morning briefing composing all Life OS subsystems.
Creates a dedicated *Copilot Briefing* buffer and streams the
agent's analysis into it."
(interactive)
(let* ((buf (get-buffer-create "*Copilot Briefing*"))
(data (copilot-briefing--gather-data))
;; Build a structured prompt for the agent
(prompt (concat
"You are generating a morning briefing. Here is data from "
"the user's Emacs subsystems. Synthesize this into a concise, "
"actionable briefing. Suggest 3-5 priorities for today.\n\n"
(when (alist-get 'agenda data)
(format "<agenda>\n%s\n</agenda>\n\n"
(alist-get 'agenda data)))
(when (alist-get 'habits data)
(format "<habits>\n%s\n</habits>\n\n"
(alist-get 'habits data)))
(when (alist-get 'feeds data)
(format "<feeds>\n%s\n</feeds>\n\n"
(alist-get 'feeds data)))
(when (alist-get 'journal data)
(format "<journal_today>\n%s\n</journal_today>\n\n"
(alist-get 'journal data)))
(when (alist-get 'plan data)
(format "<plan>\n%s\n</plan>\n\n"
(alist-get 'plan data)))
"Format the briefing with clear sections using emoji headers. "
"Be concise but insightful. End with suggested priorities.")))
;; Set up the briefing buffer
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(copilot-briefing--render-header "🌅 Morning Briefing")
(insert (propertize "Gathering data and generating briefing...\n\n"
'face 'font-lock-comment-face))
;; Show raw data sections while agent thinks
(dolist (section data)
(pcase (car section)
('agenda (copilot-briefing--render-section "📋" "Today's Agenda" (cdr section)))
('habits (copilot-briefing--render-section "🔄" "Habits" (cdr section)))
('feeds (copilot-briefing--render-section "📰" "RSS Feeds" (cdr section)))
('journal (copilot-briefing--render-section "📝" "Journal" (cdr section)))
('plan (copilot-briefing--render-section "🎯" ".plan" (cdr section)))))
(insert (make-string 40 ?═) "\n")
(insert (propertize "🤖 AI Analysis\n" 'face '(:weight bold :height 1.1)))
(insert (make-string 40 ?─) "\n\n"))
(copilot-briefing-mode))
;; Display the buffer
(switch-to-buffer buf)
;; Now send to agent for synthesis
(let* ((session (copilot-sdk-create-session nil))
(output-start (with-current-buffer buf
(goto-char (point-max))
(point-marker)))
(output-marker (copy-marker (marker-position output-start))))
(copilot-sdk-send session prompt
:on-text (lambda (text)
(when (buffer-live-p buf)
(with-current-buffer buf
(let ((inhibit-read-only t))
(goto-char (marker-position output-marker))
(insert text)
(set-marker output-marker (point))))))
:on-turn-end (lambda (_reason)
(when (buffer-live-p buf)
(with-current-buffer buf
(let* ((inhibit-read-only t)
(briefing-output
(buffer-substring-no-properties
(marker-position output-start)
(marker-position output-marker))))
;; Write morning briefing to journal
(condition-case err
(progn
(copilot-workflow--write-journal-entry
"Morning Briefing"
briefing-output)
(goto-char (marker-position output-marker))
(insert "\n\n"
(propertize
"📓 Briefing saved to journal"
'face 'font-lock-comment-face)
"\n"))
(error
(message "Workflow: failed to write journal: %s"
(error-message-string err))))
;; Update project roam nodes if plan data mentions projects
(condition-case err
(when (alist-get 'plan data)
(copilot-workflow--update-project-status
"daily-briefing"
(format "Morning briefing — %s\n\n%s"
(format-time-string "%Y-%m-%d")
(substring briefing-output
0 (min 500 (length briefing-output))))))
(error
(message "Workflow: failed to update project status: %s"
(error-message-string err))))
(goto-char (point-max))
(insert (propertize
(format-time-string
"Generated at %H:%M")
'face 'font-lock-comment-face)
"\n")))))))))
;;;###autoload
(defun copilot-evening-review ()
"Generate an evening review for reflection and journaling.
Gathers today's accomplishments and prompts for reflection."
(interactive)
(let* ((buf (get-buffer-create "*Copilot Briefing*"))
(data (copilot-briefing--gather-data))
(prompt (concat
"You are generating an evening review for reflection. "
"Here is data from today. Help the user reflect on their day, "
"celebrate wins, identify what to carry forward, and suggest "
"a journal prompt.\n\n"
(when (alist-get 'agenda data)
(format "<todays_agenda>\n%s\n</todays_agenda>\n\n"
(alist-get 'agenda data)))
(when (alist-get 'habits data)
(format "<habits_status>\n%s\n</habits_status>\n\n"
(alist-get 'habits data)))
(when (alist-get 'journal data)
(format "<todays_journal>\n%s\n</todays_journal>\n\n"
(alist-get 'journal data)))
(when (alist-get 'plan data)
(format "<plan>\n%s\n</plan>\n\n"
(alist-get 'plan data)))
"Format as: 1) Today's wins 2) What to carry forward "
"3) Reflection prompt for journaling. Be warm and encouraging.")))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(copilot-briefing--render-header "🌙 Evening Review")
(insert (propertize "Reflecting on your day...\n\n"
'face 'font-lock-comment-face)))
(copilot-briefing-mode))
(switch-to-buffer buf)
(let* ((session (copilot-sdk-create-session nil))
(output-start (with-current-buffer buf
(goto-char (point-max))
(point-marker)))
(output-marker (copy-marker (marker-position output-start))))
(copilot-sdk-send session prompt
:on-text (lambda (text)
(when (buffer-live-p buf)
(with-current-buffer buf
(let ((inhibit-read-only t))
(goto-char (marker-position output-marker))
(insert text)
(set-marker output-marker (point))))))
:on-turn-end (lambda (_reason)
(when (buffer-live-p buf)
(with-current-buffer buf
(let* ((inhibit-read-only t)
(review-output
(buffer-substring-no-properties
(marker-position output-start)
(marker-position output-marker))))
;; Write evening review to journal
(condition-case err
(progn
(copilot-workflow--write-journal-entry
"Evening Review"
review-output)
(goto-char (marker-position output-marker))
(insert "\n\n"
(propertize
"📓 Evening review saved to journal"
'face 'font-lock-comment-face)
"\n"))
(error
(message "Workflow: failed to write journal: %s"
(error-message-string err))))
(goto-char (point-max))
(insert (propertize
(format-time-string
"Generated at %H:%M")
'face 'font-lock-comment-face)
"\n")))))))))
;;; ============================================================
;;; Quick Life OS Commands (no chat needed)
;;; ============================================================
;;;###autoload
(defun copilot-habit-log ()
"Quickly log a habit completion via completing-read."
(interactive)
(require 'org-habit nil t)
(let ((habits '()))
(dolist (file (org-agenda-files))
(when (file-readable-p file)
(with-current-buffer (find-file-noselect file)
(org-map-entries
(lambda ()
(when (org-is-habit-p)
(push (org-get-heading t t t t) habits)))
"STYLE=\"habit\"" 'file))))
(if (null habits)
(message "No habits found in agenda files")
(let ((choice (completing-read "Log habit: " (nreverse habits) nil t)))
(when (fboundp 'copilot-sdk-tool--habit-log)
(message "%s"
(funcall 'copilot-sdk-tool--habit-log
`((name . ,choice)))))))))
;;;###autoload
(defun copilot-journal-quick ()
"Quickly append a note to today's journal via minibuffer."
(interactive)
(let ((text (read-string "Journal: ")))
(unless (string-empty-p (string-trim text))
(if (fboundp 'copilot-sdk-tool--journal-write)
(message "%s"
(funcall 'copilot-sdk-tool--journal-write
`((text . ,text))))
(message "org-journal not available")))))
;;; ============================================================
;;; Compound Workflows — Plan My Day
;;; ============================================================
(defun copilot-plan-day--gather-extended-data ()
"Gather briefing data plus additional context for day planning.
Returns an alist like `copilot-briefing--gather-data' but may
include extra sections."
(let ((data (copilot-briefing--gather-data)))
;; Add org-roam dailies context if available
(condition-case nil
(when (fboundp 'copilot-sdk-tool--journal-search)
(let ((recent (funcall 'copilot-sdk-tool--journal-search
'((term . "TODO\\|NEXT\\|WAITING")
(days . 3)))))
(when (and recent (not (string-prefix-p "No matches" recent)))
(push (cons 'recent-tasks recent) data))))
(error nil))
data))
;;;###autoload
(defun copilot-plan-day ()
"Generate an interactive day plan from all Life OS subsystems.
Gathers agenda, habits, feeds, journal, and recent tasks, then
asks the agent to synthesize priorities and create a day plan.
Offers to write the plan to today's journal and update ~/.plan."
(interactive)
(let* ((buf (get-buffer-create "*Copilot Day Plan*"))
(data (copilot-plan-day--gather-extended-data))
(prompt (concat
"You are helping the user plan their day. Here is data from "
"all of their Emacs Life OS subsystems. Your job:\n\n"
"1. Summarize what's on their plate today\n"
"2. Suggest 3-5 focused priorities (ordered by importance)\n"
"3. Identify any conflicts or overcommitments\n"
"4. Suggest time blocks if possible\n"
"5. End with an encouraging, concise focus statement\n\n"
"After presenting the plan, use the `journal-write' tool to "
"append a '** Day Plan' section to today's journal with the "
"priorities as a checklist. Then use `plan-write' to update "
"the user's ~/.plan file with today's focus.\n\n"
(when (alist-get 'agenda data)
(format "<agenda>\n%s\n</agenda>\n\n"
(alist-get 'agenda data)))
(when (alist-get 'habits data)
(format "<habits>\n%s\n</habits>\n\n"
(alist-get 'habits data)))
(when (alist-get 'feeds data)
(format "<feeds_summary>\n%s\n</feeds_summary>\n\n"
(alist-get 'feeds data)))
(when (alist-get 'journal data)
(format "<todays_journal>\n%s\n</todays_journal>\n\n"
(alist-get 'journal data)))
(when (alist-get 'recent-tasks data)
(format "<recent_tasks_3d>\n%s\n</recent_tasks_3d>\n\n"
(alist-get 'recent-tasks data)))
(when (alist-get 'plan data)
(format "<current_plan>\n%s\n</current_plan>\n\n"
(alist-get 'plan data)))
"Format the day plan with clear sections and emoji. "
"Be concise and actionable. Use tools to persist the plan.")))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(copilot-briefing--render-header "📅 Plan My Day")
(insert (propertize "Analyzing your day and building a plan...\n\n"
'face 'font-lock-comment-face))
(dolist (section data)
(pcase (car section)
('agenda (copilot-briefing--render-section "📋" "Agenda" (cdr section)))
('habits (copilot-briefing--render-section "🔄" "Habits" (cdr section)))
('feeds (copilot-briefing--render-section "📰" "Feeds" (cdr section)))
('journal (copilot-briefing--render-section "📝" "Journal" (cdr section)))
('recent-tasks (copilot-briefing--render-section "🔍" "Recent Tasks" (cdr section)))
('plan (copilot-briefing--render-section "🎯" ".plan" (cdr section)))))
(insert (make-string 40 ?═) "\n")
(insert (propertize "🤖 AI Day Plan\n" 'face '(:weight bold :height 1.1)))
(insert (make-string 40 ?─) "\n\n"))
(copilot-briefing-mode))
(switch-to-buffer buf)
(let* ((session (copilot-sdk-create-session nil))
(output-start (with-current-buffer buf
(goto-char (point-max))
(point-marker)))
(output-marker (copy-marker (marker-position output-start))))
(copilot-sdk-send session prompt
:on-text (lambda (text)
(when (buffer-live-p buf)
(with-current-buffer buf
(let ((inhibit-read-only t))
(goto-char (marker-position output-marker))
(insert text)
(set-marker output-marker (point))))))
:on-turn-end (lambda (_reason)
(when (buffer-live-p buf)
(with-current-buffer buf
(let* ((inhibit-read-only t)
(plan-output
(buffer-substring-no-properties
(marker-position output-start)
(marker-position output-marker))))
;; Create TODOs from the plan
(condition-case err
(let ((count (copilot-workflow--create-todos-from-plan
plan-output)))
(goto-char (marker-position output-marker))
(insert "\n\n"
(propertize
(format "📝 Created %s TODO items in todo.org"
(or count 0))
'face 'font-lock-comment-face)
"\n"))
(error
(message "Workflow: failed to create TODOs: %s"
(error-message-string err))))
;; Write plan summary to journal
(condition-case err
(copilot-workflow--write-journal-entry
"Day Plan"
plan-output)
(error
(message "Workflow: failed to write journal: %s"
(error-message-string err))))
(goto-char (point-max))
(insert (propertize
(format-time-string
"Plan generated at %H:%M")
'face 'font-lock-comment-face)
"\n")))))))))
;;; ============================================================
;;; Compound Workflows — Research & Capture
;;; ============================================================
;;;###autoload
(defun copilot-research (topic)
"Research TOPIC across all knowledge sources and capture to org-roam.
Searches the codebase, org-roam notes, elfeed articles, and project
files, then asks the agent to synthesize findings and optionally
create an org-roam node."
(interactive "sResearch topic: ")
(let* ((buf (get-buffer-create (format "*Copilot Research: %s*" topic)))
(sources '())
;; Gather from available sources
(_ (condition-case nil
(when (fboundp 'copilot-sdk-tool--org-roam-search)
(let ((roam (funcall 'copilot-sdk-tool--org-roam-search
`((query . ,topic)))))
(when (and roam (not (string-prefix-p "No " roam))
(not (string-prefix-p "org-roam" roam)))
(push (cons 'roam roam) sources))))
(error nil)))
(_ (condition-case nil
(when (fboundp 'copilot-sdk-tool--elfeed-search)
(let ((feeds (funcall 'copilot-sdk-tool--elfeed-search
`((query . ,topic) (limit . 10)))))
(when (and feeds (not (string-prefix-p "No " feeds))
(not (string= "[]" feeds)))
(push (cons 'feeds feeds) sources))))
(error nil)))
(_ (condition-case nil
(when (fboundp 'copilot-sdk-tool--emacs-find-in-files)
(let ((code (funcall 'copilot-sdk-tool--emacs-find-in-files
`((pattern . ,topic)))))
(when (and code (not (string= "[]" code)))
(push (cons 'code code) sources))))
(error nil)))
(_ (condition-case nil
(when (fboundp 'copilot-sdk-tool--journal-search)
(let ((journal (funcall 'copilot-sdk-tool--journal-search
`((term . ,topic) (days . 90)))))
(when (and journal (not (string-prefix-p "No " journal)))
(push (cons 'journal journal) sources))))
(error nil)))
(prompt (concat
(format "Research the topic: \"%s\"\n\n" topic)
"I've gathered data from the user's knowledge sources below. "
"Your job:\n\n"
"1. Synthesize all findings into a coherent summary\n"
"2. Highlight key insights and patterns\n"
"3. Identify gaps in knowledge\n"
"4. If there are org-roam notes, reference them\n"
"5. Offer to create a new org-roam node capturing the research "
"(use `org-roam-create' tool with title and content)\n\n"
(if (null sources)
"No existing data found in local sources. Provide a general "
"overview based on your knowledge and offer to create an "
"org-roam node to start building local knowledge.\n\n"
(concat
(when (alist-get 'roam sources)
(format "<org_roam_notes>\n%s\n</org_roam_notes>\n\n"
(alist-get 'roam sources)))
(when (alist-get 'feeds sources)
(format "<elfeed_articles>\n%s\n</elfeed_articles>\n\n"
(alist-get 'feeds sources)))
(when (alist-get 'code sources)
(format "<codebase_matches>\n%s\n</codebase_matches>\n\n"
(alist-get 'code sources)))
(when (alist-get 'journal sources)
(format "<journal_references>\n%s\n</journal_references>\n\n"
(alist-get 'journal sources)))))
"Format with clear sections. Be thorough but focused.")))
(with-current-buffer buf
(let ((inhibit-read-only t))
(erase-buffer)
(copilot-briefing--render-header (format "🔬 Research: %s" topic))
(insert (propertize
(format "Searching %d sources...\n\n" (length sources))
'face 'font-lock-comment-face))
(dolist (src sources)
(pcase (car src)
('roam (copilot-briefing--render-section "🧠" "Org-Roam Notes" (cdr src)))
('feeds (copilot-briefing--render-section "📰" "RSS Articles" (cdr src)))
('code (copilot-briefing--render-section "💻" "Codebase" (cdr src)))
('journal (copilot-briefing--render-section "📝" "Journal" (cdr src)))))
(insert (make-string 40 ?═) "\n")
(insert (propertize "🤖 AI Synthesis\n" 'face '(:weight bold :height 1.1)))
(insert (make-string 40 ?─) "\n\n"))
(copilot-briefing-mode))
(switch-to-buffer buf)
(let* ((session (copilot-sdk-create-session nil))
(output-marker (with-current-buffer buf
(goto-char (point-max))
(point-marker))))
(copilot-sdk-send session prompt
:on-text (lambda (text)
(when (buffer-live-p buf)
(with-current-buffer buf
(let ((inhibit-read-only t))
(goto-char (marker-position output-marker))
(insert text)
(set-marker output-marker (point))))))
:on-turn-end (lambda (_reason)
(when (buffer-live-p buf)
(with-current-buffer buf
(let ((inhibit-read-only t))
(goto-char (marker-position output-marker))
(insert "\n\n"
(propertize
(format-time-string
"Research completed at %H:%M")
'face 'font-lock-comment-face)
"\n")))))))))
(provide 'copilot-workflows)
;;; copilot-workflows.el ends here