#!/usr/bin/env python3
"""Start sessions of the session plan side by side on one server, without conflicts between them.

What can start comes from GitHub: the open issues that sync_github.py labelled `ready`. Each session gets its own
git worktree and branch (session/<SESSION-ID>, cut from origin/main), its own tmux window, and the variables
HIS_SESSION, HIS_ISSUE and COMPOSE_PROJECT_NAME, which name its issue and its integration environment. The
launcher labels the issue `running` and comments where the session runs.

  launch_sessions.py list                        what is running, in review, blocked and ready
  launch_sessions.py start [--max N] [ID ...]    tidy up, then start the named sessions or as many ready ones as fit
  launch_sessions.py watch [--every SECONDS]     do `start` again and again
  launch_sessions.py pause [ID ... | --all]      interrupt running sessions and free their places
  launch_sessions.py resume [ID ... | --all]     continue paused sessions, and running ones that lost their window
  launch_sessions.py review ID ...               review the named pull requests now, even while usage holds reviews
  launch_sessions.py tidy                        remove the worktrees and environments of sessions whose issue is closed

Permissions. The same settings file allows, without asking, the commands in SESSION_PERMISSIONS of sessions_def.py:
reading, git on the session's own branch, and gh on its own issue and pull request; it denies force pushes, pushes
to main, merging and the plan build. Anything else asks a person in the session's window.

Review and merge. When a session's pull request is open and its checks pass, `start` and `watch` have an independent
review agent (claude -p, read-only, REVIEW_PROMPT of sessions_def.py) review it. If it approves, the launcher merges
the pull request, which closes the issue. If it asks for changes or conflicts with main, the launcher passes that to
the session, which fixes it on its branch, and the next push is reviewed again. No person merges, unless AUTO_MERGE in
sessions_def.py names the session's kind, its labels or the files it changes, or sets a limit of rounds; such pull
requests are labelled `merge-by-person`.

Reviews run side by side. A pass starts a review in the background (up to --max-reviews at once) and goes on; a later
pass reads its verdict and merges or sends it back, so merges and messages to sessions still happen one at a time.
Two pull requests that change a file in common are never under review at the same time: the second waits until the
first is merged or sent back, and is then reviewed only if it still merges with main. So two approvals cannot
conflict with each other. A review whose pull request gets a new commit, or leaves review, is stopped.

Remote Control. Each agent session is started with --remote-control <SESSION-ID>, so it appears in the Claude app
(Code) and on claude.ai/code under its identifier, where it can be watched and answered from a phone; the session
itself keeps running here. --no-remote-control leaves it out.

Usage limits. Each session runs with a settings file of its own (--settings), which keeps it on one model (Opus by
default), turns off background requests that spend the plan's allowance, and points its status line and its
StopFailure hook at usage_hooks.py. Every running session so keeps <state>/usage.json up to date with the account's
five-hour and weekly usage. `start` and `watch` start no new session while the five-hour window is above
--five-hour-hold, or while the weekly window is ahead of an even pace through the week by more than --weekly-margin.
Claude Code itself continues a session when the limit resets, but gives up after three hits in a row and never
waits more than a day; `watch` continues those sessions after the reset (recover).

--max limits the agents at work, not only the sessions on their cards. A session holds a place while its issue is
open, not blocked, not paused and has no open pull request, and also while its agent window is open for any other
reason, as when it fixes what a review asked of its pull request. A message for a session whose window is gone, such as
a review's change request, would open a new window; when every place is taken it is held instead, under
<state>/held/, and passed on, oldest first and before any new session starts, as places free up. A paused session
frees its place even while its window stays open. The review agents hold no place.
The worktree of a session in review, blocked or paused is kept, so that the session can be run again in it; it is removed when the
issue closes. So are the session's integration environments: its own, the twin of its isolation check, and
anything else carrying its label care.cema.his.session (start, watch and tidy do this).

Resting environments. While a session waits, its integration environments are stopped, not removed: a session waits
when its pull request is open, it is blocked or it is paused, and its agent is not working (its window is closed, or
shows no "esc to interrupt"). On a shared 4-CPU host the idle stacks of sessions in review (a full profile with
Keycloak and telemetry keeps a CPU busy) slowed every other session and the pipeline's runners. start and watch
stop them with docker stop, keep the stopped containers' identifiers under <state>/rested/, and start exactly those
again before a message reaches the session, or on the next pass once its agent works again. Data and volumes stay.

Reads   data/sessions.csv on origin/main, definitions/sessions_def.py (the session prompt), GitHub (through gh)
Writes  worktrees under <repository>-wt/ beside the repository; labels and comments on the issues;
        <state>/settings/<SESSION-ID>.json, <state>/held/<SESSION-ID>.json and <state>/rested/<SESSION-ID>.json,
        where <state> is HIS_STATE or ~/.cache/his
Not a build step. Needs gh, signed in with the `repo` scope, and tmux.
"""
import argparse, calendar, csv, hashlib, io, json, os, re, shlex, shutil, signal, subprocess, sys, time, traceback

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, 'definitions'))
sys.path.insert(0, HERE)
sys.dont_write_bytecode = True
from sessions_def import SESSION_PROMPT, SESSION_PERMISSIONS, AUTO_MERGE, REVIEW_PROMPT  # noqa: E402
import sync_github as hub  # noqa: E402

PLAN_REL = 'docs/implementation_plan'
# Kinds that need the full integration environment. A fix ends when the slice scenario still passes, which runs the
# slice's full stack: on 29 Nov two fix sessions' stacks on one 4-CPU host made a third session's scenario time out.
FULL = ('Foundation', 'Integrate', 'Readiness', 'Gate evidence', 'Fix')
TMUX = os.environ.get('HIS_TMUX', 'his')   # the tmux session that holds the agents' windows
# tmux matches a target by prefix ('his' finds 'his-watch'); '=' asks for the exact session and window name.
TM_S = '=' + TMUX
TM_W = lambda sid: f'{TM_S}:={sid}'   # noqa: E731
STATE = os.environ.get('HIS_STATE', os.path.expanduser('~/.cache/his'))
USAGE = os.path.join(STATE, 'usage.json')
LIMITED = os.path.join(STATE, 'limited')
WEEK = 7 * 24 * 3600
USAGE_STALE = 3600     # a usage file older than this is not trusted to hold sessions back
RECOVER_GRACE = 300    # seconds after a reset before a session that did not continue is continued
LIMIT_TEXT = ("You've hit your", 'Usage limit reached', 'Automatic continue stopped', 'Automatic continue cancelled', 'rate-limit-options')
WAITING_TEXT = ('Continuing automatically at', 'Continuing shortly')
SESSION_ENV = 'CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false CLAUDE_CODE_ENABLE_AWAY_SUMMARY=0'
RESTED = os.path.join(STATE, 'rested')   # the containers stopped while their session waits, by session
WORKING_TEXT = 'esc to interrupt'        # Claude Code's status line while the agent works
# Claude Code's footer while a command the agent started in the background still runs ("· 1 shell", "2 shells still
# running"): the turn has ended, but the agent's tests or scenario run still use its integration environment.
BACKGROUND_WORK = re.compile(r'\b\d+ (?:shells?|background tasks?)\b')


def git(*a, check=True):
    r = subprocess.run(['git', '-C', REPO] + list(a), capture_output=True, text=True)
    if check and r.returncode:
        sys.exit(f'git {" ".join(a)} failed:\n{r.stderr.strip()}')
    return r


FETCH_TRIES = 4   # GitHub drops an SSH connection now and then; a fetch is tried again after 2, 4 and 8 seconds


def fetch_origin(*refs):
    """Fetch from origin, trying again on a failure. True when it worked. A fetch that still fails is reported and
    leaves the refs as the last fetch left them, so a dropped connection never ends a command or a watch."""
    for n in range(FETCH_TRIES):
        r = git('fetch', '-q', 'origin', *refs, check=False)
        if r.returncode == 0:
            return True
        if n < FETCH_TRIES - 1:
            time.sleep(2 ** (n + 1))
    print(f'  git fetch {" ".join(("origin",) + refs)} failed {FETCH_TRIES} times; going on with what was fetched before:\n'
          f'  {r.stderr.strip().splitlines()[-1] if r.stderr.strip() else "no message"}', flush=True)
    return False


REPO = subprocess.run(['git', '-C', HERE, 'rev-parse', '--show-toplevel'], capture_output=True, text=True).stdout.strip()
if not REPO:
    sys.exit('launch_sessions.py: not inside a git repository')
WT_ROOT = os.environ.get('HIS_WORKTREES', REPO.rstrip('/') + '-wt')


def load(fetch=True):
    """The sessions of the plan on origin/main, each with its issue and status from GitHub."""
    if fetch:
        fetch_origin()
    text = git('show', f'origin/main:{PLAN_REL}/data/sessions.csv').stdout
    sessions = list(csv.DictReader(io.StringIO(text)))
    repo = hub.repo_slug()
    issues, prs = hub.fetch(repo)
    done = {s['session'] for s in sessions if s['session'] in issues and issues[s['session']]['state'] == 'closed'}
    trees = set(os.listdir(WT_ROOT)) if os.path.isdir(WT_ROOT) else set()
    for s in sessions:
        sid = s['session']
        s['issue'] = issues.get(sid)
        s['state'] = hub.status_of(sid, s['issue'], prs, s['after'].split(), done)   # None: no issue yet
        s['tree'] = sid in trees
        open_prs = sorted((p for p in prs.get(sid, []) if p['state'] == 'open'), key=lambda p: p['number'])
        s['pr'] = open_prs[-1] if open_prs else None
    return repo, sessions


def settings_for(sid, model, issue):
    """The settings file of one session: its model, its permissions, no background requests, and the usage status line
    and hook."""
    me = shlex.quote(sys.executable) + ' -B ' + shlex.quote(os.path.join(HERE, 'usage_hooks.py'))
    st = dict(autoContinueAtUsageLimit=True, promptSuggestionEnabled=False, awaySummaryEnabled=False,
              statusLine=dict(type='command', command=f'{me} statusline {sid}', padding=0, refreshInterval=60),
              hooks=dict(StopFailure=[dict(matcher='rate_limit', hooks=[dict(type='command', command=f'{me} limit-hit {sid}')])]))
    fill = lambda rules: [r.replace('<SESSION-ID>', sid).replace('<ISSUE>', str(issue)) for r in rules]
    st['permissions'] = dict(allow=fill(SESSION_PERMISSIONS['allow']), deny=fill(SESSION_PERMISSIONS['deny']))
    if model:
        st['model'] = model
    path = os.path.join(STATE, 'settings', f'{sid}.json')
    os.makedirs(os.path.dirname(path), exist_ok=True)
    json.dump(st, open(path, 'w'), indent=1)
    return path


def agent_cmd(a, s, prompt, path_only=False):
    """The command line that runs the agent of session s in its window."""
    sid = s['session']
    env = f'HIS_SESSION={sid} HIS_ISSUE={s["issue"]["number"]} COMPOSE_PROJECT_NAME=his-{sid.lower()} {SESSION_ENV}'
    sp = os.path.join(STATE, 'settings', f'{sid}.json') if path_only else settings_for(sid, a.model, s['issue']['number'])
    rc = f' --remote-control {shlex.quote(sid)}' if getattr(a, 'remote_control', True) else ''   # shows in the Claude app, named by session
    return f'env {env} {a.agent}{rc} --settings {shlex.quote(sp)} {shlex.quote(prompt)}'


def usage():
    """The account's usage, from the file the sessions' status lines keep: {window: (percent, resets_at)}, and its age.
    A window whose reset has passed counts as empty."""
    u = None
    try:
        u = json.load(open(USAGE))
    except (OSError, ValueError):
        return {}, None
    now = time.time()
    out = {}
    for k in ('five_hour', 'seven_day'):
        w = u.get(k) or {}
        if w.get('used_percentage') is None or not w.get('resets_at'):
            continue
        out[k] = (0.0, None) if w['resets_at'] <= now else (float(w['used_percentage']), int(w['resets_at']))
    return out, now - u.get('captured_at', 0)


def hold_reason(a):
    """Why no new session should start now, or None."""
    u, age = usage()
    if age is None or age > USAGE_STALE:
        return None
    five, week = u.get('five_hour'), u.get('seven_day')
    if five and five[1] and five[0] >= a.five_hour_hold:
        return f'five-hour usage is {five[0]:.0f}% (hold at {a.five_hour_hold}%) until {time.strftime("%H:%M", time.localtime(five[1]))}'
    if week and week[1]:
        elapsed = max(0.0, min(1.0, 1 - (week[1] - time.time()) / WEEK))
        allowed = min(a.weekly_cap, elapsed * 100 + a.weekly_margin)
        if week[0] >= allowed:
            return (f'weekly usage is {week[0]:.0f}%, ahead of the {allowed:.0f}% allowed at this point of the week '
                    f'(resets {time.strftime("%a %H:%M", time.localtime(week[1]))})')
    return None


def usage_line():
    u, age = usage()
    if age is None:
        return 'Usage: not known yet (no session has reported it)'
    parts = [f'{label} {u[k][0]:.0f}%' + (f' (resets {time.strftime(fmt, time.localtime(u[k][1]))})' if u[k][1] else '')
             for k, label, fmt in (('five_hour', 'five-hour', '%H:%M'), ('seven_day', 'weekly', '%a %H:%M')) if k in u]
    return f'Usage: {", ".join(parts) or "no figures"}, reported {int(age // 60)} minutes ago'


def markers():
    out = {}
    if os.path.isdir(LIMITED):
        for f in os.listdir(LIMITED):
            if f.endswith('.json'):
                try:
                    out[f[:-5]] = json.load(open(os.path.join(LIMITED, f)))
                except (OSError, ValueError):
                    pass
    return out


def reset_of(m):
    """When the limit a session hit resets: the window that was full, else the earliest reset known at the hit."""
    resets = {k: v for k, v in (m.get('resets') or {}).items() if v}
    full = [resets[k] for k, p in (m.get('used') or {}).items() if k in resets and p is not None and p >= 99]
    pool = full or list(resets.values())
    return min(pool) if pool else m.get('at', 0) + 5 * 3600


def pane(sid, lines=15):
    r = subprocess.run(['tmux', 'capture-pane', '-p', '-t', TM_W(sid)], capture_output=True, text=True)
    return '\n'.join(r.stdout.rstrip().split('\n')[-lines:]) if r.returncode == 0 else ''


def recover(sessions, dry):
    """Continue the sessions that hit a usage limit and were not continued by Claude Code after the reset."""
    by = {s['session']: s for s in sessions}
    for sid, m in markers().items():
        path = os.path.join(LIMITED, f'{sid}.json')
        s = by.get(sid)
        if not s or s['state'] not in ('Running', 'Ready', 'Waiting') or not window(sid):
            if not dry and (not s or s['state'] in ('Done', 'In review', 'Blocked')):
                os.remove(path)    # finished or handed to a person: nothing to continue
            continue
        due = reset_of(m) + RECOVER_GRACE
        if time.time() < due:
            continue
        text = pane(sid)
        if any(x in text for x in WAITING_TEXT):
            continue               # Claude Code is about to continue it
        if any(x in text for x in LIMIT_TEXT):
            if dry:
                print(f'would continue {sid}: its usage limit has reset')
                continue
            subprocess.run(['tmux', 'send-keys', '-t', TM_W(sid), 'Escape'], capture_output=True)
            time.sleep(1)
            type_into(sid, f'The usage limit has reset. Continue session {sid} where you stopped.')
            print(f'continued {sid}: its usage limit has reset')
        if not dry:
            os.remove(path)        # continued now, or Claude Code already continued it


def active(s):
    """A session on its card: it has a worktree and an agent may still be working in it."""
    return s['tree'] and s['state'] in ('Running', 'Ready', 'Waiting')


def windows():
    """The names of the open windows of the agents' tmux session."""
    r = subprocess.run(['tmux', 'list-windows', '-t', TM_S, '-F', '#{window_name}'], capture_output=True, text=True)
    return set(r.stdout.split()) if r.returncode == 0 else set()


def holding(sessions, leave=()):
    """The sessions that hold a place against --max: those on their cards, and any other whose agent window is open,
    such as one fixing its pull request, unless it is paused or blocked. A blocked session's agent has stopped to wait
    for a person (rule 3), so its open window holds no place: counting it could keep out the very session it waits for.
    Sessions named in leave are not counted."""
    wins = windows()
    return {s['session'] for s in sessions if s['session'] not in leave
            and (active(s) or (s['session'] in wins and s['state'] not in ('Paused', 'Blocked')))}


def line(s):
    flags = ', '.join(x for x in ['full environment' if s['kind'] in FULL else '', 'needs a person' if s['needs_a_person'] else '',
                                  'safety review' if s['safety_review'] else '', 'worktree' if s['tree'] else ''] if x)
    num = f'#{s["issue"]["number"]}' if s['issue'] else '-'
    return f'  {s["session"]:<12} {num:<6} {s["kind"]:<14} {s["title"]}' + (f'   [{flags}]' if flags else '')


def cmd_list(_):
    _, sessions = load()
    print(usage_line())
    hold = hold_reason(ARGS_DEFAULT)
    if hold:
        print(f'Holding new sessions: {hold}')
    hit = markers()
    for state in ('Running', 'Paused', 'In review', 'Blocked', 'Ready'):
        ss = [s for s in sessions if s['state'] == state]
        print(f'{state} ({len(ss)}):')
        for s in ss:
            note = ''
            if state == 'Running' and not window(s['session']):
                note = '   (no window: interrupted, use resume)'
            elif state == 'In review' and (review_state(s['session']).get('verdict') or review_state(s['session']).get('running')):
                rv = review_state(s['session'])
                note = '   (review running)' if rv.get('running') else {'approve': '   (approved; merging)', 'person': '   (merge by a person)',
                        'changes': f'   (changes requested, round {rv.get("rounds", 1)})',
                        'conflict': '   (conflicts with main; the session is bringing it up to date)'}.get(rv['verdict'], '')
            elif s['session'] in hit:
                note = f'   (usage limit hit; continues after {time.strftime("%a %H:%M", time.localtime(reset_of(hit[s["session"]])))})'
            if os.path.exists(os.path.join(HELD, f"{s['session']}.json")):
                note += '   (a message for it waits for a free place)'
            print(line(s) + note)
    c = sum(1 for s in sessions if s['state'] == 'Done')
    w = sum(1 for s in sessions if s['state'] == 'Waiting')
    n = sum(1 for s in sessions if s['state'] is None)
    print(f'Done: {c}   Waiting: {w}   No issue yet: {n}   (worktrees in {WT_ROOT})')


def tidy(sessions, dry):
    """Remove the worktree and window of every session whose issue is closed."""
    for s in sessions:
        if s['state'] == 'Blocked' and 'running' in hub.labels_of(s['issue']) and not dry:   # the agent stopped: it no longer runs
            hub.gh('api', '-X', 'DELETE', f'repos/{hub.repo_slug()}/issues/{s["issue"]["number"]}/labels/running', check=False)
        if s['tree'] and s['state'] == 'Done':
            path = os.path.join(WT_ROOT, s['session'])
            if dry:
                print(f'would remove worktree {path}')
                continue
            end_session(s['session'])
            subprocess.run(['tmux', 'kill-window', '-t', TM_W(s['session'])], capture_output=True)
            r = git('worktree', 'remove', path, check=False)
            if r.returncode:
                print(f'kept {path}: it has changes that are not committed ({r.stderr.strip()})')
            else:
                s['tree'] = False
                print(f'removed worktree of {s["session"]} (done)')
    tidy_environments(sessions, dry)


def end_session(sid, wait=30):
    """Let a finished session's agent exit on its own before its window closes: closing the window cuts it off, and
    its claude.ai record can then stay behind as idle instead of being archived. Escape closes any open dialog, and
    /exit ends the agent; the window is closed after `wait` seconds either way."""
    r = subprocess.run(['tmux', 'display-message', '-p', '-t', TM_W(sid), '#{pane_pid}'], capture_output=True, text=True)
    pid = r.stdout.strip()
    if r.returncode or not pid.isdigit():
        return
    subprocess.run(['tmux', 'send-keys', '-t', TM_W(sid), 'Escape'], capture_output=True)
    time.sleep(1)
    subprocess.run(['tmux', 'send-keys', '-t', TM_W(sid), '-l', '/exit'], capture_output=True)
    subprocess.run(['tmux', 'send-keys', '-t', TM_W(sid), 'Enter'], capture_output=True)
    for _ in range(wait):
        if not os.path.exists(f'/proc/{pid}'):
            return
        time.sleep(1)


SESSION_LABEL = 'care.cema.his.session'   # on every container, volume and network of a session's environments


def docker_session_labels():
    """The sessions that still own containers, volumes or networks: {session: {compose projects}}. Empty without Docker."""
    found = {}
    for kind in (['ps', '-a'], ['volume', 'ls'], ['network', 'ls']):
        try:
            r = subprocess.run(['docker', *kind, '--filter', f'label={SESSION_LABEL}', '--format',
                                f'{{{{.Label "{SESSION_LABEL}"}}}}|{{{{.Label "com.docker.compose.project"}}}}'],
                               capture_output=True, text=True, timeout=60)
        except (OSError, subprocess.TimeoutExpired):
            return {}
        if r.returncode:
            return {}
        for row in r.stdout.split():
            sid, _, project = row.partition('|')
            found.setdefault(sid, set()).update({project} if project else set())
    return found


def tidy_environments(sessions, dry):
    """Remove the integration environments of every session whose issue is closed: its own (his-env reset), the
    twin of its isolation check, and anything else carrying its session label (a testbed, a throwaway registry).
    A session that is done never uses them again, and each holds a PostgreSQL and its volumes."""
    owned = docker_session_labels()
    for s in sessions:
        if s['state'] != 'Done':
            continue
        sid = s['session']
        names = [n for n in (sid, f'{sid}-twin') if n in owned]
        if not names:
            continue
        if dry:
            print(f'would remove the integration environments of {sid} (done): {", ".join(names)}')
            continue
        for name in names:
            remove_environment(name)
        left = docker_session_labels()
        if any(n in left for n in names):
            print(f'kept part of the integration environments of {sid}: docker could not remove all of it')
        else:
            print(f'removed the integration environments of {sid} (done)')
    tidy_ci_environments(owned, dry)
    rest_environments(sessions, dry)


def remove_environment(name):
    """his-env reset for one environment, then anything else that still carries its label."""
    his_env = os.path.join(REPO, 'platform', 'dev-environment', 'his-env')
    env = {k: v for k, v in os.environ.items() if k != 'COMPOSE_PROJECT_NAME'}
    if os.access(his_env, os.X_OK):
        subprocess.run([his_env, 'reset'], env={**env, 'HIS_SESSION': name}, capture_output=True, timeout=300)
    for kind, rm in ((['ps', '-aq'], ['rm', '-f']), (['volume', 'ls', '-q'], ['volume', 'rm']),
                     (['network', 'ls', '-q'], ['network', 'rm'])):
        r = subprocess.run(['docker', *kind, '--filter', f'label={SESSION_LABEL}={name}'], capture_output=True, text=True)
        if r.stdout.split():
            subprocess.run(['docker', *rm, *r.stdout.split()], capture_output=True)


def session_containers(sid, status):
    """The identifiers of the containers of a session's environments (its own and its twin) in a docker status."""
    ids = []
    for name in (sid, f'{sid}-twin'):
        try:
            r = subprocess.run(['docker', 'ps', '-aq', '--no-trunc', '--filter', f'label={SESSION_LABEL}={name}',
                                '--filter', f'status={status}'], capture_output=True, text=True, timeout=60)
        except (OSError, subprocess.TimeoutExpired):
            return []
        ids += r.stdout.split() if r.returncode == 0 else []
    return ids


def waiting(s, wins):
    """True when a session waits and its agent is not working: its pull request is open, or it is blocked or paused,
    no held message is due to it, and its window is closed or shows the agent idle with nothing running in the
    background."""
    sid = s['session']
    if s['state'] not in ('In review', 'Blocked', 'Paused') or os.path.exists(os.path.join(HELD, f'{sid}.json')):
        return False
    if sid not in wins:
        return True
    text = pane(sid)
    return WORKING_TEXT not in text and not BACKGROUND_WORK.search(text)


def rest_environments(sessions, dry):
    """Stop the environments of the sessions that wait, and start again those of sessions whose agent works again
    (a person answered in its window, for example). Stopping keeps containers, data and volumes."""
    wins = windows()
    for s in sessions:
        sid = s['session']
        if s['state'] == 'Done':
            if os.path.exists(os.path.join(RESTED, f'{sid}.json')) and not dry:
                os.remove(os.path.join(RESTED, f'{sid}.json'))   # tidy_environments has removed them
            continue
        if waiting(s, wins):
            ids = session_containers(sid, 'running')
            if not ids:
                continue
            if dry:
                print(f'would stop the integration environments of {sid} while it waits ({len(ids)} containers)')
                continue
            path = os.path.join(RESTED, f'{sid}.json')
            before = json.load(open(path))['ids'] if os.path.exists(path) else []
            os.makedirs(RESTED, exist_ok=True)
            json.dump(dict(ids=sorted(set(before) | set(ids)), at=int(time.time())), open(path, 'w'))
            subprocess.run(['docker', 'stop', *ids], capture_output=True, timeout=600)
            print(f'stopped the integration environments of {sid} while it waits ({s["state"].lower()}, {len(ids)} containers)')
        elif sid in wins and os.path.exists(os.path.join(RESTED, f'{sid}.json')):
            if dry:
                print(f'would start the integration environments of {sid} again: its agent works')
                continue
            wake_environments(sid)
            print(f'started the integration environments of {sid} again: its agent works')


def wake_environments(sid):
    """Start again the containers rest_environments stopped for a session. Returns a note for the session's message,
    empty when nothing was stopped."""
    path = os.path.join(RESTED, f'{sid}.json')
    if not os.path.exists(path):
        return ''
    ids = json.load(open(path))['ids']
    os.remove(path)
    exited = set(session_containers(sid, 'exited')) | set(session_containers(sid, 'created'))
    todo = [i for i in ids if i in exited]
    if todo:
        subprocess.run(['docker', 'start', *todo], capture_output=True, timeout=600)
    return (' Your integration environment was stopped while you waited and has been started again; its published ports '
            'may have changed, so read them again with platform/dev-environment/his-env env before you use it.')


CI_ENV = re.compile(r'^ci-.+-(\d{6,})-\d+$')   # build-test's own environment: ci-<folder>-<run id>-<attempt>
# A container a job's tests start with a plain `docker run` (a contract stub, say) carries no session label, only a
# name made from the job's environment: his-<environment>-<what it is>.
CI_CONTAINER = re.compile(r'^his-(ci-.+?-(\d{6,})-\d+)-.+$')


def unlabelled_ci_containers():
    """{run id: [container names]} of the containers named after a pipeline job's environment that carry no session
    label, so that remove_environment does not find them. Empty without Docker."""
    try:
        r = subprocess.run(['docker', 'ps', '-a', '--format', f'{{{{.Names}}}}|{{{{.Label "{SESSION_LABEL}"}}}}'],
                           capture_output=True, text=True, timeout=60)
    except (OSError, subprocess.TimeoutExpired):
        return {}
    found = {}
    for row in r.stdout.split() if not r.returncode else []:
        name, _, label = row.partition('|')
        m = CI_CONTAINER.match(name)
        if m and not label:
            found.setdefault(m.group(2), []).append(name)
    return found


def tidy_ci_environments(owned, dry):
    """Remove the environments that pipeline jobs left behind. build-test resets its environment when it ends, but
    a job that is cancelled or killed never gets there, and its PostgreSQL (or a whole testbed) keeps running on
    the runner host. So does a container its tests started without the session label, whose test never reached its
    teardown. One is removed once its workflow run has finished; a run that is queued or in progress, including a
    later attempt of the same run, keeps it."""
    envs = {}
    for name in owned:
        m = CI_ENV.match(name)
        if m:
            envs.setdefault(m.group(1), []).append(name)
    loose = unlabelled_ci_containers()
    for run in sorted(set(envs) | set(loose)):
        r = hub.gh('api', f'repos/{hub.repo_slug()}/actions/runs/{run}', '--jq', '.status', check=False)
        if r.returncode or r.stdout.strip() != 'completed':
            continue
        for name in sorted(envs.get(run, [])):
            if dry:
                print(f'would remove {name}: its pipeline run {run} has finished')
                continue
            remove_environment(name)
            print(f'removed {name}: its pipeline run {run} had finished')
        for name in sorted(loose.get(run, [])):
            if dry:
                print(f'would remove container {name}: its pipeline run {run} has finished')
                continue
            subprocess.run(['docker', 'rm', '-f', name], capture_output=True)
            print(f'removed container {name}: its pipeline run {run} had finished')


def unblock(a, repo, sessions):
    """Continue a blocked session once what it waits for is closed. What it waits for is recorded as a "blocked by"
    link on its issue to an issue that is not one of its plan predecessors (the sync links those): for example a
    person links RC-1-S09's issue as blocked by RC-2-S01's when RC-1-S09 waits for that contract. When every such
    link is closed, the label `blocked` goes, the session is told, and it holds a place again."""
    for s in sessions:
        if s['state'] != 'Blocked' or not s['issue']:
            continue
        num, after = s['issue']['number'], set(s['after'].split())
        try:
            deps = [d for page in hub.get(f'repos/{repo}/issues/{num}/dependencies/blocked_by')
                    for d in (page if isinstance(page, list) else [page])]
        except SystemExit as e:
            print(f'  cannot read what #{num} is blocked by: {e}')
            continue
        waits = [d for d in deps if (d.get('title') or '').split()[:1] and d['title'].split()[0] not in after]
        if not waits or any(d.get('state') != 'closed' for d in waits):
            continue
        names = ', '.join(f'#{d["number"]} ({d["title"].split()[0]})' for d in waits)
        if a.dry_run:
            print(f'would unblock {s["session"]}: {names} closed')
            continue
        relabel(repo, s, 'running', 'blocked')
        hub.send('POST', f'repos/{repo}/issues/{num}/comments', dict(body=f'**Launcher: unblocked.** What this session waited for is closed: '
                                                                    f'{names}. The session goes on.'), check=False)
        s['state'] = 'Running'
        tell_session(a, s, sessions, f'What you were blocked on is closed: {names}. Your issue #{num} is no longer labelled blocked. '
                           f'Bring your branch up to date (git fetch origin, then git merge origin/main), read the latest comments on '
                           f'#{num} and on your pull request, and go on with your card from where you stopped.')
        print(f'unblocked {s["session"]}: {names} closed')


def start(a):
    repo, sessions = load()
    by = {s['session']: s for s in sessions}
    tidy(sessions, a.dry_run)
    recover(sessions, a.dry_run)
    unblock(a, repo, sessions)
    if not a.ids:
        pass_held(a, sessions)
        review_step(a, repo, sessions)
    hold = None if a.ids else hold_reason(a)
    if hold:
        print(f'holding new sessions: {hold}')
        return
    if a.ids:
        unknown = [i for i in a.ids if i not in by]
        if unknown:
            sys.exit('unknown session: ' + ', '.join(unknown))
        noissue = [i for i in a.ids if not by[i]['issue']]
        if noissue:
            sys.exit('no issue yet (run sync_github.py sync): ' + ', '.join(noissue))
        notready = [i for i in a.ids if by[i]['state'] != 'Ready']
        if notready and not a.force:
            sys.exit('not ready: ' + ', '.join(f'{i} is {by[i]["state"]}' for i in notready)
                     + '\nuse --force to start anyway, for example to run a session in review again after changes were requested')
        todo = [by[i] for i in a.ids]
    else:
        todo = [s for s in sessions if s['state'] == 'Ready' and not window(s['session'])]
    if not a.dry_run and not shutil.which('tmux'):
        sys.exit('tmux is not installed')
    if git('diff', '--quiet', 'origin/main', '--', f'{PLAN_REL}/tools/definitions/sessions_def.py', check=False).returncode:
        print('note: the session prompt in this checkout differs from origin/main; pull main to use the current one')
    held = holding(sessions, {s['session'] for s in todo})
    n_run = len(held)
    n_full = sum(1 for s in sessions if s['session'] in held and s['kind'] in FULL)
    started = 0
    for s in todo:
        sid, num = s['session'], s['issue']['number']
        full = s['kind'] in FULL
        if n_run >= a.max:
            print(f'limit of {a.max} running sessions reached; {len(todo) - started} left for later')
            break
        if full and n_full >= a.max_full:
            print(f'  skipped {sid}: it needs the full environment and {a.max_full} such sessions are running')
            continue
        path, branch = os.path.join(WT_ROOT, sid), f'session/{sid}'
        prompt = '\n'.join(SESSION_PROMPT).replace('<SESSION-ID>', sid).replace('<GROUP>', s['group']).replace('<ISSUE>', str(num))
        run = agent_cmd(a, s, prompt, path_only=a.dry_run)
        if a.dry_run:
            print(f'would start {sid} (issue #{num}): worktree {path}{" (kept from before)" if s["tree"] else ""}, branch {branch}, '
                  f'tmux window {TMUX}:{sid}\n    {run.split(" --settings ")[0]} --settings ... "Run session {sid} ..."')
        else:
            if not s['tree']:
                os.makedirs(WT_ROOT, exist_ok=True)
                if git('rev-parse', '--verify', '--quiet', branch, check=False).returncode == 0:
                    git('worktree', 'add', path, branch)                               # run again from the local branch
                elif git('rev-parse', '--verify', '--quiet', f'origin/{branch}', check=False).returncode == 0:
                    git('worktree', 'add', path, '-b', branch, f'origin/{branch}')     # run again from the pushed branch
                else:
                    git('worktree', 'add', path, '-b', branch, 'origin/main')
            has = subprocess.run(['tmux', 'has-session', '-t', TM_S], capture_output=True).returncode == 0
            tm = ['tmux', 'new-window', '-d', '-t', TM_S + ':'] if has else ['tmux', 'new-session', '-d', '-s', TMUX]
            subprocess.run(tm + ['-n', sid, '-c', path, run], check=True)
            hub.send('POST', f'repos/{repo}/issues/{num}/labels', dict(labels=['running']))
            hub.gh('api', '-X', 'DELETE', f'repos/{repo}/issues/{num}/labels/ready', check=False)
            hub.send('POST', f'repos/{repo}/issues/{num}/comments',
                     dict(body=f'Started by the launcher on `{os.uname().nodename}`: branch `{branch}`, worktree `{path}`.'))
            print(f'started {sid} (issue #{num}) in {path} (tmux window {TMUX}:{sid})')
        started += 1
        n_run += 1
        n_full += full
    if started and not a.dry_run:
        print(f'attach with: tmux attach -t {TMUX}')
    if not started:
        print('nothing to start')


def window(sid):
    """True when a tmux window of this session is open."""
    r = subprocess.run(['tmux', 'list-windows', '-t', TM_S, '-F', '#{window_name}'], capture_output=True, text=True)
    return r.returncode == 0 and sid in r.stdout.split()


def relabel(repo, s, add, remove):
    num = s['issue']['number']
    hub.send('POST', f'repos/{repo}/issues/{num}/labels', dict(labels=[add]))
    hub.gh('api', '-X', 'DELETE', f'repos/{repo}/issues/{num}/labels/{remove}', check=False)


def pick(a, sessions, states, what):
    by = {s['session']: s for s in sessions}
    if a.ids:
        bad = [i for i in a.ids if i not in by or by[i]['state'] not in states]
        if bad:
            sys.exit(f'cannot {what}: ' + ', '.join(f'{i} is {by[i]["state"] if i in by else "unknown"}' for i in bad))
        return [by[i] for i in a.ids]
    if not a.all:
        sys.exit(f'name the sessions to {what}, or use --all')
    return [s for s in sessions if s['state'] in states]


def cmd_pause(a):
    """Interrupt the agent (Escape in its window) and mark the session paused. The window, the worktree and the
    conversation stay; with --close the window is closed and resume continues the conversation from disk."""
    repo, sessions = load()
    todo = pick(a, sessions, ('Running',), 'pause')
    for s in todo:
        sid = s['session']
        if a.dry_run:
            print(f'would pause {sid}')
            continue
        if window(sid):
            subprocess.run(['tmux', 'send-keys', '-t', TM_W(sid), 'Escape'], capture_output=True)
            if a.close:
                time.sleep(2)   # let the agent take the interrupt before its window goes
                subprocess.run(['tmux', 'kill-window', '-t', TM_W(sid)], capture_output=True)
        relabel(repo, s, 'paused', 'running')
        print(f'paused {sid} (issue #{s["issue"]["number"]})')
    if not todo:
        print('nothing to pause')


def cmd_resume(a):
    """Continue paused sessions, and running ones whose window is gone (after a restart of the server)."""
    repo, sessions = load()
    todo = [s for s in pick(a, sessions, ('Paused', 'Running'), 'resume') if s['state'] == 'Paused' or not window(s['session'])]
    n_run = len(holding(sessions, {s['session'] for s in todo}))
    resumed = 0
    for s in todo:
        sid, path = s['session'], os.path.join(WT_ROOT, s['session'])
        if n_run >= a.max:
            print(f'limit of {a.max} running sessions reached; {len(todo) - resumed} left paused')
            break
        if not s['tree']:
            print(f'  skipped {sid}: it has no worktree on this server; use start --force {sid} to run it from its branch')
            continue
        word = f'Continue session {sid} where you stopped.'
        if not a.dry_run:
            word += wake_environments(sid)
        if a.dry_run:
            print(f'would resume {sid} in {"its open window" if window(sid) else "a new window, continuing its conversation"}')
        else:
            if window(sid):
                type_into(sid, word)
            else:
                run = agent_cmd(a, s, word)
                has = subprocess.run(['tmux', 'has-session', '-t', TM_S], capture_output=True).returncode == 0
                tm = ['tmux', 'new-window', '-d', '-t', TM_S + ':'] if has else ['tmux', 'new-session', '-d', '-s', TMUX]
                subprocess.run(tm + ['-n', sid, '-c', path, run], check=True)
            relabel(repo, s, 'running', 'paused')
            print(f'resumed {sid} (issue #{s["issue"]["number"]})')
        resumed += 1
        n_run += 1
    if not resumed:
        print('nothing to resume')


REVIEWS = os.path.join(STATE, 'reviews')
PERSON_LABEL = 'merge-by-person'
FAILED = ('failure', 'cancelled', 'timed_out', 'action_required', 'startup_failure', 'stale')


def review_state(sid):
    try:
        return json.load(open(os.path.join(REVIEWS, f'{sid}.json')))
    except (OSError, ValueError):
        return {}


def save_review(sid, st):
    os.makedirs(REVIEWS, exist_ok=True)
    json.dump(st, open(os.path.join(REVIEWS, f'{sid}.json'), 'w'), indent=1)


def checks(repo, sha):
    """'passed', 'failed' or 'pending' for the checks of a commit."""
    runs = []
    for page in hub.get(f'repos/{repo}/commits/{sha}/check-runs?per_page=100'):
        runs += page.get('check_runs', []) if isinstance(page, dict) else []
    if not runs:
        return 'pending'
    if any(r['status'] != 'completed' for r in runs):
        return 'pending'
    return 'failed' if any(r['conclusion'] in FAILED for r in runs) else 'passed'


def person_reasons(repo, s, n):
    """Why this pull request must be merged by a person, from the card and the files it changes."""
    why = []
    if s['kind'] in AUTO_MERGE['person_kinds']:
        why.append(f'a {s["kind"].lower()} session is approved by a person (session plan, section 4)')
    lab = hub.labels_of(s['issue'])
    why += [f'the issue is labelled {x}' for x in AUTO_MERGE['person_labels'] if x in lab]
    files = [f['filename'] for f in hub.get(f'repos/{repo}/pulls/{n}/files?per_page=100')]
    hit = sorted({p for f in files for p in AUTO_MERGE['person_paths'] if f.startswith(p)})
    if hit:
        why.append('it changes ' + ', '.join(hit))
    return why


def to_person(a, repo, s, pr, why, st):
    n = pr['number']
    if a.dry_run:
        print(f'would hand pull request #{n} of {s["session"]} to a person: {"; ".join(why)}')
        return
    hub.send('POST', f'repos/{repo}/labels', dict(name=PERSON_LABEL, color='d93f0b', description='This pull request is merged by a person, not by the launcher'), check=False)
    hub.send('POST', f'repos/{repo}/issues/{n}/labels', dict(labels=[PERSON_LABEL]))
    hub.send('POST', f'repos/{repo}/issues/{n}/comments', dict(body='**Merge by a person.** The launcher does not merge this pull request because '
                                                              + '; '.join(why) + '.'))
    st.update(sha=pr['head']['sha'], verdict='person')
    save_review(s['session'], st)
    print(f'pull request #{n} of {s["session"]} goes to a person: {"; ".join(why)}')


def review_settings(sid):
    """Read-only settings for the review agent."""
    writes = ('git add', 'git commit', 'git push', 'gh issue comment', 'gh issue edit', 'gh pr create')
    allow = [r for r in SESSION_PERMISSIONS['allow'] if not any(w in r for w in writes)]
    deny = SESSION_PERMISSIONS['deny'] + ['Edit', 'Write', 'NotebookEdit', 'Bash(git add *)', 'Bash(git commit *)', 'Bash(git push *)',
                                          'Bash(gh pr create *)', 'Bash(gh pr review *)', 'Bash(gh pr comment *)', 'Bash(gh issue *)']
    st = dict(permissions=dict(allow=allow, deny=deny), promptSuggestionEnabled=False, awaySummaryEnabled=False)
    path = os.path.join(STATE, 'settings', f'{sid}-review.json')
    os.makedirs(os.path.dirname(path), exist_ok=True)
    json.dump(st, open(path, 'w'), indent=1)
    return path


def review_command(a, s, n):
    sid = s['session']
    prompt = '\n'.join(REVIEW_PROMPT).replace('<SESSION-ID>', sid).replace('<GROUP>', s['group']) \
        .replace('<ISSUE>', str(s['issue']['number'])).replace('<PR>', str(n))
    return shlex.split(a.reviewer) + ['-p', '--output-format', 'json', '--settings', review_settings(sid)] \
        + (['--model', a.model] if a.model else []) + [prompt]


def start_review(a, s, n, sha, files):
    """Start the review agent in the background. Its output goes to <state>/reviews/<SESSION-ID>.out, and its exit
    status to .exit when it ends. Returns the record of the running review, or None when it could not start."""
    sid = s['session']
    env = dict(os.environ, HIS_SESSION=sid, CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION='false', CLAUDE_CODE_ENABLE_AWAY_SUMMARY='0')
    where, temp = os.path.join(WT_ROOT, sid), None
    if not os.path.isdir(where):   # no worktree here: review a checkout of the pushed branch, removed afterwards
        temp = os.path.join(WT_ROOT, f'.review-{sid}')
        if os.path.isdir(temp):
            git('worktree', 'remove', '--force', temp, check=False)
        fetch_origin(f'session/{sid}')
        if git('worktree', 'add', '--detach', temp, f'origin/session/{sid}', check=False).returncode:
            print(f'  cannot check out session/{sid} for its review; it is tried again on the next pass')
            return None
        where = temp
    os.makedirs(REVIEWS, exist_ok=True)
    out = os.path.join(REVIEWS, f'{sid}.out')
    for x in (out, out + '.exit'):
        if os.path.exists(x):
            os.remove(x)
    # The shell writes the exit status when the agent ends, so a later pass (or a restarted launcher) can tell an ended
    # review from a running one without being its parent.
    wrap = f'{shlex.join(review_command(a, s, n))} >{shlex.quote(out)} 2>&1; echo $? >{shlex.quote(out + ".exit")}'
    proc = subprocess.Popen(['sh', '-c', wrap], cwd=where, env=env, stdin=subprocess.DEVNULL,
                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
    return dict(pid=proc.pid, sha=sha, pr=n, files=sorted(files), started=int(time.time()), out=out, temp=temp)


def alive(pid):
    try:
        if os.waitpid(pid, os.WNOHANG)[0] == pid:   # our own child that has ended: reap it
            return False
    except ChildProcessError:                      # started by an earlier launcher: not ours to reap
        pass
    try:
        os.kill(pid, 0)
        return True
    except ProcessLookupError:
        return False
    except PermissionError:
        return True


def stop_review(run):
    """Stop a running review and remove what it left."""
    if alive(run['pid']):
        try:
            os.killpg(run['pid'], signal.SIGTERM)    # the agent and the shell around it
        except (ProcessLookupError, PermissionError):
            pass
        alive(run['pid'])
    if run.get('temp'):
        git('worktree', 'remove', '--force', run['temp'], check=False)


def poll_review(sid, run):
    """'running' while the review runs; else (verdict, summary, findings), or None when it gave no usable answer or
    took longer than review_timeout. A review that ended is cleaned up."""
    done = os.path.exists(run['out'] + '.exit')
    if not done and alive(run['pid']):
        if time.time() - run['started'] <= AUTO_MERGE['review_timeout']:
            return 'running'
        stop_review(run)
        print(f'  the review of {sid} took longer than {AUTO_MERGE["review_timeout"]} seconds; it is tried again on the next pass')
        return None
    stop_review(run)                                 # ended: reap it and remove its checkout
    code = open(run['out'] + '.exit').read().strip() if done else 'none: the review stopped without an exit status'
    try:
        stdout = open(run['out']).read()
    except OSError:
        stdout = ''
    result = parse_review(stdout)
    if result is None:
        print(f'  the review of {sid} gave no verdict (exit {code}); it is tried again on the next pass')
    return result


def parse_review(stdout):
    """(verdict, summary, findings) from the review agent's output, or None."""
    text = stdout
    try:
        text = json.loads(stdout).get('result', '')
    except ValueError:
        pass
    for raw in reversed([x.strip() for x in (text or '').strip().split('\n') if x.strip()]):
        if raw.startswith('{') and '"verdict"' in raw:
            try:
                v = json.loads(raw)
            except ValueError:
                return None
            if v.get('verdict') in ('approve', 'changes', 'person'):
                return v['verdict'], v.get('summary', ''), [str(x) for x in v.get('findings', [])]
            return None
    return None


def reviews_running():
    """{session: record} of the reviews that run now, from their state files."""
    out = {}
    for name in os.listdir(REVIEWS) if os.path.isdir(REVIEWS) else []:
        if name.endswith('.json'):
            run = review_state(name[:-len('.json')]).get('running')
            if run:
                out[name[:-len('.json')]] = run
    return out


HELD = os.path.join(STATE, 'held')


def hold_message(sid, text):
    """Keep a message for a session until a place frees; a newer message for the same session replaces it."""
    os.makedirs(HELD, exist_ok=True)
    json.dump(dict(text=text, at=int(time.time())), open(os.path.join(HELD, f'{sid}.json'), 'w'))


def pass_held(a, sessions):
    """Pass on the held messages, oldest first, while places are free. A message for a session whose pull request is
    no longer open is dropped."""
    if not os.path.isdir(HELD):
        return
    by = {s['session']: s for s in sessions}
    for name in sorted(os.listdir(HELD), key=lambda n: os.path.getmtime(os.path.join(HELD, n))):
        sid, path = name[:-len('.json')], os.path.join(HELD, name)
        s = by.get(sid)
        if not s or not s.get('pr'):
            if not a.dry_run:
                os.remove(path)
            continue
        if not window(sid) and len(holding(sessions)) >= a.max:
            print(f'every place is taken; held messages wait, {sid} first')
            return
        if a.dry_run:
            print(f'would pass {sid} its held message')
            continue
        text = json.load(open(path))['text']
        os.remove(path)
        tell_session(a, s, sessions, text)
        print(f'passed {sid} its held message')


def pending_input(sid):
    """The text in the input box of a session's window: the lines from the last prompt marker to the rule below it."""
    lines = pane(sid, 60).split('\n')
    start = max((i for i, x in enumerate(lines) if x.lstrip().startswith('❯')), default=None)
    if start is None:
        return ''
    box = []
    for x in lines[start:]:
        if x.strip().startswith('─'):
            break
        box.append(x.strip().lstrip('❯').strip())
    return ' '.join(box)


def type_into(sid, text, tries=3):
    """Type a message into a session's window and press Enter, then check that it left the input box. On 29 Nov the
    Enter after a long message was lost and RC-1-S28-F3 sat 3.5 hours with its review request unsent; so the Enter is
    sent again, up to `tries` times, while the start of the message is still in the box. True when it was sent."""
    subprocess.run(['tmux', 'send-keys', '-t', TM_W(sid), '-l', text], capture_output=True)
    time.sleep(1)                      # let the window take the whole text before the Enter
    head = ''.join(text.split())[:40]
    for _ in range(tries):
        subprocess.run(['tmux', 'send-keys', '-t', TM_W(sid), 'Enter'], capture_output=True)
        time.sleep(3)
        if head not in ''.join(pending_input(sid).split()):
            return True
    print(f'  the message to {sid} is still in its input box after {tries} presses of Enter')
    return False


def tell_session(a, s, sessions, text):
    """Pass a message to a session: type it in its window, or reopen its conversation with it. When every place is
    taken the message is held, and pass_held gives it once a place frees."""
    sid = s['session']
    if window(sid):
        type_into(sid, text + wake_environments(sid))
        return
    if len(holding(sessions, {sid})) >= a.max:
        hold_message(sid, text)
        print(f'  every place is taken: the message for {sid} is held until one frees')
        return
    text += wake_environments(sid)
    path, branch = os.path.join(WT_ROOT, sid), f'session/{sid}'
    if not s['tree']:   # no worktree here: check out the pushed branch and start a new agent on the card, with the message
        os.makedirs(WT_ROOT, exist_ok=True)
        fetch_origin(branch)
        if git('rev-parse', '--verify', '--quiet', branch, check=False).returncode == 0:
            r = git('worktree', 'add', path, branch, check=False)
        else:
            r = git('worktree', 'add', path, '-b', branch, f'origin/{branch}', check=False)
        if r.returncode:
            print(f'  cannot check out {branch} for {sid}: {r.stderr.strip()}')
            return
        s['tree'] = True
        prompt = '\n'.join(SESSION_PROMPT).replace('<SESSION-ID>', sid).replace('<GROUP>', s['group']).replace('<ISSUE>', str(s['issue']['number']))
        run = agent_cmd(a, s, prompt + '\n\nYour branch and pull request already exist. ' + text)
    else:
        b = argparse.Namespace(**vars(a))
        b.agent = a.agent if '--continue' in a.agent else f'{a.agent} --continue'
        run = agent_cmd(b, s, text)
    has = subprocess.run(['tmux', 'has-session', '-t', TM_S], capture_output=True).returncode == 0
    tm = ['tmux', 'new-window', '-d', '-t', TM_S + ':'] if has else ['tmux', 'new-session', '-d', '-s', TMUX]
    subprocess.run(tm + ['-n', sid, '-c', os.path.join(WT_ROOT, sid), run], check=True)


def merge(a, repo, s, pr, summary):
    n, sid = pr['number'], s['session']
    full = json.loads(hub.gh('api', f'repos/{repo}/pulls/{n}').stdout) if not a.dry_run else pr
    if full and full.get('mergeable') is False:
        return 'conflict'
    if a.dry_run:
        print(f'would merge pull request #{n} of {sid}')
        return 'merged'
    hub.send('POST', f'repos/{repo}/issues/{n}/comments', dict(body=f'**Review agent: approved.** {summary}\n\nMerged by the launcher (session plan, rule 11).'))
    r = hub.send('PUT', f'repos/{repo}/pulls/{n}/merge', dict(merge_method='squash', sha=pr['head']['sha'],
                                                          commit_title=f'{pr["title"]} (#{n})'), check=False)
    if r is None:
        return 'failed'
    hub.send('DELETE', f'repos/{repo}/git/refs/heads/session/{sid}', check=False)
    print(f'merged pull request #{n} of {sid}')
    return 'merged'


def body_hash(pr):
    return hashlib.sha256((pr.get('body') or '').encode()).hexdigest()[:16]


LAUNCHER_COMMENT = ('**Review agent', '**Launcher', '**Merge by a person')


def answered(repo, pr, st):
    """Whether the session answered a review that asked for changes without pushing a commit: the description of the
    pull request changed since the review, or someone other than the launcher commented after it. On 29 Nov
    RC-1-S28-F7's second review asked only for a better description; the session rewrote it and replied, pushed
    nothing, and the pull request waited for a commit that would never come."""
    if st.get('body') and st['body'] != body_hash(pr):
        return True
    since = st.get('at', 0)
    for page in hub.get(f'repos/{repo}/issues/{pr["number"]}/comments?per_page=100'):
        for c in (page if isinstance(page, list) else [page]):
            when = calendar.timegm(time.strptime(c['created_at'], '%Y-%m-%dT%H:%M:%SZ'))
            if when > since and not (c.get('body') or '').lstrip().startswith(LAUNCHER_COMMENT):
                return True
    return False


def review_step(a, repo, sessions):
    """Review the open pull requests of the sessions, and merge those the review approves and no person must merge."""
    by = {s['session']: s for s in sessions}
    for sid, run in reviews_running().items():     # a pull request that left review: its review is stopped
        s = by.get(sid)
        if not s or s['state'] != 'In review' or not s.get('pr') or s['pr']['number'] != run['pr']:
            if a.dry_run:
                print(f'would stop the review of {sid}: its pull request is no longer in review')
                continue
            stop_review(run)
            st = review_state(sid)
            st.pop('running', None)
            save_review(sid, st)
            print(f'stopped the review of {sid}: its pull request is no longer in review')
    for s in sessions:
        try:
            review_one(a, repo, s, sessions)
        except (SystemExit, OSError, subprocess.SubprocessError) as e:   # one pull request must not stop the others
            print(f'  the review step of {s["session"]} failed: {e}')


def review_one(a, repo, s, sessions):
    if True:
        pr = s.get('pr')
        if s['state'] != 'In review' or not pr:
            return
        sid, n, sha = s['session'], pr['number'], pr['head']['sha']
        st = review_state(sid)
        run = st.get('running')
        if run and run['sha'] != sha:    # a new commit came while it was reviewed: that review no longer counts
            if a.dry_run:
                print(f'would stop the review of {sid}: #{n} has a new commit')
                return
            stop_review(run)
            st.pop('running')
            save_review(sid, st)
            print(f'stopped the review of {sid}: #{n} has a new commit')
            run = None
        if run:
            result = poll_review(sid, run) if not a.dry_run else 'running'
            if result == 'running':
                return
            st.pop('running')
            save_review(sid, st)
            if result is None:
                return
            apply_review(a, repo, s, pr, st, result, sessions)
            return
        if PERSON_LABEL in {x['name'] for x in pr.get('labels', [])} or (st.get('verdict') == 'person' and st.get('sha') == sha):
            return
        why = person_reasons(repo, s, n)
        if a.no_merge:
            why.append('automatic merging is switched off (--no-merge)')
        if why:
            to_person(a, repo, s, pr, why, st)
            return
        if st.get('sha') == sha and st.get('verdict') == 'conflict':
            return                     # waiting for the session to push its merge of main
        if st.get('sha') == sha and st.get('verdict') == 'changes' and not answered(repo, pr, st):
            return                     # waiting for the session to push its fixes, or to answer on the pull request
        # GitHub runs no pull_request checks while a pull request conflicts with main, so the checks would stay
        # 'pending' for ever: look first whether it can merge, and if not, have the session bring it up to date.
        mergeable = json.loads(hub.gh('api', f'repos/{repo}/pulls/{n}').stdout).get('mergeable')
        if mergeable is None:
            return                     # GitHub is still working it out; asked again on the next pass
        if mergeable is False:
            st.update(sha=sha, verdict='conflict', at=int(time.time()))
            if a.dry_run:
                print(f'would ask {sid} to bring #{n} up to date with main: it conflicts')
                return
            # The session is told first and the state saved last: if a call fails, the next pass tells it again,
            # instead of waiting for ever on a session that was never told.
            tell_session(a, s, sessions, f'Your pull request #{n} conflicts with main, so GitHub runs no checks on it and it cannot be reviewed. '
                               f'Bring the branch up to date (git fetch origin, then git merge origin/main), resolve the conflicts within '
                               f'the card (a decision record number already taken on main moves to the next free one, with every reference '
                               f'to it), run the checks, commit and push. Stop any loop that is waiting for the checks of the old commit.')
            if hub.send('POST', f'repos/{repo}/issues/{n}/comments', dict(body='**Launcher: the branch conflicts with main.** GitHub runs no checks '
                        'on it until the conflict is resolved. The session brings it up to date and pushes again.'), check=False) is None:
                print(f'  the comment on #{n} did not go through; the session was told')
            save_review(sid, st)
            print(f'asked {sid} to bring #{n} up to date with main: it conflicts')
            return
        state = checks(repo, sha)
        if state == 'pending':
            return
        st.setdefault('rounds', 0)
        if state == 'failed':
            result = ('changes', 'The checks of the pull request failed.', ['Run the failing checks of the pull request and fix them (gh pr checks %d).' % n])
        elif st.get('sha') == sha and st.get('verdict') == 'approve':
            result = ('approve', st.get('summary', ''), [])   # approved before; the merge did not go through then
        else:
            if hold_reason(a) and not getattr(a, 'ignore_hold', False):
                return                 # a review spends the plan's allowance too; `review <ID>` runs one anyway
            running = reviews_running()
            if len(running) >= a.max_reviews:
                return                 # every review place is taken; tried again on the next pass
            files = {f['filename'] for page in hub.get(f'repos/{repo}/pulls/{n}/files?per_page=100')
                     for f in (page if isinstance(page, list) else [page])}
            shared = {other: sorted(files & set(r['files'])) for other, r in running.items() if files & set(r['files'])}
            if shared:                 # reviewed after the other is merged or sent back, if it still merges then
                other, common = next(iter(shared.items()))
                print(f'  #{n} of {sid} waits for the review of {other}: both change {", ".join(common[:3])}'
                      + (f' and {len(common) - 3} more' if len(common) > 3 else ''))
                return
            if a.dry_run:
                print(f'would start the review of pull request #{n} of {sid}')
                return
            run = start_review(a, s, n, sha, files)
            if run is None:
                return
            st['running'] = run
            save_review(sid, st)
            print(f'reviewing pull request #{n} of {sid} (in the background, {len(running) + 1} of at most {a.max_reviews})')
            if not getattr(a, 'wait', False):
                return
            while (result := poll_review(sid, run)) == 'running':   # `review <ID>`: wait for it
                time.sleep(10)
            st.pop('running')
            save_review(sid, st)
            if result is None:
                return
        apply_review(a, repo, s, pr, st, result, sessions)


def apply_review(a, repo, s, pr, st, result, sessions):
    """Act on a review's result: merge an approval, send back a request for changes."""
    if True:
        sid, n, sha = s['session'], pr['number'], pr['head']['sha']
        st.setdefault('rounds', 0)
        verdict, summary, findings = result
        st.update(sha=sha, verdict=verdict, summary=summary, at=int(time.time()), body=body_hash(pr))
        if verdict == 'approve':
            out = merge(a, repo, s, pr, summary)
            if out == 'conflict':
                st.update(verdict='changes')
                save_review(sid, st)
                if not a.dry_run:
                    hub.send('POST', f'repos/{repo}/issues/{n}/comments', dict(body='**Review agent: approved, but the branch conflicts with main.** '
                                                                              'The session brings it up to date and pushes again.'))
                    tell_session(a, s, sessions, f'Your pull request #{n} was approved but conflicts with main. Bring the branch up to date '
                                       f'(git fetch origin, then git merge origin/main), resolve the conflicts within the card, run the checks, '
                                       f'commit and push.')
                print(f'asked {sid} to bring #{n} up to date with main: it conflicts')
                return
            elif out == 'failed':
                print(f'  the merge of #{n} did not go through; it is tried again on the next pass')
            save_review(sid, st)
            return
        if verdict == 'person':   # a question: it goes back to the session, which settles it or stops under rule 3
            verdict = st['verdict'] = 'changes'
            findings = findings + ['The review raised a question. Settle it from the specification; if the specification does not settle it, stop under rule 3.']
        st['rounds'] += 1
        of = f' of {AUTO_MERGE["rounds"]}' if AUTO_MERGE['rounds'] is not None else ''
        body = f'**Review agent: changes requested** (round {st["rounds"]}{of}). {summary}\n\n' + '\n'.join(f'- {x}' for x in findings)
        if a.dry_run:
            print(f'would ask {sid} for changes: {summary}')
            return
        posted = hub.send('POST', f'repos/{repo}/issues/{n}/comments', dict(body=body), check=False) is not None
        if AUTO_MERGE['rounds'] is not None and st['rounds'] > AUTO_MERGE['rounds']:
            to_person(a, repo, s, pr, [f'the review asked for changes {AUTO_MERGE["rounds"]} times'], st)
            return
        if posted:
            where = f'they are in its latest comment (gh pr view {n} --comments)'
        else:                          # the comment did not go through: the findings go to the session itself
            print(f'  the comment on #{n} did not go through; the findings are passed to the session')
            where = 'the comment with them did not go through, so here they are: ' + summary + ' ' + ' '.join(f'({i}) {x}' for i, x in enumerate(findings, 1))
        tell_session(a, s, sessions, f'The review of your pull request #{n} asks for changes; {where}. '
                           f'Fix them on your branch, push, and reply on the pull request.')
        save_review(sid, st)
        print(f'asked {sid} for changes (round {st["rounds"]}): {summary}')


def cmd_review(a):
    """Review the named sessions' pull requests now, also while usage holds new sessions and reviews, and merge or
    send back as a pass would."""
    repo, sessions = load()
    a.ignore_hold, a.wait = True, True
    for s in pick(a, sessions, ('In review',), 'review'):
        before = review_state(s['session'])
        review_one(a, repo, s, sessions)
        after = review_state(s['session'])
        if after == before and not a.dry_run:
            print(f'  {s["session"]}: nothing to review now (verdict {after.get("verdict", "none")} on '
                  f'{(after.get("sha") or "-")[:7]}; checks pending or a conflict open)')


def cmd_watch(a):
    print(f'watching: starting ready sessions every {a.every} seconds, up to {a.max} running; stop with Ctrl-C')
    while True:
        try:
            start(a)
        except KeyboardInterrupt:
            raise
        except SystemExit as e:     # a failed call must not end the watch
            print(f'  {e}', flush=True)
        except Exception:           # nor must anything else: report it and try again on the next pass
            print(time.strftime('%Y-%m-%d %H:%M:%S'), 'the pass failed; trying again in', a.every, 'seconds', flush=True)
            traceback.print_exc()
            sys.stderr.flush()
        time.sleep(a.every)


def cmd_tidy(a):
    _, sessions = load()
    tidy(sessions, a.dry_run)


def usage_options(s):
    s.add_argument('--five-hour-hold', type=float, default=80, help='start no new session while the five-hour usage is at or above this percentage (default 80)')
    s.add_argument('--weekly-margin', type=float, default=10, help='how far, in percentage points, weekly usage may run ahead of an even pace through the week (default 10)')
    s.add_argument('--weekly-cap', type=float, default=95, help='start no new session while weekly usage is at or above this percentage (default 95)')
    s.add_argument('--model', default='opus', help='model of every session (default opus; empty for the user setting)')
    s.add_argument('--no-remote-control', dest='remote_control', action='store_false',
                   help='do not connect sessions to the Claude app (by default each session joins Remote Control under its session identifier)')


def options(s):
    s.add_argument('--max', type=int, default=3, help='most sessions running at once, counting those already running (default 3)')
    s.add_argument('--max-full', type=int, default=2, help='most running sessions that need the full integration environment (default 2)')
    s.add_argument('--agent', default='claude', help='command that starts the agent; the prompt is added as its last argument (default: claude)')
    s.add_argument('--dry-run', action='store_true', help='show what would start, change nothing')
    s.add_argument('--reviewer', default='claude', help='command that runs the review agent in print mode (default: claude)')
    s.add_argument('--no-merge', action='store_true', help='review pull requests but leave every merge to a person')
    s.add_argument('--max-reviews', type=int, default=2, help='most reviews running at once (default 2)')
    usage_options(s)


p = argparse.ArgumentParser(description='Start the sessions GitHub shows as ready, each in its own worktree.')
sub = p.add_subparsers(dest='cmd', required=True)
sub.add_parser('list', help='what is running, in review, blocked and ready').set_defaults(fn=cmd_list)
s = sub.add_parser('start', help='start sessions, each in its own worktree and tmux window')
s.add_argument('ids', nargs='*', help='sessions to start; default: those GitHub shows as ready, in plan order')
s.add_argument('--force', action='store_true', help='start a named session that is not ready')
options(s)
s.set_defaults(fn=start)
s = sub.add_parser('watch', help='start ready sessions again and again')
s.add_argument('--every', type=int, default=300, help='seconds between passes (default 300)')
options(s)
s.set_defaults(fn=cmd_watch, ids=[], force=False)
s = sub.add_parser('pause', help='interrupt running sessions and free their places')
s.add_argument('ids', nargs='*', help='sessions to pause')
s.add_argument('--all', action='store_true', help='every running session')
s.add_argument('--close', action='store_true', help='also close the window; resume then continues the conversation from disk')
s.add_argument('--dry-run', action='store_true')
s.set_defaults(fn=cmd_pause)
s = sub.add_parser('resume', help='continue paused sessions, and running ones that lost their window')
s.add_argument('ids', nargs='*', help='sessions to resume')
s.add_argument('--all', action='store_true', help='every paused session and every running session without a window')
s.add_argument('--max', type=int, default=3, help='most sessions running at once (default 3)')
s.add_argument('--agent', default='claude --continue', help='command that continues the agent in its worktree when its window is gone (default: claude --continue)')
s.add_argument('--dry-run', action='store_true')
usage_options(s)
s.set_defaults(fn=cmd_resume)
s = sub.add_parser('review', help='review the named sessions\' pull requests now, even while usage holds reviews')
s.add_argument('ids', nargs='+', help='sessions in review')
options(s)
s.set_defaults(fn=cmd_review, all=False)
s = sub.add_parser('tidy', help='remove the worktrees and integration environments of sessions whose issue is closed')
s.add_argument('--dry-run', action='store_true')
s.set_defaults(fn=cmd_tidy)
ARGS_DEFAULT = p.parse_args(['start'])   # the default thresholds, for list
a = p.parse_args()
a.fn(a)
