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/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/commands/events.rb,
lib/harnex/commands/skills.rb,
lib/harnex/commands/status.rb,
lib/harnex/runtime/message.rb,
lib/harnex/runtime/session.rb,
lib/harnex/watcher/inotify.rb,
lib/harnex/watcher/polling.rb,
lib/harnex/adapters/generic.rb,
lib/harnex/commands/recipes.rb,
lib/harnex/runtime/api_server.rb,
lib/harnex/runtime/session_state.rb,
lib/harnex/commands/watch_presets.rb,
lib/harnex/runtime/file_change_hook.rb
Defined Under Namespace
Modules: Adapters, Inotify, Polling, WatchPresets, Watcher
Classes: ApiServer, BinaryNotFound, CLI, Events, FileChangeHook, Guide, Inbox, Logs, Message, Pane, Recipes, RunWatcher, Runner, Sender, Session, SessionState, Skills, Status, Stopper, Waiter, 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.5.0"
- RELEASE_DATE =
"2026-05-01"
Class Method Summary
collapse
-
.active_session_ids(repo_root) ⇒ Object
-
.active_sessions(repo_root = nil, id: nil, cli: nil) ⇒ Object
-
.alive_pid?(pid) ⇒ Boolean
-
.allocate_port(repo_root, id, requested_port = nil, host: DEFAULT_HOST) ⇒ Object
-
.build_adapter(cli, argv) ⇒ Object
-
.build_watch_config(path, repo_root) ⇒ Object
-
.cli_key(cli) ⇒ Object
-
.current_session_context(env = ENV) ⇒ Object
-
.default_summary_out_path(repo_root) ⇒ Object
-
.env_value(name, default: nil) ⇒ Object
-
.events_log_path(repo_root, id) ⇒ Object
-
.exit_status_path(repo_root, id) ⇒ Object
-
.format_relay_message(text, from:, id:, at: Time.now) ⇒ Object
-
.generate_id(repo_root) ⇒ Object
-
.git_capture_end(repo_root, start_sha) ⇒ Object
-
.git_capture_start(repo_root) ⇒ Object
-
.git_output(repo_root, *args) ⇒ Object
-
.harness_version ⇒ Object
-
.host_info ⇒ Object
-
.id_key(id) ⇒ Object
-
.normalize_id(id) ⇒ Object
-
.output_log_path(repo_root, id) ⇒ Object
-
.parent_pid(pid) ⇒ Object
-
.parse_duration_seconds(value, option_name:) ⇒ Object
-
.parse_git_shortstat(text) ⇒ Object
-
.port_available?(host, port) ⇒ Boolean
-
.read_registry(repo_root, id = DEFAULT_ID, cli: nil) ⇒ Object
-
.registry_path(repo_root, id = DEFAULT_ID) ⇒ Object
-
.repo_key(repo_root) ⇒ Object
-
.resolve_repo_root(path = Dir.pwd) ⇒ Object
-
.session_cli(session) ⇒ Object
-
.session_file_slug(repo_root, id) ⇒ Object
-
.strip_ansi(text) ⇒ Object
-
.tmux_pane_for_pid(pid) ⇒ Object
-
.write_registry(path, payload) ⇒ Object
Class Method Details
.active_session_ids(repo_root) ⇒ Object
173
174
175
|
# File 'lib/harnex/core.rb', line 173
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
|
# File 'lib/harnex/core.rb', line 216
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
246
247
248
249
250
251
252
253
|
# File 'lib/harnex/core.rb', line 246
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
|
# File 'lib/harnex/core.rb', line 326
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) ⇒ Object
352
353
354
355
356
|
# File 'lib/harnex/core.rb', line 352
def build_adapter(cli, argv)
raise ArgumentError, "cli is required" if cli.to_s.strip.empty?
Adapters.build(cli, argv)
end
|
.build_watch_config(path, repo_root) ⇒ Object
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
|
# File 'lib/harnex/core.rb', line 362
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
143
144
145
146
147
148
|
# File 'lib/harnex/core.rb', line 143
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
|
# File 'lib/harnex/core.rb', line 150
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
87
88
89
90
91
92
|
# File 'lib/harnex/core.rb', line 87
def default_summary_out_path(repo_root)
koder_dir = File.join(repo_root.to_s, "koder")
return nil unless File.directory?(koder_dir)
File.join(koder_dir, "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
204
205
206
207
208
|
# File 'lib/harnex/core.rb', line 204
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
192
193
194
195
196
|
# File 'lib/harnex/core.rb', line 192
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
|
165
166
167
168
169
170
171
|
# File 'lib/harnex/core.rb', line 165
def format_relay_message(text, from:, id:, at: Time.now)
= "[harnex relay from=#{from} id=#{normalize_id(id)} at=#{at.iso8601}]"
body = text.to_s
return if body.empty?
"#{}\n#{body}"
end
|
.generate_id(repo_root) ⇒ Object
177
178
179
180
181
182
183
184
185
|
# File 'lib/harnex/core.rb', line 177
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
# File 'lib/harnex/core.rb', line 107
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)
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),
commits: commits
}
rescue StandardError
{}
end
|
.git_capture_start(repo_root) ⇒ Object
94
95
96
97
98
99
100
101
102
103
104
105
|
# File 'lib/harnex/core.rb', line 94
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
381
382
383
384
385
386
|
# File 'lib/harnex/core.rb', line 381
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_version ⇒ Object
67
68
69
|
# File 'lib/harnex/core.rb', line 67
def harness_version
VERSION
end
|
.host_info ⇒ Object
71
72
73
74
75
76
77
78
79
80
81
|
# File 'lib/harnex/core.rb', line 71
def host_info
{
host: Socket.gethostname,
platform: RUBY_PLATFORM
}
rescue StandardError
{
host: nil,
platform: RUBY_PLATFORM
}
end
|
.id_key(id) ⇒ Object
139
140
141
|
# File 'lib/harnex/core.rb', line 139
def id_key(id)
normalize_id(id).downcase.gsub(/[^a-z0-9]+/, "-").gsub(/\A-+|-+\z/, "")
end
|
.normalize_id(id) ⇒ Object
132
133
134
135
136
137
|
# File 'lib/harnex/core.rb', line 132
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
198
199
200
201
202
|
# File 'lib/harnex/core.rb', line 198
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
310
311
312
313
314
315
316
317
318
|
# File 'lib/harnex/core.rb', line 310
def parent_pid(pid)
stat = File.read("/proc/#{pid}/stat")
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
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
388
389
390
391
392
393
394
|
# File 'lib/harnex/core.rb', line 388
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
344
345
346
347
348
349
350
|
# File 'lib/harnex/core.rb', line 344
def port_available?(host, port)
server = TCPServer.new(host, port)
server.close
true
rescue Errno::EADDRINUSE, Errno::EACCES
false
end
|
.read_registry(repo_root, id = DEFAULT_ID, cli: nil) ⇒ Object
255
256
257
258
259
260
|
# File 'lib/harnex/core.rb', line 255
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
187
188
189
190
|
# File 'lib/harnex/core.rb', line 187
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
128
129
130
|
# File 'lib/harnex/core.rb', line 128
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)
status.success? ? output.strip : File.expand_path(path)
rescue StandardError
File.expand_path(path)
end
|
.session_cli(session) ⇒ Object
358
359
360
|
# File 'lib/harnex/core.rb', line 358
def session_cli(session)
(session["cli"] || Array(session["command"]).first).to_s
end
|
.session_file_slug(repo_root, id) ⇒ Object
210
211
212
213
214
|
# File 'lib/harnex/core.rb', line 210
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
83
84
85
|
# File 'lib/harnex/core.rb', line 83
def strip_ansi(text)
text.to_s.gsub(/\e\[[0-9;]*[a-zA-Z]/, "")
end
|
.tmux_pane_for_pid(pid) ⇒ Object
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
|
# File 'lib/harnex/core.rb', line 262
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
matches = panes.select { |p| p[:pane_pid] == target_pid }
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
|
.write_registry(path, payload) ⇒ Object
320
321
322
323
324
|
# File 'lib/harnex/core.rb', line 320
def write_registry(path, payload)
tmp = "#{path}.tmp.#{Process.pid}"
File.write(tmp, JSON.pretty_generate(payload))
File.rename(tmp, path)
end
|