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 --meta --summary-out
  --timeout --inbox-ttl --legacy-pty --help
].freeze
VALUE_FLAGS =
%w[
  --id --description --host --port --watch --watch-file --stall-after
  --max-resumes --preset --context --meta --summary-out --timeout --inbox-ttl
].freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Runner

Returns a new instance of Runner.



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

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,
    meta: nil,
    summary_out: nil,
    detach: false,
    tmux: false,
    tmux_name: nil,
    timeout: DEFAULT_TIMEOUT,
    inbox_ttl: default_inbox_ttl,
    legacy_pty: false,
    help: false
  }
end

Class Method Details

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



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

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)
      --meta JSON        Attach parsed JSON metadata to the started event
      --summary-out PATH Append dispatch telemetry summary JSONL to PATH
      --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})
      --legacy-pty       (codex only) Use the legacy PTY adapter instead of
                         the JSON-RPC `app-server` adapter. Deprecated; will
                         be removed in 0.7.0.
      -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>.

    Common patterns:
      #{program_name} codex --id cx-i-42 --tmux cx-i-42 --context "Read /tmp/task-impl-42.md"
      #{program_name} codex --id cx-i-42 --watch --preset impl --context "Read /tmp/task-impl-42.md"
      #{program_name} claude --id cl-r-42 --tmux cl-r-42 --description "Review task 42"

    Gotchas:
      Always pair --id and --tmux with the same value for delegated work.
      Passing --tmux without --id creates a random harnex session ID.
      --watch is foreground-only; do not combine it with --tmux or --detach.
      Use -- before child CLI flags when a flag could be parsed by harnex.
  TEXT
end

Instance Method Details

#runObject

Raises:

  • (OptionParser::MissingArgument)


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

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[:summary_out] = resolve_summary_out(repo_root)
  @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, legacy_pty: @options[:legacy_pty])
  @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



127
128
129
130
131
132
133
134
135
136
# File 'lib/harnex/commands/run.rb', line 127

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



120
121
122
123
124
125
# File 'lib/harnex/commands/run.rb', line 120

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



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

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



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

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 += ["--meta", JSON.generate(@options[:meta])] if @options[:meta]
  tmux_cmd += ["--summary-out", @options[:summary_out]] if @options[:summary_out]
  tmux_cmd += ["--inbox-ttl", @options[:inbox_ttl].to_s]
  tmux_cmd += ["--legacy-pty"] if @options[:legacy_pty]
  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



138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/harnex/commands/run.rb', line 138

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