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
@@ -1,6 +1,7 @@
1
1
  require "json"
2
2
  require "optparse"
3
3
  require "shellwords"
4
+ require "stringio"
4
5
 
5
6
  module Harnex
6
7
  class Runner
@@ -31,10 +32,10 @@ module Harnex
31
32
 
32
33
  KNOWN_FLAGS = %w[
33
34
  --id --description --detach --tmux --host --port --watch --watch-file
34
- --stall-after --max-resumes --preset --context --meta
35
- --artifact-report --validation-report --cwd --root --timeout --inbox-ttl
36
- --require-artifact-report --require-attribution --auto-stop --on-done --fast --legacy-pty
37
- --allow-live-parent --help
35
+ --stall-after --max-resumes --preset --context --context-file --context-section
36
+ --meta --meta-file --artifact-report --validation-report --cwd --root --timeout --inbox-ttl
37
+ --require-artifact-report --require-attribution --auto-stop --on-done --max-runtime
38
+ --allow-live-parent --final-gate --wait-done --wait-timeout --owner-tag --help
38
39
  ].concat(TELEMETRY_FLAGS.keys).freeze
39
40
 
40
41
  # Attempt kinds that redo the parent's work; dispatching one while the
@@ -42,8 +43,9 @@ module Harnex
42
43
  LIVE_PARENT_GUARDED_KINDS = %w[retry fix fallback superseding].freeze
43
44
  VALUE_FLAGS = %w[
44
45
  --id --description --host --port --watch --watch-file --stall-after
45
- --max-resumes --preset --context --meta --artifact-report
46
- --validation-report --on-done --cwd --root --timeout --inbox-ttl
46
+ --max-resumes --preset --context --context-file --context-section --meta
47
+ --meta-file --artifact-report --validation-report --on-done --max-runtime --cwd --root --timeout --inbox-ttl
48
+ --final-gate --wait-timeout --owner-tag
47
49
  ].concat(TELEMETRY_FLAGS.keys).freeze
48
50
 
49
51
  def self.usage(program_name = "harnex run")
@@ -63,11 +65,24 @@ module Harnex
63
65
  --preset NAME Watch preset: impl, plan, gate (requires --watch)
64
66
  --watch-file PATH Auto-send a file-change hook on modification
65
67
  --context TEXT Inject as the initial prompt (prepends session header)
68
+ --context-file PATH
69
+ Read the initial prompt from PATH; refuses an empty result.
70
+ Records meta.context_file and meta.context_sha256 (SHA-256
71
+ of the text actually sent, i.e. the trimmed section)
72
+ --context-section TEXT
73
+ With --context-file: send only the section after the first
74
+ line starting with TEXT (a heading runs to the next heading
75
+ of its level or higher; a plain marker line to end of file)
66
76
  --auto-stop Stop after the first accepted task completion from --context
77
+ --wait-done With --tmux/--detach: block until the first turn's result
78
+ and print it with the launch fields (the worker's reply is
79
+ turn_result.final_message). Exit codes of wait --until done
80
+ --wait-timeout DUR Cap --wait-done (default: none); on 124 the output has
81
+ `resume`, the command that keeps waiting
67
82
  --on-done CMD Launch /bin/sh -c CMD once at the first typed work result
68
- --fast (codex only) Use Codex service_tier="fast".
69
- Default Codex runs force service_tier="flex".
83
+ --max-runtime DUR Fixed worker runtime budget (e.g. 30m); not a watch timeout
70
84
  --meta JSON Attach parsed JSON metadata to the started event
85
+ --meta-file PATH Read --meta JSON from PATH (inline --meta keys win)
71
86
  --artifact-report PATH
72
87
  Override the harness-authored observed-state receipt path
73
88
  --validation-report PATH
@@ -75,6 +90,11 @@ module Harnex
75
90
  --require-artifact-report
76
91
  Compatibility strict-proof flag; a default harness receipt
77
92
  path is used when no explicit path is provided
93
+ --final-gate CMD Declare a final acceptance command (repeatable; or meta
94
+ "final_gates": [...]). The receipt's validation.status
95
+ then reports the last observed exit of each gate,
96
+ matched by exact command string; earlier failures
97
+ stay visible as validation.commands_had_failures
78
98
  --project-id ID Queue telemetry project id (first-class flags override --meta)
79
99
  --queue-id ID Queue telemetry queue id
80
100
  --entry-id ID Queue telemetry entry id
@@ -105,7 +125,11 @@ module Harnex
105
125
  --orchestration-role ROLE
106
126
  primary or worker; defaults to worker in rollups when omitted
107
127
  --orchestration-session-id ID
108
- External primary session id to preserve in rollups
128
+ External primary session id for rollups and owned
129
+ completion delivery (default: shell PI_SESSION_ID)
130
+ --owner-tag TAG Own this dispatch as "<owner>/<TAG>" (owner: the session id
131
+ below). A Claude subagent shares its parent's session id;
132
+ a tag gives it its own `watch --owner --owner-tag TAG` stream
109
133
  --orchestration-rotation-reason TEXT
110
134
  Clean rotation/recovery reason for the generation
111
135
  --require-attribution
@@ -114,22 +138,22 @@ module Harnex
114
138
  --root DIR Override harnex session/root attribution without changing child cwd
115
139
  --timeout SECS Max seconds to wait for detached registration (default: #{DEFAULT_TIMEOUT})
116
140
  --inbox-ttl SECS Expire queued inbox messages after SECS (default: #{Inbox::DEFAULT_TTL})
117
- --legacy-pty (codex only) Use the legacy PTY adapter instead of
118
- the JSON-RPC `app-server` adapter. Long-term
119
- supported fallback for interactive/TUI use; JSON-RPC
120
- remains the default for autonomous dispatches.
121
141
  -h, --help Show this help
122
142
 
123
143
  Notes:
124
144
  Compatibility: `--watch PATH` and `--watch=PATH` still configure file-hook mode.
125
145
  Bare `--watch` enables the babysitter.
126
- --auto-stop requires --context. Structured Codex turns only count as
127
- accepted completion after command/tool activity or a Git delta.
146
+ --auto-stop requires --context (or --context-file).
128
147
  --on-done CMD is trusted local shell input. Do not put secrets in CMD;
129
148
  command lines may be visible to local process inspection.
149
+ --max-runtime is opt-in and never resets on prompts/retries/activity.
150
+ It terminates the worker, unlike watch --max-wait which only stops waiting.
130
151
  Every dispatch gets a harness-authored receipt. Workers may write only
131
152
  optional claims to HARNEX_ARTIFACT_CLAIMS_PATH; claims never accept work.
132
153
  Explicit --stall-after/--max-resumes values override --preset defaults.
154
+ --final-gate is receipt diagnostics, not proof: replay the gate commands
155
+ yourself before accepting work. Only Pi observes command exits, so only
156
+ Pi dispatches can pass a gate; PTY dispatches report unknown.
133
157
  CLIs with smart prompt detection: #{Adapters.known.join(', ')}
134
158
  Any other CLI name is launched with generic wrapping.
135
159
  Wrapper options may appear before or after <cli>.
@@ -138,7 +162,7 @@ module Harnex
138
162
  #{program_name} pi --id pi-i-42 --tmux pi-i-42 --context "Read /tmp/task-impl-42.md"
139
163
  #{program_name} pi --id pi-i-42 --tmux pi-i-42 --context "Read /tmp/task-impl-42.md" --auto-stop
140
164
  #{program_name} pi --id pi-i-42 --watch --preset impl --context "Read /tmp/task-impl-42.md"
141
- #{program_name} codex --cwd /tmp/public-bundle --id eval-001 --context "Read README.md and write OUTPUT.md" --auto-stop
165
+ #{program_name} pi --cwd ../wt-42 --root . --id pi-i-42 --tmux pi-i-42 --context-file /tmp/task-42.md --auto-stop --wait-done --wait-timeout 9m
142
166
  #{program_name} pi --id pi-r-64 --context 'Optionally write review claims to $HARNEX_ARTIFACT_CLAIMS_PATH' --auto-stop
143
167
  #{program_name} pi --project-id harnex --queue-id queue-005 --entry-id SP-4 --phase implement --intent queue-work --require-attribution --context "Implement SP-4"
144
168
  #{program_name} claude --id cl-r-42 --tmux cl-r-42 --description "Review task 42"
@@ -149,10 +173,8 @@ module Harnex
149
173
  --watch is foreground-only; do not combine it with --tmux or --detach.
150
174
  Use -- before child CLI flags when a flag could be parsed by harnex.
151
175
  Pi RPC requires Pi >= 0.80.4 (`harnex doctor --adapter pi`). Prefer
152
- provider/model for Harnex --model, and explicitly pass child
153
- --approve or --no-approve for deterministic project trust.
154
- Codex JSON-RPC: pass model as `-c model=NAME`, not `-m NAME`. The
155
- legacy PTY adapter (--legacy-pty) accepts `-m`.
176
+ provider/model for Harnex --model. Pi runs with --no-approve
177
+ (project-local Pi resources ignored) unless you pass -- --approve.
156
178
  TEXT
157
179
  end
158
180
 
@@ -172,7 +194,10 @@ module Harnex
172
194
  preset: nil,
173
195
  watch: nil,
174
196
  context: nil,
197
+ context_file: nil,
198
+ context_section: nil,
175
199
  meta: nil,
200
+ meta_file: nil,
176
201
  telemetry: {},
177
202
  require_attribution: false,
178
203
  artifact_report: nil,
@@ -181,14 +206,17 @@ module Harnex
181
206
  root: nil,
182
207
  auto_stop: false,
183
208
  on_done: nil,
209
+ max_runtime_s: nil,
184
210
  allow_live_parent: false,
185
211
  detach: false,
186
212
  tmux: false,
187
213
  tmux_name: nil,
188
214
  timeout: DEFAULT_TIMEOUT,
189
215
  inbox_ttl: default_inbox_ttl,
190
- fast: false,
191
- legacy_pty: false,
216
+ final_gates: [],
217
+ wait_done: false,
218
+ wait_timeout_s: nil,
219
+ owner_tag: nil,
192
220
  help: false
193
221
  }
194
222
  end
@@ -201,9 +229,14 @@ module Harnex
201
229
  end
202
230
 
203
231
  raise OptionParser::MissingArgument, "cli" if cli_name.nil?
232
+ apply_meta_file!
233
+ apply_context_file!
204
234
  validate_auto_stop_context!
235
+ validate_wait_done!
205
236
  validate_required_artifact_report!
206
237
  apply_telemetry_options!
238
+ apply_owner_tag!
239
+ apply_final_gates!
207
240
  validate_attempt_metadata!
208
241
  validate_orchestration_metadata!
209
242
  validate_required_attribution!
@@ -214,8 +247,8 @@ module Harnex
214
247
  @options[:id] ||= Harnex.generate_id(repo_root)
215
248
  validate_unique_id!(repo_root)
216
249
  validate_live_parent_guard!(repo_root)
217
- effective_child_args = apply_context(apply_codex_service_tier(cli_name, child_args))
218
- adapter = Harnex.build_adapter(cli_name, effective_child_args, legacy_pty: @options[:legacy_pty])
250
+ effective_child_args = apply_context(child_args)
251
+ adapter = Harnex.build_adapter(cli_name, effective_child_args)
219
252
  @options[:detach] = true if @options[:tmux]
220
253
  validate_watch_mode!
221
254
  resolve_watch_preset!
@@ -263,15 +296,25 @@ module Harnex
263
296
 
264
297
  def run_in_tmux(cli_name, child_args, repo_root)
265
298
  harnex_bin = File.expand_path("../../../bin/harnex", __dir__)
266
- tmux_cmd = [harnex_bin, "run", cli_name]
299
+ # The owner was resolved here, before tmux; the inner runner must not
300
+ # adopt an ambient id from the tmux server's (possibly stale) env.
301
+ tmux_cmd = ["env", "HARNEX_OWNER_RESOLVED=1", harnex_bin, "run", cli_name]
267
302
  tmux_cmd += ["--id", @options[:id]]
268
303
  tmux_cmd += ["--description", @options[:description]] if @options[:description]
269
304
  tmux_cmd += ["--host", @options[:host]]
270
305
  tmux_cmd += ["--port", @options[:port].to_s] if @options[:port]
271
306
  tmux_cmd += ["--watch-file", @options[:watch]] if @options[:watch]
272
- tmux_cmd += ["--context", @options[:context]] if @options[:context]
307
+ # A brief file travels by path: tmux refuses commands over ~16 KB, and
308
+ # the inner runner re-reads it under the same rules.
309
+ if @options[:context_file]
310
+ tmux_cmd += ["--context-file", File.expand_path(@options[:context_file], @launch_cwd)]
311
+ tmux_cmd += ["--context-section", @options[:context_section]] if @options[:context_section]
312
+ elsif @options[:context]
313
+ tmux_cmd += ["--context", @options[:context]]
314
+ end
273
315
  tmux_cmd << "--auto-stop" if @options[:auto_stop]
274
316
  tmux_cmd += ["--on-done", @options[:on_done]] if @options[:on_done]
317
+ tmux_cmd += ["--max-runtime", @options[:max_runtime_s].to_s] if @options[:max_runtime_s]
275
318
  tmux_cmd += ["--meta", JSON.generate(@options[:meta])] if @options[:meta]
276
319
  @options[:telemetry].each do |key, value|
277
320
  flag = TELEMETRY_KEYS_TO_FLAGS[key]
@@ -284,8 +327,6 @@ module Harnex
284
327
  tmux_cmd += ["--cwd", @options[:cwd]] if @options[:cwd]
285
328
  tmux_cmd += ["--root", @options[:root]] if @options[:root]
286
329
  tmux_cmd += ["--inbox-ttl", @options[:inbox_ttl].to_s]
287
- tmux_cmd << "--fast" if @options[:fast]
288
- tmux_cmd += ["--legacy-pty"] if @options[:legacy_pty]
289
330
  tmux_cmd += ["--"] + child_args unless child_args.empty?
290
331
 
291
332
  window_name = @options[:tmux_name] || @options[:id]
@@ -313,11 +354,14 @@ module Harnex
313
354
  port: registry["port"],
314
355
  mode: "tmux",
315
356
  window: window_name,
357
+ tmux_target: registry["tmux_target"],
316
358
  output_log_path: Harnex.output_log_path(repo_root, @options[:id]),
317
359
  artifact_report_path: registry["artifact_report_path"],
318
360
  artifact_claims_path: registry["artifact_claims_path"]
319
361
  }
320
362
  payload[:description] = @options[:description] if @options[:description]
363
+ return wait_for_first_result(payload, repo_root) if @options[:wait_done]
364
+
321
365
  puts JSON.generate(payload)
322
366
  0
323
367
  end
@@ -359,10 +403,35 @@ module Harnex
359
403
  artifact_claims_path: registry["artifact_claims_path"]
360
404
  }
361
405
  payload[:description] = @options[:description] if @options[:description]
406
+ if @options[:wait_done] && emit_payload
407
+ return { ok: true, exit_code: wait_for_first_result(payload, repo_root), registry: registry, payload: payload }
408
+ end
409
+
362
410
  puts JSON.generate(payload) if emit_payload
363
411
  { ok: true, exit_code: 0, registry: registry, payload: payload }
364
412
  end
365
413
 
414
+ # One call from launch to the first turn's result: a Claude Code subagent
415
+ # cannot be woken later, so it blocks here. Exit codes follow
416
+ # `wait --until done`; a timeout says how to keep waiting.
417
+ def wait_for_first_result(payload, repo_root)
418
+ argv = ["--id", @options[:id], "--repo", repo_root, "--until", "done"]
419
+ argv += ["--timeout", @options[:wait_timeout_s].to_s] if @options[:wait_timeout_s]
420
+ out = StringIO.new
421
+ exit_code = Waiter.new(argv, out: out, err: $stderr).run
422
+ turn = begin
423
+ JSON.parse(out.string.lines.last.to_s)
424
+ rescue JSON::ParserError
425
+ {}
426
+ end
427
+ result = payload.merge(ok: turn["ok"] == true, wait_result: turn["wait_result"], turn_result: turn)
428
+ if exit_code == Waiter::DONE_EXIT_TIMEOUT
429
+ result[:resume] = "#{Harnex.cli_command} wait --id #{@options[:id]} --repo #{Shellwords.escape(repo_root)} --until done --timeout 9m"
430
+ end
431
+ puts JSON.generate(result)
432
+ exit_code
433
+ end
434
+
366
435
  private
367
436
 
368
437
  def validate_watch_mode!
@@ -417,7 +486,8 @@ module Harnex
417
486
  metadata = @options[:meta].is_a?(Hash) ? @options[:meta] : {}
418
487
  phase = metadata["phase"].to_s
419
488
  allowlist = phase_config.fetch("allowlist")
420
- return if allowlist.include?(phase)
489
+ # `harnex preflight` tags its own probe; repo phase policy governs work.
490
+ return if allowlist.include?(phase) || phase == Preflight::PHASE
421
491
 
422
492
  policy = phase_config.fetch("policy")
423
493
  message = "harnex run: meta.phase #{phase.empty? ? '(none)' : phase.inspect} " \
@@ -463,13 +533,14 @@ module Harnex
463
533
  inbox_ttl: @options[:inbox_ttl],
464
534
  auto_stop: @options[:auto_stop],
465
535
  on_done: @options[:on_done],
536
+ max_runtime_s: @options[:max_runtime_s],
466
537
  launch_cwd: history_cwd,
467
538
  child_cwd: session_child_cwd
468
539
  )
469
540
  end
470
541
 
471
542
  def adapter_repo_path(cli_name, child_args)
472
- Harnex.build_adapter(cli_name, child_args, legacy_pty: @options[:legacy_pty]).infer_repo_path(child_args)
543
+ Harnex.build_adapter(cli_name, child_args).infer_repo_path(child_args)
473
544
  end
474
545
 
475
546
  def resolve_run_root(cli_name, child_args)
@@ -628,24 +699,67 @@ module Harnex
628
699
  @options[:context] = required_option_value(arg, argv[index])
629
700
  when /\A--context=(.+)\z/
630
701
  @options[:context] = required_option_value("--context", Regexp.last_match(1))
702
+ when "--context-file"
703
+ index += 1
704
+ @options[:context_file] = required_option_value(arg, argv[index])
705
+ when /\A--context-file=(.+)\z/
706
+ @options[:context_file] = required_option_value("--context-file", Regexp.last_match(1))
707
+ when "--context-section"
708
+ index += 1
709
+ @options[:context_section] = required_option_value(arg, argv[index])
710
+ when /\A--context-section=(.+)\z/
711
+ @options[:context_section] = required_option_value("--context-section", Regexp.last_match(1))
631
712
  when "--auto-stop"
632
713
  @options[:auto_stop] = true
714
+ when "--wait-done"
715
+ @options[:wait_done] = true
716
+ when "--owner-tag"
717
+ index += 1
718
+ @options[:owner_tag] = required_option_value(arg, argv[index])
719
+ when /\A--owner-tag=(.+)\z/
720
+ @options[:owner_tag] = Regexp.last_match(1)
721
+ when "--wait-timeout"
722
+ index += 1
723
+ @options[:wait_timeout_s] = Harnex.parse_duration_seconds(
724
+ required_option_value(arg, argv[index]), option_name: "--wait-timeout"
725
+ )
726
+ when /\A--wait-timeout=(.+)\z/
727
+ @options[:wait_timeout_s] = Harnex.parse_duration_seconds(
728
+ Regexp.last_match(1), option_name: "--wait-timeout"
729
+ )
633
730
  when "--on-done"
634
731
  index += 1
635
732
  @options[:on_done] = required_option_value(arg, argv[index])
636
733
  when /\A--on-done=(.+)\z/
637
734
  @options[:on_done] = required_option_value("--on-done", Regexp.last_match(1))
735
+ when "--max-runtime"
736
+ index += 1
737
+ @options[:max_runtime_s] = Harnex.parse_duration_seconds(
738
+ required_option_value(arg, argv[index]), option_name: "--max-runtime"
739
+ )
740
+ when /\A--max-runtime=(.*)\z/
741
+ @options[:max_runtime_s] = Harnex.parse_duration_seconds(
742
+ Regexp.last_match(1), option_name: "--max-runtime"
743
+ )
638
744
  when "--allow-live-parent"
639
745
  @options[:allow_live_parent] = true
640
746
  when "--require-attribution"
641
747
  @options[:require_attribution] = true
642
- when "--fast"
643
- @options[:fast] = true
748
+ when "--final-gate"
749
+ index += 1
750
+ @options[:final_gates] << required_option_value(arg, argv[index])
751
+ when /\A--final-gate=(.+)\z/
752
+ @options[:final_gates] << required_option_value("--final-gate", Regexp.last_match(1))
644
753
  when "--meta"
645
754
  index += 1
646
755
  @options[:meta] = parse_meta(required_option_value(arg, argv[index]))
647
756
  when /\A--meta=(.+)\z/
648
757
  @options[:meta] = parse_meta(required_option_value("--meta", Regexp.last_match(1)))
758
+ when "--meta-file"
759
+ index += 1
760
+ @options[:meta_file] = required_option_value(arg, argv[index])
761
+ when /\A--meta-file=(.+)\z/
762
+ @options[:meta_file] = required_option_value("--meta-file", Regexp.last_match(1))
649
763
  when *TELEMETRY_FLAGS.keys
650
764
  index += 1
651
765
  @options[:telemetry][TELEMETRY_FLAGS.fetch(arg)] = required_option_value(arg, argv[index])
@@ -681,8 +795,6 @@ module Harnex
681
795
  @options[:inbox_ttl] = Float(required_option_value(arg, argv[index]))
682
796
  when /\A--inbox-ttl=(.+)\z/
683
797
  @options[:inbox_ttl] = Float(required_option_value("--inbox-ttl", Regexp.last_match(1)))
684
- when "--legacy-pty"
685
- @options[:legacy_pty] = true
686
798
  else
687
799
  reject_unknown_long_flag!(arg) if unknown_long_flag?(arg)
688
800
  if cli_name.nil?
@@ -737,13 +849,13 @@ module Harnex
737
849
  case arg
738
850
  when "--"
739
851
  return false
740
- when "-h", "--help", "--detach", "--tmux", "--auto-stop", "--require-artifact-report", "--require-attribution", "--fast", "--legacy-pty", "--allow-live-parent"
852
+ when "-h", "--help", "--detach", "--tmux", "--auto-stop", "--require-artifact-report", "--require-attribution", "--allow-live-parent", "--wait-done"
741
853
  nil
742
854
  when /\A--tmux=/
743
855
  nil
744
856
  when *VALUE_FLAGS
745
857
  index += 1
746
- when /\A--(?:id|description|host|port|watch|watch-file|stall-after|max-resumes|context|meta|artifact-report|validation-report|on-done|cwd|root|timeout|inbox-ttl)=/
858
+ when /\A--(?:id|description|host|port|watch|watch-file|stall-after|max-resumes|context|context-file|context-section|meta|meta-file|artifact-report|validation-report|on-done|max-runtime|cwd|root|timeout|inbox-ttl|final-gate|wait-timeout|owner-tag)=/
747
859
  nil
748
860
  when telemetry_equals_regex
749
861
  nil
@@ -763,9 +875,10 @@ module Harnex
763
875
  arg == "-h" ||
764
876
  arg.start_with?(
765
877
  "--id=", "--description=", "--tmux=", "--host=", "--port=", "--watch=", "--watch-file=",
766
- "--stall-after=", "--max-resumes=", "--preset=", "--context=", "--meta=",
767
- "--artifact-report=", "--validation-report=", "--on-done=", "--cwd=", "--root=", "--timeout=", "--inbox-ttl=",
768
- *TELEMETRY_EQUALS_PREFIXES
878
+ "--stall-after=", "--max-resumes=", "--preset=", "--context=", "--context-file=",
879
+ "--context-section=", "--meta=", "--meta-file=",
880
+ "--artifact-report=", "--validation-report=", "--on-done=", "--max-runtime=", "--cwd=", "--root=", "--timeout=", "--inbox-ttl=",
881
+ "--final-gate=", "--wait-timeout=", "--owner-tag=", *TELEMETRY_EQUALS_PREFIXES
769
882
  )
770
883
  end
771
884
 
@@ -787,6 +900,17 @@ module Harnex
787
900
  @options[:max_resumes] = preset[:max_resumes] unless @options[:max_resumes_explicit]
788
901
  end
789
902
 
903
+ def validate_wait_done!
904
+ if @options[:wait_timeout_s] && !@options[:wait_done]
905
+ raise OptionParser::InvalidOption, "harnex run: --wait-timeout requires --wait-done"
906
+ end
907
+ return unless @options[:wait_done]
908
+ raise OptionParser::InvalidOption, "harnex run: --wait-done requires --context or --context-file" unless @options[:context]
909
+ return if @options[:tmux] || @options[:detach]
910
+
911
+ raise OptionParser::InvalidOption, "harnex run: --wait-done requires --tmux or --detach"
912
+ end
913
+
790
914
  def validate_auto_stop_context!
791
915
  return unless @options[:auto_stop]
792
916
  return if @options[:context]
@@ -801,12 +925,91 @@ module Harnex
801
925
  true
802
926
  end
803
927
 
928
+ # Applied before --context validation so --auto-stop sees the file's text.
929
+ def apply_meta_file!
930
+ return unless @options[:meta_file]
931
+
932
+ path = File.expand_path(@options[:meta_file], @launch_cwd)
933
+ unless File.file?(path)
934
+ raise OptionParser::InvalidOption, "harnex run: --meta-file not found: #{@options[:meta_file]}"
935
+ end
936
+
937
+ from_file = parse_meta(File.read(path), option_name: "--meta-file")
938
+ @options[:meta] = from_file.merge(@options[:meta] || {})
939
+ end
940
+
941
+ # --context-file (#83): the brief's path and the hash of the text actually
942
+ # sent ride in meta, so the started event and dispatch rows name the brief
943
+ # that launched the lane. An explicit meta task_brief wins.
944
+ def apply_context_file!
945
+ if @options[:context_section] && !@options[:context_file]
946
+ raise OptionParser::InvalidOption, "harnex run: --context-section requires --context-file"
947
+ end
948
+ return unless @options[:context_file]
949
+ if @options[:context]
950
+ raise OptionParser::InvalidOption, "harnex run: use --context or --context-file, not both"
951
+ end
952
+
953
+ brief = ContextFile.load(
954
+ File.expand_path(@options[:context_file], @launch_cwd),
955
+ section: @options[:context_section]
956
+ )
957
+ @options[:context] = brief[:text]
958
+ provenance = { "context_file" => brief[:path], "context_sha256" => brief[:sha256] }
959
+ provenance["context_section"] = brief[:section] if brief[:section]
960
+ metadata = @options[:meta].is_a?(Hash) ? @options[:meta] : {}
961
+ @options[:meta] = { "task_brief" => brief[:path] }.merge(metadata).merge(provenance)
962
+ rescue ContextFile::Error => e
963
+ raise OptionParser::InvalidOption, "harnex run: #{e.message}"
964
+ end
965
+
804
966
  def apply_telemetry_options!
805
967
  explicit = @options[:telemetry]
806
- return if explicit.empty? && @options[:meta].is_a?(Hash)
807
- return if explicit.empty?
968
+ # A nested Harnex worker's session id identifies the worker itself,
969
+ # which is intentionally not an eligible primary consumer. Nested
970
+ # orchestration must name its external primary explicitly.
971
+ primary = Harnex.ambient_owner_id.to_s
972
+ return if explicit.empty? && primary.empty?
973
+
974
+ # Capture the invoker before tmux switches to the server environment.
975
+ # --meta / explicit flags win, including when the inner runner inherits
976
+ # a stale PI_SESSION_ID from that server.
977
+ defaults = primary.empty? ? {} : { "orchestration_session_id" => primary }
978
+ @options[:meta] = defaults.merge(@options[:meta] || {}).merge(explicit)
979
+ end
980
+
981
+ # Resolved once, before tmux: the inner runner receives the tagged id in
982
+ # meta and never re-derives it.
983
+ def apply_owner_tag!
984
+ return unless @options[:owner_tag]
985
+
986
+ metadata = @options[:meta].is_a?(Hash) ? @options[:meta] : {}
987
+ base = metadata["orchestration_session_id"] || Harnex.ambient_owner_id
988
+ tagged = Harnex.tagged_owner_id(base, @options[:owner_tag])
989
+ @options[:meta] = metadata.merge("orchestration_session_id" => tagged)
990
+ rescue ArgumentError => e
991
+ raise OptionParser::InvalidArgument, "harnex run: --owner-tag: #{e.message}"
992
+ end
993
+
994
+ # Gates travel in meta so tmux/detached children and dispatch rows carry
995
+ # them without a second transport. --final-gate appends to meta's list.
996
+ def apply_final_gates!
997
+ metadata = @options[:meta].is_a?(Hash) ? @options[:meta] : {}
998
+ declared = metadata["final_gates"]
999
+ unless declared.nil? || (declared.is_a?(Array) && declared.all? { |gate| gate.is_a?(String) })
1000
+ raise OptionParser::InvalidOption, "harnex run: meta final_gates must be an array of command strings"
1001
+ end
1002
+ return if @options[:final_gates].empty?
1003
+
1004
+ gates = Array(declared) + @options[:final_gates]
1005
+ if gates.any? { |gate| gate.strip.empty? }
1006
+ raise OptionParser::InvalidOption, "harnex run: --final-gate needs a non-empty command"
1007
+ end
1008
+ if gates.uniq.length > ArtifactReport::MAX_FINAL_GATES
1009
+ raise OptionParser::InvalidOption, "harnex run: at most #{ArtifactReport::MAX_FINAL_GATES} final gates"
1010
+ end
808
1011
 
809
- @options[:meta] = (@options[:meta].is_a?(Hash) ? @options[:meta].dup : {}).merge(explicit)
1012
+ @options[:meta] = metadata.merge("final_gates" => gates.uniq)
810
1013
  end
811
1014
 
812
1015
  def validate_attempt_metadata!
@@ -845,25 +1048,6 @@ module Harnex
845
1048
  value.nil? || value.to_s.strip.empty?
846
1049
  end
847
1050
 
848
- def apply_codex_service_tier(cli_name, child_args)
849
- return child_args unless cli_name.to_s == "codex"
850
- return child_args if child_service_tier_config?(child_args)
851
-
852
- child_args + ["-c", "service_tier=\"#{@options[:fast] ? 'fast' : 'flex'}\""]
853
- end
854
-
855
- def child_service_tier_config?(child_args)
856
- child_args.each_with_index.any? do |arg, index|
857
- text = arg.to_s
858
- text.start_with?("service_tier=") ||
859
- text.start_with?("service_tier.") ||
860
- text == "-c" && child_args[index + 1].to_s.start_with?("service_tier") ||
861
- text == "--config" && child_args[index + 1].to_s.start_with?("service_tier") ||
862
- text.start_with?("-cservice_tier") ||
863
- text.start_with?("--config=service_tier")
864
- end
865
- end
866
-
867
1051
  def parse_non_negative_integer(value, option_name:)
868
1052
  integer = Integer(value)
869
1053
  raise OptionParser::InvalidArgument, "#{option_name} must be 0 or greater" if integer.negative?
@@ -880,13 +1064,13 @@ module Harnex
880
1064
  raise OptionParser::InvalidArgument, "#{option_name} must be an existing directory: #{value}"
881
1065
  end
882
1066
 
883
- def parse_meta(value)
1067
+ def parse_meta(value, option_name: "--meta")
884
1068
  parsed = JSON.parse(value)
885
1069
  return parsed if parsed.is_a?(Hash)
886
1070
 
887
- raise OptionParser::InvalidOption, "--meta must be a JSON object"
1071
+ raise OptionParser::InvalidOption, "#{option_name} must be a JSON object"
888
1072
  rescue JSON::ParserError => e
889
- raise OptionParser::InvalidOption, "--meta must be valid JSON: #{e.message}"
1073
+ raise OptionParser::InvalidOption, "#{option_name} must be valid JSON: #{e.message}"
890
1074
  end
891
1075
 
892
1076
  def resolve_artifact_report(repo_root)