#!/usr/bin/env python3
# Modified by the Noite project on 2026-11-10 under the Apache License 2.0: every name in it says Noite instead of the product it grew from (identifiers, files, strings, URLs).
"""Keep the Mac's total CPU under a cap by throttling only the agents' own work.

  scripts/agent/cpu-cap [--cap 70] [--resume 55] [--every 3]

"Ours" is every process whose command line mentions this checkout or the agents' scratch folders (/private/tmp/claude-*)
plus all their descendants: builds (xcodebuild, clang, swift, ld, hermesc), benches, Metro, hidden test instances,
Codex runs started from here. The owner's apps (/Applications/Noite.app, Claude, games) are never touched.

  - Every process of ours is moved to background QoS (taskpolicy -b -p): efficiency cores, lowest I/O. Except
    processes whose command line holds "/perf-gate/" (put a release gate's app copies in such a folder) so its
    timings stand for what users get; those can still be paused.
  - While total CPU is over --cap, the busiest processes of ours are paused (SIGSTOP), busiest first.
  - Once total CPU is under --resume, they are resumed (SIGCONT), one per tick.
  - On exit (any signal) everything paused is resumed.
Agents: a paused build or instance just runs slower; give waits their deadlines as usual.

  scripts/agent/cpu-cap --league            (= --during /Game/LeagueOfLegends.app/ --share 40)
  scripts/agent/cpu-cap --during PATTERN --share PCT

Share mode caps our own work instead of the total, and only while a process whose command line holds PATTERN runs
(League's game itself, not its client; matched ignoring case, as the game's path is spelled either way). Then: ours go to background QoS, and our share of the whole machine,
measured from each process's CPU time over the tick, stays at or under PCT by pausing our busiest processes. A paused
one resumes once its last rate fits under PCT again. When the match ends, everything is resumed and taken out of
background QoS: full speed.
"""
import argparse, os, re, signal, subprocess, sys, time

REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MARKERS = (REPO + "/", REPO + " ", "/private/tmp/claude-", "/tmp/ac-")
NEVER = ("/Applications/Noite.app/", "/Applications/Claude.app/", "/Applications/League of Legends.app/",
         "/System/", "/usr/libexec/", "/sbin/launchd")
COORD = {"SWBBuildService", "ibtoold", "xcodebuild", "XCBBuildService", "lockf", "siso", "ninja", "autoninja", "gn"}
TOOLS = COORD | {"bash", "zsh", "sh", "-zsh", "top", "ps", "git", "perl", "lockf", "timeout", "sleep", "python3", "Python",
         "osascript", "log", "caffeinate", "codex", "node_repl"}
ME = os.getpid()

ap = argparse.ArgumentParser()
ap.add_argument("--cap", type=float, default=70)
ap.add_argument("--resume", type=float, default=60)
ap.add_argument("--every", type=float, default=3)
ap.add_argument("--max-pause", type=float, default=60, help="seconds; a job paused this long gets a turn (no starvation)")
ap.add_argument("--during", action="append", default=[], help="share mode: throttle only while this process runs")
ap.add_argument("--share", type=float, help="share mode: our CPU, in %% of the whole machine, while --during runs")
ap.add_argument("--league", action="store_true", help="--during /Game/LeagueOfLegends.app/ --share 40")
a = ap.parse_args()
if a.league:
    a.during.append("/Game/LeagueOfLegends.app/")
    a.share = a.share if a.share is not None else 40
if bool(a.during) != (a.share is not None):
    ap.error("--during and --share go together")

paused = []
paused_at = {}
turn_until = {}
backgrounded = set()


def log(msg):
    print(time.strftime("%H:%M:%S"), msg, flush=True)


def total_cpu():
    out = subprocess.run(["top", "-l", "2", "-s", "1", "-n", "0"], capture_output=True, text=True).stdout
    lines = [l for l in out.splitlines() if l.startswith("CPU usage")]
    m = re.search(r"([\d.]+)% idle", lines[-1]) if lines else None
    return 100 - float(m.group(1)) if m else 0.0


def cpu_seconds(t):
    """ps's time column: [[dd-]hh:]mm:ss.ss"""
    days, _, t = t.rpartition("-")
    secs = 0.0
    for part in t.split(":"):
        secs = secs * 60 + float(part)
    return secs + (int(days) * 86400 if days else 0)


def snapshot():
    """Every process: pid -> (ppid, pcpu, command, CPU seconds so far)."""
    out = subprocess.run(["ps", "-axo", "pid=,ppid=,pcpu=,time=,command="], capture_output=True, text=True).stdout
    procs = {}
    for line in out.splitlines():
        p = line.split(None, 4)
        if len(p) < 5:
            continue
        try:
            procs[int(p[0])] = (int(p[1]), float(p[2]), p[4], cpu_seconds(p[3]))
        except ValueError:
            continue
    return procs


def ours(procs=None):
    procs = procs if procs is not None else snapshot()
    roots = {pid for pid, (_, _, cmd, _) in procs.items()
             if any(m in cmd for m in MARKERS) and not any(n in cmd for n in NEVER)}
    mine = set()
    for pid in procs:
        seen, cur = [], pid
        while cur in procs and cur > 1 and cur not in seen:
            if cur in roots or cur in mine:
                mine.add(pid)
                break
            seen.append(cur)
            cur = procs[cur][0]
    cur = ME
    while cur in procs and cur > 1:
        mine.discard(cur)
        cur = procs[cur][0]
    mine = {p for p in mine if not any(n in procs[p][2] for n in NEVER)}
    return {p: procs[p] for p in mine}


def alive(pid):
    try:
        os.kill(pid, 0)
        return True
    except ProcessLookupError:
        return False
    except PermissionError:
        return True


def resume_all(*_):
    for pid in paused:
        try:
            os.kill(pid, signal.SIGCONT)
        except ProcessLookupError:
            pass
    log(f"exit: resumed {len(paused)}")
    sys.exit(0)


for s in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
    signal.signal(s, resume_all)

def pausable(cmd):
    return os.path.basename(cmd.split()[0]) not in TOOLS


def share_loop():
    ncpu = os.cpu_count()
    active = False
    last, last_at = {}, time.time()
    rate = {}
    log(f"share mode: ours <= {a.share}% while {a.during} runs; repo {REPO}")
    while True:
        time.sleep(a.every)
        procs = snapshot()
        now = time.time()
        dt, last_at = now - last_at, now
        mine = ours(procs)
        paused[:] = [p for p in paused if alive(p)]
        mine_up = set()
        cur = ME
        while cur in procs and cur > 1:
            mine_up.add(cur)
            cur = procs[cur][0]
        running = any(any(d.lower() in cmd.lower() for d in a.during)
                      for pid, (_, _, cmd, _) in procs.items() if pid not in mine_up)
        if not running:
            if active:
                for pid in paused:
                    try:
                        os.kill(pid, signal.SIGCONT)
                    except ProcessLookupError:
                        pass
                for pid in backgrounded:
                    subprocess.run(["taskpolicy", "-B", "-p", str(pid)], capture_output=True)
                log(f"match over: resumed {len(paused)}, {len(backgrounded)} back to normal QoS")
                paused.clear(); paused_at.clear(); turn_until.clear(); backgrounded.clear()
                active = False
            last = {pid: procs[pid][3] for pid in mine}
            continue
        if not active:
            log("match on: capping ours")
            active = True
        for pid in mine.keys() - backgrounded:
            if "/perf-gate/" not in mine[pid][2]:
                subprocess.run(["taskpolicy", "-b", "-p", str(pid)], capture_output=True)
                backgrounded.add(pid)
        backgrounded.intersection_update(mine.keys() | set(paused))
        for pid, (_, _, _, secs) in mine.items():
            if pid not in paused:
                rate[pid] = max(0.0, secs - last.get(pid, 0.0)) / dt / ncpu * 100
        last = {pid: procs[pid][3] for pid in mine}
        for pid in list(rate):
            if pid not in mine and pid not in paused:
                del rate[pid]
        share = sum(r for pid, r in rate.items() if pid not in paused)
        for pid in [p for p in paused if now - paused_at.get(p, now) > a.max_pause]:
            try:
                os.kill(pid, signal.SIGCONT)
            except ProcessLookupError:
                pass
            paused.remove(pid); paused_at.pop(pid, None)
            turn_until[pid] = now + a.max_pause / 2
            share += rate.get(pid, 0)
        if share > a.share:
            for pid in sorted((p for p in mine if p not in paused), key=lambda p: -rate.get(p, 0)):
                if share <= a.share:
                    break
                if rate.get(pid, 0) < 1 or turn_until.get(pid, 0) > now or not pausable(mine[pid][2]):
                    continue
                try:
                    os.kill(pid, signal.SIGSTOP)
                except ProcessLookupError:
                    continue
                paused.append(pid); paused_at[pid] = now
                share -= rate[pid]
                log(f"ours {share + rate[pid]:.0f}%: paused {pid} ({rate[pid]:.0f}%) {mine[pid][2][:80]}")
        else:
            for pid in list(paused):
                if share + rate.get(pid, 0) > a.share:
                    break
                try:
                    os.kill(pid, signal.SIGCONT)
                except ProcessLookupError:
                    pass
                paused.remove(pid); paused_at.pop(pid, None)
                share += rate.get(pid, 0)


if a.share is not None:
    try:
        share_loop()
    except Exception as e:
        log(f"error {e!r}")
        resume_all()

log(f"cap {a.cap}% resume {a.resume}% repo {REPO}")
try:
    while True:
        procs = ours()
        for pid in procs.keys() - backgrounded:
            if "/perf-gate/" in procs[pid][2]:
                continue
            subprocess.run(["taskpolicy", "-b", "-p", str(pid)], capture_output=True)
            backgrounded.add(pid)
        backgrounded &= procs.keys() | set(paused)
        paused[:] = [p for p in paused if alive(p)]
        now = time.time()
        for pid in [p for p in paused if now - paused_at.get(p, now) > a.max_pause]:
            try:
                os.kill(pid, signal.SIGCONT)
                log(f"turn: resumed {pid} after {now - paused_at[pid]:.0f}s")
            except ProcessLookupError:
                pass
            paused.remove(pid)
            paused_at.pop(pid, None)
            turn_until[pid] = now + a.max_pause / 2
        cpu = total_cpu()
        if cpu > a.cap:
            budget = cpu - a.cap + 5
            for pid, (_, pcpu, cmd, _) in sorted(procs.items(), key=lambda kv: -kv[1][1]):
                if budget <= 0 or pcpu < 3 or pid in paused or turn_until.get(pid, 0) > now:
                    continue
                if not pausable(cmd):
                    continue
                try:
                    os.kill(pid, signal.SIGSTOP)
                except ProcessLookupError:
                    continue
                paused.append(pid)
                paused_at[pid] = now
                budget -= pcpu / os.cpu_count()
                log(f"cpu {cpu:.0f}%: paused {pid} ({pcpu:.0f}%) {cmd[:90]}")
        elif cpu < a.resume and paused:
            pid = paused.pop(0)
            paused_at.pop(pid, None)
            try:
                os.kill(pid, signal.SIGCONT)
                log(f"cpu {cpu:.0f}%: resumed {pid}")
            except ProcessLookupError:
                pass
        time.sleep(a.every)
except Exception as e:
    log(f"error {e!r}")
    resume_all()
