harnex 0.12.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +592 -0
  3. data/GUIDE.md +222 -68
  4. data/README.md +78 -48
  5. data/TECHNICAL.md +235 -98
  6. data/agents/gpt.md +60 -0
  7. data/docs/agents.md +119 -0
  8. data/docs/dispatch-telemetry.md +184 -50
  9. data/docs/events.md +20 -7
  10. data/docs/lanes.md +202 -0
  11. data/docs/mcp.md +102 -0
  12. data/docs/pi-rpc.md +81 -7
  13. data/docs/upgrading-to-0.29.md +87 -0
  14. data/guides/01_dispatch.md +101 -34
  15. data/guides/04_monitoring.md +223 -25
  16. data/guides/05_naming.md +0 -1
  17. data/guides/06_claude.md +96 -0
  18. data/lib/harnex/adapters/base.rb +4 -8
  19. data/lib/harnex/adapters/pi.rb +92 -12
  20. data/lib/harnex/adapters.rb +1 -16
  21. data/lib/harnex/artifact_report.rb +206 -12
  22. data/lib/harnex/cli.rb +68 -50
  23. data/lib/harnex/commands/ask.rb +278 -0
  24. data/lib/harnex/commands/delegate.rb +202 -0
  25. data/lib/harnex/commands/doctor.rb +34 -36
  26. data/lib/harnex/commands/events.rb +3 -3
  27. data/lib/harnex/commands/history.rb +2 -8
  28. data/lib/harnex/commands/land.rb +150 -0
  29. data/lib/harnex/commands/lanes.rb +84 -0
  30. data/lib/harnex/commands/logs.rb +3 -3
  31. data/lib/harnex/commands/mcp.rb +208 -0
  32. data/lib/harnex/commands/orchestration.rb +88 -9
  33. data/lib/harnex/commands/pane.rb +3 -3
  34. data/lib/harnex/commands/preflight.rb +566 -0
  35. data/lib/harnex/commands/reply.rb +125 -0
  36. data/lib/harnex/commands/result.rb +108 -0
  37. data/lib/harnex/commands/run.rb +248 -64
  38. data/lib/harnex/commands/send.rb +121 -16
  39. data/lib/harnex/commands/status.rb +32 -4
  40. data/lib/harnex/commands/stop.rb +14 -4
  41. data/lib/harnex/commands/telemetry.rb +19 -1
  42. data/lib/harnex/commands/wait.rb +421 -56
  43. data/lib/harnex/commands/watch.rb +134 -21
  44. data/lib/harnex/context_file.rb +85 -0
  45. data/lib/harnex/core.rb +100 -15
  46. data/lib/harnex/dispatch_history.rb +157 -10
  47. data/lib/harnex/lanes.rb +513 -0
  48. data/lib/harnex/mcp.rb +362 -0
  49. data/lib/harnex/orchestration.rb +128 -5
  50. data/lib/harnex/owned_process_group.rb +50 -0
  51. data/lib/harnex/owner_stream.rb +399 -0
  52. data/lib/harnex/pricing.rb +4 -9
  53. data/lib/harnex/runtime/activity_tracker.rb +107 -0
  54. data/lib/harnex/runtime/api_server.rb +11 -1
  55. data/lib/harnex/runtime/completion_notifier.rb +90 -11
  56. data/lib/harnex/runtime/inbox.rb +26 -7
  57. data/lib/harnex/runtime/message.rb +5 -2
  58. data/lib/harnex/runtime/runtime_budget.rb +96 -0
  59. data/lib/harnex/runtime/session.rb +684 -294
  60. data/lib/harnex/runtime/stop_request.rb +39 -0
  61. data/lib/harnex/stall.rb +46 -0
  62. data/lib/harnex/telemetry_reconciler.rb +42 -20
  63. data/lib/harnex/terminal_status.rb +5 -5
  64. data/lib/harnex/version.rb +2 -2
  65. data/lib/harnex.rb +16 -0
  66. data/recipes/01_fire_and_watch.md +14 -14
  67. data/recipes/02_chain_implement.md +35 -31
  68. data/recipes/03_buddy.md +1 -1
  69. metadata +34 -12
  70. data/docs/codex-appserver.md +0 -175
  71. data/lib/harnex/adapters/codex.rb +0 -160
  72. data/lib/harnex/adapters/codex_appserver.rb +0 -407
  73. data/lib/harnex/codex/app_server/client.rb +0 -347
@@ -212,12 +212,15 @@ module Harnex
212
212
 
213
213
  class TerminalWatcher
214
214
  TIMEOUT_EXIT_CODE = 124
215
+ STALLED_EXIT_CODE = 4 # Waiter::DONE_EXIT_STALLED (wait.rb loads after this file)
215
216
 
216
217
  def initialize(
217
218
  id:,
218
219
  repo_path: Dir.pwd,
219
220
  until_state: "done",
220
221
  max_wait: nil,
222
+ heartbeat: nil,
223
+ stall_after: nil,
221
224
  done_marker: nil,
222
225
  fail_marker: nil,
223
226
  stop_on_terminal: false,
@@ -228,6 +231,8 @@ module Harnex
228
231
  @repo_path = repo_path
229
232
  @until_state = until_state.to_s.strip.empty? ? "done" : until_state.to_s
230
233
  @max_wait = max_wait
234
+ @heartbeat = heartbeat
235
+ @stall_after = stall_after
231
236
  @done_marker = done_marker
232
237
  @fail_marker = fail_marker
233
238
  @stop_on_terminal = stop_on_terminal
@@ -238,8 +243,7 @@ module Harnex
238
243
  def run
239
244
  raise "harnex watch: only --until done is supported" unless @until_state == "done"
240
245
 
241
- output, warnings, exit_code = capture_wait
242
- @err.write(warnings) unless warnings.empty?
246
+ output, exit_code = capture_wait
243
247
  @out.write(output) unless output.empty?
244
248
 
245
249
  payload = parse_payload(output)
@@ -251,7 +255,8 @@ module Harnex
251
255
  write_marker(@fail_marker, payload, outcome: outcome, exit_code: exit_code)
252
256
  end
253
257
 
254
- stop_session if @stop_on_terminal && outcome != :timeout
258
+ # Timeouts and stalls are observer verdicts: the worker keeps running.
259
+ stop_session if @stop_on_terminal && !%i[timeout stalled].include?(outcome)
255
260
  exit_code
256
261
  end
257
262
 
@@ -260,18 +265,14 @@ module Harnex
260
265
  def capture_wait
261
266
  argv = ["--id", @id, "--repo", @repo_path, "--until", @until_state]
262
267
  argv += ["--timeout", @max_wait.to_s] if @max_wait
268
+ argv += ["--heartbeat", @heartbeat.to_s] if @heartbeat
269
+ argv += ["--stall-after", @stall_after.to_s] if @stall_after
263
270
 
271
+ # Buffer only the one final JSON result for marker classification.
272
+ # Diagnostics (including heartbeats) stream directly to the caller.
264
273
  out_buffer = StringIO.new
265
- err_buffer = StringIO.new
266
- original_stdout = $stdout
267
- original_stderr = $stderr
268
- $stdout = out_buffer
269
- $stderr = err_buffer
270
- exit_code = Waiter.new(argv).run
271
- [out_buffer.string, err_buffer.string, exit_code]
272
- ensure
273
- $stdout = original_stdout
274
- $stderr = original_stderr
274
+ exit_code = Waiter.new(argv, out: out_buffer, err: @err).run
275
+ [out_buffer.string, exit_code]
275
276
  end
276
277
 
277
278
  def parse_payload(output)
@@ -286,6 +287,7 @@ module Harnex
286
287
 
287
288
  def classify(exit_code, payload)
288
289
  return :timeout if exit_code == TIMEOUT_EXIT_CODE || payload["status"].to_s == "timeout"
290
+ return :stalled if exit_code == STALLED_EXIT_CODE || payload["status"].to_s == "stalled"
289
291
  return :success if exit_code.to_i.zero? && (payload.empty? || payload["ok"] != false)
290
292
 
291
293
  :failed
@@ -323,6 +325,8 @@ module Harnex
323
325
  uri = URI("http://#{registry.fetch('host')}:#{registry.fetch('port')}/stop")
324
326
  request = Net::HTTP::Post.new(uri)
325
327
  request["Authorization"] = "Bearer #{registry['token']}" if registry["token"]
328
+ request["Content-Type"] = "application/json"
329
+ request.body = JSON.generate(reason: "completion", origin: "watch")
326
330
 
327
331
  response = Net::HTTP.start(uri.host, uri.port, open_timeout: 1, read_timeout: 2) do |http|
328
332
  http.request(request)
@@ -337,13 +341,35 @@ module Harnex
337
341
  def self.usage(program_name = "harnex watch")
338
342
  <<~TEXT
339
343
  Usage: #{program_name} --id ID [options]
344
+ #{program_name} --owner [ID] [--stall-after DUR] [--max-wait DUR]
345
+ #{program_name} --owner [ID] --once [--timeout DUR] [--cursor NAME]
340
346
 
341
347
  Options:
342
- --id ID Existing session ID to watch (required)
348
+ --id ID Existing session ID to watch
349
+ --owner [ID] Stream every dispatch this owner started (see below);
350
+ ID defaults to $PI_SESSION_ID or $CLAUDE_CODE_SESSION_ID
351
+ --once With --owner: wait for undelivered results or stalls,
352
+ print every one that is ready, advance the cursor and
353
+ exit 0 (124 on timeout)
354
+ --until-idle With --owner: like --once, but keep printing results
355
+ until no (matching) lane is still running; exit 0
356
+ then, 124 on timeout. One call for a whole batch
357
+ --cursor NAME With --owner: keep a separate named cursor. A Claude
358
+ Code subagent inherits its parent's
359
+ $CLAUDE_CODE_SESSION_ID, so both own the same lanes;
360
+ give each consumer its own cursor
361
+ --owner-tag TAG With --owner: watch "<owner>/<TAG>", the lanes launched
362
+ with `run --owner-tag TAG`
363
+ --match GLOB[,GLOB] With --owner: only lanes whose id matches (e.g.
364
+ 'pi-s2-*'); repeatable
343
365
  --until done Watch work-level terminal state (default: done)
344
366
  --repo PATH Resolve session using PATH's repo root (default: current repo)
345
- --max-wait DUR Wall-clock cap before returning timeout (examples: 900, 15m, 2h)
367
+ --max-wait DUR Hard observer cap (examples: 900, 15m, 2h)
346
368
  --timeout DUR Alias for --max-wait
369
+ --heartbeat DUR Flush observed progress to stderr (default: off)
370
+ --stall-after DUR Exit 4 when the session shows no progress for DUR
371
+ (Pi/structured: model/tool/turn events in an active
372
+ turn; PTY: transcript idle). Observes only.
347
373
  --done-marker PATH Write a JSON marker when work completes successfully
348
374
  --fail-marker PATH Write a JSON marker when work fails
349
375
  --stop-on-terminal Stop the live session after success/failure (not on timeout)
@@ -352,9 +378,30 @@ module Harnex
352
378
  `harnex watch` is the safe watcher for existing --tmux or detached
353
379
  dispatches. Exit codes follow the `harnex wait --until done` contract:
354
380
  0 accepted work, 1 failed, 2 completed-but-proof-rejected, 3 no such
355
- session, 124 for --max-wait timeouts.
356
-
357
- For launch-and-babysit stall recovery, use `harnex run --watch`.
381
+ session, 4 stalled (--stall-after), 124 for --max-wait timeouts.
382
+ Stalls and timeouts write no marker and skip --stop-on-terminal.
383
+
384
+ Owner stream (--owner): runs until killed or --max-wait (exit 124) and
385
+ prints one JSON line (schema harnex.owner_event.v1, with a readable
386
+ `msg`) per change: started, done, rejected, failed, stalled (with
387
+ --stall-after), stopped, timeout. No heartbeats. On start it repeats
388
+ `started` for running dispatches and delivers results not yet
389
+ delivered to this owner; a cursor prevents repeats across restarts.
390
+ Built for Claude Code's Monitor tool, e.g.:
391
+ #{program_name} --owner --stall-after 25m
392
+ Each turn reports its own result: a lane nudged with `harnex send`
393
+ reports again when that turn ends (the line carries `turn`).
394
+
395
+ --once is for a caller that must block in one foreground command (a
396
+ Claude Code subagent cannot be woken later): one call waits on every
397
+ lane the owner launched (or the --match lanes) and returns the next
398
+ results or stalls. It never returns `started`. Loop it, e.g.:
399
+ #{program_name} --owner --once --timeout 9m --cursor sub-a --match 'pi-a-*'
400
+
401
+ For launch-and-babysit stall recovery, use `harnex run --watch`: it
402
+ nudges with "resume" on output-log idle and is independent of this
403
+ observer. If both run, set --stall-after here above run's
404
+ stall-after x (max-resumes + 1).
358
405
  TEXT
359
406
  end
360
407
 
@@ -365,9 +412,18 @@ module Harnex
365
412
  repo_path: Dir.pwd,
366
413
  until_state: "done",
367
414
  max_wait: nil,
415
+ heartbeat: nil,
416
+ stall_after: nil,
368
417
  done_marker: nil,
369
418
  fail_marker: nil,
370
419
  stop_on_terminal: false,
420
+ owner: nil,
421
+ owner_flag: false,
422
+ once: false,
423
+ until_idle: false,
424
+ cursor: nil,
425
+ match: [],
426
+ owner_tag: nil,
371
427
  help: false
372
428
  }
373
429
  end
@@ -379,6 +435,11 @@ module Harnex
379
435
  return 0
380
436
  end
381
437
 
438
+ return run_owner_stream if @options[:owner_flag]
439
+ if @options[:once] || @options[:until_idle] || @options[:cursor] || @options[:match].any? || @options[:owner_tag]
440
+ raise OptionParser::InvalidOption, "--once, --cursor, --match and --owner-tag require --owner"
441
+ end
442
+
382
443
  raise "--id is required for harnex watch" unless @options[:id]
383
444
 
384
445
  TerminalWatcher.new(
@@ -386,6 +447,8 @@ module Harnex
386
447
  repo_path: @options[:repo_path],
387
448
  until_state: @options[:until_state],
388
449
  max_wait: @options[:max_wait],
450
+ heartbeat: @options[:heartbeat],
451
+ stall_after: @options[:stall_after],
389
452
  done_marker: @options[:done_marker],
390
453
  fail_marker: @options[:fail_marker],
391
454
  stop_on_terminal: @options[:stop_on_terminal]
@@ -394,17 +457,67 @@ module Harnex
394
457
 
395
458
  private
396
459
 
460
+ def run_owner_stream
461
+ if @options[:id]
462
+ raise OptionParser::InvalidOption, "--owner and --id are mutually exclusive"
463
+ end
464
+ unsupported = { done_marker: "--done-marker", fail_marker: "--fail-marker",
465
+ stop_on_terminal: "--stop-on-terminal", heartbeat: "--heartbeat" }
466
+ .select { |key, _flag| @options[key] }.values
467
+ unless unsupported.empty?
468
+ raise OptionParser::InvalidOption, "#{unsupported.join(', ')} cannot be combined with --owner"
469
+ end
470
+
471
+ owner = @options[:owner].to_s.strip
472
+ owner = Harnex.ambient_owner_id.to_s if owner.empty?
473
+ if owner.empty? && @options[:owner_tag].nil?
474
+ raise OptionParser::MissingArgument,
475
+ "--owner ID (no $PI_SESSION_ID or $CLAUDE_CODE_SESSION_ID to default to)"
476
+ end
477
+ if @options[:owner_tag]
478
+ begin
479
+ owner = Harnex.tagged_owner_id(owner, @options[:owner_tag])
480
+ rescue ArgumentError => e
481
+ raise OptionParser::InvalidArgument, "--owner-tag: #{e.message}"
482
+ end
483
+ end
484
+
485
+ cursor = @options[:cursor]
486
+ if cursor && !cursor.match?(OwnerStream::CURSOR_NAME)
487
+ raise OptionParser::InvalidArgument, "--cursor must be 1-64 letters, digits, '.', '_' or '-'"
488
+ end
489
+
490
+ OwnerStream.new(owner_id: owner, stall_after: @options[:stall_after], max_wait: @options[:max_wait],
491
+ once: @options[:once], cursor: cursor, match: @options[:match],
492
+ until_idle: @options[:until_idle]).run
493
+ end
494
+
397
495
  def parser
398
496
  @parser ||= OptionParser.new do |opts|
399
497
  opts.banner = "Usage: harnex watch --id ID [options]"
400
498
  opts.on("--id ID", "Existing session ID to watch") { |value| @options[:id] = Harnex.normalize_id(value) }
499
+ opts.on("--owner [ID]", "Stream every dispatch this owner started") do |value|
500
+ @options[:owner_flag] = true
501
+ @options[:owner] = value
502
+ end
503
+ opts.on("--once", "With --owner: exit after the first delivered event") { @options[:once] = true }
504
+ opts.on("--until-idle", "With --owner: exit once no lane is running") { @options[:until_idle] = true }
505
+ opts.on("--cursor NAME", "With --owner: use a named cursor") { |value| @options[:cursor] = value }
506
+ opts.on("--match GLOB", "With --owner: only matching lane ids") { |value| @options[:match] << value }
507
+ opts.on("--owner-tag TAG", "With --owner: the owner's tagged sub-owner") { |value| @options[:owner_tag] = value }
401
508
  opts.on("--until STATE", "Watch until terminal state") { |value| @options[:until_state] = value }
402
509
  opts.on("--repo PATH", "Resolve session using PATH's repo root") { |value| @options[:repo_path] = value }
403
- opts.on("--max-wait DUR", "Wall-clock cap") do |value|
404
- @options[:max_wait] = Harnex.parse_duration_seconds(value, option_name: "--max-wait")
510
+ opts.on("--max-wait DUR", "Hard observer cap") do |value|
511
+ @options[:max_wait] = Waiter.duration(value, option_name: "--max-wait")
405
512
  end
406
513
  opts.on("--timeout DUR", "Alias for --max-wait") do |value|
407
- @options[:max_wait] = Harnex.parse_duration_seconds(value, option_name: "--timeout")
514
+ @options[:max_wait] = Waiter.duration(value, option_name: "--timeout")
515
+ end
516
+ opts.on("--heartbeat DUR", "Flush progress to stderr") do |value|
517
+ @options[:heartbeat] = Waiter.duration(value, option_name: "--heartbeat")
518
+ end
519
+ opts.on("--stall-after DUR", "Exit 4 after DUR without progress") do |value|
520
+ @options[:stall_after] = Waiter.duration(value, option_name: "--stall-after")
408
521
  end
409
522
  opts.on("--done-marker PATH", "Write marker on successful completion") { |value| @options[:done_marker] = value }
410
523
  opts.on("--fail-marker PATH", "Write marker on failed completion") { |value| @options[:fail_marker] = value }
@@ -0,0 +1,85 @@
1
+ require "digest"
2
+
3
+ module Harnex
4
+ # `harnex run --context-file PATH [--context-section TEXT]` (#83): read a
5
+ # brief from disk, optionally keep only one section, and refuse an empty
6
+ # result so a bad extraction never launches a session with no task.
7
+ module ContextFile
8
+ class Error < StandardError; end
9
+
10
+ HEADING = /\A(\#{1,6})[ \t]+(.*?)(?:[ \t]+\#+)?[ \t]*\z/
11
+ FENCE = /\A[ \t]{0,3}(```|~~~)/
12
+
13
+ module_function
14
+
15
+ # Returns { text:, path:, section:, sha256: }. A section starts at the first
16
+ # line (outside code fences) whose text, with any heading markers removed,
17
+ # begins with SECTION. After a Markdown heading it runs to the next heading
18
+ # of the same or a higher level; after a plain marker line, to end of file.
19
+ def load(path, section: nil)
20
+ absolute = File.expand_path(path)
21
+ raise Error, "--context-file not found: #{path}" unless File.file?(absolute)
22
+
23
+ content = File.read(absolute, encoding: "UTF-8")
24
+ raise Error, "--context-file is not valid UTF-8: #{path}" unless content.valid_encoding?
25
+
26
+ text = section ? extract_section(content, section, path) : content
27
+ text = trim_blank_lines(text)
28
+ if text.strip.empty?
29
+ where = section ? "section #{section.inspect} of #{path}" : path
30
+ raise Error, "--context-file refused: #{where} is empty"
31
+ end
32
+
33
+ { text: text, path: absolute, section: section, sha256: Digest::SHA256.hexdigest(text) }
34
+ end
35
+
36
+ def extract_section(content, section, path)
37
+ # "## Task" and "Task" both name the heading "## Task".
38
+ needle = section.to_s.strip.sub(/\A\#{1,6}[ \t]+/, "")
39
+ raise Error, "--context-section needs a non-empty heading" if needle.empty?
40
+
41
+ lines = content.lines
42
+ start, level = find_marker(lines, needle)
43
+ raise Error, "--context-section #{section.inspect} not found in #{path}" unless start
44
+
45
+ body = lines[(start + 1)..] || []
46
+ return body.join if level.nil?
47
+
48
+ in_fence = false
49
+ taken = body.take_while do |line|
50
+ in_fence = !in_fence if line.match?(FENCE)
51
+ next true if in_fence
52
+
53
+ heading = line.chomp.match(HEADING)
54
+ heading.nil? || heading[1].length > level
55
+ end
56
+ taken.join
57
+ end
58
+
59
+ def find_marker(lines, needle)
60
+ in_fence = false
61
+ lines.each_with_index do |line, index|
62
+ if line.match?(FENCE)
63
+ in_fence = !in_fence
64
+ next
65
+ end
66
+ next if in_fence
67
+
68
+ stripped = line.chomp
69
+ heading = stripped.match(HEADING)
70
+ text = heading ? heading[2] : stripped.strip
71
+ next unless text.start_with?(needle)
72
+
73
+ return [index, heading && heading[1].length]
74
+ end
75
+ nil
76
+ end
77
+
78
+ def trim_blank_lines(text)
79
+ lines = text.lines
80
+ lines.shift while lines.first&.strip&.empty?
81
+ lines.pop while lines.last&.strip&.empty?
82
+ lines.join.chomp
83
+ end
84
+ end
85
+ end
data/lib/harnex/core.rb CHANGED
@@ -43,28 +43,51 @@ module Harnex
43
43
  File.expand_path(path)
44
44
  end
45
45
 
46
+ # #87: harnex state inside a repo (.harnex/: dispatch rows, lane worktrees)
47
+ # must never show up as untracked work, in the checkout or its worktrees.
48
+ # info/exclude in the common git dir is local to this clone and covers
49
+ # every worktree; nothing tracked changes.
50
+ def ensure_git_excluded(repo_root, entry = ".harnex/")
51
+ common, status = Open3.capture2("git", "-C", repo_root.to_s, "rev-parse", "--git-common-dir", err: File::NULL)
52
+ return false unless status.success?
53
+
54
+ path = File.join(File.expand_path(common.strip, repo_root.to_s), "info", "exclude")
55
+ existing = File.file?(path) ? File.read(path) : ""
56
+ return true if existing.lines.map(&:strip).include?(entry)
57
+
58
+ FileUtils.mkdir_p(File.dirname(path))
59
+ File.open(path, "a") do |file|
60
+ file.write("\n") unless existing.empty? || existing.end_with?("\n")
61
+ file.puts(entry)
62
+ end
63
+ true
64
+ rescue StandardError
65
+ false
66
+ end
67
+
46
68
  def parse_duration_seconds(value, option_name:)
47
69
  text = value.to_s.strip
48
70
  raise OptionParser::InvalidArgument, "#{option_name} requires a value" if text.empty?
49
71
 
50
- match = text.match(/\A([0-9]+(?:\.[0-9]+)?)([smhSMH]?)\z/)
51
- unless match
72
+ match = text.match(/\A([0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)([smhSMH]?)\z/)
73
+ # Compound forms such as 1h30m or 8m30s: whole numbers, units in order.
74
+ compound = text.match(/\A(?:(\d+)[hH])?(?:(\d+)[mM])?(?:(\d+)[sS])?\z/) unless match
75
+ unless match || (compound && compound.captures.any?)
52
76
  raise OptionParser::InvalidArgument,
53
- "#{option_name} must be a positive duration (examples: 30, 30s, 5m, 2h)"
77
+ "#{option_name} must be a positive duration (examples: 30, 30s, 5m, 8m30s, 2h)"
54
78
  end
55
79
 
56
- amount = Float(match[1])
57
- multiplier =
58
- case match[2].downcase
59
- when "", "s" then 1.0
60
- when "m" then 60.0
61
- when "h" then 3600.0
80
+ seconds =
81
+ if match
82
+ amount = Float(match[1])
83
+ amount * { "" => 1.0, "s" => 1.0, "m" => 60.0, "h" => 3600.0 }.fetch(match[2].downcase)
62
84
  else
63
- raise OptionParser::InvalidArgument, "#{option_name} has an unsupported duration suffix"
85
+ hours, minutes, secs = compound.captures.map(&:to_i)
86
+ (hours * 3600 + minutes * 60 + secs).to_f
64
87
  end
65
-
66
- seconds = amount * multiplier
67
- raise OptionParser::InvalidArgument, "#{option_name} must be greater than 0" if seconds <= 0.0
88
+ unless seconds.finite? && seconds.positive?
89
+ raise OptionParser::InvalidArgument, "#{option_name} must be finite and greater than 0"
90
+ end
68
91
 
69
92
  seconds
70
93
  end
@@ -410,12 +433,69 @@ module Harnex
410
433
  COMPLETION_OUTCOMES.map { |outcome| completion_marker_path(repo_root, id, outcome) }
411
434
  end
412
435
 
436
+ # The external primary that owns dispatches launched from this shell: Pi's
437
+ # shell tool sets PI_SESSION_ID, Claude Code's Bash sets
438
+ # CLAUDE_CODE_SESSION_ID (Pi wins if both leaked in). A nested Harnex
439
+ # worker (HARNEX_ID) is never an eligible owner of its own children, and a
440
+ # runner the outer launcher already resolved (tmux hand-off) ignores
441
+ # ambient ids that may be the tmux server's stale environment.
442
+ def ambient_owner_id(env = ENV)
443
+ return nil unless env["HARNEX_ID"].to_s.strip.empty?
444
+ return nil if env["HARNEX_OWNER_RESOLVED"] == "1"
445
+
446
+ %w[PI_SESSION_ID CLAUDE_CODE_SESSION_ID].each do |key|
447
+ value = env[key].to_s.strip
448
+ return value unless value.empty?
449
+ end
450
+ nil
451
+ end
452
+
453
+ # How to invoke this harnex in a printed hint: the checkout's bin when
454
+ # running from source, plain `harnex` for the installed gem.
455
+ def cli_command
456
+ lib = File.expand_path("..", __dir__)
457
+ return "harnex" if Gem.path.any? { |dir| lib.start_with?(File.join(File.expand_path(dir), "")) }
458
+
459
+ File.expand_path("../bin/harnex", lib)
460
+ end
461
+
462
+ OWNER_TAG = /\A[A-Za-z0-9._-]{1,64}\z/
463
+
464
+ # #85: a subagent shares its parent's session id; a tag gives it its own
465
+ # owner ("<base>/<tag>"), so its stream holds only the lanes it launched.
466
+ def tagged_owner_id(base, tag)
467
+ raise ArgumentError, "owner tag must be 1-64 letters, digits, '.', '_' or '-'" unless tag.to_s.match?(OWNER_TAG)
468
+
469
+ base = base.to_s.strip
470
+ base.empty? ? tag.to_s : "#{base}/#{tag}"
471
+ end
472
+
473
+ def owned_notifications_dir(owner_id)
474
+ File.join(STATE_DIR, "notifications", Digest::SHA256.hexdigest(owner_id.to_s))
475
+ end
476
+
477
+ # Both keys are opaque identities, not paths or reusable dispatch names.
478
+ # Records are retained until the owner reconciles them; normal id reuse and
479
+ # marker cleanup must never delete another attempt's pending delivery.
480
+ def owned_notification_path(owner_id, session_id)
481
+ File.join(STATE_DIR, "notifications", Digest::SHA256.hexdigest(owner_id.to_s),
482
+ "#{Digest::SHA256.hexdigest(session_id.to_s)}.json")
483
+ end
484
+
413
485
  def output_log_path(repo_root, id)
414
486
  output_dir = File.join(STATE_DIR, "output")
415
487
  FileUtils.mkdir_p(output_dir)
416
488
  File.join(output_dir, "#{session_file_slug(repo_root, id)}.log")
417
489
  end
418
490
 
491
+ # The worker's final reply for one turn (#85): the full text behind the
492
+ # bounded `final_message` in events, wait output and owner events.
493
+ def final_message_path(repo_root, id, turn)
494
+ output_dir = File.join(STATE_DIR, "output")
495
+ FileUtils.mkdir_p(output_dir)
496
+ File.join(output_dir, "#{session_file_slug(repo_root, id)}.turn-#{turn}.md")
497
+ end
498
+
419
499
  def events_log_path(repo_root, id)
420
500
  events_dir = File.join(STATE_DIR, "events")
421
501
  FileUtils.mkdir_p(events_dir)
@@ -455,6 +535,11 @@ module Harnex
455
535
  rescue JSON::ParserError
456
536
  FileUtils.rm_f(path)
457
537
  nil
538
+ rescue Errno::ENOENT
539
+ # A peer session finalized between the glob and the read. Treat it as
540
+ # gone, exactly as if it had been removed before the scan; raising here
541
+ # would kill observers watching a different, still-live session.
542
+ nil
458
543
  end
459
544
  end
460
545
 
@@ -585,10 +670,10 @@ module Harnex
585
670
  false
586
671
  end
587
672
 
588
- def build_adapter(cli, argv, legacy_pty: false)
673
+ def build_adapter(cli, argv)
589
674
  raise ArgumentError, "cli is required" if cli.to_s.strip.empty?
590
675
 
591
- Adapters.build(cli, argv, legacy_pty: legacy_pty)
676
+ Adapters.build(cli, argv)
592
677
  end
593
678
 
594
679
  def session_cli(session)