Module: Harnex

Defined in:
lib/harnex/cli.rb,
lib/harnex/core.rb,
lib/harnex/version.rb,
lib/harnex/watcher.rb,
lib/harnex/adapters.rb,
lib/harnex/adapters/pi.rb,
lib/harnex/commands/run.rb,
lib/harnex/adapters/base.rb,
lib/harnex/commands/logs.rb,
lib/harnex/commands/pane.rb,
lib/harnex/commands/send.rb,
lib/harnex/commands/stop.rb,
lib/harnex/commands/wait.rb,
lib/harnex/runtime/inbox.rb,
lib/harnex/adapters/codex.rb,
lib/harnex/commands/guide.rb,
lib/harnex/commands/watch.rb,
lib/harnex/adapters/claude.rb,
lib/harnex/artifact_report.rb,
lib/harnex/commands/doctor.rb,
lib/harnex/commands/events.rb,
lib/harnex/commands/status.rb,
lib/harnex/runtime/message.rb,
lib/harnex/runtime/session.rb,
lib/harnex/terminal_status.rb,
lib/harnex/watcher/inotify.rb,
lib/harnex/watcher/polling.rb,
lib/harnex/adapters/generic.rb,
lib/harnex/commands/history.rb,
lib/harnex/commands/recipes.rb,
lib/harnex/dispatch_history.rb,
lib/harnex/adapters/opencode.rb,
lib/harnex/context_telemetry.rb,
lib/harnex/runtime/api_server.rb,
lib/harnex/commands/agents_guide.rb,
lib/harnex/runtime/session_state.rb,
lib/harnex/commands/watch_presets.rb,
lib/harnex/codex/app_server/client.rb,
lib/harnex/adapters/codex_appserver.rb,
lib/harnex/runtime/file_change_hook.rb

Defined Under Namespace

Modules: Adapters, ArtifactReport, Codex, DispatchHistory, Inotify, Polling, TerminalStatus, WatchPresets, Watcher Classes: AgentsGuide, ApiServer, BinaryNotFound, CLI, ContextTelemetry, Doctor, Events, FileChangeHook, Guide, History, Inbox, Logs, Message, Pane, Recipes, RunWatcher, Runner, Sender, Session, SessionState, Status, Stopper, TerminalWatcher, Waiter, WatchCommand, WatchConfig

Constant Summary collapse

DEFAULT_HOST =
env_value("HARNEX_HOST", default: "127.0.0.1")
DEFAULT_BASE_PORT =
Integer(env_value("HARNEX_BASE_PORT", default: "43000"))
DEFAULT_PORT_SPAN =
Integer(env_value("HARNEX_PORT_SPAN", default: "4000"))
DEFAULT_ID =
"default"
WATCH_DEBOUNCE_SECONDS =
1.0
STATE_DIR =
File.expand_path(env_value("HARNEX_STATE_DIR", default: "~/.local/state/harnex"))
SESSIONS_DIR =
File.join(STATE_DIR, "sessions")
ID_ADJECTIVES =
%w[
  bold blue calm cool dark dry fast gold gray green
  keen loud mint pale pink red shy slim soft warm
].freeze
ID_NOUNS =
%w[
  ant bat bee cat cod cow cub doe elk fox
  hen jay kit owl pug ram ray seal wasp yak
].freeze
VERSION =
"0.7.13"
RELEASE_DATE =
"2026-07-15"

Class Method Summary collapse

Class Method Details

.active_session_ids(repo_root) ⇒ Object



205
206
207
# File 'lib/harnex/core.rb', line 205

def active_session_ids(repo_root)
  active_sessions(repo_root).map { |session| session["id"].to_s.downcase }.to_set
end

.active_sessions(repo_root = nil, id: nil, cli: nil) ⇒ Object



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
# File 'lib/harnex/core.rb', line 248

def active_sessions(repo_root = nil, id: nil, cli: nil)
  FileUtils.mkdir_p(SESSIONS_DIR)
  pattern =
    if repo_root
      File.join(SESSIONS_DIR, "#{repo_key(repo_root)}--*.json")
    else
      File.join(SESSIONS_DIR, "*.json")
    end

  target_id_key = id.nil? ? nil : id_key(id)
  normalized_cli = cli_key(cli)

  Dir.glob(pattern).sort.filter_map do |path|
    data = JSON.parse(File.read(path))
    if data["pid"] && alive_pid?(data["pid"])
      session = data.merge("registry_path" => path)
      next if target_id_key && id_key(session["id"].to_s) != target_id_key
      next if normalized_cli && cli_key(session_cli(session)) != normalized_cli

      session
    else
      FileUtils.rm_f(path)
      nil
    end
  rescue JSON::ParserError
    FileUtils.rm_f(path)
    nil
  end
end

.alive_pid?(pid) ⇒ Boolean

Returns:

  • (Boolean)


278
279
280
281
282
283
284
285
# File 'lib/harnex/core.rb', line 278

def alive_pid?(pid)
  Process.kill(0, Integer(pid))
  true
rescue Errno::ESRCH
  false
rescue Errno::EPERM
  true
end

.allocate_port(repo_root, id, requested_port = nil, host: DEFAULT_HOST) ⇒ Object



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/harnex/core.rb', line 358

def allocate_port(repo_root, id, requested_port = nil, host: DEFAULT_HOST)
  if requested_port
    return requested_port if port_available?(host, requested_port)

    raise "port #{requested_port} is already in use on #{host}"
  end

  seed = Digest::SHA256.hexdigest("#{repo_root}\0#{normalize_id(id)}").to_i(16)
  offset = seed % DEFAULT_PORT_SPAN

  DEFAULT_PORT_SPAN.times do |index|
    port = DEFAULT_BASE_PORT + ((offset + index) % DEFAULT_PORT_SPAN)
    return port if port_available?(host, port)
  end

  raise "could not find a free port in #{DEFAULT_BASE_PORT}-#{DEFAULT_BASE_PORT + DEFAULT_PORT_SPAN - 1}"
end

.build_adapter(cli, argv, legacy_pty: false) ⇒ Object

Raises:

  • (ArgumentError)


384
385
386
387
388
# File 'lib/harnex/core.rb', line 384

def build_adapter(cli, argv, legacy_pty: false)
  raise ArgumentError, "cli is required" if cli.to_s.strip.empty?

  Adapters.build(cli, argv, legacy_pty: legacy_pty)
end

.build_watch_config(path, repo_root) ⇒ Object

Raises:

  • (ArgumentError)


394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/harnex/core.rb', line 394

def build_watch_config(path, repo_root)
  return nil if path.nil?

  raise "file watch is unsupported on this system" unless Watcher.available?

  display_path = path.to_s.strip
  raise ArgumentError, "--watch requires a value" if display_path.empty?

  absolute_path = File.expand_path(display_path, repo_root)
  FileUtils.mkdir_p(File.dirname(absolute_path))

  WatchConfig.new(
    absolute_path: absolute_path,
    display_path: display_path,
    hook_message: "file-change-hook: read #{display_path}",
    debounce_seconds: WATCH_DEBOUNCE_SECONDS
  )
end

.cli_key(cli) ⇒ Object



175
176
177
178
179
180
# File 'lib/harnex/core.rb', line 175

def cli_key(cli)
  value = cli.to_s.strip.downcase
  return nil if value.empty?

  value.gsub(/[^a-z0-9]+/, "-").gsub(/\A-+|-+\z/, "")
end

.current_session_context(env = ENV) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/harnex/core.rb', line 182

def current_session_context(env = ENV)
  session_id = env["HARNEX_SESSION_ID"].to_s.strip
  cli = env["HARNEX_SESSION_CLI"].to_s.strip
  id = env["HARNEX_ID"].to_s.strip
  repo_root = env["HARNEX_SESSION_REPO_ROOT"].to_s.strip
  return nil if session_id.empty? || cli.empty? || id.empty?

  {
    session_id: session_id,
    cli: cli,
    id: id,
    repo_root: repo_root.empty? ? nil : repo_root
  }
end

.default_summary_out_path(repo_root) ⇒ Object



117
118
119
120
121
122
# File 'lib/harnex/core.rb', line 117

def default_summary_out_path(repo_root)
  root = repo_root.to_s
  return nil if root.empty?

  File.join(root, ".harnex", "dispatch.jsonl")
end

.env_value(name, default: nil) ⇒ Object



13
14
15
# File 'lib/harnex/core.rb', line 13

def env_value(name, default: nil)
  ENV.fetch(name, default)
end

.events_log_path(repo_root, id) ⇒ Object



236
237
238
239
240
# File 'lib/harnex/core.rb', line 236

def events_log_path(repo_root, id)
  events_dir = File.join(STATE_DIR, "events")
  FileUtils.mkdir_p(events_dir)
  File.join(events_dir, "#{session_file_slug(repo_root, id)}.jsonl")
end

.exit_status_path(repo_root, id) ⇒ Object



224
225
226
227
228
# File 'lib/harnex/core.rb', line 224

def exit_status_path(repo_root, id)
  exit_dir = File.join(STATE_DIR, "exits")
  FileUtils.mkdir_p(exit_dir)
  File.join(exit_dir, "#{session_file_slug(repo_root, id)}.json")
end

.format_relay_message(text, from:, id:, at: Time.now) ⇒ Object



197
198
199
200
201
202
203
# File 'lib/harnex/core.rb', line 197

def format_relay_message(text, from:, id:, at: Time.now)
  header = "[harnex relay from=#{from} id=#{normalize_id(id)} at=#{at.iso8601}]"
  body = text.to_s
  return header if body.empty?

  "#{header}\n#{body}"
end

.generate_id(repo_root) ⇒ Object



209
210
211
212
213
214
215
216
217
# File 'lib/harnex/core.rb', line 209

def generate_id(repo_root)
  taken = active_session_ids(repo_root)
  ID_ADJECTIVES.product(ID_NOUNS).shuffle.each do |adj, noun|
    candidate = "#{adj}-#{noun}"
    return candidate unless taken.include?(candidate)
  end

  "session-#{SecureRandom.hex(4)}"
end

.git_capture_end(repo_root, start_sha) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/harnex/core.rb', line 137

def git_capture_end(repo_root, start_sha)
  start_sha = start_sha.to_s.strip
  return {} if start_sha.empty?

  end_sha = git_output(repo_root, "rev-parse", "HEAD")
  range = "#{start_sha}..#{end_sha}"
  shortstat = git_output(repo_root, "diff", "--shortstat", range)
  changed_paths = git_output(repo_root, "diff", "--name-only", range).lines.map(&:strip).reject(&:empty?).first(200)
  commits = Integer(git_output(repo_root, "rev-list", "--count", range))
  stats = parse_git_shortstat(shortstat)

  {
    sha: end_sha,
    loc_added: stats.fetch(:loc_added),
    loc_removed: stats.fetch(:loc_removed),
    files_changed: stats.fetch(:files_changed),
    changed_paths: changed_paths,
    commits: commits
  }
rescue StandardError
  {}
end

.git_capture_start(repo_root) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/harnex/core.rb', line 124

def git_capture_start(repo_root)
  sha = git_output(repo_root, "rev-parse", "HEAD")
  branch = git_output(repo_root, "rev-parse", "--abbrev-ref", "HEAD")
  return {} if sha.empty? || branch.empty?

  {
    sha: sha,
    branch: branch
  }
rescue StandardError
  {}
end

.git_output(repo_root, *args) ⇒ Object



413
414
415
416
417
418
# File 'lib/harnex/core.rb', line 413

def git_output(repo_root, *args)
  stdout, _stderr, status = Open3.capture3("git", "-C", repo_root.to_s, *args)
  raise "git #{args.join(' ')} failed" unless status.success?

  stdout.strip
end

.harness_versionObject



67
68
69
# File 'lib/harnex/core.rb', line 67

def harness_version
  VERSION
end

.host_infoObject



101
102
103
104
105
106
107
108
109
110
111
# File 'lib/harnex/core.rb', line 101

def host_info
  {
    host: Socket.gethostname,
    platform: RUBY_PLATFORM
  }
rescue StandardError
  {
    host: nil,
    platform: RUBY_PLATFORM
  }
end

.id_key(id) ⇒ Object



171
172
173
# File 'lib/harnex/core.rb', line 171

def id_key(id)
  normalize_id(id).downcase.gsub(/[^a-z0-9]+/, "-").gsub(/\A-+|-+\z/, "")
end

.normalize_id(id) ⇒ Object



164
165
166
167
168
169
# File 'lib/harnex/core.rb', line 164

def normalize_id(id)
  value = id.to_s.strip
  raise "id is required" if value.empty?

  value
end

.output_log_path(repo_root, id) ⇒ Object



230
231
232
233
234
# File 'lib/harnex/core.rb', line 230

def output_log_path(repo_root, id)
  output_dir = File.join(STATE_DIR, "output")
  FileUtils.mkdir_p(output_dir)
  File.join(output_dir, "#{session_file_slug(repo_root, id)}.log")
end

.parent_pid(pid) ⇒ Object



342
343
344
345
346
347
348
349
350
# File 'lib/harnex/core.rb', line 342

def parent_pid(pid)
  stat = File.read("/proc/#{pid}/stat")
  # Field 4 is ppid (fields are space-separated, field 1 is pid,
  # field 2 is (comm) which may contain spaces, field 3 is state, field 4 is ppid)
  parts = stat.match(/\A\d+\s+\(.*?\)\s+\S+\s+(\d+)/)
  parts ? parts[1].to_i : nil
rescue Errno::ENOENT, Errno::EACCES
  nil
end

.parse_duration_seconds(value, option_name:) ⇒ Object

Raises:

  • (OptionParser::InvalidArgument)


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
# File 'lib/harnex/core.rb', line 41

def parse_duration_seconds(value, option_name:)
  text = value.to_s.strip
  raise OptionParser::InvalidArgument, "#{option_name} requires a value" if text.empty?

  match = text.match(/\A([0-9]+(?:\.[0-9]+)?)([smhSMH]?)\z/)
  unless match
    raise OptionParser::InvalidArgument,
          "#{option_name} must be a positive duration (examples: 30, 30s, 5m, 2h)"
  end

  amount = Float(match[1])
  multiplier =
    case match[2].downcase
    when "", "s" then 1.0
    when "m" then 60.0
    when "h" then 3600.0
    else
      raise OptionParser::InvalidArgument, "#{option_name} has an unsupported duration suffix"
    end

  seconds = amount * multiplier
  raise OptionParser::InvalidArgument, "#{option_name} must be greater than 0" if seconds <= 0.0

  seconds
end

.parse_git_shortstat(text) ⇒ Object



420
421
422
423
424
425
426
# File 'lib/harnex/core.rb', line 420

def parse_git_shortstat(text)
  {
    files_changed: text.to_s[/(\d+)\s+files?\s+changed/, 1].to_i,
    loc_added: text.to_s[/(\d+)\s+insertions?\(\+\)/, 1].to_i,
    loc_removed: text.to_s[/(\d+)\s+deletions?\(-\)/, 1].to_i
  }
end

.port_available?(host, port) ⇒ Boolean

Returns:

  • (Boolean)


376
377
378
379
380
381
382
# File 'lib/harnex/core.rb', line 376

def port_available?(host, port)
  server = TCPServer.new(host, port)
  server.close
  true
rescue Errno::EADDRINUSE, Errno::EACCES
  false
end

.process_state_for(session_state, terminal: false) ⇒ Object



90
91
92
93
94
95
96
97
98
99
# File 'lib/harnex/core.rb', line 90

def process_state_for(session_state, terminal: false)
  return "running" unless terminal

  case session_state.to_s
  when "completed", "failed"
    "exited"
  else
    "unknown"
  end
end

.read_registry(repo_root, id = DEFAULT_ID, cli: nil) ⇒ Object



287
288
289
290
291
292
# File 'lib/harnex/core.rb', line 287

def read_registry(repo_root, id = DEFAULT_ID, cli: nil)
  sessions = active_sessions(repo_root, id: id, cli: cli)
  return nil unless sessions.length == 1

  sessions.first
end

.registry_path(repo_root, id = DEFAULT_ID) ⇒ Object



219
220
221
222
# File 'lib/harnex/core.rb', line 219

def registry_path(repo_root, id = DEFAULT_ID)
  FileUtils.mkdir_p(SESSIONS_DIR)
  File.join(SESSIONS_DIR, "#{session_file_slug(repo_root, id)}.json")
end

.repo_key(repo_root) ⇒ Object



160
161
162
# File 'lib/harnex/core.rb', line 160

def repo_key(repo_root)
  Digest::SHA256.hexdigest(repo_root)[0, 16]
end

.resolve_repo_root(path = Dir.pwd) ⇒ Object



34
35
36
37
38
39
# File 'lib/harnex/core.rb', line 34

def resolve_repo_root(path = Dir.pwd)
  output, status = Open3.capture2("git", "rev-parse", "--show-toplevel", chdir: path, err: File::NULL)
  status.success? ? output.strip : File.expand_path(path)
rescue StandardError
  File.expand_path(path)
end

.session_cli(session) ⇒ Object



390
391
392
# File 'lib/harnex/core.rb', line 390

def session_cli(session)
  (session["cli"] || Array(session["command"]).first).to_s
end

.session_file_slug(repo_root, id) ⇒ Object



242
243
244
245
246
# File 'lib/harnex/core.rb', line 242

def session_file_slug(repo_root, id)
  slug = id_key(id)
  slug = "default" if slug.empty?
  "#{repo_key(repo_root)}--#{slug}"
end

.strip_ansi(text) ⇒ Object



113
114
115
# File 'lib/harnex/core.rb', line 113

def strip_ansi(text)
  text.to_s.gsub(/\e\[[0-9;]*[a-zA-Z]/, "")
end

.tmux_pane_for_pid(pid) ⇒ Object



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
# File 'lib/harnex/core.rb', line 294

def tmux_pane_for_pid(pid)
  target_pid = Integer(pid)
  stdout, status = Open3.capture2(
    "tmux", "list-panes", "-a", "-F",
    "\#{pane_id}\t\#{pane_pid}\t\#{session_name}\t\#{window_name}"
  )
  return nil unless status.success?

  panes = stdout.each_line.filter_map do |line|
    pane_id, pane_pid, session_name, window_name = line.chomp.split("\t", 4)
    next if pane_id.to_s.empty?

    {
      target: pane_id,
      pane_id: pane_id,
      pane_pid: pane_pid.to_i,
      session_name: session_name,
      window_name: window_name
    }
  end

  pane_pids = panes.map { |p| p[:pane_pid] }.to_set

  # Direct match first
  matches = panes.select { |p| p[:pane_pid] == target_pid }

  # If no direct match, walk up the process tree from target_pid
  # to find an ancestor that is a tmux pane root process.
  if matches.empty?
    ancestor = parent_pid(target_pid)
    while ancestor && ancestor > 1
      if pane_pids.include?(ancestor)
        matches = panes.select { |p| p[:pane_pid] == ancestor }
        break
      end
      ancestor = parent_pid(ancestor)
    end
  end

  return nil unless matches.length == 1

  result = matches.first
  result.delete(:pane_pid)
  result
rescue ArgumentError, Errno::ENOENT
  nil
end

.work_done_for(session_state, task_complete: false) ⇒ Object



86
87
88
# File 'lib/harnex/core.rb', line 86

def work_done_for(session_state, task_complete: false)
  work_state_for(session_state, task_complete: task_complete) == "completed"
end

.work_state_for(session_state, task_complete: false) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/harnex/core.rb', line 71

def work_state_for(session_state, task_complete: false)
  return "completed" if task_complete

  case session_state.to_s
  when "completed"
    "completed"
  when "failed"
    "failed"
  when "running"
    "running"
  else
    "unknown"
  end
end

.write_registry(path, payload) ⇒ Object



352
353
354
355
356
# File 'lib/harnex/core.rb', line 352

def write_registry(path, payload)
  tmp = "#{path}.tmp.#{Process.pid}"
  File.write(tmp, JSON.pretty_generate(payload))
  File.rename(tmp, path)
end