hexaqueue-cli 0.6.0__tar.gz → 0.8.0__tar.gz

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 (30) hide show
  1. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/PKG-INFO +1 -1
  2. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/pyproject.toml +1 -1
  3. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/pyproject.toml.orig +1 -1
  4. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/__init__.py +2 -0
  5. hexaqueue_cli-0.8.0/src/hexaqueue_cli/commands/cluster.py +983 -0
  6. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/main.py +2 -0
  7. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/README.md +0 -0
  8. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/__init__.py +0 -0
  9. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/adapters/__init__.py +0 -0
  10. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/adapters/local.py +0 -0
  11. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/adapters/presenter.py +0 -0
  12. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/admin.py +0 -0
  13. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/collateral.py +0 -0
  14. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/mcp.py +0 -0
  15. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/node.py +0 -0
  16. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/run.py +0 -0
  17. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/scanner.py +0 -0
  18. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/server.py +0 -0
  19. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/suite.py +0 -0
  20. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/commands/workflow.py +0 -0
  21. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/domain/__init__.py +0 -0
  22. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/domain/models.py +0 -0
  23. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/domain/options.py +0 -0
  24. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/domain/parser.py +0 -0
  25. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/domain/session.py +0 -0
  26. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/infra/__init__.py +0 -0
  27. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/infra/bootstrap.py +0 -0
  28. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/infra/options.py +0 -0
  29. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/ports/__init__.py +0 -0
  30. {hexaqueue_cli-0.6.0 → hexaqueue_cli-0.8.0}/src/hexaqueue_cli/ports/client.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hexaqueue-cli
3
- Version: 0.6.0
3
+ Version: 0.8.0
4
4
  Summary: Hexaqueue CLI - Modern developer and operator terminal interface
5
5
  Author: Richard West
6
6
  Author-email: Richard West <dopplereffect.us@gmail.com>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "hexaqueue-cli"
3
- version = "0.6.0"
3
+ version = "0.8.0"
4
4
  description = "Hexaqueue CLI - Modern developer and operator terminal interface"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "hexaqueue-cli"
3
- version = "0.6.0"
3
+ version = "0.8.0"
4
4
  description = "Hexaqueue CLI - Modern developer and operator terminal interface"
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -5,6 +5,7 @@ Notes/Architectural Intent:
5
5
  """
6
6
 
7
7
  from hexaqueue_cli.commands.admin import app as admin_app
8
+ from hexaqueue_cli.commands.cluster import app as cluster_app
8
9
  from hexaqueue_cli.commands.collateral import app as collateral_app
9
10
  from hexaqueue_cli.commands.node import app as node_app
10
11
  from hexaqueue_cli.commands.run import app as run_app
@@ -13,6 +14,7 @@ from hexaqueue_cli.commands.workflow import app as workflow_app
13
14
 
14
15
  __all__ = [
15
16
  "admin_app",
17
+ "cluster_app",
16
18
  "collateral_app",
17
19
  "node_app",
18
20
  "run_app",
@@ -0,0 +1,983 @@
1
+ """CLI subcommand group for remote cluster management, SSH tunnels, and CSP monitoring.
2
+
3
+ Notes/Architectural Intent:
4
+ Provides turnkey `hq cluster` commands (status, ping, tunnel, sync, discover) to manage
5
+ hybrid and remote cluster nodes across CSP environments (OCI, GCP, AWS, Local) without
6
+ requiring manual raw SSH commands or complex shell scripts.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import json
13
+ import os
14
+ import signal
15
+ import socket
16
+ import subprocess
17
+ import sys
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ import typer
25
+ from rich.console import Console
26
+ from rich.panel import Panel
27
+ from rich.table import Table
28
+
29
+ from hexaqueue_cli.infra.options import format_option, resolve_format
30
+ from hexaqueue_core.domain.credentials import discover_and_merge_env
31
+ from hexaqueue_core.domain.runner_config import (
32
+ load_project_config,
33
+ resolve_runner_config,
34
+ )
35
+
36
+ app = typer.Typer(
37
+ name="cluster",
38
+ help="Manage and monitor remote cluster nodes, SSH tunnels, and CSP controllers",
39
+ no_args_is_help=True,
40
+ )
41
+ console = Console()
42
+
43
+
44
+ def _probe_host_reachability(
45
+ host: str, port: int = 22, timeout: float = 1.0
46
+ ) -> tuple[bool, float]:
47
+ """Execute a rapid network reachability probe (TCP socket connect) against candidate host.
48
+
49
+ Args:
50
+ host: Target IP address or hostname.
51
+ port: Destination port to probe (default 22 for SSH).
52
+ timeout: Socket timeout in seconds.
53
+
54
+ Returns:
55
+ Tuple of (is_reachable, latency_ms).
56
+ """
57
+ if not host or not host.strip():
58
+ return False, 0.0
59
+ start = time.perf_counter()
60
+ try:
61
+ with socket.create_connection((host, port), timeout=timeout):
62
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
63
+ return True, elapsed_ms
64
+ except Exception:
65
+ pass
66
+ return False, 0.0
67
+
68
+
69
+ def _probe_health(
70
+ url: str, timeout: float = 3.0
71
+ ) -> tuple[bool, dict[str, Any] | None, float]:
72
+ """Execute a single HTTP GET health probe against target URL.
73
+
74
+ Args:
75
+ url: Controller base URL or health endpoint.
76
+ timeout: Network timeout in seconds.
77
+
78
+ Returns:
79
+ Tuple of (is_healthy, payload_dict_or_none, elapsed_time_ms).
80
+ """
81
+ health_url = (
82
+ url if url.rstrip("/").endswith("/health") else f"{url.rstrip('/')}/health"
83
+ )
84
+ if not health_url.startswith(("http://", "https://")):
85
+ return False, None, 0.0
86
+ start = time.perf_counter()
87
+ try:
88
+ req = urllib.request.Request( # noqa: S310
89
+ health_url, headers={"User-Agent": "hexaqueue-cli"}
90
+ )
91
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
92
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
93
+ if resp.status == 200:
94
+ payload = json.loads(resp.read().decode("utf-8"))
95
+ return True, payload, elapsed_ms
96
+ except Exception:
97
+ pass
98
+ return False, None, 0.0
99
+
100
+
101
+ def _poll_health(
102
+ url: str, timeout_seconds: float = 10.0
103
+ ) -> tuple[bool, dict[str, Any] | None, float]:
104
+ """Poll health endpoint until healthy response or timeout deadline.
105
+
106
+ Args:
107
+ url: Target controller health URL.
108
+ timeout_seconds: Maximum total duration to poll in seconds.
109
+
110
+ Returns:
111
+ Tuple of (is_healthy, payload_dict_or_none, elapsed_time_ms).
112
+ """
113
+ deadline = time.time() + timeout_seconds
114
+ while time.time() < deadline:
115
+ ok, payload, latency = _probe_health(url, timeout=2.0)
116
+ if ok:
117
+ return True, payload, latency
118
+ time.sleep(0.5)
119
+ return False, None, 0.0
120
+
121
+
122
+ def _find_ssh_tunnel_pids(port: int = 8000) -> list[int]:
123
+ """Find process IDs of running SSH background tunnels forwarding to target local port.
124
+
125
+ Args:
126
+ port: Local forwarded port to inspect.
127
+
128
+ Returns:
129
+ List of matching process IDs.
130
+ """
131
+ pids: list[int] = []
132
+ needle = f"-L {port}:"
133
+ try:
134
+ proc = subprocess.run(
135
+ ["pgrep", "-f", f"ssh.*{needle}"],
136
+ capture_output=True,
137
+ text=True,
138
+ check=False,
139
+ )
140
+ if proc.returncode == 0:
141
+ for line in proc.stdout.strip().splitlines():
142
+ cleaned = line.strip()
143
+ if cleaned.isdigit():
144
+ pids.append(int(cleaned))
145
+ except Exception:
146
+ pass
147
+ return pids
148
+
149
+
150
+ def _terminate_pids(pids: list[int]) -> int:
151
+ """Terminate target process IDs with SIGTERM followed by SIGKILL if needed.
152
+
153
+ Args:
154
+ pids: Process IDs to terminate.
155
+
156
+ Returns:
157
+ Count of successfully terminated processes.
158
+ """
159
+ count = 0
160
+ for pid in pids:
161
+ try:
162
+ os.kill(pid, signal.SIGTERM)
163
+ count += 1
164
+ except (ProcessLookupError, PermissionError):
165
+ continue
166
+ return count
167
+
168
+
169
+ def _build_ssh_tunnel_cmd(
170
+ host: str,
171
+ port: int = 8000,
172
+ remote_port: int = 8000,
173
+ user: str = "hexaqueue-ci",
174
+ key: str | None = None,
175
+ ssh_port: int = 22,
176
+ ) -> list[str]:
177
+ """Construct command arguments for background SSH port-forwarding tunnel.
178
+
179
+ Args:
180
+ host: Target remote cluster host IP or hostname.
181
+ port: Local port to bind forwarding to.
182
+ remote_port: Target controller port on remote host.
183
+ user: SSH user identity.
184
+ key: Path to SSH private key file.
185
+ ssh_port: Remote SSH daemon port.
186
+
187
+ Returns:
188
+ List of command line string arguments for subprocess invocation.
189
+ """
190
+ cmd = [
191
+ "ssh",
192
+ "-f",
193
+ "-N",
194
+ "-o",
195
+ "StrictHostKeyChecking=no",
196
+ "-o",
197
+ "ConnectTimeout=10",
198
+ "-o",
199
+ "ServerAliveInterval=15",
200
+ "-p",
201
+ str(ssh_port),
202
+ "-L",
203
+ f"{port}:localhost:{remote_port}",
204
+ ]
205
+ if key:
206
+ expanded_key = str(Path(key).expanduser())
207
+ cmd.extend(["-i", expanded_key])
208
+ cmd.append(f"{user}@{host}")
209
+ return cmd
210
+
211
+
212
+ def _build_ssh_remote_sync_cmd(
213
+ host: str,
214
+ user: str = "hexaqueue-ci",
215
+ key: str | None = None,
216
+ ssh_port: int = 22,
217
+ repo_dir: str = "~/hexaqueue",
218
+ branch: str = "main",
219
+ ) -> list[str]:
220
+ """Construct remote SSH git synchronization command.
221
+
222
+ Args:
223
+ host: Target remote host IP or hostname.
224
+ user: SSH user identity.
225
+ key: Path to SSH private key.
226
+ ssh_port: SSH daemon port.
227
+ repo_dir: Working directory on remote host.
228
+ branch: Git branch name to pull and reset to.
229
+
230
+ Returns:
231
+ Command arguments for subprocess execution.
232
+ """
233
+ remote_script = (
234
+ f"cd {repo_dir} && git fetch origin {branch} && "
235
+ f"(git reset --hard origin/{branch} 2>/dev/null || git reset --hard FETCH_HEAD) && "
236
+ f"git clean -fd && "
237
+ f"~/.local/bin/uv sync --all-packages --all-extras && "
238
+ f"(sudo systemctl restart hexaqueue.service 2>/dev/null || true)"
239
+ )
240
+ cmd = [
241
+ "ssh",
242
+ "-o",
243
+ "StrictHostKeyChecking=no",
244
+ "-o",
245
+ "ConnectTimeout=15",
246
+ "-p",
247
+ str(ssh_port),
248
+ ]
249
+ if key:
250
+ cmd.extend(["-i", str(Path(key).expanduser())])
251
+ cmd.extend([f"{user}@{host}", remote_script])
252
+ return cmd
253
+
254
+
255
+ def _resolve_cluster_endpoint(
256
+ profile: str | None, explicit_url: str | None
257
+ ) -> tuple[str, str | None]:
258
+ """Resolve controller server URL and host from profile or explicit options.
259
+
260
+ Args:
261
+ profile: Profile name overlay.
262
+ explicit_url: Explicit URL CLI option.
263
+
264
+ Returns:
265
+ Tuple of (server_url, host_or_none).
266
+ """
267
+ proj_cfg = load_project_config()
268
+ resolved = resolve_runner_config(project_config=proj_cfg, profile=profile)
269
+ server_url = explicit_url or resolved.server_url
270
+ return server_url, resolved.host
271
+
272
+
273
+ @app.command("status")
274
+ def status_cmd(
275
+ profile: str | None = typer.Option(
276
+ None, "--profile", "-p", help="Active runner profile name to inspect"
277
+ ),
278
+ url: str | None = typer.Option(
279
+ None, "--url", "-u", help="Explicit Hexaqueue controller URL override"
280
+ ),
281
+ format_type: str = format_option(),
282
+ ) -> None:
283
+ """Inspect operational health and latency of the Hexaqueue cluster controller.
284
+
285
+ Args:
286
+ profile: Active runner profile name to inspect.
287
+ url: Explicit Hexaqueue controller URL override.
288
+ format_type: Chosen serialization output format.
289
+
290
+ Raises:
291
+ typer.Exit: With code 1 if controller is unreachable.
292
+
293
+ Notes/Architectural Intent:
294
+ Probes the cluster controller `/health` endpoint and inspects active CSP provider
295
+ guards to give operators immediate visibility into cluster readiness.
296
+ """
297
+ server_url, host = _resolve_cluster_endpoint(profile, url)
298
+ resolved_fmt = resolve_format(format_type)
299
+
300
+ ok, payload, latency = _probe_health(server_url)
301
+
302
+ if resolved_fmt in ("json", "yaml"):
303
+ result: dict[str, Any] = {
304
+ "server_url": server_url,
305
+ "host": host,
306
+ "profile": profile,
307
+ "healthy": ok,
308
+ "latency_ms": round(latency, 2) if ok else None,
309
+ "payload": payload,
310
+ }
311
+ if resolved_fmt == "json":
312
+ sys.stdout.write(json.dumps(result, indent=2) + "\n")
313
+ else:
314
+ import yaml
315
+
316
+ sys.stdout.write(yaml.safe_dump(result, sort_keys=False))
317
+ if not ok:
318
+ raise typer.Exit(code=1)
319
+ return
320
+
321
+ if not ok:
322
+ panel_content = (
323
+ f"[bold red]✖ Hexaqueue Controller Unreachable[/]\n\n"
324
+ f"[bold]Target URL:[/] {server_url}\n"
325
+ f"[bold]Host:[/] {host or 'Local / Not Specified'}\n"
326
+ f"[bold]Profile:[/] {profile or 'default'}\n\n"
327
+ f"[yellow]Troubleshooting Steps:[/]\n"
328
+ f" • Start local daemon: [cyan]hq server start[/]\n"
329
+ f" • Connect SSH tunnel to remote cluster: [cyan]hq cluster tunnel --profile {profile or 'ci'}[/]"
330
+ )
331
+ console.print(
332
+ Panel(panel_content, border_style="red", title="Cluster Controller Status")
333
+ )
334
+ raise typer.Exit(code=1)
335
+
336
+ table = Table(title="Hexaqueue Cluster Controller Health", border_style="green")
337
+ table.add_column("Property", style="bold cyan")
338
+ table.add_column("Value", style="green")
339
+
340
+ table.add_row("Status", "● ONLINE (Healthy)")
341
+ table.add_row("Server URL", server_url)
342
+ if host:
343
+ table.add_row("Remote Host", host)
344
+ table.add_row("Latency", f"{latency:.2f} ms")
345
+ if payload:
346
+ if "cores" in payload:
347
+ table.add_row("Worker Cores", str(payload["cores"]))
348
+ if "provider" in payload:
349
+ table.add_row("CSP Provider", str(payload["provider"]))
350
+ if "timestamp" in payload:
351
+ table.add_row("Timestamp", str(payload["timestamp"]))
352
+ if "correlation_id" in payload:
353
+ table.add_row("Correlation ID", str(payload["correlation_id"]))
354
+
355
+ console.print(table)
356
+
357
+
358
+ @app.command("ping")
359
+ def ping_cmd(
360
+ profile: str | None = typer.Option(
361
+ None, "--profile", "-p", help="Profile name to target"
362
+ ),
363
+ url: str | None = typer.Option(
364
+ None, "--url", "-u", help="Explicit Hexaqueue controller URL override"
365
+ ),
366
+ ) -> None:
367
+ """Perform a rapid latency probe against the cluster controller.
368
+
369
+ Args:
370
+ profile: Profile name to target.
371
+ url: Explicit Hexaqueue controller URL override.
372
+
373
+ Raises:
374
+ typer.Exit: With code 1 if ping probe fails.
375
+ """
376
+ server_url, _ = _resolve_cluster_endpoint(profile, url)
377
+ ok, _, latency = _probe_health(server_url)
378
+ if not ok:
379
+ console.print(
380
+ f"[bold red]✖ Error:[/] Could not connect to controller at {server_url}"
381
+ )
382
+ raise typer.Exit(code=1)
383
+ console.print(
384
+ f"[bold green]✓[/] Controller at [cyan]{server_url}[/] responded in [bold green]{latency:.2f} ms[/]"
385
+ )
386
+
387
+
388
+ def _stop_active_tunnels(port: int) -> None:
389
+ """Terminate active SSH tunnel processes forwarding on the specified local port.
390
+
391
+ Args:
392
+ port: Local port to check and terminate.
393
+
394
+ Notes/Architectural Intent:
395
+ Finds all background SSH port-forwarding processes bound to the local port
396
+ and terminates them gracefully or with SIGKILL if unresponsive.
397
+ """
398
+ pids = _find_ssh_tunnel_pids(port)
399
+ if not pids:
400
+ console.print(
401
+ f"[yellow]No active SSH tunnel found forwarding on port {port}.[/]"
402
+ )
403
+ return
404
+ terminated = _terminate_pids(pids)
405
+ console.print(
406
+ f"[bold green]✓[/] Terminated [bold cyan]{terminated}[/] SSH tunnel process(es) forwarding on port {port}."
407
+ )
408
+
409
+
410
+ def _resolve_tunnel_target(
411
+ profile: str | None,
412
+ host: str | None,
413
+ user: str,
414
+ key: str | None,
415
+ ssh_port: int,
416
+ remote_port: int,
417
+ ) -> tuple[str, str, str | None, int, int]:
418
+ """Resolve SSH target parameters from CLI flags, runner profile, env, or auto-discovery.
419
+
420
+ Args:
421
+ profile: Runner profile specifying target host and keys.
422
+ host: Target remote cluster host IP or hostname.
423
+ user: SSH login user.
424
+ key: Path to SSH private key identity file.
425
+ ssh_port: Remote SSH server port.
426
+ remote_port: Remote daemon port.
427
+
428
+ Returns:
429
+ Tuple of (target_host, target_user, target_key, target_ssh_port, target_remote_port).
430
+
431
+ Raises:
432
+ typer.Exit: If target host cannot be resolved.
433
+
434
+ Notes/Architectural Intent:
435
+ Applies hierarchical configuration cascading: CLI args override profile config,
436
+ profile config overrides environment variables, and auto-discovery serves as fallback.
437
+ """
438
+ proj_cfg = load_project_config()
439
+ resolved = resolve_runner_config(project_config=proj_cfg, profile=profile)
440
+ env = discover_and_merge_env()
441
+
442
+ target_host = host or resolved.host or env.get("HEXAQUEUE_CLUSTER_HOST")
443
+ target_user = (
444
+ user
445
+ if user != "hexaqueue-ci"
446
+ else (env.get("HEXAQUEUE_SSH_USER") or resolved.ssh_user or "hexaqueue-ci")
447
+ )
448
+ target_key = key or resolved.ssh_key or env.get("HEXAQUEUE_SSH_KEY")
449
+ target_ssh_port = ssh_port if ssh_port != 22 else (resolved.ssh_port or 22)
450
+ target_remote_port = (
451
+ remote_port if remote_port != 8000 else (resolved.remote_port or 8000)
452
+ )
453
+
454
+ if not target_host:
455
+ discovered = _auto_select_online_host()
456
+ if discovered:
457
+ target_host = discovered["host"]
458
+ target_user = (
459
+ user if user != "hexaqueue-ci" else discovered.get("user", target_user)
460
+ )
461
+ target_key = key or discovered.get("key") or target_key
462
+ target_ssh_port = (
463
+ ssh_port if ssh_port != 22 else int(discovered.get("ssh_port") or 22)
464
+ )
465
+ console.print(
466
+ f"[dim]Auto-discovered reachable candidate:[/] [bold cyan]{target_host}[/] "
467
+ f"({discovered.get('provider')})"
468
+ )
469
+
470
+ if not target_host:
471
+ console.print(
472
+ "[bold red]Error:[/] Target host not specified. Provide --host, specify host in "
473
+ f"profile '{profile or 'default'}', or export HEXAQUEUE_CLUSTER_HOST."
474
+ )
475
+ raise typer.Exit(code=1)
476
+
477
+ return target_host, target_user, target_key, target_ssh_port, target_remote_port
478
+
479
+
480
+ @app.command("tunnel")
481
+ def tunnel_cmd(
482
+ profile: str | None = typer.Option(
483
+ None, "--profile", "-p", help="Runner profile specifying target host and keys"
484
+ ),
485
+ host: str | None = typer.Option(
486
+ None, "--host", "-h", help="Target remote cluster host IP or hostname"
487
+ ),
488
+ port: int = typer.Option(8000, "--port", help="Local forwarding listen port"),
489
+ remote_port: int = typer.Option(8000, "--remote-port", help="Remote daemon port"),
490
+ user: str = typer.Option("hexaqueue-ci", "--user", "-u", help="SSH login user"),
491
+ key: str | None = typer.Option(
492
+ None, "--key", "-i", help="Path to SSH private key identity file"
493
+ ),
494
+ ssh_port: int = typer.Option(22, "--ssh-port", help="Remote SSH server port"),
495
+ stop: bool = typer.Option(
496
+ False, "--stop", help="Terminate active SSH tunnel on local port"
497
+ ),
498
+ ) -> None:
499
+ """Establish or terminate a secure SSH port-forwarding tunnel to the remote cluster.
500
+
501
+ Args:
502
+ profile: Runner profile specifying target host and keys.
503
+ host: Target remote cluster host IP or hostname.
504
+ port: Local forwarding listen port.
505
+ remote_port: Remote daemon port.
506
+ user: SSH login user.
507
+ key: Path to SSH private key identity file.
508
+ ssh_port: Remote SSH server port.
509
+ stop: Terminate active SSH tunnel on local port.
510
+
511
+ Raises:
512
+ typer.Exit: With code 1 if tunnel establishment or teardown fails.
513
+
514
+ Notes/Architectural Intent:
515
+ Enforces zero-trust isolation: rather than exposing port 8000 to the public internet,
516
+ this command establishes an encrypted SSH tunnel directly to the controller daemon.
517
+ """
518
+ if stop:
519
+ _stop_active_tunnels(port)
520
+ return
521
+
522
+ target_host, target_user, target_key, target_ssh_port, target_remote_port = (
523
+ _resolve_tunnel_target(
524
+ profile=profile,
525
+ host=host,
526
+ user=user,
527
+ key=key,
528
+ ssh_port=ssh_port,
529
+ remote_port=remote_port,
530
+ )
531
+ )
532
+
533
+ # Check if local port is already responding to /health
534
+ already_healthy, _, latency = _probe_health(f"http://127.0.0.1:{port}")
535
+ if already_healthy:
536
+ console.print(
537
+ f"[bold green]✓[/] Port [cyan]{port}[/] is already connected and healthy ({latency:.2f} ms). No tunnel needed."
538
+ )
539
+ return
540
+
541
+ ssh_cmd = _build_ssh_tunnel_cmd(
542
+ host=target_host,
543
+ port=port,
544
+ remote_port=target_remote_port,
545
+ user=target_user,
546
+ key=target_key,
547
+ ssh_port=target_ssh_port,
548
+ )
549
+
550
+ console.print(
551
+ f"[bold cyan]Establishing SSH tunnel to {target_user}@{target_host}:{target_remote_port}...[/]"
552
+ )
553
+ try:
554
+ proc = subprocess.run(ssh_cmd, capture_output=True, text=True, check=False)
555
+ if proc.returncode != 0 and proc.stderr:
556
+ console.print(
557
+ f"[bold red]SSH tunnel command failed:[/] {proc.stderr.strip()}"
558
+ )
559
+ raise typer.Exit(code=1)
560
+ except Exception as exc:
561
+ console.print(f"[bold red]Failed to execute SSH command:[/] {exc}")
562
+ raise typer.Exit(code=1) from exc
563
+
564
+ # Poll health to verify tunnel connectivity
565
+ ok, payload, elapsed_ms = _poll_health(
566
+ f"http://127.0.0.1:{port}", timeout_seconds=10.0
567
+ )
568
+ if not ok:
569
+ console.print(
570
+ f"[bold red]✖ Tunnel established, but health check failed on http://127.0.0.1:{port}/health[/]"
571
+ )
572
+ raise typer.Exit(code=1)
573
+
574
+ panel_content = (
575
+ f"[bold green]✓ Secure SSH Tunnel Established[/]\n\n"
576
+ f"[bold]Local Forwarding:[/] http://127.0.0.1:{port}\n"
577
+ f"[bold]Remote Endpoint:[/] {target_user}@{target_host}:{target_remote_port}\n"
578
+ f"[bold]Daemon Status:[/] {payload.get('status', 'ok') if payload else 'ok'} ({elapsed_ms:.2f} ms)\n\n"
579
+ f"[dim]To disconnect tunnel later:[/] [cyan]hq cluster tunnel --stop --port {port}[/]"
580
+ )
581
+ console.print(
582
+ Panel(panel_content, border_style="green", title="Hexaqueue Cluster Tunnel")
583
+ )
584
+
585
+
586
+ @app.command("sync")
587
+ def sync_cmd(
588
+ profile: str | None = typer.Option(
589
+ None, "--profile", "-p", help="Runner profile specifying target host and keys"
590
+ ),
591
+ host: str | None = typer.Option(
592
+ None, "--host", "-h", help="Target remote cluster host IP or hostname"
593
+ ),
594
+ user: str = typer.Option("hexaqueue-ci", "--user", "-u", help="SSH login user"),
595
+ key: str | None = typer.Option(
596
+ None, "--key", "-i", help="Path to SSH private key identity file"
597
+ ),
598
+ ssh_port: int = typer.Option(22, "--ssh-port", help="Remote SSH server port"),
599
+ repo_dir: str = typer.Option(
600
+ "~/hexaqueue", "--repo-dir", help="Remote workspace repository directory"
601
+ ),
602
+ branch: str = typer.Option(
603
+ "main", "--branch", "-b", help="Git branch to fetch and reset to"
604
+ ),
605
+ ) -> None:
606
+ """Trigger remote repository synchronization and dependency resolution over SSH.
607
+
608
+ Args:
609
+ profile: Runner profile specifying target host and keys.
610
+ host: Target remote cluster host IP or hostname.
611
+ user: SSH login user.
612
+ key: Path to SSH private key identity file.
613
+ ssh_port: Remote SSH server port.
614
+ repo_dir: Remote workspace repository directory.
615
+ branch: Git branch to fetch and reset to.
616
+
617
+ Raises:
618
+ typer.Exit: With code 1 if synchronization fails.
619
+ """
620
+ proj_cfg = load_project_config()
621
+ resolved = resolve_runner_config(project_config=proj_cfg, profile=profile)
622
+ env = discover_and_merge_env()
623
+
624
+ target_host = host or resolved.host or env.get("HEXAQUEUE_CLUSTER_HOST")
625
+ target_user = (
626
+ user
627
+ if user != "hexaqueue-ci"
628
+ else (env.get("HEXAQUEUE_SSH_USER") or resolved.ssh_user or "hexaqueue-ci")
629
+ )
630
+ target_key = key or resolved.ssh_key or env.get("HEXAQUEUE_SSH_KEY")
631
+ target_ssh_port = ssh_port if ssh_port != 22 else (resolved.ssh_port or 22)
632
+
633
+ if not target_host:
634
+ console.print(
635
+ "[bold red]Error:[/] Target host not specified. Provide --host or configure profile host."
636
+ )
637
+ raise typer.Exit(code=1)
638
+
639
+ if not target_key:
640
+ discovered = _auto_select_online_host()
641
+ if discovered and discovered.get("host") == target_host:
642
+ target_key = discovered.get("key")
643
+
644
+ cmd = _build_ssh_remote_sync_cmd(
645
+ host=target_host,
646
+ user=target_user,
647
+ key=target_key,
648
+ ssh_port=target_ssh_port,
649
+ repo_dir=repo_dir,
650
+ branch=branch,
651
+ )
652
+
653
+ console.print(
654
+ f"[bold cyan]Synchronizing remote cluster at {target_user}@{target_host}:{repo_dir} (branch: {branch})...[/]"
655
+ )
656
+ try:
657
+ proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
658
+ if proc.returncode != 0:
659
+ console.print(
660
+ f"[bold red]Remote synchronization failed (exit code {proc.returncode}):[/]\n{proc.stderr.strip()}"
661
+ )
662
+ raise typer.Exit(code=1)
663
+ console.print(
664
+ f"[bold green]✓[/] Remote repository synchronized successfully on [bold cyan]{target_host}[/].\n"
665
+ f"[dim]{proc.stdout.strip()}[/]"
666
+ )
667
+ except Exception as exc:
668
+ console.print(f"[bold red]Error executing remote sync:[/] {exc}")
669
+ raise typer.Exit(code=1) from exc
670
+
671
+
672
+ def _apply_ssh_directive(key: str, val: str, entry: dict[str, Any]) -> None:
673
+ """Apply an SSH config key-value directive to an entry dictionary."""
674
+ if key == "hostname":
675
+ entry["host"] = val
676
+ elif key == "user":
677
+ entry["user"] = val
678
+ elif key == "identityfile":
679
+ entry["key"] = val
680
+ elif key == "port":
681
+ with contextlib.suppress(ValueError):
682
+ entry["ssh_port"] = int(val)
683
+
684
+
685
+ def _read_ssh_config_entries(ssh_cfg: Path) -> list[dict[str, Any]]:
686
+ """Read host blocks from an SSH config file."""
687
+ candidates: list[dict[str, Any]] = []
688
+ current_entry: dict[str, Any] = {}
689
+ try:
690
+ with ssh_cfg.open("r", encoding="utf-8") as f:
691
+ for raw_line in f:
692
+ line = raw_line.strip()
693
+ if not line or line.startswith("#"):
694
+ continue
695
+ parts = line.split(maxsplit=1)
696
+ if len(parts) < 2:
697
+ continue
698
+ key, val = parts[0].lower(), parts[1].strip()
699
+ if key == "host":
700
+ if "host" in current_entry:
701
+ candidates.append(current_entry)
702
+ current_entry = {"alias": val, "host": val, "source": "ssh_config"}
703
+ elif current_entry:
704
+ _apply_ssh_directive(key, val, current_entry)
705
+ if "host" in current_entry:
706
+ candidates.append(current_entry)
707
+ except Exception:
708
+ pass
709
+ return candidates
710
+
711
+
712
+ def _parse_ssh_config_hosts() -> list[dict[str, Any]]:
713
+ """Parse candidate cluster hosts from ~/.ssh/config.
714
+
715
+ Returns:
716
+ List of candidate host dictionaries.
717
+ """
718
+ ssh_cfg = Path("~/.ssh/config").expanduser()
719
+ if not ssh_cfg.exists():
720
+ return []
721
+ candidates = _read_ssh_config_entries(ssh_cfg)
722
+ needles = ("hq", "hexaqueue", "oci", "cluster")
723
+ return [
724
+ c
725
+ for c in candidates
726
+ if any(
727
+ n in c.get("alias", "").lower() or n in c.get("host", "").lower()
728
+ for n in needles
729
+ )
730
+ ]
731
+
732
+
733
+ def _discover_from_env(seen_hosts: set[str]) -> list[dict[str, Any]]:
734
+ """Extract candidate cluster nodes from environment variables and .env files."""
735
+ results: list[dict[str, Any]] = []
736
+ env = discover_and_merge_env()
737
+ for k, val in env.items():
738
+ if not k.endswith("_HOST") or not val or val in seen_hosts:
739
+ continue
740
+ prefix = k[:-5]
741
+ provider = "Custom" if prefix in ("HEXAQUEUE_CLUSTER", "CLUSTER") else prefix
742
+ user = env.get("HEXAQUEUE_SSH_USER") or env.get(
743
+ f"{prefix}_USER", "hexaqueue-ci"
744
+ )
745
+ key = env.get(f"{prefix}_KEY", env.get("HEXAQUEUE_SSH_KEY"))
746
+ ssh_port_str = env.get(f"{prefix}_SSH_PORT", "22")
747
+ try:
748
+ ssh_port = int(ssh_port_str)
749
+ except ValueError:
750
+ ssh_port = 22
751
+ seen_hosts.add(val)
752
+ results.append(
753
+ {
754
+ "host": val,
755
+ "provider": provider.upper(),
756
+ "source": f"env:{k}",
757
+ "user": user,
758
+ "key": key,
759
+ "ssh_port": ssh_port,
760
+ }
761
+ )
762
+ return results
763
+
764
+
765
+ def _discover_from_profiles(seen_hosts: set[str]) -> list[dict[str, Any]]:
766
+ """Extract candidate cluster nodes from project configuration profiles."""
767
+ results: list[dict[str, Any]] = []
768
+ try:
769
+ proj_cfg = load_project_config()
770
+ for prof_name, prof_val in proj_cfg.profiles.items():
771
+ if prof_val.host and prof_val.host not in seen_hosts:
772
+ seen_hosts.add(prof_val.host)
773
+ results.append(
774
+ {
775
+ "host": prof_val.host,
776
+ "provider": prof_name.upper(),
777
+ "source": f"profile:{prof_name}",
778
+ "user": prof_val.ssh_user or "hexaqueue-ci",
779
+ "key": prof_val.ssh_key,
780
+ "ssh_port": prof_val.ssh_port or 22,
781
+ }
782
+ )
783
+ except Exception:
784
+ pass
785
+ return results
786
+
787
+
788
+ def _discover_from_ssh(seen_hosts: set[str]) -> list[dict[str, Any]]:
789
+ """Extract candidate cluster nodes from SSH config entries."""
790
+ results: list[dict[str, Any]] = []
791
+ for c in _parse_ssh_config_hosts():
792
+ h = c.get("host")
793
+ if h and h not in seen_hosts:
794
+ seen_hosts.add(h)
795
+ results.append(
796
+ {
797
+ "host": h,
798
+ "provider": "SSH Config",
799
+ "source": f"ssh:{c.get('alias')}",
800
+ "user": c.get("user", "hexaqueue-ci"),
801
+ "key": c.get("key"),
802
+ "ssh_port": c.get("ssh_port", 22),
803
+ }
804
+ )
805
+ return results
806
+
807
+
808
+ def _discover_candidates(provider: str = "auto") -> list[dict[str, Any]]:
809
+ """Aggregate candidate cluster hosts across environment, profiles, and SSH configuration.
810
+
811
+ Args:
812
+ provider: Provider filter ('auto', 'oci', 'ssh', 'env', 'profiles').
813
+
814
+ Returns:
815
+ List of candidate host dictionaries.
816
+ """
817
+ results: list[dict[str, Any]] = []
818
+ seen_hosts: set[str] = set()
819
+
820
+ if provider in ("auto", "env", "oci"):
821
+ results.extend(_discover_from_env(seen_hosts))
822
+ if provider in ("auto", "profiles", "oci"):
823
+ results.extend(_discover_from_profiles(seen_hosts))
824
+ if provider in ("auto", "ssh", "oci"):
825
+ results.extend(_discover_from_ssh(seen_hosts))
826
+
827
+ return results
828
+
829
+
830
+ def _auto_select_online_host() -> dict[str, Any] | None:
831
+ """Auto-discover candidate cluster hosts and return the first online candidate.
832
+
833
+ Returns:
834
+ Selected candidate dictionary or None if none are reachable.
835
+ """
836
+ candidates = _discover_candidates("auto")
837
+ for cand in candidates:
838
+ c_host = cand.get("host")
839
+ if not c_host:
840
+ continue
841
+ c_port = int(cand.get("ssh_port") or 22)
842
+ is_online, _ = _probe_host_reachability(c_host, port=c_port, timeout=1.0)
843
+ if is_online:
844
+ return cand
845
+ return None
846
+
847
+
848
+ def _probe_single_candidate(cand: dict[str, Any]) -> dict[str, Any]:
849
+ """Execute two-tier reachability and API health probe for a single candidate host.
850
+
851
+ Args:
852
+ cand: Candidate dictionary containing host and metadata.
853
+
854
+ Returns:
855
+ Enriched candidate dictionary with health status and capacity.
856
+ """
857
+ host = cand["host"]
858
+ ssh_port = int(cand.get("ssh_port") or 22)
859
+
860
+ # Tier 1: Host Reachability Probe
861
+ is_online, ping_latency = _probe_host_reachability(host, port=ssh_port, timeout=1.0)
862
+ if not is_online and host in ("127.0.0.1", "localhost"):
863
+ is_online, ping_latency = True, 0.1
864
+
865
+ # Tier 2: Hexaqueue API Health Probe (if host is online)
866
+ api_ok = False
867
+ payload = None
868
+ api_latency = 0.0
869
+ if is_online:
870
+ api_ok, payload, api_latency = _probe_health(f"http://{host}:8000", timeout=1.0)
871
+ if not api_ok and host in ("127.0.0.1", "localhost"):
872
+ api_ok, payload, api_latency = _probe_health(
873
+ "http://127.0.0.1:8000", timeout=1.0
874
+ )
875
+
876
+ if api_ok:
877
+ status_text = "ONLINE"
878
+ latency_ms = round(api_latency, 2)
879
+ elif is_online:
880
+ status_text = "SSH_AVAILABLE"
881
+ latency_ms = round(ping_latency, 2)
882
+ else:
883
+ status_text = "OFFLINE"
884
+ latency_ms = None
885
+
886
+ cores = payload.get("cores") if payload else None
887
+ return {
888
+ **cand,
889
+ "healthy": api_ok,
890
+ "is_online": is_online,
891
+ "status": status_text,
892
+ "latency_ms": latency_ms,
893
+ "cores": cores,
894
+ "recommended_tunnel": f"hq cluster tunnel --host {host} --user {cand.get('user', 'ubuntu')}",
895
+ }
896
+
897
+
898
+ def _render_discovered_table(probed: list[dict[str, Any]]) -> None:
899
+ """Render Rich table of probed candidate nodes."""
900
+ table = Table(title="Discovered Hexaqueue Cluster Nodes", border_style="cyan")
901
+ table.add_column("Host", style="bold cyan")
902
+ table.add_column("Provider", style="green")
903
+ table.add_column("Source", style="dim")
904
+ table.add_column("Status", style="bold")
905
+ table.add_column("Cores", justify="right")
906
+ table.add_column("Latency", justify="right")
907
+ table.add_column("Tunnel Command", style="yellow")
908
+
909
+ for p in probed:
910
+ if p.get("healthy"):
911
+ status_disp = "[green]● ONLINE[/]"
912
+ elif p.get("is_online"):
913
+ status_disp = "[yellow]○ SSH READY[/]"
914
+ else:
915
+ status_disp = "[red]✖ OFFLINE[/]"
916
+ cores_disp = str(p["cores"]) if p.get("cores") is not None else "-"
917
+ lat_disp = (
918
+ f"{p['latency_ms']:.2f} ms" if p.get("latency_ms") is not None else "-"
919
+ )
920
+ table.add_row(
921
+ p["host"],
922
+ p.get("provider", "Unknown"),
923
+ p.get("source", "Unknown"),
924
+ status_disp,
925
+ cores_disp,
926
+ lat_disp,
927
+ p["recommended_tunnel"],
928
+ )
929
+
930
+ console.print(table)
931
+
932
+
933
+ @app.command("discover")
934
+ def discover_cmd(
935
+ provider: str = typer.Option(
936
+ "auto",
937
+ "--provider",
938
+ "-p",
939
+ help="Provider discovery target ('auto', 'oci', 'ssh', 'env', 'profiles')",
940
+ ),
941
+ format_type: str = format_option(),
942
+ ) -> None:
943
+ """Discover available remote cluster nodes, active controllers, and SSH connection endpoints.
944
+
945
+ Args:
946
+ provider: Provider discovery target filter.
947
+ format_type: Output presentation format.
948
+
949
+ Notes/Architectural Intent:
950
+ Discovers remote nodes across environment variables, runner profiles, and SSH configuration,
951
+ probing for live controller readiness to eliminate hardcoded endpoint references.
952
+ """
953
+ candidates = _discover_candidates(provider)
954
+ resolved_fmt = resolve_format(format_type)
955
+
956
+ probed = [_probe_single_candidate(cand) for cand in candidates]
957
+
958
+ if resolved_fmt in ("json", "yaml"):
959
+ if resolved_fmt == "json":
960
+ sys.stdout.write(json.dumps(probed, indent=2) + "\n")
961
+ else:
962
+ import yaml
963
+
964
+ sys.stdout.write(yaml.safe_dump(probed, sort_keys=False))
965
+ return
966
+
967
+ if not probed:
968
+ console.print(
969
+ "[yellow]No candidate cluster hosts discovered. Configure a profile or export HEXAQUEUE_CLUSTER_HOST.[/]"
970
+ )
971
+ return
972
+
973
+ _render_discovered_table(probed)
974
+
975
+
976
+ __all__ = [
977
+ "app",
978
+ "discover_cmd",
979
+ "ping_cmd",
980
+ "status_cmd",
981
+ "sync_cmd",
982
+ "tunnel_cmd",
983
+ ]
@@ -17,6 +17,7 @@ from rich.console import Console
17
17
  from hexaqueue_cli.adapters.local import LocalClientAdapter
18
18
  from hexaqueue_cli.adapters.presenter import CliPresenter
19
19
  from hexaqueue_cli.commands.admin import app as admin_app
20
+ from hexaqueue_cli.commands.cluster import app as cluster_app
20
21
  from hexaqueue_cli.commands.collateral import app as collateral_app
21
22
  from hexaqueue_cli.commands.mcp import app as mcp_app
22
23
  from hexaqueue_cli.commands.node import app as node_app
@@ -35,6 +36,7 @@ app = typer.Typer(
35
36
  no_args_is_help=True,
36
37
  )
37
38
  app.add_typer(admin_app, name="admin")
39
+ app.add_typer(cluster_app, name="cluster")
38
40
  app.add_typer(run_app, name="run")
39
41
  app.add_typer(workflow_app, name="workflow")
40
42
  app.add_typer(suite_app, name="suite")
File without changes