#!/usr/bin/env python3 """Routines: actions that fire when a period has elapsed since they last ran. Definitions and state both live in the `routines:` block of ckb.yaml: routines: - name: weekly-lint do: "Lint" # any phrase from the AGENTS.md routing table, or a plain instruction every: 7d # Nh | Nd | Nw confirm: false # true: ask before running instead of running after the request last_run: 2026-10-21 # written by --mark when the action completes; blank = never ran routines.py --due [--today YYYY-MM-DD] # one line per due routine; exit 1 when any is due, 0 otherwise routines.py --list # every routine with last run, next due date and confirm flag routines.py --mark [--today ...] # set last_run to today routines.py --add --name X --do "..." --every 7d [--confirm] routines.py --remove Edits are line-level: only the lines of the routine named are touched, the rest of ckb.yaml is left byte for byte. Python 3.8+, standard library only. """ import argparse import re import sys from datetime import date, datetime, timedelta from pathlib import Path PERIOD = re.compile(r"^(\d+)([hdw])$") NAME = re.compile(r"^[a-z0-9][a-z0-9-]*$") FORBIDDEN = ("ckb-reset", "ckb-sync-changes", "reset the wiki", "sync changes", "sync with origin") KEYS = ("name", "do", "every", "confirm", "last_run") # ---------------------------------------------------------------- parsing def strip_comment(line: str) -> str: out, quote = [], None for ch in line: if quote: out.append(ch) if ch == quote: quote = None elif ch in "\"'": quote = ch out.append(ch) elif ch == "#": break else: out.append(ch) return "".join(out).rstrip() def unquote(v: str) -> str: v = v.strip() if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'": return v[1:-1] return v def parse(path: Path): """Return (lines, block) where block is None when there is no `routines:` key, else a dict with start/end line indexes and a list of routine items, each carrying its own line span and key->(value, line_index).""" lines = path.read_text(encoding="utf-8").splitlines() if path.exists() else [] start = None for i, raw in enumerate(lines): if strip_comment(raw).strip() == "routines:" and not raw.startswith((" ", "\t")): start = i break if strip_comment(raw).strip().startswith("routines:") and not raw.startswith((" ", "\t")): # `routines: []` or similar inline value start = i break if start is None: return lines, None end = len(lines) for j in range(start + 1, len(lines)): raw = lines[j] if raw.strip() and not raw.startswith((" ", "\t")) and not raw.lstrip().startswith("#"): end = j break items, cur = [], None for j in range(start + 1, end): text = strip_comment(lines[j]) if not text.strip(): continue m = re.match(r"^(\s*)-\s*(.*)$", text) if m: cur = {"first": j, "last": j, "indent": len(m.group(1)), "fields": {}} items.append(cur) rest = m.group(2) if ":" in rest: k, v = rest.split(":", 1) cur["fields"][k.strip()] = (unquote(v), j) continue if cur is not None and ":" in text: k, v = text.strip().split(":", 1) cur["fields"][k.strip()] = (unquote(v), j) cur["last"] = j inline = strip_comment(lines[start]).split(":", 1)[1].strip() return lines, {"start": start, "end": end, "items": items, "inline_empty": inline in ("[]", "")} def routine(item): f = item["fields"] get = lambda k: f.get(k, ("", None))[0] return { "name": get("name"), "do": get("do"), "every": get("every"), "confirm": get("confirm").lower() in ("true", "yes", "on"), "last_run": get("last_run"), } def period_delta(spec: str) -> timedelta: m = PERIOD.match(spec.strip()) if not m: raise ValueError(f"bad period {spec!r}: use Nh, Nd or Nw (e.g. 24h, 7d, 2w)") n, unit = int(m.group(1)), m.group(2) return {"h": timedelta(hours=n), "d": timedelta(days=n), "w": timedelta(weeks=n)}[unit] def parse_day(s: str): try: return datetime.strptime(s.strip(), "%Y-%m-%d") except ValueError: return None def status(r, today: datetime): """(due: bool, next_due: datetime|None, detail: str). last_run is a date, taken at 00:00, so hour periods are coarse: 24h behaves like 1d.""" if not r["every"]: return False, None, "no period" try: every = period_delta(r["every"]) except ValueError as e: return False, None, str(e) if not r["last_run"]: return True, today, "never ran" last = parse_day(r["last_run"]) if last is None: return True, today, f"unreadable last_run {r['last_run']!r}" nxt = last + every if nxt <= today: over = today - nxt return True, nxt, f"overdue by {over.days}d" if over.days else "due today" return False, nxt, f"next {nxt.strftime('%Y-%m-%d')}" # ---------------------------------------------------------------- writing def write(path: Path, lines): path.write_text("\n".join(lines) + "\n", encoding="utf-8") def find(block, name): for it in block["items"]: if it["fields"].get("name", ("",))[0] == name: return it return None def cmd_mark(path, name, today): lines, block = parse(path) it = block and find(block, name) if not it: sys.exit(f"error: no routine named {name!r} in {path}") stamp = today.strftime("%Y-%m-%d") if "last_run" in it["fields"]: j = it["fields"]["last_run"][1] lines[j] = re.sub(r"(last_run:\s*)\S*", r"\g<1>" + stamp, lines[j], count=1) else: pad = " " * (it["indent"] + 2) lines.insert(it["last"] + 1, f"{pad}last_run: {stamp}") write(path, lines) print(f"marked {name}: last_run {stamp}") def cmd_add(path, name, do, every, confirm): if not NAME.match(name): sys.exit("error: name must be lower-case letters, digits and hyphens") period_delta(every) low = do.lower() if any(f in low for f in FORBIDDEN): sys.exit("error: a routine may not run ckb-reset or ckb-sync-changes (destructive / touches the remote)") lines, block = parse(path) if block and find(block, name): sys.exit(f"error: routine {name!r} already exists; --remove it first") do_q = '"' + do.replace('"', "'") + '"' item = [f" - name: {name}", f" do: {do_q}", f" every: {every}", f" confirm: {'true' if confirm else 'false'}", f" last_run:"] if block is None: if lines and lines[-1].strip(): lines.append("") lines.append("routines: # actions that fire when `every` has elapsed since `last_run`") lines.extend(item) else: if block["inline_empty"]: # `routines: [] # comment` -> `routines: # comment`: drop the brackets, keep the width lines[block["start"]] = lines[block["start"]].replace("[]", " ", 1).rstrip() lines[block["end"]:block["end"]] = item write(path, lines) print(f"added {name}: {do} every {every}" + (" (confirm first)" if confirm else "") + " — fires at the next session start") def cmd_remove(path, name): lines, block = parse(path) it = block and find(block, name) if not it: sys.exit(f"error: no routine named {name!r} in {path}") del lines[it["first"]:it["last"] + 1] if len(block["items"]) == 1: # that was the last one: leave an explicit empty list head = lines[block["start"]] if re.match(r"^routines:\s{3,}#", head): # width was kept by --add: put the brackets back lines[block["start"]] = re.sub(r"^routines: ", "routines: []", head, count=1) else: lines[block["start"]] = "routines: []" write(path, lines) print(f"removed {name}") # ---------------------------------------------------------------- main def main(argv=None): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) g = ap.add_mutually_exclusive_group(required=True) g.add_argument("--due", action="store_true") g.add_argument("--list", action="store_true") g.add_argument("--mark", metavar="NAME") g.add_argument("--add", action="store_true") g.add_argument("--remove", metavar="NAME") ap.add_argument("--name"); ap.add_argument("--do"); ap.add_argument("--every") ap.add_argument("--confirm", action="store_true") ap.add_argument("--root", default=".", help="KB root (default: current directory)") ap.add_argument("--today", help="override today's date, YYYY-MM-DD (tests)") a = ap.parse_args(argv) path = Path(a.root) / "ckb.yaml" today = parse_day(a.today) if a.today else datetime.combine(date.today(), datetime.min.time()) if today is None: sys.exit("error: --today must be YYYY-MM-DD") if a.mark: cmd_mark(path, a.mark, today); return 0 if a.add: if not (a.name and a.do and a.every): sys.exit("error: --add needs --name, --do and --every") cmd_add(path, a.name, a.do, a.every, a.confirm); return 0 if a.remove: cmd_remove(path, a.remove); return 0 _, block = parse(path) items = [routine(it) for it in (block["items"] if block else [])] if a.list: if not items: print("no routines in ckb.yaml"); return 0 for r in items: due, _, detail = status(r, today) flag = "DUE " if due else " " print(f"{flag}{r['name']:<20} every {r['every']:<5} last {r['last_run'] or 'never':<10} {detail}" + (" [confirm]" if r["confirm"] else "") + f" — {r['do']}") return 0 # --due due_items = [] for r in items: due, _, detail = status(r, today) if due: due_items.append((r, detail)) for r, detail in due_items: print(f"{r['name']} {r['do']} {detail}" + (" [confirm]" if r["confirm"] else "")) return 1 if due_items else 0 if __name__ == "__main__": sys.exit(main())