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
|
# File 'lib/hiiro/queue.rb', line 437
def self.build_hiiro(parent_hiiro, q=nil, task_info: nil)
q ||= current(parent_hiiro)
parent_hiiro.make_child do |h|
h.add_subcmd(:watch) {
q.queue_dirs
current_version = hiiro_version
puts "Watching #{File.join(DIR, 'pending')} (v#{current_version}) ..."
puts "Press Ctrl-C to stop"
loops = 0
loop do
loops += 1
if current_version
latest = hiiro_version rescue nil
if latest && latest != current_version
puts "New hiiro version detected (#{latest}), restarting..."
exec('h', 'queue', 'watch')
end
end
q.tasks_in(:pending).each { |name| q.launch_task(name) }
sleep 2
end
}
h.add_subcmd(:run) { |name = nil|
if name
name = name.sub(/\.md$/, '')
found = q.find_task(name)
if found.nil?
puts "Task not found: #{name}"
next
end
if found[:status] != 'pending'
puts "Task '#{name}' is #{found[:status]}, not pending"
next
end
q.launch_task(name)
else
pending = q.tasks_in(:pending)
if pending.empty?
puts "No pending tasks"
next
end
pending.each { |n| q.launch_task(n) }
end
}
h.add_subcmd(:ls, :list) { |*args|
opts = Hiiro::Options.parse(args) do
flag(:all, short: :a, desc: 'Show all tasks without limit; use pager if output exceeds terminal height')
option(:status, short: :s, desc: "Filter by status (#{Queue::STATUSES.join(', ')}); repeat for multiple", multi: true)
end
statuses = Array(opts.status)
opts.args.each do |arg|
matched = Queue::STATUSES.select { |s| s.start_with?(arg) }
if matched.empty?
puts "Unknown status: '#{arg}' (valid: #{Queue::STATUSES.join(', ')})"
next
end
statuses.concat(matched)
end
lines = q.list_lines(all: opts.all, statuses: statuses.uniq)
if lines.empty?
puts "No tasks"
next
end
if opts.all
terminal_lines = ENV['LINES']&.to_i || 24
if lines.size > terminal_lines
IO.popen(ENV['PAGER'] || 'less', 'w') { |io| io.puts lines }
else
puts lines
end
else
puts lines
end
}
h.add_subcmd(:status) {
tasks = q.all_tasks
if tasks.empty?
puts "No tasks"
next
end
tasks.each do |t|
meta = q.meta_for(t[:name], t[:status].to_sym)
line = "%-10s %s" % [t[:status], t[:name]]
if meta
started = meta['started_at']
if started && t[:status] == 'running'
elapsed = Time.now - Time.parse(started)
mins = (elapsed / 60).to_i
line += " (#{mins}m elapsed)"
end
if meta['tmux_pane']
line += " [pane #{meta['tmux_pane']}]"
elsif meta['tmux_session']
line += " [#{meta['tmux_session']}:#{meta['tmux_window']}]"
end
line += " dir:#{meta['working_dir']}" if meta['working_dir']
end
puts line
end
}
h.add_subcmd(:attach) { |name = nil|
running = q.tasks_in(:running)
if running.empty?
puts "No running tasks"
next
end
if name.nil?
name = h.fuzzyfind(running)
else
result = Matcher.by_prefix(running, name)
if result.one?
name = result.first.item
elsif result.ambiguous?
puts "Ambiguous match for '#{name}':"
result.matches.each { |m| puts " #{m.item}" }
next
else
puts "No running task matching: #{name}"
next
end
end
next unless name
meta = q.meta_for(name, :running)
session = meta&.[]('tmux_session') || TMUX_SESSION
win = meta&.[]('tmux_window') || name
system('tmux', 'switch-client', '-t', "#{session}:#{win}")
}
h.add_subcmd(:session) {
work_dir = File.expand_path('~/work')
Tmux.open_session(TMUX_SESSION, start_directory: work_dir)
}
do_add = lambda do |args, split: nil, session: false|
q.queue_dirs
opts = Hiiro::Options.parse(args) do
option(:task, short: :t, desc: 'Task name', flag_ifs: [:find])
option(:name, short: :n, desc: 'Base filename for the queue task')
flag(:find, short: :f, desc: 'Choose task/session interactively (fuzzyfind)')
flag(:horizontal, short: :h, desc: 'Split horizontally in the current tmux window')
flag(:vertical, short: :v, desc: 'Split vertically in the current tmux window')
flag(:session, short: :s, desc: 'Use current tmux session')
flag(:ignore, short: :i, desc: 'Background task — close window when done, no shell')
end
if opts.help?
puts opts.help_text
exit 1
end
split ||= :hsplit if opts.horizontal
split ||= :vsplit if opts.vertical
args = opts.args
ti = q.resolve_task_info(opts, h, task_info)
if ti.nil? && !opts.find && opts.task.nil?
env = Environment.current rescue nil
auto_task = env&.task
ti = q.task_info_for(auto_task.name) if auto_task
end
if opts.session || session
session_name = h.tmux_client.current_session&.name
ti = (ti || {}).merge(session_name: session_name) if session_name
end
if split && args.empty? && $stdin.tty?
fm_lines = ["---"]
fm_lines << "task_name: #{ti[:task_name]}" if ti&.dig(:task_name)
fm_lines << "tree_name: #{ti[:tree_name]}" if ti&.dig(:tree_name)
fm_lines << "session_name: #{ti[:session_name]}" if ti&.dig(:session_name)
fm_lines << "ignore: true" if opts.ignore
fm_lines << "# app: <partial-app-name> (run claude from this app's directory)"
fm_lines << "# dir: <relative-path> (subdir within app or tree root)"
fm_lines << "---"
fm_lines << ""
tmp_dir = File.join(Dir.home, '.config/hiiro/tmp')
FileUtils.mkdir_p(tmp_dir)
base = File.join(tmp_dir, "hq-#{Time.now.strftime('%Y%m%d%H%M%S%L')}")
prompt_path = "#{base}.md"
script_path = "#{base}.sh"
File.write(prompt_path, fm_lines.join("\n"))
task_base_dir = nil
if ti
if ti[:tree_name]
env = Environment.current rescue nil
if env
tree = env.find_tree(ti[:tree_name])
task_base_dir = tree&.path || File.join(Hiiro::WORK_DIR, ti[:tree_name])
task_base_dir = nil unless task_base_dir && Dir.exist?(task_base_dir)
end
elsif ti[:session_name]
pane_path = `tmux display-message -t #{Shellwords.shellescape(ti[:session_name])}: -p '\#{pane_current_path}' 2>/dev/null`.strip
task_base_dir = pane_path unless pane_path.empty? || !Dir.exist?(pane_path)
end
end
Dir.chdir(task_base_dir) if task_base_dir
orig_pane = `tmux display-message -p '\#{pane_id}'`.strip
split_flag = split == :hsplit ? '-v' : '-h'
claude_cmd = opts.ignore ? 'claude -p' : 'claude'
shell_line = opts.ignore ? '' : "exec ${SHELL:-zsh}"
File.write(script_path, <<~SH)
#!/usr/bin/env bash
_PROMPT=#{Shellwords.shellescape(prompt_path)}
_BASE_DIR="$(pwd)"
${EDITOR:-vim} "$_PROMPT"
tmux select-pane -t #{Shellwords.shellescape(orig_pane)}
if [ -s "$_PROMPT" ]; then
_WD="$(h queue pane-dir "$_PROMPT" "$_BASE_DIR" 2>/dev/null)"
[ -n "$_WD" ] && [ -d "$_WD" ] && cd "$_WD"
cat "$_PROMPT" | #{claude_cmd}
fi
rm -f #{Shellwords.shellescape(prompt_path)} #{Shellwords.shellescape(script_path)}
#{shell_line}
SH
FileUtils.chmod(0755, script_path)
new_pane = `tmux split-window #{split_flag} -P -F '\#{pane_id}' #{Shellwords.shellescape(script_path)} 2>/dev/null`.strip
system('tmux', 'select-pane', '-t', new_pane) unless new_pane.empty?
next
end
if args.empty? && !$stdin.tty?
content = $stdin.read.strip
elsif args.any?
content = args.join(' ')
else
fm_lines = ["---"]
fm_lines << "task_name: #{ti[:task_name]}" if ti&.dig(:task_name)
fm_lines << "tree_name: #{ti[:tree_name]}" if ti&.dig(:tree_name)
fm_lines << "session_name: #{ti[:session_name]}" if ti&.dig(:session_name)
fm_lines << "ignore: true" if opts.ignore
fm_lines << "# app: <partial-app-name> (run claude from this app's directory)"
fm_lines << "# dir: <relative-path> (subdir within app or tree root)"
fm_lines << "---"
fm_lines << ""
fm_content = fm_lines.join("\n")
if ti&.dig(:session_name) && !ti[:tree_name]
pane_path = `tmux display-message -t #{Shellwords.shellescape(ti[:session_name])}: -p '\#{pane_current_path}' 2>/dev/null`.strip
Dir.chdir(pane_path) if !pane_path.empty? && Dir.exist?(pane_path)
end
input = InputFile.md_file(hiiro: h, content: fm_content, append: !!fm_content, prefix: 'hq-')
input.edit
content = input.contents
input.cleanup
if content.empty?
puts "Aborted (empty file)"
next
end
end
result = q.add_with_frontmatter(content, task_info: ti, ignore: opts.ignore, name: opts.name)
unless result
puts "Could not generate a task name"
next
end
if split
q.launch_in_pane(result[:name], split: split)
elsif session
q.launch_task(result[:name])
else
puts "Created: #{result[:path]}"
end
end
h.add_subcmd(:add) { |*args| do_add.call(args) }
h.add_subcmd(:cadd) { |*args| do_add.call(args, split: :current) }
h.add_subcmd(:hadd) { |*args| do_add.call(args, split: :hsplit) }
h.add_subcmd(:vadd) { |*args| do_add.call(args, split: :vsplit) }
h.add_subcmd(:wip) { |*args|
q.queue_dirs
opts = Hiiro::Options.parse(args) do
option(:task, short: :t, desc: 'Task name', flag_ifs: [:find])
flag(:find, short: :f, desc: 'Choose task/session interactively (fuzzyfind)')
flag(:session, short: :s, desc: 'Use current tmux session')
end
args = opts.args
ti = q.resolve_task_info(opts, h, task_info)
if ti.nil? && !opts.find && opts.task.nil?
env = Environment.current rescue nil
auto_task = env&.task
ti = q.task_info_for(auto_task.name) if auto_task
end
if opts.session
session_name = h.tmux_client.current_session&.name
ti = (ti || {}).merge(session_name: session_name) if session_name
end
name = args.first
if name.nil?
existing = q.tasks_in(:wip)
if existing.any?
name = h.fuzzyfind(existing)
next unless name
else
puts "No wip tasks. Provide a name to create one."
next
end
end
name = name.sub(/\.md$/, '')
path = File.join(q.queue_dirs[:wip], "#{name}.md")
unless File.exist?(path)
fm_lines = ["---"]
fm_lines << "task_name: #{ti[:task_name]}" if ti&.dig(:task_name)
fm_lines << "tree_name: #{ti[:tree_name]}" if ti&.dig(:tree_name)
fm_lines << "session_name: #{ti[:session_name]}" if ti&.dig(:session_name)
fm_lines << "# app: <partial-app-name> (run claude from this app's directory)"
fm_lines << "# dir: <relative-path> (subdir within app or tree root)"
fm_lines << "---"
fm_lines << ""
File.write(path, fm_lines.join("\n"))
end
h.edit_files(path)
}
h.add_subcmd(:ready) { |name = nil|
wip = q.tasks_in(:wip)
if wip.empty?
puts "No wip tasks"
next
end
if name.nil?
name = wip.size == 1 ? wip.first : h.fuzzyfind(wip)
end
next unless name
name = name.sub(/\.md$/, '')
src = File.join(q.queue_dirs[:wip], "#{name}.md")
unless File.exist?(src)
puts "Wip task not found: #{name}"
next
end
dst, dest_name = Hiiro::Paths.unique_path(q.queue_dirs[:pending], name)
if dest_name != name
FileUtils.mv(src, File.join(q.queue_dirs[:wip], "#{dest_name}.md"))
src = File.join(q.queue_dirs[:wip], "#{dest_name}.md")
end
FileUtils.mv(src, dst)
puts "Moved to pending: #{dest_name}"
}
h.add_subcmd(:kill) { |name = nil|
running = q.tasks_in(:running)
if running.empty?
puts "No running tasks"
next
end
if name.nil?
name = running.size == 1 ? running.first : h.fuzzyfind(running)
end
next unless name
meta = q.meta_for(name, :running)
if meta&.key?('tmux_pane')
system('tmux', 'kill-pane', '-t', meta['tmux_pane'])
else
session = meta&.[]('tmux_session') || TMUX_SESSION
win = meta&.[]('tmux_window') || name
system('tmux', 'kill-window', '-t', "#{session}:#{win}")
end
dirs = q.queue_dirs
md = File.join(dirs[:running], "#{name}.md")
meta_path = File.join(dirs[:running], "#{name}.meta")
FileUtils.mv(md, File.join(dirs[:failed], "#{name}.md")) if File.exist?(md)
FileUtils.mv(meta_path, File.join(dirs[:failed], "#{name}.meta")) if File.exist?(meta_path)
puts "Killed: #{name}"
}
h.add_subcmd(:retry) { |name = nil|
retryable = q.tasks_in(:failed) + q.tasks_in(:done)
if retryable.empty?
puts "No failed/done tasks to retry"
next
end
if name.nil?
name = retryable.size == 1 ? retryable.first : h.fuzzyfind(retryable)
end
next unless name
found = q.find_task(name)
unless found && %w[failed done].include?(found[:status])
puts "Task '#{name}' is not in failed/done state"
next
end
dirs = q.queue_dirs
src_dir = dirs[found[:status].to_sym]
dst, dest_name = Hiiro::Paths.unique_path(dirs[:pending], name)
FileUtils.mv(File.join(src_dir, "#{name}.md"), dst)
meta_path = File.join(src_dir, "#{name}.meta")
FileUtils.rm_f(meta_path) if File.exist?(meta_path)
puts "Moved to pending: #{dest_name}"
}
h.add_subcmd(:clean) {
dirs = q.queue_dirs
count = 0
%i[done failed].each do |status|
Dir.glob(File.join(dirs[status], '*')).each do |f|
FileUtils.rm_f(f)
count += 1
end
end
puts "Cleaned #{count} files"
}
h.add_subcmd(:sadd) { |*args|
do_add.call(args, session: true)
}
h.add_subcmd(:tadd) { |*args|
exec('h', 'task', 'queue', 'add', *args)
}
h.add_subcmd(:dir) {
q.queue_dirs
puts DIR
}
h.add_subcmd(:'pane-dir') { |prompt_path = nil, base_dir = Dir.pwd|
print q.resolve_pane_dir(prompt_path.to_s, base_dir.to_s)
}
h.add_subcmd(:migrate) {
old_dir = File.join(Dir.home, '.config/hiiro/queue')
new_dir = DIR
unless Dir.exist?(old_dir)
puts "Nothing to migrate: #{old_dir} does not exist"
next
end
if old_dir == new_dir
puts "Source and destination are the same: #{old_dir}"
next
end
if Dir.exist?(new_dir) && Dir.glob(File.join(new_dir, '**', '*')).any?
puts "Destination already has files: #{new_dir}"
puts "Remove it manually if you want to migrate from #{old_dir}"
next
end
FileUtils.mkdir_p(File.dirname(new_dir))
FileUtils.mv(old_dir, new_dir)
puts "Migrated: #{old_dir} -> #{new_dir}"
}
end
end
|