Compare commits
1 Commits
queue/375-
...
triage/350
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb0b38d5cd |
@@ -26,7 +26,7 @@ from cron.jobs import (
|
||||
trigger_job,
|
||||
JOBS_FILE,
|
||||
)
|
||||
from cron.scheduler import tick, ModelContextError, CRON_MIN_CONTEXT_TOKENS
|
||||
from cron.scheduler import tick
|
||||
|
||||
__all__ = [
|
||||
"create_job",
|
||||
@@ -39,6 +39,4 @@ __all__ = [
|
||||
"trigger_job",
|
||||
"tick",
|
||||
"JOBS_FILE",
|
||||
"ModelContextError",
|
||||
"CRON_MIN_CONTEXT_TOKENS",
|
||||
]
|
||||
|
||||
@@ -186,7 +186,14 @@ _SCRIPT_FAILURE_PHRASES = (
|
||||
"unable to execute",
|
||||
"permission denied",
|
||||
"no such file",
|
||||
"no such file or directory",
|
||||
"command not found",
|
||||
"hermes binary not found",
|
||||
"hermes not found",
|
||||
"traceback",
|
||||
"ssh: connect to host",
|
||||
"connection timed out",
|
||||
"host key verification failed",
|
||||
)
|
||||
|
||||
|
||||
|
||||
192
cron/ssh_dispatch.py
Normal file
192
cron/ssh_dispatch.py
Normal file
@@ -0,0 +1,192 @@
|
||||
"""SSH dispatch utilities for VPS agent operations.
|
||||
|
||||
Provides validated SSH execution with proper failure detection.
|
||||
Used by cron jobs that dispatch work to remote VPS agents.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_SSH_TIMEOUT = int(os.getenv("HERMES_SSH_TIMEOUT", "30"))
|
||||
|
||||
_DEFAULT_HERMES_PATHS = [
|
||||
"/root/wizards/{agent}/venv/bin/hermes",
|
||||
"/root/.local/bin/hermes",
|
||||
"/usr/local/bin/hermes",
|
||||
"~/.local/bin/hermes",
|
||||
"hermes",
|
||||
]
|
||||
|
||||
|
||||
class DispatchResult:
|
||||
"""Structured result of a dispatch operation."""
|
||||
|
||||
__slots__ = (
|
||||
"success", "host", "command", "exit_code",
|
||||
"stdout", "stderr", "error", "duration_ms", "hermes_path",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self, success: bool, host: str, command: str,
|
||||
exit_code: int = -1, stdout: str = "", stderr: str = "",
|
||||
error: str = "", duration_ms: int = 0, hermes_path: str = "",
|
||||
):
|
||||
self.success = success
|
||||
self.host = host
|
||||
self.command = command
|
||||
self.exit_code = exit_code
|
||||
self.stdout = stdout
|
||||
self.stderr = stderr
|
||||
self.error = error
|
||||
self.duration_ms = duration_ms
|
||||
self.hermes_path = hermes_path
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"success": self.success, "host": self.host,
|
||||
"exit_code": self.exit_code, "error": self.error,
|
||||
"duration_ms": self.duration_ms, "hermes_path": self.hermes_path,
|
||||
"stderr_tail": self.stderr[-200:] if self.stderr else "",
|
||||
}
|
||||
|
||||
@property
|
||||
def failure_reason(self) -> str:
|
||||
if self.success:
|
||||
return ""
|
||||
if self.error:
|
||||
return self.error
|
||||
if "No such file" in self.stderr or "command not found" in self.stderr:
|
||||
return f"Hermes binary not found on {self.host}"
|
||||
if self.exit_code != 0:
|
||||
return f"Remote command exited {self.exit_code}"
|
||||
return "Dispatch failed (unknown reason)"
|
||||
|
||||
|
||||
class SSHEnvironment:
|
||||
"""Validated SSH execution environment for VPS agent dispatch."""
|
||||
|
||||
def __init__(
|
||||
self, host: str, agent: str = "", ssh_key: str = "",
|
||||
ssh_port: int = 22, timeout: int = _SSH_TIMEOUT,
|
||||
hermes_path: str = "",
|
||||
):
|
||||
self.host = host
|
||||
self.agent = agent
|
||||
self.ssh_key = ssh_key
|
||||
self.ssh_port = ssh_port
|
||||
self.timeout = timeout
|
||||
self.hermes_path = hermes_path
|
||||
self._validated_path: str = ""
|
||||
|
||||
def _ssh_base_cmd(self) -> list[str]:
|
||||
cmd = ["ssh", "-o", "StrictHostKeyChecking=accept-new"]
|
||||
cmd.extend(["-o", "ConnectTimeout=10", "-o", "BatchMode=yes"])
|
||||
if self.ssh_key:
|
||||
cmd.extend(["-i", self.ssh_key])
|
||||
if self.ssh_port != 22:
|
||||
cmd.extend(["-p", str(self.ssh_port)])
|
||||
cmd.append(self.host)
|
||||
return cmd
|
||||
|
||||
def _resolve_hermes_paths(self) -> list[str]:
|
||||
if self.hermes_path:
|
||||
return [self.hermes_path]
|
||||
return [t.format(agent=self.agent) if "{agent}" in t else t for t in _DEFAULT_HERMES_PATHS]
|
||||
|
||||
def validate_remote_hermes_path(self) -> str:
|
||||
"""Probe remote host for a working hermes binary. Returns path or raises."""
|
||||
if self._validated_path:
|
||||
return self._validated_path
|
||||
for path in self._resolve_hermes_paths():
|
||||
try:
|
||||
result = subprocess.run(
|
||||
self._ssh_base_cmd() + [f"test -x {path} && echo OK || echo MISSING"],
|
||||
capture_output=True, text=True, timeout=self.timeout,
|
||||
)
|
||||
if result.returncode == 0 and "OK" in (result.stdout or ""):
|
||||
logger.info("SSH %s: hermes validated at %s", self.host, path)
|
||||
self._validated_path = path
|
||||
return path
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning("SSH %s: timeout probing %s", self.host, path)
|
||||
except Exception as exc:
|
||||
logger.debug("SSH %s: probe %s failed: %s", self.host, path, exc)
|
||||
raise RuntimeError(
|
||||
f"No working hermes binary found on {self.host}. "
|
||||
f"Checked: {', '.join(self._resolve_hermes_paths())}."
|
||||
)
|
||||
|
||||
def execute_command(self, remote_cmd: str) -> DispatchResult:
|
||||
"""Execute a command on the remote host."""
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
result = subprocess.run(
|
||||
self._ssh_base_cmd() + [remote_cmd],
|
||||
capture_output=True, text=True, timeout=self.timeout,
|
||||
)
|
||||
elapsed = int((time.monotonic() - t0) * 1000)
|
||||
stderr = (result.stderr or "").strip()
|
||||
stdout = (result.stdout or "").strip()
|
||||
if result.returncode != 0:
|
||||
return DispatchResult(
|
||||
success=False, host=self.host, command=remote_cmd,
|
||||
exit_code=result.returncode, stdout=stdout, stderr=stderr,
|
||||
error=stderr.split("\n")[0] if stderr else f"exit code {result.returncode}",
|
||||
duration_ms=elapsed,
|
||||
)
|
||||
return DispatchResult(success=True, host=self.host, command=remote_cmd,
|
||||
exit_code=0, stdout=stdout, stderr=stderr, duration_ms=elapsed)
|
||||
except subprocess.TimeoutExpired:
|
||||
return DispatchResult(success=False, host=self.host, command=remote_cmd,
|
||||
error=f"SSH timed out after {self.timeout}s",
|
||||
duration_ms=int((time.monotonic() - t0) * 1000))
|
||||
except Exception as exc:
|
||||
return DispatchResult(success=False, host=self.host, command=remote_cmd,
|
||||
error=str(exc), duration_ms=int((time.monotonic() - t0) * 1000))
|
||||
|
||||
def dispatch(self, hermes_args: str, validate: bool = True) -> DispatchResult:
|
||||
"""Dispatch a hermes command. Only success=True if command actually ran."""
|
||||
if validate:
|
||||
try:
|
||||
hermes_path = self.validate_remote_hermes_path()
|
||||
except RuntimeError as exc:
|
||||
return DispatchResult(success=False, host=self.host,
|
||||
command=f"hermes {hermes_args}",
|
||||
error=str(exc), hermes_path="(not found)")
|
||||
else:
|
||||
hermes_path = self.hermes_path or "hermes"
|
||||
result = self.execute_command(f"{hermes_path} {hermes_args}")
|
||||
result.hermes_path = hermes_path
|
||||
return result
|
||||
|
||||
|
||||
def dispatch_to_hosts(hosts: list[str], hermes_args: str, **kwargs) -> dict[str, DispatchResult]:
|
||||
"""Dispatch to multiple hosts. Returns host -> DispatchResult."""
|
||||
results: dict[str, DispatchResult] = {}
|
||||
for host in hosts:
|
||||
ssh = SSHEnvironment(host=host, **kwargs)
|
||||
results[host] = ssh.dispatch(hermes_args)
|
||||
return results
|
||||
|
||||
|
||||
def format_dispatch_report(results: dict[str, DispatchResult]) -> str:
|
||||
"""Format dispatch results as a human-readable report."""
|
||||
ok = [r for r in results.values() if r.success]
|
||||
failed = [r for r in results.values() if not r.success]
|
||||
lines = [f"Dispatch report: {len(ok)} OK, {len(failed)} failed", ""]
|
||||
for host, r in results.items():
|
||||
s = "OK" if r.success else f"FAILED -- {r.failure_reason}"
|
||||
lines.append(f" {host}: {s}" + (f" ({r.duration_ms}ms)" if r.duration_ms else ""))
|
||||
if failed:
|
||||
lines += ["", "Failed dispatches:"]
|
||||
for host, r in results.items():
|
||||
if not r.success:
|
||||
lines.append(f" {host}: {r.failure_reason}")
|
||||
return "\n".join(lines)
|
||||
353
deploy-crons.py
353
deploy-crons.py
@@ -1,292 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
deploy-crons -- deploy cron jobs from YAML config and normalize jobs.json.
|
||||
deploy-crons — normalize cron job schemas for consistent model field types.
|
||||
|
||||
Two modes:
|
||||
--deploy Sync jobs from cron-jobs.yaml into jobs.json (create / update).
|
||||
--normalize Normalize model field types in existing jobs.json.
|
||||
|
||||
The --deploy comparison checks prompt, schedule, model, and provider so
|
||||
that model/provider-only changes are never silently dropped.
|
||||
This script ensures that the model field in jobs.json is always a dict when
|
||||
either model or provider is specified, preventing schema inconsistency.
|
||||
|
||||
Usage:
|
||||
python deploy-crons.py --deploy [--config PATH] [--jobs-file PATH] [--dry-run]
|
||||
python deploy-crons.py --normalize [--jobs-file PATH] [--dry-run]
|
||||
python deploy-crons.py [--dry-run] [--jobs-file PATH]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
try:
|
||||
import yaml
|
||||
HAS_YAML = True
|
||||
except ImportError:
|
||||
HAS_YAML = False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _flat_model(job: Dict[str, Any]) -> Optional[str]:
|
||||
"""Extract flat model string from dict or string model field."""
|
||||
m = job.get("model")
|
||||
if isinstance(m, dict):
|
||||
return m.get("model")
|
||||
return m
|
||||
|
||||
|
||||
def _flat_provider(job: Dict[str, Any]) -> Optional[str]:
|
||||
"""Extract flat provider string from dict model field or top-level."""
|
||||
m = job.get("model")
|
||||
if isinstance(m, dict):
|
||||
return m.get("provider")
|
||||
return job.get("provider")
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
def normalize_job(job: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Normalize a job dict to ensure consistent model field types."""
|
||||
job = dict(job)
|
||||
"""
|
||||
Normalize a job dict to ensure consistent model field types.
|
||||
|
||||
Before normalization:
|
||||
- If model AND provider: model = raw string, provider = raw string (inconsistent)
|
||||
- If only model: model = raw string
|
||||
- If only provider: provider = raw string at top level
|
||||
|
||||
After normalization:
|
||||
- If model exists: model = {"model": "xxx"}
|
||||
- If provider exists: model = {"provider": "yyy"}
|
||||
- If both exist: model = {"model": "xxx", "provider": "yyy"}
|
||||
- If neither: model = None
|
||||
"""
|
||||
job = dict(job) # Create a copy to avoid modifying the original
|
||||
|
||||
model = job.get("model")
|
||||
provider = job.get("provider")
|
||||
|
||||
|
||||
# Skip if already normalized (model is a dict)
|
||||
if isinstance(model, dict):
|
||||
return job
|
||||
|
||||
|
||||
# Build normalized model dict
|
||||
model_dict = {}
|
||||
|
||||
if model is not None and isinstance(model, str):
|
||||
model_dict["model"] = model.strip()
|
||||
|
||||
if provider is not None and isinstance(provider, str):
|
||||
model_dict["provider"] = provider.strip()
|
||||
|
||||
job["model"] = model_dict if model_dict else None
|
||||
|
||||
# Set model field
|
||||
if model_dict:
|
||||
job["model"] = model_dict
|
||||
else:
|
||||
job["model"] = None
|
||||
|
||||
# Remove top-level provider field if it was moved into model dict
|
||||
if provider is not None and "provider" in model_dict:
|
||||
# Keep provider field for backward compatibility but mark it as deprecated
|
||||
# This allows existing code that reads job["provider"] to continue working
|
||||
pass
|
||||
|
||||
return job
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deploy from YAML
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _jobs_changed(cur: Dict[str, Any], desired: Dict[str, Any]) -> bool:
|
||||
"""
|
||||
Return True if desired differs from cur.
|
||||
|
||||
Compares prompt, schedule, model, and provider -- the fix for #375.
|
||||
Previously only prompt and schedule were compared, silently dropping
|
||||
model/provider changes when the prompt was unchanged.
|
||||
"""
|
||||
if cur.get("prompt") != desired.get("prompt"):
|
||||
return True
|
||||
if cur.get("schedule") != desired.get("schedule"):
|
||||
return True
|
||||
if _flat_model(cur) != _flat_model(desired):
|
||||
return True
|
||||
if _flat_provider(cur) != _flat_provider(desired):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _parse_schedule(schedule: str) -> Dict[str, Any]:
|
||||
"""Parse schedule string into structured format."""
|
||||
try:
|
||||
from cron.jobs import parse_schedule
|
||||
return parse_schedule(schedule)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
schedule = schedule.strip()
|
||||
if schedule.startswith("every "):
|
||||
dur = schedule[6:].strip()
|
||||
unit = dur[-1]
|
||||
val = int(dur[:-1])
|
||||
minutes = val * {"m": 1, "h": 60, "d": 1440}.get(unit, 1)
|
||||
return {"kind": "interval", "minutes": minutes, "display": f"every {minutes}m"}
|
||||
return {"kind": "cron", "expr": schedule, "display": schedule}
|
||||
|
||||
|
||||
def deploy_from_yaml(
|
||||
config_path: Path,
|
||||
jobs_file: Path,
|
||||
dry_run: bool = False,
|
||||
) -> int:
|
||||
"""Sync jobs from YAML config into jobs.json."""
|
||||
if not HAS_YAML:
|
||||
print("Error: PyYAML required for --deploy. pip install pyyaml", file=sys.stderr)
|
||||
return 1
|
||||
if not config_path.exists():
|
||||
print(f"Error: Config not found: {config_path}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
yaml_jobs = (yaml.safe_load(f) or {}).get("jobs", [])
|
||||
|
||||
if jobs_file.exists():
|
||||
with open(jobs_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
else:
|
||||
data = {"jobs": [], "updated_at": None}
|
||||
|
||||
existing: List[Dict[str, Any]] = data.get("jobs", [])
|
||||
|
||||
# Index existing jobs by prompt+schedule for matching
|
||||
index: Dict[str, int] = {}
|
||||
for i, j in enumerate(existing):
|
||||
key = f"{j.get('prompt', '')}||{json.dumps(j.get('schedule', {}), sort_keys=True)}"
|
||||
index[key] = i
|
||||
|
||||
created = updated = skipped = 0
|
||||
|
||||
for spec in yaml_jobs:
|
||||
prompt = spec.get("prompt", "")
|
||||
schedule_str = spec.get("schedule", "")
|
||||
name = spec.get("name", "")
|
||||
model = spec.get("model")
|
||||
provider = spec.get("provider")
|
||||
skills = spec.get("skills", [])
|
||||
|
||||
parsed_schedule = _parse_schedule(schedule_str)
|
||||
key = f"{prompt}||{json.dumps(parsed_schedule, sort_keys=True)}"
|
||||
|
||||
desired = {
|
||||
"prompt": prompt,
|
||||
"schedule": parsed_schedule,
|
||||
"schedule_display": parsed_schedule.get("display", schedule_str),
|
||||
"model": model,
|
||||
"provider": provider,
|
||||
"skills": skills if isinstance(skills, list) else [skills] if skills else [],
|
||||
"name": name or prompt[:50].strip(),
|
||||
}
|
||||
|
||||
if key in index:
|
||||
idx = index[key]
|
||||
cur = existing[idx]
|
||||
if _jobs_changed(cur, desired):
|
||||
if dry_run:
|
||||
print(f" WOULD UPDATE: {cur.get('id', '?')} ({cur.get('name', '?')})")
|
||||
print(f" model: {_flat_model(cur)!r} -> {model!r}")
|
||||
print(f" provider: {_flat_provider(cur)!r} -> {provider!r}")
|
||||
else:
|
||||
existing[idx].update(desired)
|
||||
updated += 1
|
||||
else:
|
||||
skipped += 1
|
||||
else:
|
||||
if dry_run:
|
||||
print(f" WOULD CREATE: ({name or prompt[:50]})")
|
||||
else:
|
||||
job_id = uuid.uuid4().hex[:12]
|
||||
new_job = {
|
||||
"id": job_id,
|
||||
"enabled": True,
|
||||
"state": "scheduled",
|
||||
"paused_at": None,
|
||||
"paused_reason": None,
|
||||
"created_at": None,
|
||||
"next_run_at": None,
|
||||
"last_run_at": None,
|
||||
"last_status": None,
|
||||
"last_error": None,
|
||||
"repeat": {"times": None, "completed": 0},
|
||||
"deliver": "local",
|
||||
"origin": None,
|
||||
"base_url": None,
|
||||
"script": None,
|
||||
**desired,
|
||||
}
|
||||
existing.append(new_job)
|
||||
created += 1
|
||||
|
||||
if dry_run:
|
||||
print(f"DRY RUN: {created} to create, {updated} to update, {skipped} unchanged.")
|
||||
return 0
|
||||
|
||||
data["jobs"] = existing
|
||||
jobs_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(jobs_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Deployed: {created} created, {updated} updated, {skipped} unchanged.")
|
||||
return 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Normalize standalone
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def normalize_jobs_file(jobs_file: Path, dry_run: bool = False) -> int:
|
||||
"""Normalize model field types in jobs.json."""
|
||||
"""
|
||||
Normalize all jobs in a jobs.json file.
|
||||
|
||||
Returns the number of jobs that were modified.
|
||||
"""
|
||||
if not jobs_file.exists():
|
||||
print(f"Error: {jobs_file}", file=sys.stderr)
|
||||
print(f"Error: Jobs file not found: {jobs_file}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
with open(jobs_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
|
||||
try:
|
||||
with open(jobs_file, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error: Invalid JSON in {jobs_file}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
jobs = data.get("jobs", [])
|
||||
if not jobs:
|
||||
print("No jobs found.")
|
||||
print("No jobs found in file.")
|
||||
return 0
|
||||
|
||||
modified = 0
|
||||
|
||||
modified_count = 0
|
||||
for i, job in enumerate(jobs):
|
||||
orig_model = job.get("model")
|
||||
orig_provider = job.get("provider")
|
||||
normed = normalize_job(job)
|
||||
if normed.get("model") != orig_model or normed.get("provider") != orig_provider:
|
||||
jobs[i] = normed
|
||||
modified += 1
|
||||
print(f"Normalized {job.get('id', '?')} ({job.get('name', '?')}):")
|
||||
print(f" model: {orig_model!r} -> {normed.get('model')!r}")
|
||||
print(f" provider: {orig_provider!r} -> {normed.get('provider')!r}")
|
||||
|
||||
if modified == 0:
|
||||
print("All jobs already consistent.")
|
||||
original_model = job.get("model")
|
||||
original_provider = job.get("provider")
|
||||
|
||||
normalized_job = normalize_job(job)
|
||||
|
||||
# Check if anything changed
|
||||
if (normalized_job.get("model") != original_model or
|
||||
normalized_job.get("provider") != original_provider):
|
||||
jobs[i] = normalized_job
|
||||
modified_count += 1
|
||||
|
||||
job_id = job.get("id", "?")
|
||||
job_name = job.get("name", "(unnamed)")
|
||||
print(f"Normalized job {job_id} ({job_name}):")
|
||||
print(f" model: {original_model!r} -> {normalized_job.get('model')!r}")
|
||||
print(f" provider: {original_provider!r} -> {normalized_job.get('provider')!r}")
|
||||
|
||||
if modified_count == 0:
|
||||
print("All jobs already have consistent model field types.")
|
||||
return 0
|
||||
|
||||
if dry_run:
|
||||
print(f"DRY RUN: Would normalize {modified} jobs.")
|
||||
print(f"DRY RUN: Would normalize {modified_count} jobs.")
|
||||
return 0
|
||||
|
||||
|
||||
# Write back to file
|
||||
data["jobs"] = jobs
|
||||
with open(jobs_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Normalized {modified} jobs in {jobs_file}")
|
||||
return 0
|
||||
try:
|
||||
with open(jobs_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
print(f"Normalized {modified_count} jobs in {jobs_file}")
|
||||
return 0
|
||||
except Exception as e:
|
||||
print(f"Error writing to {jobs_file}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Deploy and normalize cron jobs.")
|
||||
group = parser.add_mutually_exclusive_group(required=True)
|
||||
group.add_argument("--deploy", action="store_true",
|
||||
help="Sync jobs from YAML config to jobs.json")
|
||||
group.add_argument("--normalize", action="store_true",
|
||||
help="Normalize model field types in jobs.json")
|
||||
|
||||
parser.add_argument("--config", type=Path,
|
||||
default=Path.home() / ".hermes" / "cron-jobs.yaml",
|
||||
help="Path to cron-jobs.yaml")
|
||||
parser.add_argument("--jobs-file", type=Path,
|
||||
default=Path.home() / ".hermes" / "cron" / "jobs.json",
|
||||
help="Path to jobs.json")
|
||||
parser.add_argument("--dry-run", action="store_true",
|
||||
help="Show changes without modifying files")
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Normalize cron job schemas for consistent model field types."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Show what would be changed without modifying the file."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--jobs-file",
|
||||
type=Path,
|
||||
default=Path.home() / ".hermes" / "cron" / "jobs.json",
|
||||
help="Path to jobs.json file (default: ~/.hermes/cron/jobs.json)"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
if args.dry_run:
|
||||
print("DRY RUN MODE.")
|
||||
print("DRY RUN MODE — no changes will be made.")
|
||||
print()
|
||||
|
||||
if args.deploy:
|
||||
return deploy_from_yaml(args.config, args.jobs_file, args.dry_run)
|
||||
else:
|
||||
return normalize_jobs_file(args.jobs_file, args.dry_run)
|
||||
|
||||
return normalize_jobs_file(args.jobs_file, args.dry_run)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user