gerodp/hermes-productivity-skills / calendar/meeting-reminder
meeting-reminder
FlaggedDesktop reminder N minutes before each meeting starts, with a deep link to the matching Obsidian note (runs from hermes cron).
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 8.7 KB |
| scripts/meeting_reminder.py | script | 35.5 KB |
| scripts/test_meeting_reminder.py | script | 21.0 KB |
scripts/meeting_reminder.py
View on GitHub#!/usr/bin/env python3
"""meeting-reminder — desktop reminder N minutes before a meeting, with the
matching Obsidian note.
Polls Google Calendar (via the builtin **google-workspace** skill, same
delegation as the sibling ``calendar`` skill), and for every timed event
starting within the next ``--lead`` minutes posts a **macOS notification**
that names the meeting and the Obsidian note that matches its title, plus an
``obsidian://`` deep link to open it.
Designed to run unattended from ``hermes cron`` (``--no-agent`` watchdog
pattern): ``scan`` is silent when nothing is due, prints one line per reminder
sent, and dedupes via a small state file so a reminder fires **once** per
event instance no matter how often the scheduler ticks.
Python stdlib only. Notification backends (first available wins):
``terminal-notifier`` (clickable — opens the note) → ``osascript`` banner.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import unicodedata
from datetime import datetime, timedelta
from urllib.parse import quote
# Event titles/locations come from calendar invites and note names from a
# possibly-synced vault — treat as untrusted: strip control chars (terminal
# escapes) before printing or embedding in a notification. JSON output is safe.
CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")
CHILD_TIMEOUT = 60 # seconds per subprocess
def sanitize_text(s):
return CONTROL_CHARS_RE.sub(" ", s or "").strip()
class ReminderError(Exception):
"""User-facing error — message is safe to print (never contains secrets)."""
# --------------------------------------------------------------------------- #
# Hermes home / dotenv fallback (cron runs with a sanitized env — gotcha #1)
# --------------------------------------------------------------------------- #
def hermes_home():
return os.environ.get("HERMES_HOME") or os.path.expanduser("~/.hermes")
def _env_file_value(name, env_path=None):
"""Read NAME from ~/.hermes/.env (used when the var isn't in the process
env — cron jobs and nested children don't get skill env injection)."""
path = env_path or os.path.join(hermes_home(), ".env")
try:
with open(path, encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, val = line.partition("=")
if key.strip() == name:
val = val.strip()
if len(val) >= 2 and val[0] == val[-1] and val[0] in "\"'":
val = val[1:-1]
return val or None
except OSError:
return None
return None
# Shared config with the weekly-report skill: comma-separated substrings;
# events whose summary contains any of them (case-insensitive) are ignored
# entirely — no reminder, no curation. Undeclared on purpose (gotcha #5).
CAL_EXCLUDE_ENV = "CALENDAR_EXCLUDE"
def resolve_cal_excludes(cli_value=None):
"""Precedence: --exclude-events > $CALENDAR_EXCLUDE (real env) >
CALENDAR_EXCLUDE in ~/.hermes/.env. Same semantics as weekly-report."""
src = cli_value or os.environ.get(CAL_EXCLUDE_ENV) or \
_env_file_value(CAL_EXCLUDE_ENV) or ""
return [p.strip() for p in src.split(",") if p.strip()]
def event_excluded(summary, excludes):
"""True if `summary` contains any excluded substring (case-insensitive)."""
s = (summary or "").lower()
return any(x.lower() in s for x in excludes)
def vault_path(override=None):
p = override or os.environ.get("OBSIDIAN_VAULT") or _env_file_value("OBSIDIAN_VAULT")
if not p:
raise ReminderError(
"OBSIDIAN_VAULT is not configured — set it in ~/.hermes/.env "
"(absolute path to the vault folder)")
p = os.path.realpath(os.path.expanduser(p))
if not os.path.isdir(p):
raise ReminderError(f"vault folder not found: {p}")
return p
# --------------------------------------------------------------------------- #
# Google Calendar via the builtin google-workspace skill
# (same interpreter-probing pattern as the sibling calendar skill)
# --------------------------------------------------------------------------- #
_ABS_PYTHONS = ("/opt/homebrew/bin/python3", "/usr/local/bin/python3",
"/usr/bin/python3")
_PROBE = "import googleapiclient, google.auth, ssl"
_GCAL_PY = None
def _gws_dir():
return os.path.join(hermes_home(), "skills", "productivity",
"google-workspace", "scripts")
def gws_script(override=None):
return os.path.expanduser(override) if override else \
os.path.join(_gws_dir(), "google_api.py")
def _can_drive(py):
try:
r = subprocess.run([py, "-c", _PROBE], capture_output=True, timeout=20)
return r.returncode == 0
except (OSError, subprocess.TimeoutExpired):
return False
def gcal_python():
"""First interpreter that can import the Google client libs **and** ssl
(PATH python3 may be a pyenv shim with broken ssl under Hermes)."""
global _GCAL_PY
if _GCAL_PY:
return _GCAL_PY
candidates = []
for p in (os.environ.get("HERMES_GCAL_PYTHON"),
os.path.join(hermes_home(), ".venvs", "google", "bin", "python3")):
if p and p not in candidates:
candidates.append(os.path.expanduser(p))
for name in ("python3", "python"):
p = shutil.which(name)
if p and p not in candidates:
candidates.append(p)
for p in _ABS_PYTHONS:
if os.path.exists(p) and p not in candidates:
candidates.append(p)
if sys.executable and sys.executable not in candidates:
candidates.append(sys.executable)
for p in candidates:
if _can_drive(p):
_GCAL_PY = p
return p
return None
def _first_line(text):
for line in (text or "").splitlines():
line = line.strip()
if line:
return line[7:] if line.lower().startswith("error: ") else line
return ""
def _child_env():
"""Env for google_api.py that forces its Python-libs backend.
google_api.py prefers a Node ``gws`` CLI whenever one is on PATH. That CLI
needs keyring/Keychain access, which a GUI shell has but the Hermes
gateway's cron context does not — every scheduled scan died with
'Using keyring backend: keyring'. Dropping gws-bearing PATH entries (and
the HERMES_GWS_BIN override) makes google_api.py fall back to the Python
client libs + token file, which work in both contexts."""
env = os.environ.copy()
keep = [d for d in env.get("PATH", "").split(os.pathsep)
if d and not os.path.exists(os.path.join(d, "gws"))]
env["PATH"] = os.pathsep.join(keep) or "/usr/bin:/bin"
env.pop("HERMES_GWS_BIN", None)
return env
def run_gws_json(args, *, gws=None):
"""Run ``<py> google_api.py <args>`` → {"data": …} or {"error": …}."""
script = gws or gws_script()
if not os.path.exists(script):
return {"error": f"google-workspace skill not found at {script}"}
py = gcal_python()
if not py:
return {"error": "google API libraries not installed — see "
"`calendar check` in the calendar skill for setup"}
try:
proc = subprocess.run([py, script] + list(args),
capture_output=True, text=True, timeout=CHILD_TIMEOUT,
env=_child_env())
except subprocess.TimeoutExpired:
return {"error": f"timed out after {CHILD_TIMEOUT}s"}
except OSError as e:
return {"error": f"could not run google_api.py: {e.strerror or e}"}
if proc.returncode != 0:
return {"error": _first_line(proc.stderr) or f"exit code {proc.returncode}"}
try:
return {"data": json.loads(proc.stdout)}
except json.JSONDecodeError:
return {"error": _first_line(proc.stderr) or "google_api.py: non-JSON output"}
def _local_now():
return datetime.now().astimezone()
def parse_event_start(s):
"""RFC3339 datetime → aware local datetime; all-day 'YYYY-MM-DD' → None."""
if not s or (len(s) == 10 and s[4] == "-" and s[7] == "-"):
return None
try:
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
except ValueError:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=_local_now().tzinfo)
return dt.astimezone(_local_now().tzinfo)
def fetch_events(time_min, time_max, *, calendar="primary", gws=None):
"""Events overlapping [time_min, time_max] (aware datetimes) — raw list."""
res = run_gws_json(["calendar", "list",
"--start", time_min.isoformat(),
"--end", time_max.isoformat(),
"--max", "50", "--calendar", calendar], gws=gws)
if "error" in res:
raise ReminderError(f"calendar unavailable: {res['error']}")
return res.get("data") or []
# --------------------------------------------------------------------------- #
# Matching an event title to an Obsidian note
# --------------------------------------------------------------------------- #
_STOPWORDS = frozenset(
"de la el los las un una con y o en del al a por para sobre "
"the with and or of for on in to at about".split())
def _normalize(s):
"""Lowercase, strip accents, tokenize on non-alphanumerics."""
s = unicodedata.normalize("NFKD", s or "")
s = "".join(c for c in s if not unicodedata.combining(c)).lower()
return [t for t in re.split(r"[^a-z0-9]+", s) if t]
def _tokens(s):
return frozenset(t for t in _normalize(s) if t not in _STOPWORDS) or \
frozenset(_normalize(s))
def list_notes(vault):
"""[(rel_path, basename_no_ext, mtime)] for every .md note in the vault.
Skips dot-folders; contains every resolved path inside the vault (synced
folders can hold symlinks that escape)."""
base = os.path.realpath(vault)
out = []
for root, dirs, files in os.walk(base):
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
for f in files:
if not f.lower().endswith(".md"):
continue
full = os.path.join(root, f)
real = os.path.realpath(full)
if os.path.commonpath([base, real]) != base:
continue
try:
mtime = os.stat(full).st_mtime
except OSError:
continue
out.append((os.path.relpath(full, base), f[:-3], mtime))
return out
def _rel_tokens(rel):
"""Tokens of the whole vault-relative path — folders + basename — so a
note filed under `Acme 3.0/Kick-off ….md` matches an event titled
'Kick-off Acme 3.0'."""
if rel.lower().endswith(".md"):
rel = rel[:-3]
return _tokens(rel.replace(os.sep, " "))
def norm_key(summary):
"""Canonical form of an event title — the key for manual overrides
(case/accent/punctuation-insensitive, so every instance of a recurring
meeting hits the same mapping)."""
return " ".join(_normalize(summary))
def match_note(summary, notes, overrides=None):
"""Best note for an event title, or None.
A manual override (norm_key(title) → rel, from `map set`) wins outright
as long as that note still exists. Otherwise score each note by how much
of the event title it explains: basename token hits count double, folder
-path hits once, normalized by title length. A note qualifies when
(a) at least half the title's tokens appear in its path (with a basename
hit, or ≥2 path hits so a lone folder word can't match), or
(b) its entire basename appears in the title (hub-note fallback).
Ties break on most recently modified note. The half-coverage floor is what
keeps a 3-word title from latching onto any recent note sharing one word."""
ev = _tokens(summary)
if not ev:
return None
if overrides:
rel = overrides.get(norm_key(summary))
if rel and any(r == rel for r, _, _ in notes):
return rel
best, best_key = None, (0.0, 0.0)
for rel, name, mtime in notes:
base = _tokens(name)
path = _rel_tokens(rel)
ib = len(ev & base)
ip = len(ev & path)
if not ip and not ib:
continue
score = (2 * ib + ip) / len(ev)
if not ((2 * ip >= len(ev) and (ib > 0 or ip >= 2))
or (base and base <= ev)):
continue
key = (score, mtime)
if key > best_key:
best, best_key = rel, key
return best
def default_map_path():
"""Manual title→note overrides live outside cache/ — they're user data."""
return os.path.join(hermes_home(), "meeting_reminder_map.json")
def load_map(path=None):
"""{norm_key: {"title": original, "note": rel}} — {} when absent/corrupt."""
try:
with open(path or default_map_path(), encoding="utf-8") as fh:
data = json.load(fh)
return data if isinstance(data, dict) else {}
except (OSError, json.JSONDecodeError):
return {}
def map_overrides(mapping):
"""Flatten a loaded map to {norm_key: rel} for match_note."""
return {k: v.get("note") for k, v in mapping.items()
if isinstance(v, dict) and v.get("note")}
def save_map(mapping, path=None):
path = path or default_map_path()
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(mapping, fh, indent=2, ensure_ascii=False)
os.replace(tmp, path)
def resolve_note(notes, ref):
"""A user/agent-supplied note reference → exact rel path.
Accepts the vault-relative path or a unique basename (with or without
.md). Ambiguity or no match raises with the candidates listed."""
ref = (ref or "").strip().lstrip("/").replace("\\", "/")
if not ref:
raise ReminderError("empty note reference")
stem = ref[:-3] if ref.lower().endswith(".md") else ref
rels = {r for r, _, _ in notes}
for cand in (ref, stem + ".md"):
if cand in rels:
return cand
hits = [r for r, name, _ in notes if name.lower() == stem.lower()]
if len(hits) == 1:
return hits[0]
if hits:
raise ReminderError("ambiguous note name; use the full relative path: "
+ "; ".join(sanitize_text(h) for h in sorted(hits)))
raise ReminderError(f"note not found in vault: {sanitize_text(ref)}")
def obsidian_uri(vault, rel):
"""obsidian://open deep link for a note (rel path inside the vault)."""
name = os.path.basename(os.path.realpath(vault))
file = rel[:-3] if rel.lower().endswith(".md") else rel
return ("obsidian://open?vault=" + quote(name, safe="") +
"&file=" + quote(file.replace(os.sep, "/"), safe="/"))
# --------------------------------------------------------------------------- #
# Notification backends (argv-only — never interpolate untrusted text into
# a shell string or an AppleScript source line)
# --------------------------------------------------------------------------- #
# The cron scheduler's PATH may lack the Homebrew dirs (same trap as the
# interpreter probe), so check absolute locations too, not just which().
_TN_PATHS = ("/opt/homebrew/bin/terminal-notifier",
"/usr/local/bin/terminal-notifier")
def _terminal_notifier():
p = shutil.which("terminal-notifier")
if p:
return p
for cand in _TN_PATHS:
if os.path.exists(cand):
return cand
return None
def _osascript():
p = shutil.which("osascript")
if p:
return p
return "/usr/bin/osascript" if os.path.exists("/usr/bin/osascript") else None
def notifier_backend():
if _terminal_notifier():
return "terminal-notifier"
if _osascript():
return "osascript"
return None
def send_notification(title, body, uri=None):
"""Post a desktop notification; returns the backend used.
terminal-notifier gets ``-open uri`` (click opens the note in Obsidian);
the osascript fallback is a plain banner. Untrusted text is passed as
**argv** (osascript: via ``on run argv``) so it can't inject script."""
title, body = sanitize_text(title), sanitize_text(body)
backend = notifier_backend()
if backend == "terminal-notifier":
argv = [_terminal_notifier(), "-title", title, "-message", body,
"-sound", "Glass", "-group", "hermes-meeting-reminder"]
if uri:
argv += ["-open", uri]
elif backend == "osascript":
argv = [_osascript(),
"-e", "on run argv",
"-e", 'display notification (item 1 of argv) '
'with title (item 2 of argv) sound name "Glass"',
"-e", "end run",
body, title]
else:
raise ReminderError("no notification backend found "
"(need terminal-notifier or osascript)")
try:
proc = subprocess.run(argv, capture_output=True, text=True, timeout=30)
except (OSError, subprocess.TimeoutExpired) as e:
raise ReminderError(f"notification failed: {e}")
if proc.returncode != 0:
raise ReminderError(
f"notification failed: {_first_line(proc.stderr) or proc.returncode}")
return backend
# --------------------------------------------------------------------------- #
# Dedup state — one reminder per event instance
# --------------------------------------------------------------------------- #
def default_state_path():
return os.path.join(hermes_home(), "cache", "meeting_reminder_state.json")
def load_state(path):
try:
with open(path, encoding="utf-8") as fh:
data = json.load(fh)
return data if isinstance(data, dict) else {}
except (OSError, json.JSONDecodeError):
return {}
def save_state(path, state, *, now=None):
"""Persist, pruning entries whose reminder was sent > 48h ago."""
now = now or _local_now()
cutoff = (now - timedelta(hours=48)).isoformat()
pruned = {k: v for k, v in state.items()
if isinstance(v, str) and v >= cutoff}
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(pruned, fh)
os.replace(tmp, path)
def event_key(event):
return f"{event.get('id') or event.get('summary') or '?'}|{event.get('start')}"
# --------------------------------------------------------------------------- #
# Core: find due reminders
# --------------------------------------------------------------------------- #
GRACE_S = 90 # still remind for an event that started up to 90s ago
def due_reminders(events, state, *, lead_min, now):
"""Timed events starting within (now-grace, now+lead] not yet reminded."""
lo = now - timedelta(seconds=GRACE_S)
hi = now + timedelta(minutes=lead_min)
due = []
for e in events:
start = parse_event_start(e.get("start"))
if start is None or not (lo < start <= hi):
continue
if event_key(e) in state:
continue
due.append((e, start))
due.sort(key=lambda pair: pair[1])
return due
def reminder_payload(event, start, vault, notes, *, now, overrides=None):
"""(title, body, uri, info-dict) for one due event."""
summary = sanitize_text(event.get("summary") or "(no title)")
mins = max(0, round((start - now).total_seconds() / 60))
when = "now" if mins == 0 else f"in {mins} min"
title = f"{summary} — {when}"
parts = [f"Starts {start.strftime('%H:%M')}"]
loc = sanitize_text(event.get("location") or "")
if loc:
parts.append(f"@ {loc}")
rel = match_note(event.get("summary") or "", notes, overrides)
uri = obsidian_uri(vault, rel) if rel else None
if rel:
parts.append(f"note: {os.path.splitext(os.path.basename(rel))[0]}")
else:
parts.append("no matching note")
body = " · ".join(parts)
info = {"summary": summary, "start": start.isoformat(),
"start_local": start.strftime("%H:%M"), "minutes_until": mins,
"note": rel, "obsidian_uri": uri}
return title, body, uri, info
# --------------------------------------------------------------------------- #
# Subcommands
# --------------------------------------------------------------------------- #
def do_scan(args):
now = _local_now()
vault = vault_path(args.vault)
state_path = args.state or default_state_path()
state = load_state(state_path)
excludes = resolve_cal_excludes(args.exclude_events)
events = fetch_events(now - timedelta(seconds=GRACE_S),
now + timedelta(minutes=args.lead, seconds=60),
calendar=args.calendar, gws=args.gws_script)
events = [e for e in events
if not event_excluded(e.get("summary"), excludes)]
due = due_reminders(events, state, lead_min=args.lead, now=now)
if not due:
if args.json:
print(json.dumps({"sent": []}))
return 0
notes = list_notes(vault)
overrides = map_overrides(load_map(args.map_file))
sent = []
for event, start in due:
title, body, uri, info = reminder_payload(event, start, vault, notes,
now=now, overrides=overrides)
if not args.dry_run:
info["backend"] = send_notification(title, body, uri)
state[event_key(event)] = now.isoformat()
sent.append(info)
if not args.dry_run:
save_state(state_path, state, now=now)
if args.json:
print(json.dumps({"sent": sent, "dry_run": bool(args.dry_run)},
ensure_ascii=False))
else:
for i in sent:
note = i["note"] or "(no matching note)"
prefix = "[dry-run] " if args.dry_run else ""
print(f"{prefix}reminder: {i['summary']} at {i['start_local']} "
f"({i['minutes_until']} min) — {sanitize_text(note)}")
return 0
def do_upcoming(args):
now = _local_now()
vault = vault_path(args.vault)
events = fetch_events(now, now + timedelta(hours=args.hours),
calendar=args.calendar, gws=args.gws_script)
notes = list_notes(vault)
overrides = map_overrides(load_map(args.map_file))
excludes = resolve_cal_excludes(args.exclude_events)
rows = []
for e in events:
start = parse_event_start(e.get("start"))
if start is None or start < now:
continue
summary = e.get("summary") or ""
if event_excluded(summary, excludes):
continue
rel = match_note(summary, notes, overrides)
rows.append({
"summary": sanitize_text(summary or "(no title)"),
"start": start.isoformat(),
"start_local": start.strftime("%a %H:%M"),
"note": rel,
"mapped": bool(rel) and overrides.get(norm_key(summary)) == rel,
"obsidian_uri": obsidian_uri(vault, rel) if rel else None,
})
rows.sort(key=lambda r: r["start"])
if args.json:
print(json.dumps({"count": len(rows), "events": rows},
indent=2, ensure_ascii=False))
return 0
if not rows:
print(f"(no timed events in the next {args.hours}h)")
return 0
for r in rows:
note = sanitize_text(r["note"]) if r["note"] else "— no matching note"
tag = " (mapped)" if r["mapped"] else ""
print(f"{r['start_local']:>10} {r['summary']}\n"
f"{'':>10} ↳ {note}{tag}")
return 0
def do_map(args):
path = args.map_file or default_map_path()
mapping = load_map(path)
if args.action == "list":
if args.json:
print(json.dumps(mapping, indent=2, ensure_ascii=False))
elif not mapping:
print("(no manual mappings)")
else:
for v in mapping.values():
print(f"{sanitize_text(v.get('title', '?'))} -> "
f"{sanitize_text(v.get('note', '?'))}")
return 0
title, note = args.title, args.note
if args.action == "set" and args.spec_file:
# Agents must pass untrusted event titles via a JSON file, never
# inline in the command line (a title can contain $(…)/backticks).
try:
with open(args.spec_file, encoding="utf-8") as fh:
spec = json.load(fh)
except (OSError, json.JSONDecodeError) as e:
raise ReminderError(f"cannot read --spec-file: {e}")
if not isinstance(spec, dict) or \
not isinstance(spec.get("title"), str) or \
not isinstance(spec.get("note"), str):
raise ReminderError(
'--spec-file must be JSON: {"title": "...", "note": "..."}')
title, note = spec["title"], spec["note"]
if not title:
raise ReminderError(f"map {args.action} needs an event title")
key = norm_key(title)
if not key:
raise ReminderError("event title has no matchable words")
if args.action == "rm":
if mapping.pop(key, None) is None:
print(f"(no mapping for {sanitize_text(title)!r})")
return 1
save_map(mapping, path)
print(f"✓ removed mapping for {sanitize_text(title)!r}")
return 0
# set
if not note:
raise ReminderError("map set needs an event title and a note")
notes = list_notes(vault_path(args.vault))
rel = resolve_note(notes, note)
mapping[key] = {"title": sanitize_text(title), "note": rel}
save_map(mapping, path)
print(f"✓ mapped {sanitize_text(title)!r} -> {sanitize_text(rel)}")
return 0
def do_test_notify(args):
vault = vault_path(args.vault)
notes = list_notes(vault)
rel = notes[0][0] if notes else None
uri = obsidian_uri(vault, rel) if rel else None
backend = send_notification(
"Hermes meeting reminder — test",
f"Notifications work. Sample note: {rel or '(vault is empty)'}", uri)
print(f"✓ test notification sent via {backend}"
+ (f" (click opens: {rel})" if backend == "terminal-notifier" and rel
else ""))
if backend == "osascript" and uri:
print(" (banner only — `brew install terminal-notifier` makes the "
"notification clickable, opening the note in Obsidian)")
return 0
# ---- cron install ---------------------------------------------------------- #
JOB_NAME = "meeting-reminder"
WRAPPER_NAME = "meeting_reminder_cron.py"
WRAPPER_TEMPLATE = '''#!/usr/bin/env python3
"""Auto-generated by `meeting_reminder.py install-cron` — do not edit.
Runs the meeting-reminder scan; regenerate with install-cron --force."""
import runpy, sys
sys.argv = ["meeting_reminder.py", "scan", "--lead", {lead!r}]
runpy.run_path({script!r}, run_name="__main__")
'''
def _jobs_file():
return os.path.join(hermes_home(), "cron", "jobs.json")
def existing_job():
try:
with open(_jobs_file(), encoding="utf-8") as fh:
jobs = (json.load(fh) or {}).get("jobs") or []
except (OSError, json.JSONDecodeError):
return None
for j in jobs:
if isinstance(j, dict) and j.get("name") == JOB_NAME:
return j
return None
def _hermes_cmd():
exe = shutil.which("hermes")
if not exe:
raise ReminderError("`hermes` CLI not found on PATH — run install-cron "
"from a shell where hermes works")
return exe
def do_install_cron(args):
job = existing_job()
if job and not args.force:
print(f"✓ cron job '{JOB_NAME}' already installed "
f"(id {job.get('id', '?')}). Use --force to recreate.")
return 0
hermes = _hermes_cmd()
if job and args.force:
subprocess.run([hermes, "cron", "remove", str(job.get("id"))],
capture_output=True, text=True, timeout=CHILD_TIMEOUT)
scripts_dir = os.path.join(hermes_home(), "scripts")
os.makedirs(scripts_dir, exist_ok=True)
wrapper = os.path.join(scripts_dir, WRAPPER_NAME)
with open(wrapper, "w", encoding="utf-8") as fh:
fh.write(WRAPPER_TEMPLATE.format(lead=str(args.lead),
script=os.path.realpath(__file__)))
proc = subprocess.run(
[hermes, "cron", "create", args.schedule,
"--name", JOB_NAME, "--no-agent", "--script", WRAPPER_NAME,
"--deliver", "local"],
capture_output=True, text=True, timeout=CHILD_TIMEOUT)
if proc.returncode != 0:
raise ReminderError("hermes cron create failed: "
+ (_first_line(proc.stderr or proc.stdout)
or f"exit {proc.returncode}"))
print(f"✓ installed: wrapper {wrapper}")
print(f"✓ cron job '{JOB_NAME}' — schedule '{args.schedule}', "
f"lead {args.lead} min, no-agent scan")
print(" Reminders fire while Hermes (app or gateway) is running; for "
"always-on delivery run `hermes gateway install`.")
return 0
def do_uninstall_cron(_args):
job = existing_job()
if job:
subprocess.run([_hermes_cmd(), "cron", "remove", str(job.get("id"))],
capture_output=True, text=True, timeout=CHILD_TIMEOUT)
print(f"✓ removed cron job '{JOB_NAME}'")
else:
print(f"(no cron job named '{JOB_NAME}')")
wrapper = os.path.join(hermes_home(), "scripts", WRAPPER_NAME)
if os.path.exists(wrapper):
os.remove(wrapper)
print(f"✓ removed wrapper {wrapper}")
return 0
def do_check(args):
ok = True
# Vault
try:
vault = vault_path(args.vault)
n = len(list_notes(vault))
print(f"✓ vault: {vault} ({n} notes)")
except ReminderError as e:
ok = False
print(f"✗ vault: {e}")
# Calendar backend
if not os.path.exists(gws_script(args.gws_script)):
ok = False
print("✗ calendar: google-workspace skill not found")
elif gcal_python() is None:
ok = False
print("✗ calendar: google API libraries not installed "
"(see `calendar check` in the calendar skill)")
else:
print(f"✓ calendar: backend ready (interpreter {gcal_python()})")
# Notifier
backend = notifier_backend()
if backend:
extra = "" if backend == "terminal-notifier" else \
" (banner only — `brew install terminal-notifier` for clickable)"
print(f"✓ notifier: {backend}{extra}")
else:
ok = False
print("✗ notifier: neither terminal-notifier nor osascript found")
# Event excludes (shared CALENDAR_EXCLUDE config)
n_excl = len(resolve_cal_excludes())
if n_excl:
print(f"✓ excludes: {n_excl} summary substring(s) ignored "
f"(${CAL_EXCLUDE_ENV})")
else:
print(f"• excludes: none (set ${CAL_EXCLUDE_ENV} in ~/.hermes/.env "
"to ignore matching meetings)")
# Cron job + scheduler tick
job = existing_job()
if job:
state = "paused" if job.get("paused") else "active"
print(f"✓ cron job: '{JOB_NAME}' installed ({state})")
else:
print("• cron job: not installed — run `install-cron` to schedule scans")
tick = os.path.join(hermes_home(), "cron", "ticker_last_success")
try:
with open(tick, encoding="utf-8") as fh:
age = _local_now().timestamp() - float(fh.read().strip())
if age < 600:
print(f"✓ scheduler: ticking (last tick {int(age)}s ago)")
else:
print(f"• scheduler: last tick {int(age / 60)} min ago — start the "
"Hermes app or `hermes gateway install` for reminders to fire")
except (OSError, ValueError):
print("• scheduler: no tick recorded yet — reminders fire only while "
"Hermes (app or gateway) is running")
return 0 if ok else 1
# --------------------------------------------------------------------------- #
def build_parser():
p = argparse.ArgumentParser(
prog="meeting_reminder",
description="Desktop reminders before meetings, linking the matching "
"Obsidian note.")
sub = p.add_subparsers(dest="cmd")
def add_common(sp, calendar=True):
sp.add_argument("--vault", help="override OBSIDIAN_VAULT path")
if calendar:
sp.add_argument("--calendar", default="primary",
help="calendar id (default primary)")
sp.add_argument("--gws-script", help="override path to google_api.py")
chk = sub.add_parser("check", help="verify vault, calendar, notifier, cron")
add_common(chk)
sc = sub.add_parser("scan", help="send due reminders (cron entrypoint)")
sc.add_argument("--lead", type=int, default=5,
help="minutes before start to remind (default 5)")
sc.add_argument("--dry-run", action="store_true",
help="print what would be sent; no notification, no state")
sc.add_argument("--state", help="override state file path")
sc.add_argument("--exclude-events",
help="comma-separated summary substrings to ignore "
"(default: $CALENDAR_EXCLUDE)")
sc.add_argument("--map-file", help="override manual-mapping file path")
sc.add_argument("--json", action="store_true", help="machine-readable output")
add_common(sc)
up = sub.add_parser("upcoming", help="preview events + matched notes")
up.add_argument("--hours", type=int, default=24,
help="look-ahead window in hours (default 24)")
up.add_argument("--exclude-events",
help="comma-separated summary substrings to ignore "
"(default: $CALENDAR_EXCLUDE)")
up.add_argument("--map-file", help="override manual-mapping file path")
up.add_argument("--json", action="store_true", help="machine-readable output")
add_common(up)
mp = sub.add_parser("map",
help="manual event-title → note overrides (set/list/rm)")
mp.add_argument("action", choices=("set", "list", "rm"))
mp.add_argument("title", nargs="?", help="event title (as on the calendar)")
mp.add_argument("note", nargs="?",
help="note: vault-relative path or unique basename")
mp.add_argument("--spec-file",
help='set via JSON file {"title": …, "note": …} — the '
"safe way for agents (titles are untrusted)")
mp.add_argument("--map-file", help="override manual-mapping file path")
mp.add_argument("--json", action="store_true", help="machine-readable output")
mp.add_argument("--vault", help="override OBSIDIAN_VAULT path")
tn = sub.add_parser("test-notify", help="send a test desktop notification")
add_common(tn, calendar=False)
ic = sub.add_parser("install-cron",
help="create the hermes cron job (every minute)")
ic.add_argument("--lead", type=int, default=5,
help="minutes before start to remind (default 5)")
ic.add_argument("--schedule", default="* * * * *",
help="cron schedule (default every minute)")
ic.add_argument("--force", action="store_true",
help="recreate the job/wrapper if already installed")
sub.add_parser("uninstall-cron", help="remove the cron job + wrapper")
return p
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
handlers = {
"check": do_check,
"scan": do_scan,
"upcoming": do_upcoming,
"map": do_map,
"test-notify": do_test_notify,
"install-cron": do_install_cron,
"uninstall-cron": do_uninstall_cron,
}
if args.cmd is None:
parser.print_help()
return 2
try:
return handlers[args.cmd](args)
except ReminderError as e:
print(f"error: {e}", file=sys.stderr)
return 1
except KeyboardInterrupt:
return 130
if __name__ == "__main__":
sys.exit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| planning-and-task-breakdownaddyosmani/agent-skillsBreaks work into ordered tasks. Use when you have a spec or clear requirements and need to break work into implementable tasks. Use when a task feels too large to start, when you need to estimate scope, or when parallel work is possible. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| screenpipethedotmack/claude-memSearch screen and audio history recorded by Screenpipe and optionally save selected context into claude-mem. Use when the user asks to recall desktop activity, a meeting, or something seen in another app through Screenpipe. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |
| contact-widgetnexu-io/open-designSelf-contained floating chat widget with welcome screen, social links, meeting button, and message input. Single HTML file, zero dependencies. | Stars: 108k | Updated | Claude CodeCodex | Verified | Install |
| meeting-notesnexu-io/open-designMeeting notes page — title bar with attendees, agenda checklist, decisions block, action items table with owners + dates, and a "next meeting" footer. Use when the brief mentions "meeting notes", "minutes", "1:1 notes", "all-hands recap", or "会议纪要". | Stars: 108k | Updated | Claude CodeCodex | Verified | Install |