Class: Hiiro::Queue

Inherits:
Object
  • Object
show all
Defined in:
lib/hiiro/queue.rb

Defined Under Namespace

Classes: Prompt

Constant Summary collapse

DIR =
Hiiro::Config.data_path('queue')
TMUX_SESSION =
'hq'
STATUSES =
%w[wip pending running done failed].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hiiro = nil) ⇒ Queue

Returns a new instance of Queue.



18
19
20
# File 'lib/hiiro/queue.rb', line 18

def initialize(hiiro=nil)
  @hiiro = hiiro
end

Instance Attribute Details

#hiiroObject (readonly)

Returns the value of attribute hiiro.



16
17
18
# File 'lib/hiiro/queue.rb', line 16

def hiiro
  @hiiro
end

Class Method Details

.build_hiiro(parent_hiiro, q = nil, task_info: nil) ⇒ Object



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)

      # Auto-detect current task from environment when no explicit context given
      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

      # Split+interactive: open editor AND run claude in a new tmux pane
      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"))

        # Resolve working dir and chdir so the new pane inherits it
        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]
            # Session selected (no task) — use active pane's CWD from that session
            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")

        # cd to the session's active pane dir so the editor opens from there
        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
    }

    # Internal: resolve working directory for a pane-launched prompt after editing.
    # Used by the cadd/hadd/vadd shell scripts: cd $(h queue pane-dir $file $base)
    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

.current(hiiro = nil) ⇒ Object



12
13
14
# File 'lib/hiiro/queue.rb', line 12

def self.current(hiiro=nil)
  @current ||= new(hiiro)
end

.hiiro_versionObject



433
434
435
# File 'lib/hiiro/queue.rb', line 433

def self.hiiro_version
  `gem which hiiro`.sub(/.*hiiro-/, '').sub(/\/.*/, '').strip
end

Instance Method Details

#add_with_frontmatter(content, task_info: nil, ignore: false, name: nil) ⇒ Object



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
# File 'lib/hiiro/queue.rb', line 401

def add_with_frontmatter(content, task_info: nil, ignore: false, name: nil)
  queue_dirs # ensure dirs exist

  if (task_info || ignore) && !content.start_with?("---")
    fm = {}
    fm['task_name'] = task_info[:task_name] if task_info&.dig(:task_name)
    fm['tree_name'] = task_info[:tree_name] if task_info&.dig(:tree_name)
    fm['session_name'] = task_info[:session_name] if task_info&.dig(:session_name)
    fm['ignore'] = true if ignore

    if fm.any?
      content = "---\n#{fm.map { |k, v| "#{k}: #{v}" }.join("\n")}\n---\n#{content}"
    end
  end

  if name && !name.empty?
    name = slugify(name)
  else
    content_lines = content.lines.drop_while { |l| l.strip.empty? || l.start_with?('---') || l.match?(/^\w+:/) || l.start_with?('# ') }.first.to_s.strip
    name = slugify(content_lines)
  end

  if name.empty?
    name = Time.now.strftime("%Y%m%d%H%M%S")
    name += '-' + task_info[:task_name] if task_info&.key?(:task_name)
  end

  path, name = Hiiro::Paths.unique_path(queue_dirs[:pending], name)
  File.write(path, content + "\n")
  { name: name, path: path }
end

#all_tasksObject



91
92
93
94
95
# File 'lib/hiiro/queue.rb', line 91

def all_tasks
  STATUSES.flat_map do |status|
    tasks_in(status.to_sym).map { |name| { name: name, status: status } }
  end
end

#ensure_tmux_sessionObject



126
127
128
129
130
# File 'lib/hiiro/queue.rb', line 126

def ensure_tmux_session
  unless system('tmux', 'has-session', '-t', TMUX_SESSION, out: File::NULL, err: File::NULL)
    system('tmux', 'new-session', '-d', '-s', TMUX_SESSION)
  end
end

#existing_window_name?(wname) ⇒ Boolean

Returns:

  • (Boolean)


360
361
362
363
# File 'lib/hiiro/queue.rb', line 360

def existing_window_name?(wname)
  windows = `tmux list-windows -a -F '#\{window_name\}' 2>/dev/null`.lines(chomp: true)
  windows.include?(wname)
end

#find_task(name) ⇒ Object



118
119
120
121
122
123
124
# File 'lib/hiiro/queue.rb', line 118

def find_task(name)
  STATUSES.each do |status|
    md = File.join(queue_dirs[status.to_sym], "#{name}.md")
    return { name: name, status: status } if File.exist?(md)
  end
  nil
end

#format_mtime(mtime) ⇒ Object



48
49
50
51
# File 'lib/hiiro/queue.rb', line 48

def format_mtime(mtime)
  now = Time.now
  mtime.year == now.year ? mtime.strftime("%m-%d %H:%M") : mtime.strftime("%Y-%m-%d %H:%M")
end

#git_root_of(dir) ⇒ Object



392
393
394
395
# File 'lib/hiiro/queue.rb', line 392

def git_root_of(dir)
  root = `git -C #{Shellwords.shellescape(dir)} rev-parse --show-toplevel 2>/dev/null`.strip
  root.empty? ? dir : root
end

#launch_in_pane(name, split:) ⇒ Object



136
137
138
# File 'lib/hiiro/queue.rb', line 136

def launch_in_pane(name, split:)
  launch_in_mode(name, mode: split)
end

#launch_task(name) ⇒ Object



132
133
134
# File 'lib/hiiro/queue.rb', line 132

def launch_task(name)
  launch_in_mode(name, mode: :window)
end

#list_lines(all: false, statuses: nil) ⇒ Object



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
# File 'lib/hiiro/queue.rb', line 53

def list_lines(all: false, statuses: nil)
  filter = statuses && Array(statuses).map(&:to_s).reject(&:empty?)
  active_statuses = filter&.any? ? STATUSES.select { |s| filter.include?(s) } : STATUSES
  lines = []
  active_statuses.each do |status|
    tasks = tasks_in_sorted(status.to_sym)
    next if tasks.empty?

    display = all ? tasks : tasks.first(10)
    display.each do |t|
      ts = format_mtime(t[:mtime])
      line = "%-10s %-12s %s" % [status, ts, t[:name]]
      meta = meta_for(t[:name], status.to_sym)
      if meta && status == 'running'
        started = meta['started_at']
        if started
          elapsed = Time.now - Time.parse(started)
          mins = (elapsed / 60).to_i
          line += "  (#{mins}m)"
        end
        if meta['tmux_pane']
          line += "  [pane #{meta['tmux_pane']}]"
        elsif meta['tmux_session']
          line += "  [#{meta['tmux_session']}:#{meta['tmux_window']}]"
        end
      end
      preview = task_preview(t[:name], status.to_sym)
      line += "  #{preview}" if preview
      lines << line
    end

    if !all && tasks.size > 10
      lines << "  ... and #{tasks.size - 10} more"
    end
  end
  lines
end

#meta_for(name, status) ⇒ Object



97
98
99
100
# File 'lib/hiiro/queue.rb', line 97

def meta_for(name, status)
  path = File.join(queue_dirs[status], "#{name}.meta")
  File.exist?(path) ? YAML.safe_load_file(path) : nil
end

#queue_dirsObject



28
29
30
31
32
33
34
# File 'lib/hiiro/queue.rb', line 28

def queue_dirs
  @queue_dirs ||= STATUSES.each_with_object({}) do |name, h|
    dir = File.join(DIR, name)
    FileUtils.mkdir_p(dir)
    h[name.to_sym] = dir
  end
end

#read_prompt(filepath) ⇒ Object



22
23
24
25
26
# File 'lib/hiiro/queue.rb', line 22

def read_prompt(filepath)
  return false unless File.exist?(filepath)

  Prompt.from_file(filepath)
end

#resolve_pane_dir(prompt_path, base_dir = Dir.pwd) ⇒ Object

Given a (possibly-edited) prompt file and a base directory (task root), return the resolved working directory accounting for app: and dir: frontmatter.



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/hiiro/queue.rb', line 367

def resolve_pane_dir(prompt_path, base_dir = Dir.pwd)
  prompt_obj = Prompt.from_file(prompt_path.to_s, hiiro: @hiiro)
  return base_dir unless prompt_obj

  tree_root   = base_dir
  working_dir = base_dir

  if prompt_obj.app_name
    env = Environment.current rescue nil
    app = env&.find_app(prompt_obj.app_name)
    if app
      app_dir     = File.join(tree_root, app.relative_path)
      working_dir = prompt_obj.rel_dir ? File.join(app_dir, prompt_obj.rel_dir) : app_dir
    elsif prompt_obj.rel_dir
      working_dir = File.join(tree_root, prompt_obj.rel_dir)
    end
  elsif prompt_obj.rel_dir
    working_dir = File.join(tree_root, prompt_obj.rel_dir)
  end

  Dir.exist?(working_dir) ? working_dir : base_dir
rescue
  base_dir
end

#resolve_task_info(opts, hiiro, default_task_info) ⇒ Object



310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/hiiro/queue.rb', line 310

def resolve_task_info(opts, hiiro, default_task_info)
  if opts.find
    selection = select_task_or_session(hiiro)
    if selection
      case selection[:type]
      when :task    then task_info_for(selection[:task].name)
      when :session then { session_name: selection[:name] }
      end
    else
      default_task_info
    end
  elsif opts.task.is_a?(String)
    task_info_for(opts.task) || session_info_for(opts.task)
  else
    default_task_info
  end
end

#select_task_or_session(hiiro) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/hiiro/queue.rb', line 287

def select_task_or_session(hiiro)
  mapping = {}

  env = Environment.current rescue nil
  if env
    env.all_tasks.sort_by(&:name).each do |task|
      line = format("task     %-25s  tree: %s", task.name, task.tree_name || '(none)')
      mapping[line] = { type: :task, task: task }
    end
  end

  sessions = Hiiro::Tmux::Sessions.fetch rescue nil
  if sessions
    sessions.names.sort.each do |name|
      mapping[format("session  %s", name)] = { type: :session, name: name }
    end
  end

  return nil if mapping.empty?

  hiiro.fuzzyfind_from_map(mapping)
end

#session_info_for(prefix) ⇒ Object

Prefix-match opts.task against live tmux sessions; return session_name hash or nil.



329
330
331
332
333
334
335
336
337
338
# File 'lib/hiiro/queue.rb', line 329

def session_info_for(prefix)
  sessions = Hiiro::Tmux::Sessions.fetch rescue nil
  return nil unless sessions

  names   = sessions.names
  matches = names.select { |n| n.start_with?(prefix) }
  return nil unless matches.length == 1

  { session_name: matches.first }
end

#short_window_name(name) ⇒ Object



348
349
350
351
352
353
354
355
356
357
358
# File 'lib/hiiro/queue.rb', line 348

def short_window_name(name)
  base = name[0, 8]
  return base unless existing_window_name?(base)

  # append digits to make unique
  (2..99).each do |i|
    candidate = "#{base[0, 7]}#{i}"
    return candidate unless existing_window_name?(candidate)
  end
  base
end

#slugify(text) ⇒ Object



397
398
399
# File 'lib/hiiro/queue.rb', line 397

def slugify(text)
  text.downcase.gsub(/[^a-z0-9]+/, '-').gsub(/^-|-$/, '')[0, 60]
end

#strip_frontmatter(text) ⇒ Object



340
341
342
343
344
345
346
# File 'lib/hiiro/queue.rb', line 340

def strip_frontmatter(text)
  lines = text.lines
  return text unless lines.first&.strip == '---'
  end_idx = lines[1..].index { |l| l.strip == '---' }
  return text unless end_idx
  lines[(end_idx + 2)..].join.strip
end

#task_info_for(task_name) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/hiiro/queue.rb', line 273

def task_info_for(task_name)
  env = Environment.current rescue nil
  return nil unless env

  task = env.find_task(task_name)
  return nil unless task

  {
    task_name: task.name,
    tree_name: task.tree_name,
    session_name: task.session_name,
  }
end

#task_preview(name, status) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/hiiro/queue.rb', line 102

def task_preview(name, status)
  path = File.join(queue_dirs[status], "#{name}.md")
  return nil unless File.exist?(path)

  lines = File.readlines(path, chomp: true)
  # Skip frontmatter
  if lines.first == '---'
    end_idx = lines[1..].index('---')
    lines = lines[(end_idx + 2)..] if end_idx
  end
  first = lines&.find { |l| !l.strip.empty? }&.strip
  return nil unless first

  first.length > 60 ? "| #{first[0, 57]}..." : "| #{first}"
end

#tasks_in(status) ⇒ Object



36
37
38
39
# File 'lib/hiiro/queue.rb', line 36

def tasks_in(status)
  dir = queue_dirs[status]
  Dir.glob(File.join(dir, '*.md')).sort.map { |f| File.basename(f, '.md') }
end

#tasks_in_sorted(status) ⇒ Object



41
42
43
44
45
46
# File 'lib/hiiro/queue.rb', line 41

def tasks_in_sorted(status)
  dir = queue_dirs[status]
  Dir.glob(File.join(dir, '*.md')).map { |f|
    { name: File.basename(f, '.md'), mtime: File.mtime(f) }
  }.sort_by { |t| -t[:mtime].to_i }
end