Class: Harnex::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/harnex/commands/run.rb

Constant Summary collapse

DEFAULT_TIMEOUT =
5.0
KNOWN_FLAGS =
%w[
  --id --description --detach --tmux --host --port --watch --watch-file
  --stall-after --max-resumes --preset --context --timeout --inbox-ttl --help
].freeze
VALUE_FLAGS =
%w[
  --id --description --host --port --watch --watch-file --stall-after
  --max-resumes --preset --context --timeout --inbox-ttl
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Runner

Returns a new instance of Runner.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/harnex/commands/run.rb', line 48

def initialize(argv)
  @argv = argv.dup
  @options = {
    id: nil,
    description: nil,
    host: DEFAULT_HOST,
    port: nil,
    watch_enabled: false,
    stall_after_s: RunWatcher::DEFAULT_STALL_AFTER_S,
    stall_after_explicit: false,
    max_resumes: RunWatcher::DEFAULT_MAX_RESUMES,
    max_resumes_explicit: false,
    preset: nil,
    watch: nil,
    context: nil,
    detach: false,
    tmux: false,
    tmux_name: nil,
    timeout: DEFAULT_TIMEOUT,
    inbox_ttl: default_inbox_ttl,
    help: false
  }
end

Class Method Details

.usage(program_name = "harnex run") ⇒ Object



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
# File 'lib/harnex/commands/run.rb', line 17

def self.usage(program_name = "harnex run")
  <<~TEXT
    Usage: #{program_name} <cli> [options] [--] [cli-args...]

    Options:
      --id ID            Session identifier (default: random two-word ID)
      --description TEXT Short description of what this session is doing
      --detach           Start session in background and return JSON on stdout
      --tmux [NAME]      Run in a tmux window (implies --detach)
      --host HOST        Bind host for the local API (default: #{DEFAULT_HOST})
      --port PORT        Force a specific local API port
      --watch            Enable blocking babysitter mode (foreground only)
      --stall-after DUR  Force-resume threshold (default: #{RunWatcher::DEFAULT_STALL_AFTER_S.to_i}s)
      --max-resumes N    Max forced resumes before escalation (default: #{RunWatcher::DEFAULT_MAX_RESUMES})
      --preset NAME      Watch preset: impl, plan, gate (requires --watch)
      --watch-file PATH  Auto-send a file-change hook on modification
      --context TEXT     Inject as the initial prompt (prepends session header)
      --timeout SECS     Max seconds to wait for detached registration (default: #{DEFAULT_TIMEOUT})
      --inbox-ttl SECS   Expire queued inbox messages after SECS (default: #{Inbox::DEFAULT_TTL})
      -h, --help         Show this help

    Notes:
      Compatibility: `--watch PATH` and `--watch=PATH` still configure file-hook mode.
      Bare `--watch` enables the babysitter.
      Explicit --stall-after/--max-resumes values override --preset defaults.
      CLIs with smart prompt detection: #{Adapters.known.join(', ')}
      Any other CLI name is launched with generic wrapping.
      Wrapper options may appear before or after <cli>.
  TEXT
end

Instance Method Details

#runObject

Raises:

  • (OptionParser::MissingArgument)


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
# File 'lib/harnex/commands/run.rb', line 72

def run
  cli_name, child_args = extract_wrapper_options(@argv)
  if @options[:help]
    puts self.class.usage
    return 0
  end

  raise OptionParser::MissingArgument, "cli" if cli_name.nil?

  repo_root = Harnex.resolve_repo_root(adapter_repo_path(cli_name, child_args))
  @options[:id] ||= Harnex.generate_id(repo_root)
  validate_unique_id!(repo_root)
  effective_child_args = apply_context(child_args)
  adapter = Harnex.build_adapter(cli_name, effective_child_args)
  @options[:detach] = true if @options[:tmux]
  validate_watch_mode!
  resolve_watch_preset!

  if @options[:watch_enabled]
    run_watch_mode(adapter, repo_root)
  elsif @options[:detach]
    run_detached(adapter, cli_name, child_args, repo_root)
  else
    run_foreground(adapter, repo_root)
  end
end

#run_detached(adapter, cli_name, child_args, repo_root) ⇒ Object



106
107
108
109
110
111
112
113
114
115
# File 'lib/harnex/commands/run.rb', line 106

def run_detached(adapter, cli_name, child_args, repo_root)
  Session.validate_binary!(adapter.build_command)

  if @options[:tmux]
    run_in_tmux(cli_name, child_args, repo_root)
  else
    result = run_headless(adapter, repo_root)
    result[:exit_code]
  end
end

#run_foreground(adapter, repo_root) ⇒ Object



99
100
101
102
103
104
# File 'lib/harnex/commands/run.rb', line 99

def run_foreground(adapter, repo_root)
  session = build_session(adapter, repo_root)
  session.validate_binary!
  warn("harnex: session #{session.id} on #{session.host}:#{session.port}")
  session.run(validate_binary: false)
end

#run_headless(adapter, repo_root, emit_payload: true) ⇒ Object



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
# File 'lib/harnex/commands/run.rb', line 174

def run_headless(adapter, repo_root, emit_payload: true)
  log_dir = File.join(Harnex::STATE_DIR, "logs")
  FileUtils.mkdir_p(log_dir)
  log_path = File.join(log_dir, "#{@options[:id]}.log")

  child_pid = fork do
    Process.setsid
    STDIN.reopen("/dev/null")
    log_file = File.open(log_path, "a")
    STDOUT.reopen(log_file)
    STDERR.reopen(log_file)
    STDOUT.sync = true
    STDERR.sync = true

    session = build_session(adapter, repo_root)
    exit_code = session.run(validate_binary: false)
    exit(exit_code || 1)
  end

  Process.detach(child_pid)

  registry = wait_for_registration(repo_root)
  return { ok: false, exit_code: registration_timeout(@options[:id]) } unless registry

  payload = {
    ok: true,
    id: @options[:id],
    cli: adapter.key,
    pid: registry["pid"],
    port: registry["port"],
    mode: "headless",
    log: log_path,
    output_log_path: Harnex.output_log_path(repo_root, @options[:id])
  }
  payload[:description] = @options[:description] if @options[:description]
  puts JSON.generate(payload) if emit_payload
  { ok: true, exit_code: 0, registry: registry, payload: payload }
end

#run_in_tmux(cli_name, child_args, repo_root) ⇒ Object



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
# File 'lib/harnex/commands/run.rb', line 131

def run_in_tmux(cli_name, child_args, repo_root)
  harnex_bin = File.expand_path("../../../bin/harnex", __dir__)
  tmux_cmd = [harnex_bin, "run", cli_name]
  tmux_cmd += ["--id", @options[:id]]
  tmux_cmd += ["--description", @options[:description]] if @options[:description]
  tmux_cmd += ["--host", @options[:host]]
  tmux_cmd += ["--port", @options[:port].to_s] if @options[:port]
  tmux_cmd += ["--watch-file", @options[:watch]] if @options[:watch]
  tmux_cmd += ["--context", @options[:context]] if @options[:context]
  tmux_cmd += ["--inbox-ttl", @options[:inbox_ttl].to_s]
  tmux_cmd += ["--"] + child_args unless child_args.empty?

  window_name = @options[:tmux_name] || @options[:id]
  shell_cmd = tmux_cmd.map { |arg| Shellwords.shellescape(arg) }.join(" ")

  started =
    if ENV["TMUX"]
      system("tmux", "new-window", "-n", window_name, "-d", shell_cmd)
    else
      system("tmux", "new-session", "-d", "-s", "harnex", "-n", window_name, shell_cmd)
    end

  raise "tmux failed to start #{cli_name.inspect}" unless started

  registry = wait_for_registration(repo_root)
  return registration_timeout(@options[:id]) unless registry
  registry = annotate_tmux_registry(registry)

  payload = {
    ok: true,
    id: @options[:id],
    cli: cli_name,
    pid: registry["pid"],
    port: registry["port"],
    mode: "tmux",
    window: window_name,
    output_log_path: Harnex.output_log_path(repo_root, @options[:id])
  }
  payload[:description] = @options[:description] if @options[:description]
  puts JSON.generate(payload)
  0
end

#run_watch_mode(adapter, repo_root) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/harnex/commands/run.rb', line 117

def run_watch_mode(adapter, repo_root)
  Session.validate_binary!(adapter.build_command)

  result = run_headless(adapter, repo_root, emit_payload: false)
  return result[:exit_code] unless result[:ok]

  RunWatcher.new(
    id: @options[:id],
    repo_root: repo_root,
    stall_after_s: @options[:stall_after_s],
    max_resumes: @options[:max_resumes]
  ).run
end