#!/usr/bin/env python3
"""Build the session plan: every vertical slice cut into AI agent sessions, with the foundation sessions in front.

Reads   tools/definitions/sessions_def.py, tools/definitions/slices_def.py, data/slices.csv, data/backlog.csv,
        data/module-dependencies.csv, data/screens.csv, data/decisions.csv, delivery/session-status.csv,
        section 15.2 of the specifications, docs/design/screen-briefs
Writes  delivery/sessions.md, delivery/sessions/<GROUP>.md, data/sessions.csv   (under docs/implementation_plan)
Run:    python3 docs/implementation_plan/tools/build_sessions.py   (after build_gates.py and build_screens.py)
Fails if a functional requirement or a screen is not in exactly one session, if the session order has a
cycle, or if session-status.csv names an unknown session or status.
"""
import re, os, glob, csv, collections, sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, 'definitions'))
sys.dont_write_bytecode = True
from slices_def import FLOWS, SLICES, PHASES  # noqa: E402
from sessions_def import MAX_REQUIREMENTS, MAX_SCREENS, MAX_CONTRACT_MODULES, KINDS, UNITS, FOUNDATION, FOUNDATION_INTRO, SAFETY_REVIEW, NFR_CLASS, SLICE_DUTIES, SESSION_PROMPT  # noqa: E402

PLAN = os.path.dirname(HERE)
DOCS = os.path.dirname(PLAN)
SPECS = os.path.join(DOCS, 'domain_specs')
ABBR = ['ADM', 'ISE', 'CLI', 'ANC', 'FIN', 'HIM', 'PEX', 'ANL', 'EBP', 'ESS']
FOLDER = {a: f'D{i + 1:02d}-{a}' for i, a in enumerate(ABBR)}
NUM = {a: i + 1 for i, a in enumerate(ABBR)}
GENERATED = ('<!-- Generated by tools/build_sessions.py from tools/definitions/sessions_def.py, tools/definitions/slices_def.py, '
             'delivery/session-status.csv and docs/domain_specs. Edit those, not this file. -->')
STATUSES = ['Not started', 'In progress', 'Blocked', 'Done']
KIND = {k[0]: k for k in KINDS}
FN = 'FN'  # group code of the foundation sessions


def rows(name):
    return list(csv.DictReader(open(os.path.join(PLAN, 'data', name))))


def chunks(items, cap):
    """Split into the fewest groups of at most `cap`, as evenly as possible, keeping order."""
    n = -(-len(items) // cap)
    size, extra = divmod(len(items), n)
    out, i = [], 0
    for k in range(n):
        j = i + size + (1 if k < extra else 0)
        out.append(items[i:j])
        i = j
    return out


def td(t):
    return t.replace('|', '\\|')


def write(rel, lines):
    path = os.path.join(PLAN, rel)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    open(path, 'w').write('\n'.join(lines).rstrip('\n') + '\n')


# ------------------------------------------------------------------ load
BACK = {r['requirement_id']: r for r in rows('backlog.csv')}
MODS = {r['module_id']: r for r in rows('module-dependencies.csv')}
OPEN_DEC = {r['decision_id'] for r in rows('decisions.csv') if r['status'].startswith('Open')}
SLICE_FRS = collections.defaultdict(list)
for r in rows('slices.csv'):
    SLICE_FRS[r['slice']].append(r['requirement_id'])
SCREENS = rows('screens.csv')
MODFILE = {}
for ab in ABBR:
    for p in glob.glob(os.path.join(SPECS, FOLDER[ab], '05-functional-requirements', 'MOD-*.md')):
        MODFILE[re.match(r'(MOD-[A-Z]+-\d{3})', os.path.basename(p)).group(1)] = os.path.basename(p)
TESTS = collections.defaultdict(list)  # requirement -> test ids
for ab in ABBR:
    t = open(os.path.join(SPECS, FOLDER[ab], '15-testing.md')).read()
    for row in re.findall(r'^\| <a id="test-[^\n]*$', t, re.M):
        c = row.strip().strip('|').split('|')
        tid = re.search(r'TEST-[A-Z]{3}-\d{3}', c[0]).group(0)
        for fid in re.findall(r'\[(FR-[A-Z]{3}-[A-Z]{2,4}-\d{3})\]', c[1]):
            TESTS[fid].append(tid)
BRIEF, UISPEC = set(), set()
for ab in ABBR:
    p = os.path.join(DOCS, 'design', 'screen-briefs', ab + '.md')
    if os.path.isfile(p):
        BRIEF |= set(re.findall(r'<a id="(ui-[a-z0-9-]+)"></a>', open(p).read()))
    UISPEC |= set(re.findall(r'<a id="(ui-[a-z0-9-]+)"></a>', open(os.path.join(SPECS, FOLDER[ab], '06-user-interface.md')).read()))


def ab_of(i):
    return re.match(r'[A-Z]+-([A-Z]{3})-', i).group(1)


def strip_links(x):
    return re.sub(r'\[([^\]\[]+)\]\([^)\s]+\)', r'\1', x).strip()


SAFE_FN = collections.defaultdict(list)   # requirement -> safety-critical functions whose control cites it
for ab in ABBR:
    sec = open(os.path.join(SPECS, FOLDER[ab], '11-safety-and-risk.md')).read().split('## 11.1', 1)[1].split('## 11.2', 1)[0]
    for row in re.findall(r'^\| (?!Function \||---)(.*) \|$', sec, re.M):
        c = row.split(' | ')
        if len(c) < 4:
            continue
        fn = dict(ab=ab, function=strip_links(c[0]), hazard=strip_links(c[1]), tests=re.findall(r'TEST-[A-Z]{3}-\d{3}', c[3]))
        for x in dict.fromkeys(re.findall(r'\[(FR-[A-Z]{3}-[A-Z]{2,4}-\d{3})\]', c[2])):
            SAFE_FN[x].append(fn)
NFR = collections.defaultdict(lambda: collections.defaultdict(list))   # domain -> class -> [(id, category)]
nfr_errors = []
for ab in ABBR:
    for row in re.findall(r'^\| <a id="nfr-[^\n]*$', open(os.path.join(SPECS, FOLDER[ab], '10-non-functional.md')).read(), re.M):
        c = row.strip().strip('|').split(' | ')
        nid, cat = re.search(r'NFR-[A-Z]{3}-\d{3}', c[0]).group(0), strip_links(c[1])
        cls = next((k for k, cats in NFR_CLASS.items() if any(cat.lower().startswith(x) for x in cats)), None)
        if not cls:
            nfr_errors.append(f'sessions_def.py: NFR category "{cat}" ({nid}) is in no NFR_CLASS list')
        else:
            NFR[ab][cls].append((nid, cat))
if nfr_errors:
    sys.exit('build_sessions.py:\n  ' + '\n  '.join(nfr_errors))


def mod_key(m):
    return (int(MODS[m]['domain_wave']), NUM[ab_of(m)], int(MODS[m]['module_wave']), m)


# ------------------------------------------------------------------ cut the sessions
S = []     # all sessions in plan order
BYID = {}


def add(group, slice_id, kind, title, after, sid=None, **kw):
    n = sum(1 for s in S if s['group_key'] == (slice_id or group)) + 1
    sid = sid or f'{slice_id or group}-S{n:02d}'
    s = dict(id=sid, group=group, group_key=slice_id or group, slice=slice_id, kind=kind, title=title, after=list(after),
             frs=[], screens=[], modules=[], unit='', domain='', human=[], builds_on=[], **kw)
    S.append(s)
    BYID[sid] = s
    return s


def pack(mods, reqs):
    """Pack the modules of one unit, in order, into sessions of at most MAX_REQUIREMENTS requirements.
    A module with more is split evenly into sessions of its own. Returns a list of requirement lists."""
    out, cur = [], []
    for m in mods:
        r = sorted(reqs[m])
        if len(r) > MAX_REQUIREMENTS:
            if cur:
                out.append(cur)
                cur = []
            out += chunks(r, MAX_REQUIREMENTS)
        elif len(cur) + len(r) > MAX_REQUIREMENTS:
            out.append(cur)
            cur = list(r)
        else:
            cur += r
    return out + ([cur] if cur else [])


# deployable units
UNIT_OF, UNIT_DOM = {}, {}
errors = []
for name, ab, mods in UNITS:
    UNIT_DOM[name] = ab
    for m in mods:
        if m in UNIT_OF:
            errors.append(f'sessions_def.py: {m} is in units {UNIT_OF[m]} and {name}')
        if ab_of(m) != ab:
            errors.append(f'sessions_def.py: {m} is in unit {name} of domain {ab}')
        UNIT_OF[m] = name
errors += [f'sessions_def.py: {m} is in no deployable unit' for m in MODS if m not in UNIT_OF]
errors += [f'sessions_def.py: unit module {m} is not a module of the specifications' for m in UNIT_OF if m not in MODS]
if errors:
    sys.exit('build_sessions.py:\n  ' + '\n  '.join(errors))
UNIT_ORDER = {name: n for n, (name, _, _) in enumerate(UNITS)}

# fixes recorded by gate evidence sessions
FIXES = collections.defaultdict(list)   # gate session -> fix rows
fp = os.path.join(PLAN, 'delivery', 'session-fixes.csv')
FIX_ROWS = list(csv.DictReader(open(fp))) if os.path.isfile(fp) else []
for r in FIX_ROWS:
    m = re.fullmatch(r'(.+-S\d{2})-F(\d+)', r['fix'])
    if not m or not r['round'].isdigit() or int(r['round']) < 1:
        errors.append(f'session-fixes.csv: fix "{r["fix"]}" must be <gate session>-F<n> with a round of 1 or more')
        continue
    FIXES[m.group(1)].append(r)
if errors:
    sys.exit('build_sessions.py:\n  ' + '\n  '.join(errors))

for f in FOUNDATION:
    s = add(FN, '', 'F', f['title'], [f'{FN}-S{a:02d}' for a in f['after']], fdef=f)
    if f.get('human'):
        s['human'].append(f['human'])
assert [s['id'] for s in S] == [f'{FN}-S{f["n"]:02d}' for f in FOUNDATION], 'foundation sessions must be numbered 1..n in order'
LAST = {}        # slice -> its last gate evidence session
CP = {}          # slice -> the session that fixes its contracts (last contract session, or its single build session)
IP = {}          # slice -> the session that makes its scenario pass (integrate session, or its single build session)
AREA_LAST = {}   # ('unit', unit) -> the last build session placed on it, across slices
BUILT_BY = collections.defaultdict(list)   # module -> build sessions in plan order, across slices
ORDER, left = [], list(SLICES)   # slices in an order that puts every slice after the slices it comes after
while left:
    nxt = next((sl for sl in left if all(a in {o['id'] for o in ORDER} for a in sl['after'])), None)
    if nxt is None:
        sys.exit('build_sessions.py: the slice order has a cycle among ' + ', '.join(sl['id'] for sl in left))
    ORDER.append(nxt)
    left.remove(nxt)
for sl in ORDER:
    sid, flow = sl['id'], sl['id'].split('-')[0]
    frs = SLICE_FRS[sid]
    doms = sorted({ab_of(x) for x in frs}, key=NUM.get)
    tier1 = sl['tier'].startswith('1')
    # a slice starts on the contracts of the slices it comes after; its scenario and its gate wait for theirs
    pre = [CP[a] for a in sl['after']] or [s['id'] for s in S if s['group'] == FN]
    pre_int = [IP[a] for a in sl['after']]
    pre_gate = [LAST[a] for a in sl['after']]
    # plan the build sessions: by deployable unit; sessions on one unit follow one another
    reqs = collections.defaultdict(list)
    for x in frs:
        reqs[BACK[x]['module_id']].append(x)
    byunit = collections.defaultdict(list)
    for m in sorted(reqs, key=mod_key):
        byunit[UNIT_OF[m]].append(m)
    pending = sorted(byunit, key=lambda u: (min(mod_key(m) for m in byunit[u]), UNIT_ORDER[u]))
    placed = []
    while pending:   # place a unit after the units whose modules it needs, where both are in the slice
        def needs_of(u):
            return {n for m in byunit[u] for x in reqs[m] for n in BACK[x]['needs_modules'].split()
                    if n in reqs and UNIT_OF[n] != u}
        u = next((u for u in pending if all(UNIT_OF[n] in placed for n in needs_of(u))), pending[0])
        pending.remove(u)
        placed.append(u)
    plan = [(u, pack(byunit[u], reqs)) for u in placed]
    bydom = collections.defaultdict(list)   # the screens first released in this slice, by domain
    for r in SCREENS:
        if r['main_slice'] == sid:
            bydom[r['domain'].split('-')[1]].append(r)
    single = sum(len(parts) for _, parts in plan) == 1
    # contract sessions: none when the slice has one build session (it takes the contract work);
    # one per domain, in domain wave order, when the slice crosses more than MAX_CONTRACT_MODULES modules
    contracts = []
    if not single:
        def needed(a):   # requirements of the slice's other domains that name domain a as upstream
            return sum(1 for x in frs if ab_of(x) != a and f'D{NUM[a]}' in BACK[x]['needs_domains'].split())
        cdoms = sorted(doms, key=lambda a: (min(int(MODS[m]['domain_wave']) for m in reqs if ab_of(m) == a), -needed(a), NUM[a]))
        if len(reqs) > MAX_CONTRACT_MODULES and len(cdoms) > 1:
            for n, ab in enumerate(cdoms):
                lastc = n == len(cdoms) - 1
                c = add(flow, sid, 'C', f'Contracts and stubs: D{NUM[ab]} {ab}' + (', and the failing scenario test' if lastc else ''),
                        [x['id'] for x in contracts] if lastc else pre, domains=[ab])   # side by side; the last one joins them
                c['domain'], c['contract_mods'], c['scenario'] = ab, sorted((m for m in reqs if ab_of(m) == ab), key=mod_key), lastc
                contracts.append(c)
        else:
            c = add(flow, sid, 'C', 'Contracts, stubs and the failing scenario test', pre, domains=doms)
            c['contract_mods'], c['scenario'] = sorted(reqs, key=mod_key), True
            contracts.append(c)
    start = [contracts[-1]['id']] if contracts else pre
    built = {}   # module -> last session of this slice that builds it
    for u, parts in plan:
        prev = None
        first = start + [AREA_LAST[x] for x in [('unit', u)] if x in AREA_LAST]   # after the last session on the unit in an earlier slice
        for k, part in enumerate(parts):
            mods = sorted({BACK[x]['module_id'] for x in part}, key=mod_key)
            needs = {n for x in part for n in BACK[x]['needs_modules'].split()} - set(mods)
            after = ([prev['id']] if prev else first) + sorted({built[n]['id'] for n in needs if n in built and UNIT_OF[n] != u},
                                                               key=lambda i: S.index(BYID[i]))
            if single and not bydom:   # this session also makes the scenario pass, so it waits as an integrate session does
                after += pre_int
            after = list(dict.fromkeys(after))
            name = u + (f' (part {k + 1} of {len(parts)})' if len(parts) > 1 else '')
            b = add(flow, sid, 'B', name, after, domains=doms)
            b['modules'], b['unit'], b['domain'], b['frs'] = mods, u, UNIT_DOM[u], part
            b['with_contract'] = single
            b['with_integrate'] = single and not bydom
            b['builds_on'] = sorted({s['id'] for m in mods for s in BUILT_BY[m] if s['slice'] != sid}, key=lambda i: S.index(BYID[i]))
            decs = sorted({d for x in part for d in BACK[x]['open_decisions'].split() if d in OPEN_DEC})
            if decs:
                b['human'].append('Open decision cited by a requirement: ' + ', '.join(decs) + '. Build on the agreed approach recorded in the specification and stop if it does not cover the case')
            if single:
                b['human'].append('Leads of the domains in the slice review the contracts it fixes, as for a contract session')
            for m in mods:
                built[m] = b
            prev = b
        AREA_LAST[('unit', u)] = prev['id']
        for m in byunit[u]:
            BUILT_BY[m].append(built[m])
    # screen sessions start on the contracts and stubs; each screen has a folder of its own in the domain workspace,
    # so screen sessions have no order between them
    CP[sid] = contracts[-1]['id'] if contracts else next(s['id'] for s in S if s['slice'] == sid and s['kind'] == 'B')
    for ab in sorted(bydom, key=NUM.get):
        parts = chunks(sorted(bydom[ab], key=lambda r: r['ui_id']), MAX_SCREENS)
        prev = None
        for k, part in enumerate(parts):
            mods = {m for r in part for m in r['modules'].split()}
            after = [CP[sid]]
            name = f'{ab} screens' + (f' (part {k + 1} of {len(parts)})' if len(parts) > 1 else '')
            u = add(flow, sid, 'U', name, after)
            u['domain'], u['screens'] = ab, part
    work = [s for s in S if s['slice'] == sid and s['kind'] in 'BU']
    ends = [s['id'] for s in work if not any(s['id'] in o['after'] for o in work)]
    if any(s.get('with_integrate') for s in work):
        last = work[0]
    else:
        last = add(flow, sid, 'I', 'End-to-end scenario across ' + ', '.join(doms), list(dict.fromkeys((ends or start) + pre_int)), domains=doms)
    IP[sid] = last['id']
    if tier1:
        last = add(flow, sid, 'R', 'Downtime, runbooks and readiness evidence', [last['id']], domains=doms)
        last['human'].append('The departments that use the workflows rehearse the downtime procedure and restoration reconciliation (ACC-007); the service owner approves the runbook entries')
    g = add(flow, sid, 'G', 'Slice gate evidence', [last['id']] + pre_gate, domains=doms)
    sign = 'Clinical owner signs the scenario (ACC-002, Tier 1)' if tier1 else 'Business owner signs the scenario'
    g['human'].append(sign)
    # fix rounds: fixes of round 1 come after the gate session; each round ends in a further gate evidence session
    rows_ = FIXES.pop(g['id'], [])
    gate0 = g['id']
    rounds = sorted({int(r['round']) for r in rows_})
    if rounds and rounds != list(range(1, len(rounds) + 1)):
        sys.exit(f'build_sessions.py: session-fixes.csv: the rounds of {g["id"]} must run 1, 2, ... without a gap')
    for rd in rounds:
        fixes = []
        for r in sorted((r for r in rows_ if int(r['round']) == rd), key=lambda r: int(r['fix'].rsplit('F', 1)[1])):
            owner = BYID.get(r['owner_session'])
            if not owner or owner['slice'] != sid or owner['kind'] not in 'CBUIRX':
                sys.exit(f'build_sessions.py: session-fixes.csv: {r["fix"]} names owner "{r["owner_session"]}", which is not a contract, build, screen, integrate, readiness or fix session of {sid}')
            same = [f for f in fixes if BYID[f]['owner_area'] == (owner['kind'], owner['unit'] or owner['domain'])]
            x = add(flow, sid, 'X', r['problem'], [g['id']] + same[-1:], sid=r['fix'], domains=doms)
            x['owner_area'] = (owner['kind'], owner['unit'] or owner['domain'])
            x['owner'], x['gate_line'], x['domain'], x['unit'] = owner['id'], r['gate_line'], owner['domain'], owner['unit']
            fixes.append(x['id'])
        g = add(flow, sid, 'G', f'Slice gate evidence, round {rd + 1}', fixes, sid=f'{gate0}-G{rd + 1}', domains=doms)
        g['human'].append(sign)
    LAST[sid] = g['id']
errors += [f'session-fixes.csv: {k} is not a gate evidence session' for k in FIXES]

# ------------------------------------------------------------------ safety and non-functional duties
SCREEN_IDS = {r['ui_id'] for r in SCREENS}
for a in SAFETY_REVIEW:
    for i in a['match']:
        if i not in MODS and i not in BACK and i not in SCREEN_IDS:
            errors.append(f'sessions_def.py: SAFETY_REVIEW "{a["area"]}" names {i}, which is not a module, requirement or screen')
for s in S:
    ids = set(s['frs']) | set(s['modules'])
    for r in s['screens']:
        ids |= {r['ui_id']} | set(r['modules'].split())
    s['safety'] = list({id(f): f for x in s['frs'] for f in SAFE_FN.get(x, [])}.values())
    s['review'] = [a for a in SAFETY_REVIEW if ids & set(a['match'])] if s['kind'] in 'BUX' else []
    for a in s['review']:
        s['human'].append(f'{a["who"]}, on the merged work ({a["area"]})')
    doms = [s['domain']] if s['kind'] in 'BU' else s.get('domains', [])
    s['nfr'] = []
    if s['kind'] == 'B':
        s['nfr'] = [x for ab in doms for x in NFR[ab]['BUILD']]
    elif s['kind'] == 'U':
        s['nfr'] = [x for ab in doms for x in NFR[ab]['SCREEN']]
    elif s['kind'] == 'R':
        s['nfr'] = [x for ab in doms for x in NFR[ab]['READINESS']]
    s['nfr_runtime'] = [x for ab in (s.get('domains') or doms) for x in NFR[ab]['RUNTIME']] if s['kind'] == 'I' or s.get('with_integrate') else []
for s in S:
    d = SLICE_DUTIES.get((s['slice'], s['kind'])) if s['slice'] and not s['id'].split('-')[-1].startswith(('G', 'F')) else None
    s['duty'] = d
errors += [f'sessions_def.py: SLICE_DUTIES names {k}, which has no such session' for k in SLICE_DUTIES
           if not any(s['slice'] == k[0] and s['kind'] == k[1] for s in S)]
for sl in SLICES:   # a slice without a readiness session leaves the readiness targets to its gate session
    if not any(s['slice'] == sl['id'] and s['kind'] == 'R' for s in S):
        for s in S:
            if s['slice'] == sl['id'] and s['kind'] == 'G' and not s['id'].split('-')[-1].startswith('G'):
                s['nfr'] = [x for ab in s['domains'] for x in NFR[ab]['READINESS']]

# ------------------------------------------------------------------ validate
seen = collections.Counter(x for s in S for x in s['frs'])
errors += [f'{x} is in {n} sessions' for x, n in seen.items() if n != 1]
errors += [f'{x} is in no session' for x in BACK if x not in seen]
seen = collections.Counter(r['ui_id'] for s in S for r in s['screens'])
errors += [f'{r["ui_id"]} is in {seen[r["ui_id"]]} sessions' for r in SCREENS if seen[r['ui_id']] != 1]
STEP = {}   # depth of the session in the whole plan (longest chain of predecessors)
for s in S:  # S is built so that every predecessor comes first
    for a in s['after']:
        if a not in STEP:
            errors.append(f'{s["id"]} comes after {a}, which is not before it')
    STEP[s['id']] = 1 + max([STEP.get(a, 0) for a in s['after']], default=0)
ANC = {}   # every session a session comes after, directly or through others
for s in S:
    ANC[s['id']] = set().union(*[ANC[a] | {a} for a in s['after'] if a in ANC]) if s['after'] else set()
AREA = {}
for s in S:
    if s['kind'] == 'B':
        AREA[s['id']] = ('unit', s['unit'])
ss = [s['id'] for s in S if s['id'] in AREA]   # across the whole plan, since slices overlap
for n, a in enumerate(ss):
    for b in ss[n + 1:]:
        if AREA[a] == AREA[b] and a not in ANC[b] and b not in ANC[a]:
            errors.append(f'{a} and {b} can run side by side but both change {AREA[a][0]} {AREA[a][1]}')
STATUS, REF = {}, {}
sp = os.path.join(PLAN, 'delivery', 'session-status.csv')
if os.path.isfile(sp):
    for r in csv.DictReader(open(sp)):
        if r['session'] not in BYID:
            errors.append(f'session-status.csv: unknown session {r["session"]}')
        elif r['status'] not in STATUSES:
            errors.append(f'session-status.csv: {r["session"]} has status "{r["status"]}"; use one of {", ".join(STATUSES)}')
        else:
            STATUS[r['session']], REF[r['session']] = r['status'], r.get('pull_request', '')
for s in S:
    s['status'] = STATUS.get(s['id'], 'Not started')
    if s['status'] in ('In progress', 'Done'):
        errors += [f'session-status.csv: {s["id"]} is {s["status"]} but {a}, which it comes after, is not Done' for a in s['after'] if STATUS.get(a) != 'Done']
if errors:
    sys.exit('build_sessions.py:\n  ' + '\n  '.join(errors[:40]))
for s in S:   # step within the slice, for the tables: sessions on the same step have no order between them
    s['step'] = 1 + max([BYID[a]['step'] for a in s['after'] if BYID[a]['group_key'] == s['group_key']], default=0)
ENABLES = collections.defaultdict(list)
for s in S:
    for a in s['after']:
        ENABLES[a].append(s['id'])
READY = [s for s in S if s['status'] == 'Not started' and all(BYID[a]['status'] == 'Done' for a in s['after'])]


# ------------------------------------------------------------------ links
def page(group):
    return f'{group}.md'


def L(sid, depth):
    """Link to a session card from the index (depth 1) or from a group page (depth 2)."""
    return f'[{sid}]({"" if depth == 2 else "sessions/"}{page(BYID[sid]["group"])}#{sid.lower()})'


def Ls(ids, depth):
    """Links to sessions, with three or more consecutive sessions of one slice written as a range."""
    pos = {s['id']: n for n, s in enumerate(S)}
    ids = sorted(ids, key=pos.get)
    runs = []
    for i in ids:
        if runs and pos[i] == pos[runs[-1][-1]] + 1 and BYID[i]['group_key'] == BYID[runs[-1][-1]]['group_key']:
            runs[-1].append(i)
        else:
            runs.append([i])
    parts = [f'{L(r[0], depth)} to {L(r[-1], depth)}' if len(r) > 2 else ', '.join(L(i, depth) for i in r) for r in runs]
    return ', '.join(parts) or '–'


def spec(ab, rel, frag=''):
    return f'../../../domain_specs/{FOLDER[ab]}/{rel}' + (f'#{frag}' if frag else '')


def fr_link(x):
    return f'[{x}]({spec(ab_of(x), "05-functional-requirements/" + MODFILE[BACK[x]["module_id"]], x.lower())})'


def mod_link(m):
    return f'[{m}]({spec(ab_of(m), "05-functional-requirements/" + MODFILE[m])})'


def test_link(t):
    return f'[{t}]({spec(ab_of(t), "15-testing.md", t.lower())})'


def ui_link(r):
    i, ab = r['ui_id'], r['domain'].split('-')[1]
    if i.lower() in BRIEF:
        return f'[{i}](../../../design/screen-briefs/{ab}.md#{i.lower()}) {r["screen"]}'
    if i.lower() in UISPEC:
        note = 'detailed in section 6.3 of the specification; work from that entry' if r['specification_detail'] == 'Detailed' else 'no brief yet; work from the catalogue entry'
        return f'[{i}]({spec(ab, "06-user-interface.md", i.lower())}) {r["screen"]} ({note})'
    return f'{i} {r["screen"]}'


def slice_link(sid, depth):
    return f'[{sid}]({"../" if depth == 2 else ""}slices/{sid.split("-")[0]}.md#{sid.lower()})'


def gate_link(sid, word='slice gate'):
    return f'[{word} {sid}](../gates/{sid.split("-")[0]}.md#{sid.lower()})'


def dom_reads(doms, files):
    return [f'[D{NUM[ab]} {ab} {label}]({spec(ab, rel)})' for ab in doms for label, rel in files]


def scope(s):
    if s['kind'] == 'C':
        mods = ', '.join(mod_link(m) for m in s['contract_mods'])
        if len(s['domains']) == 1 and s['domain']:
            return (f'The contracts and stubs of D{NUM[s["domain"]]} {s["domain"]} for this slice, for modules {mods}. '
                    + ('It comes after the contract sessions of the other domains: it first checks that every reference between the domains\' contracts resolves and repairs those that do not, '
                       'then writes the end-to-end scenario as an automated test that fails, against the contracts of every domain of the slice.' if s['scenario']
                       else 'It runs side by side with the contract sessions of the other domains and changes only the contract files and section 7.3 of its own domain; '
                            'where it refers to an entity or event of another domain, it uses the name in that specification and in the event catalogue. '
                            'The last contract session of the slice joins the domains and writes the scenario test.'))
        return KIND['C'][2] + f' Modules: {mods}.'
    if s['kind'] == 'B' and s.get('with_contract'):
        return ('This slice has one build session, so it also does the contract work: first fix the contracts and stubs the slice needs and write the end-to-end scenario '
                'as a failing test; then build. ' + ('There are no screens, so it ends by making the scenario pass, as an integrate session would. ' if s['with_integrate'] else '')
                + '<br>' + '<br>'.join(f'{mod_link(m)} {MODS[m]["module"]}: ' + ', '.join(fr_link(x) for x in s['frs'] if BACK[x]['module_id'] == m) for m in s['modules']))
    if s['kind'] == 'B':
        return '<br>'.join(f'{mod_link(m)} {MODS[m]["module"]}: ' + ', '.join(fr_link(x) for x in s['frs'] if BACK[x]['module_id'] == m) for m in s['modules'])
    if s['kind'] == 'X':
        return f'{s["title"]} (gate line: {s["gate_line"]}). Owned by {L(s["owner"], 2)}.'
    if s['kind'] == 'U':
        return '; '.join(ui_link(r) for r in s['screens'])
    if s['kind'] == 'F':
        return s['fdef']['does']
    return KIND[s['kind']][2]


def reads(s):
    sid = s['slice']
    if s['kind'] == 'F':
        return [f'[{label}](../../../{path})' for label, path in s['fdef']['reads']]
    card = f'Slice {slice_link(sid, 2)}'
    if s['kind'] == 'C':
        prior = [a for a in s['after'] if BYID[a]['slice'] == sid]
        return [card + ' (outcome, scenario, requirements, dependencies met by contract)'] + \
            ([f'The contracts and handovers of {Ls(prior, 2)}'] if prior else []) + [
                '[Architecture, section 6](../../../architecture/system-architecture.md#s6)',
                '[Event catalogue](../event-catalogue.md)'] + dom_reads(s['domains'], [('integration', '08-integration.md'), ('data', '07-data.md')])
    if s['kind'] == 'B':
        ab = s['domain']
        return [f'Module{"s" if len(s["modules"]) > 1 else ""} {", ".join(mod_link(m) for m in s["modules"])}: the overview and the requirements above in full',
                f'[D{NUM[ab]} {ab} workflows and business rules]({spec(ab, "04-processes-and-workflows.md")}) cited by those requirements'] + \
            dom_reads([ab], [('data', '07-data.md'), ('security, privacy and compliance', '09-security-privacy-compliance.md'), ('non-functional requirements', '10-non-functional.md')]) + \
            ([f'The contracts and handover of {L(next(x["id"] for x in reversed(S) if x["slice"] == sid and x["kind"] == "C"), 2)}'] if not s.get('with_contract') else
             [card + ' (outcome, scenario, requirements, dependencies met by contract)', '[Architecture, section 6](../../../architecture/system-architecture.md#s6)',
              '[Event catalogue](../event-catalogue.md)'] + dom_reads(s['domains'], [('integration', '08-integration.md')])) + \
            ([f'The handovers of the earlier sessions on the same modules: {Ls(s["builds_on"], 2)}. Extend what they built; do not rebuild it'] if s['builds_on'] else [])
    if s['kind'] == 'U':
        ab = s['domain']
        return ['The briefs above', f'The contracts, stubs and handover of {L(CP[sid], 2)}', '[Application shell](../../../design/application-shell.md)', '[Clinical UX safety rules](../../../design/clinical-ux-safety-rules.md)',
                '[Design system](../../../design/DESIGN.md)', '[User roles](../../../design/user-roles.md)',
                f'[D{NUM[ab]} {ab} user interface]({spec(ab, "06-user-interface.md")})']
    if s['kind'] == 'I':
        return [card + ' (scenario and "done when")', 'The handovers of every session of this slice'] + \
            ([f'The handovers of the sessions that made the scenarios of the earlier slices pass: {Ls([a for a in s["after"] if BYID[a]["slice"] != sid], 2)}'] if any(BYID[a]['slice'] != sid for a in s['after']) else []) + dom_reads(s['domains'], [('integration', '08-integration.md')])
    if s['kind'] == 'R':
        return [card + ' ("done when")', gate_link(sid, 'Slice gate') + ' (criteria and readiness items)', '[Architecture, section 9](../../../architecture/system-architecture.md#s9) (tiers, shared-service failure, downtime)',
                f'The handover of {L(IP[sid], 2)}'] + \
            dom_reads(s['domains'], [('safety and risk', '11-safety-and-risk.md'), ('implementation (operational readiness, section 16.4)', '16-implementation.md')])
    if s['kind'] == 'X':
        return [f'The failure report in the handover of {L(s["after"][0], 2)}', f'The handover of {L(s["owner"], 2)}, the session that owns the work',
                gate_link(sid, 'Slice gate') + ' (the failed line)']
    return [card + ' ("done when")', gate_link(sid, 'Slice gate'), '[Stage gates, section 1](../stage-gates.md) (evidence and waivers)'] + \
        dom_reads(s['domains'], [('test scenarios', '15-testing.md')])


def nfr_link(n):
    return f'[{n[0]}]({spec(ab_of(n[0]), "10-non-functional.md", n[0].lower())}) {n[1]}'


def tests_of(s):
    return sorted({t for x in s['frs'] for t in TESTS.get(x, [])})


# ------------------------------------------------------------------ group pages
GROUPS = [(FN, 'Foundation for agent work', FOUNDATION_INTRO)] + [(f[0], f[1], f[3]) for f in FLOWS]
BYSL = {sl['id']: sl for sl in SLICES}


def card(s, out):
    k = s['kind']
    out += [f'<a id="{s["id"].lower()}"></a>', '', f'#### {s["id"]} {KIND[k][1] if k != "F" else "Foundation"}: {s["title"]}', '']
    out += ['| | |', '|---|---|',
            f'| Status | {s["status"]}' + (f' ({td(REF[s["id"]])})' if REF.get(s['id']) else '') + ' |',
            f'| After | {Ls(s["after"], 2)} |',
            f'| Enables | {Ls(ENABLES[s["id"]], 2)} |',
            f'| Scope | {td(scope(s))} |']
    if s['builds_on']:
        out.append(f'| Builds on | {Ls(s["builds_on"], 2)} |')
    if k == 'B':
        ts = tests_of(s)
        out.append(f'| Test scenarios | {", ".join(test_link(t) for t in ts) or "None trace to these requirements; test from the acceptance criteria"} |')
    if s['safety']:
        out.append('| Safety | Safety-critical functions this session implements a control for ([section 11.1]('
                   + spec(s['domain'] or s['safety'][0]['ab'], '11-safety-and-risk.md', 's11-1') + ')): '
                   + td('; '.join(f'**{f["function"]}** (hazard: {f["hazard"][0].lower() + f["hazard"][1:]}; verified by '
                                  + (', '.join(test_link(x) for x in f['tests']) or 'the exercises in section 11.1') + ')' for f in s['safety'])) + ' |')
    for a in s['review']:
        out.append(f'| Safety duty | {td(a["area"])}: {td(a["duty"])}. |')
    if s.get('duty'):
        out.append(f'| Slice duty | {td(s["duty"][0])}. |')
    if s['nfr']:
        label = {'B': 'Design for these targets', 'U': 'Design for these targets', 'R': 'Evidence these targets', 'G': 'Collect evidence of these targets'}[k]
        out.append(f'| Non-functional | {label}: ' + ', '.join(nfr_link(n) for n in s['nfr']) + ' |')
    if s['nfr_runtime']:
        out.append('| Non-functional checks | Run in the integration environment, under the workload of section 10.1 and with the failures the targets name: '
                   + ', '.join(nfr_link(n) for n in s['nfr_runtime']) + ' |')
    out.append(f'| Reads | {td("<br>".join(reads(s)))} |')
    left = s['fdef']['produces'] if k == 'F' else KIND[k][3]
    if s.get('with_contract'):
        left = KIND['C'][3] + ' ' + left + (' ' + KIND['I'][3] if s['with_integrate'] else '')
    out.append(f'| Leaves behind | {td(left)} |')
    ends = s['fdef']['done'] if k == 'F' else KIND[k][4]
    if s.get('with_contract'):
        low = lambda x: x[0].lower() + x[1:]
        ends = 'First, ' + low(KIND['C'][4]) + ' Then, ' + low(ends) + (' Finally, ' + low(KIND['I'][4]) if s['with_integrate'] else '')
    if s['safety']:
        ends += ' The verification of each safety-critical function listed passes; where the change alters a safety control, the hazard log entry is updated (architecture section 13).'
    if s.get('duty'):
        ends += f' Also: {s["duty"][1]}.'
    if s['nfr_runtime']:
        ends += ' Each non-functional check has run, and its result is recorded against its target; a shortfall is recorded with its measurement and goes to the gate, not silently past it.'
    out.append(f'| Ends when | {td(ends)} |')
    if s['human']:
        out.append(f'| Needs a person | {td("; ".join(s["human"]))} |')
    out.append('')


def table(sessions, out):
    out += ['| Step | Session | Kind | Scope | After | Status |', '|---|---|---|---|---|---|']
    for s in sorted(sessions, key=lambda s: (s['step'], s['id'])):
        if s['kind'] == 'B':
            what = f'{s["title"]}: {len(s["frs"])} requirement{"s" if len(s["frs"]) > 1 else ""}'
        elif s['kind'] == 'U':
            what = f'{s["title"]}: {len(s["screens"])} screen{"s" if len(s["screens"]) > 1 else ""}'
        else:
            what = s['title']
        out.append(f'| {s["step"]} | [{s["id"]}](#{s["id"].lower()}) | {KIND[s["kind"]][1] if s["kind"] != "F" else "Foundation"} | {td(what)} | {Ls(s["after"], 2)} | {s["status"]} |')
    out.append('')


for code, name, intro in GROUPS:
    mine = [s for s in S if s['group'] == code]
    out = [GENERATED, '', f'[Implementation plan](../../README.md) / [Session plan](../sessions.md) / {name}', '',
           f'# Sessions {code}: {name}', '', intro, '',
           'The rules every session follows are in [sections 2 to 4 of the session plan](../sessions.md#rules). Sessions on the same step of a slice have no order between them and can run in parallel. A session of one slice can also come after a session of an earlier slice; its "After" row names it.', '']
    if code == FN:
        table(mine, out)
        for s in mine:
            card(s, out)
    else:
        out += ['| Slice | Title | Sessions | Done |', '|---|---|---|---|']
        for sl in SLICES:
            if sl['id'].startswith(code + '-'):
                ss = [s for s in mine if s['slice'] == sl['id']]
                out.append(f'| [{sl["id"]}](#{sl["id"].lower()}) | {td(sl["title"])} | {len(ss)} | {sum(s["status"] == "Done" for s in ss)} |')
        out.append('')
        for sl in SLICES:
            if not sl['id'].startswith(code + '-'):
                continue
            ss = [s for s in mine if s['slice'] == sl['id']]
            out += [f'<a id="{sl["id"].lower()}"></a>', '', f'## {sl["id"]} {sl["title"]}', '',
                    f'Slice card: {slice_link(sl["id"], 2)}. Gate: {gate_link(sl["id"])}. '
                    f'{len(ss)} sessions; at most {max(collections.Counter(s["step"] for s in ss).values())} side by side.', '']
            table(ss, out)
            for s in ss:
                card(s, out)
    write(f'delivery/sessions/{page(code)}', out)

# ------------------------------------------------------------------ index page
nk = collections.Counter(s['kind'] for s in S)
width = collections.Counter(STEP.values())
out = [GENERATED, '', '[Implementation plan](../README.md) / Session plan', '', '# Session Plan', '',
       'The work of the [vertical slices](slices.md) cut into **sessions**. A session is one AI agent session: one agent starts with an empty context, '
       'reads what its card lists, does one bounded piece of work, proves it with a check, writes a handover and stops. '
       'The slice plan says what is released and in what order; this plan says what each agent session is given and what it must leave behind.', '',
       f'There are {len(S)} sessions: {nk["F"]} foundation sessions and {len(S) - nk["F"]} across the {len(SLICES)} slices '
       f'({nk["C"]} contract, {nk["B"]} build, {nk["U"]} screens, {nk["I"]} integrate, {nk["R"]} readiness, {nk["G"]} gate evidence'
       + (f', {nk["X"]} fix' if nk['X'] else '') + '). '
       f'Every functional requirement ({len(BACK)}) and every screen ({len(SCREENS)}) is in exactly one session.', '',
       'Order is expressed as "after", as in the slice plan. No durations are implied, and the number of sessions is not a measure of effort.', '',
       '<a id="shape"></a>', '', '## 1. How a slice is cut into sessions', '',
       'Every slice is cut the same way, so that an agent meeting any card knows where it stands.', '',
       '```mermaid', 'flowchart LR',
       '  PC(["Earlier slice:<br/>contracts"]) -.-> C', '  PI(["Earlier slice:<br/>scenario passes"]) -.-> I', '  PG(["Earlier slice:<br/>gate evidence"]) -.-> G',
       '  C["Contract<br/>contracts, stubs,<br/>failing scenario test"] --> B1["Build<br/>module A"]', '  C --> B2["Build<br/>module B"]',
       '  B1 --> B3["Build<br/>unit A, part 2"]', '  B2 --> B4["Build<br/>unit C, which needs A"]', '  B3 --> B4', '  C --> U["Screens<br/>against the stubs"]',
       '  B4 --> I["Integrate<br/>scenario passes"]', '  U --> I',
       '  I --> R["Readiness<br/>Tier 1 only"]', '  R --> G["Gate evidence<br/>fresh session"]', '  G -->|failures| X["Fix"]', '  X --> G2["Gate evidence<br/>next round"]',
       '  G -->|no failures| H(["Owner signs<br/>the slice gate"])', '  G2 --> H', '```', '',
       'In the diagram, B1 to B4 are build sessions on deployable units A, B and C. A dotted arrow comes from a slice this one comes after.', '',
       '| Kind | Applies to | What the session does | Leaves behind | Ends when |', '|---|---|---|---|---|']
for k in KINDS:
    out.append(f'| **{k[1]}** | {td(k[5])} | {td(k[2])} | {td(k[3])} | {td(k[4])} |')
out += ['',
        f'- **Build sessions are cut by deployable unit** ({len(UNITS)} units, from architecture section 5.2; each Domain 2 module is a platform unit of its own). '
        f'The slice\'s requirements in one unit are packed into sessions of at most {MAX_REQUIREMENTS}, module by module, and a larger module is split evenly. '
        'Sessions on one unit follow one another, within a slice and from one slice to the next, so no two sessions running side by side change the same codebase. '
        'A session also comes after the session that builds an upstream module its requirements name, where that module is in the slice; otherwise units are built side by side behind the contracts.',
        f'- **Builds on.** {sum(1 for s in S if s["builds_on"])} build sessions extend a module that an earlier slice started. Their card names the earlier sessions, and the agent reads their handovers first.',
        f'- **Screen sessions** take the screens first released in the slice, by domain, at most {MAX_SCREENS} per session. They start once the contracts are fixed and work against the stubs, side by side with the build sessions; the integrate session runs them against the built services. '
        'Each screen has a folder of its own in the domain workspace and registers itself with the shell from there, so screen sessions have no order between them, in one domain or across slices.',
        f'- **Readiness sessions** come in the {nk["R"]} Tier 1 slices, between integration and the gate. They draft the downtime procedure, runbooks and readiness evidence the gate asks for (ACC-007), which no build session produces; people then rehearse and approve them.',
        '- **Fix sessions.** A gate evidence session does not fix. It files each failure as a fix issue against the session that owns the work ([section 3](#run)). '
        'The build adds a fix session for each row, and a further gate evidence session for each round. Finished sessions are never reopened, and the gate sessions of the next slices come after the last gate round.',
        '- **Slices overlap.** A slice does not wait for the slices it comes after to pass their gates. Its first session comes after the session that fixes the contracts of each of those slices, '
        'so it builds against their contracts and stubs while they are still being built. Its integrate session comes after theirs, since its scenario runs on their built services, '
        'and its gate evidence session comes after their last gate round, so slices still pass their gates in slice order. The first slice comes after the foundation sessions. '
        'What this costs is in [section 8](#limits).',
        f'- **Contract sessions.** A slice crossing more than {MAX_CONTRACT_MODULES} modules in more than one domain gets one contract session per domain. '
        'They run side by side, each on the contract files of its own domain, except the one for the most downstream domain (by domain wave, then by how many of the slice\'s other requirements need the domain): '
        'it comes after the others, checks that the references between the domains\' contracts resolve, and writes the failing scenario test. '
        f'{sum(1 for sl in SLICES if sum(1 for s in S if s["slice"] == sl["id"] and s["kind"] == "C") > 1)} slices are split this way.',
        f'- **A slice with a single build session** has no contract session: the build session fixes the contracts and writes the failing scenario test first. '
        'If the slice also has no screens, the same session ends by making the scenario pass, and there is no integrate session. '
        f'This applies to {sum(1 for s in S if s.get("with_contract"))} slices: ' + ', '.join(slice_link(s['slice'], 1) for s in S if s.get('with_contract')) + '. '
        'The gate evidence session is never folded: what is built is always checked by a session that did not build it.', '',
        '<a id="rules"></a>', '', '## 2. Rules for every session', '',
        '0. **You own the code base.** Claude owns this code base ([ADR-HIS-041](../../architecture/decisions/ADR-HIS-041.md)): what it is for, aligned with the specifications, and how it is built are its call, and it keeps building on it. '
        'Every session agent and review agent works as that owner: it takes the technical decisions the card leaves open, records those that shape later sessions as the next decision record, '
        'and is answerable for the quality of what it leaves behind. Ownership covers how the system is built; the rules below still hold, above all rule 3 on behaviour and rule 1 on scope.',
        '1. **One card, one pull request.** The session does what its card lists and nothing else. Work it finds outside the card goes in the handover as a follow-up, not in the change.',
        '2. **Start cold.** A session has no memory of earlier sessions. What it needs is in the agent instruction file of the repository, the card\'s "Reads", and the handovers of the sessions it comes after. If that is not enough to do the work, the card is wrong: stop and say so.',
        '3. **The specification decides.** Behaviour comes from the requirement, its acceptance criteria and the business rules it cites. A session does not change a specification to fit the code; the one addition it makes is a contract session writing missing entity attributes into section 7.3 ahead of the code (architecture section 6.6), for the domain leads to approve. Where the specification is silent, ambiguous or contradicts another, the session stops on that point and records the question on its issue; it does not guess clinical, financial or access behaviour.',
        '4. **Contracts change in the open.** Contracts are fixed by the contract session. A later session that needs a contract changed records the change and its reason in the handover and marks the session Blocked unless the change is backward compatible and passes the compatibility check.',
        '5. **Every acceptance criterion has a test, and every test names its requirement.** Tests carry the requirement identifier and, where one exists, the test scenario identifier of section 15.2, so the gate session can assemble evidence without reading the code.',
        '6. **Synthetic data only.** No session uses or asks for real patient data (architecture section 10.2).',
        '7. **Every cross-cutting duty applies.** Authorization through the policy decision point, audit, consent and segmentation, correlation identifiers and telemetry are part of every build session, as section 9 and section 10 of the owning specification require; they are not left to a later session. '
        'The non-functional targets on the card are designed for from the start, and runtime targets are measured at integration, not first discovered at the gate.',
        '8. **Safety controls are not traded away.** A card with a "Safety" row implements a control for a safety-critical function of section 11.1. The control is built as specified, its verification passes, and a change to it updates the hazard log. '
        'A card with a "Safety duty" row follows that duty; the named safety review is given on the merged work, and what it finds becomes a fix session.',
        '9. **Stop clean.** A session that cannot finish leaves the code building and the tests it wrote passing, pushes its branch, and writes what remains as a comment on its issue, which it labels `blocked`. The next run of the same card starts from that branch and that comment.',
        '10. **Side by side means separate.** Each session works in a git worktree of its own, on its own branch `session/<SESSION-ID>` cut from main, with an integration environment named after the session. It touches only their own deployable unit, the folders of their own screens, or the contract files of their own domain. The plan never puts two build sessions on one unit side by side, in one slice or across slices; the build checks this. '
        'A screen session changes nothing in the workspace outside the folders of its screens: a component two screens need comes from the design system, and one that is missing is built inside the screen folder and recorded in the handover as a follow-up for the design system.',
        '11. **Reviewed before merge.** Every session ends in a pull request that passes the pipeline and is reviewed before it is merged (FR-ISE-REL-001). '
        'The review is by a review agent that wrote none of it, and the launcher merges what it approves, with no person in between, for every kind of session '
        '([ADR-HIS-040](../../architecture/decisions/ADR-HIS-040.md)). What a review does not approve goes back to the session until it does. '
        'Approvals and signatures named under "Needs a person" are given by people, but they no longer hold up the merge; they are given on the merged work (section 4). '
        'A session is Done when its pull request is merged.',
        '12. **An earlier slice may not have passed its gate.** A session can build on the contracts of a slice that is still being built or checked. It works against those contracts and their stubs, never against unmerged code. '
        'If a fix in an earlier slice changes a contract in a way that is not backward compatible, every session not yet Done that uses the contract is marked Blocked until the change is merged, and a Done session it breaks gets a fix session at its own gate.', '',
        '<a id="run"></a>', '', '## 3. Starting and ending a session', '',
        'To start a session, give an agent this, with the session identifier and the number of its issue filled in; the launcher below does so:', '',
        '```text'] + SESSION_PROMPT + [
        '```', '',
        '**Handover.** Each session writes `delivery/handovers/<SESSION-ID>.md`. It is the only thing a later session knows of this one, so it states:', '',
        '- what was built and where it is;',
        '- how to run its checks, and their result;',
        '- each requirement and test scenario of the card, with the test that covers it;',
        '- anything done differently from the specification or the contract, and why;',
        '- questions left for a person, and follow-up work found outside the card.', '',
        '**Sessions on GitHub.** Every session has an issue in the repository, titled with the session identifier and labelled with its kind and group; the slice is its milestone. '
        '[sync_github.py](../tools/sync_github.py) creates the issues of a slice when its first session can start, links each issue to the issues it is blocked by, and keeps their state:', '',
        '| State | When | Who sets it |', '|---|---|---|',
        '| Waiting | A session it comes after is not done, or the issue carries the label `hold` | The sync |',
        '| Ready | Every session it comes after is done; the issue carries the label `ready` | The sync |',
        '| Running | The issue carries the label `running` | The launcher, when it starts the session |',
        '| Paused | The issue carries the label `paused`; the agent is interrupted, and its worktree and conversation are kept | A person, with the launcher |',
        '| Blocked | The issue carries the label `blocked`, with the question in a comment | The session, when it stops; a person removes the label once it is settled, and the session is then run again from its branch |',
        '| In review | A pull request from branch `session/<SESSION-ID>` is open | The session, by opening it |',
        '| Done | The issue is closed | Merging the pull request, whose description starts with "Closes #n" |', '',
        'The sync runs as a GitHub Actions workflow on every push to main and on every change of an issue or pull request. A person can hold a session back with the label `hold`. '
        'If `delivery/github.json` names a project board, the sync also sets the field "Session status" of each issue there.', '',
        '**Running sessions side by side.** [launch_sessions.py](../tools/launch_sessions.py) runs on the server where the agents work. It starts the sessions GitHub shows as Ready, each in its own worktree and its own terminal window, up to a limit that fits the server, '
        'and removes the worktree of a session when its issue is closed:', '',
        '```text',
        'python3 docs/implementation_plan/tools/launch_sessions.py list              what is running, in review, blocked, ready',
        'python3 docs/implementation_plan/tools/launch_sessions.py start --max 3     start ready sessions, up to 3 running',
        'python3 docs/implementation_plan/tools/launch_sessions.py watch --max 3     the same, again every five minutes',
        'python3 docs/implementation_plan/tools/launch_sessions.py pause RC-1-S04    interrupt a session (or --all); its place is freed',
        'python3 docs/implementation_plan/tools/launch_sessions.py resume RC-1-S04   continue it (or --all), also after a server restart',
        '```', '',
        'A session starts from `origin/main`, and one that is Ready always finds the work it comes after already merged. '
        'When a session\'s pull request is open and its checks pass, the launcher has a review agent review it, read-only and with the card, the diff and the handover (REVIEW_PROMPT in sessions_def.py). '
        'If the review approves, the launcher merges the pull request; if it asks for changes, the launcher passes them to the session, which fixes them on its branch, and the next push is reviewed again; '
        'a branch that conflicts with main goes back to the session to bring up to date. Failing checks go back to the session without a review. '
        'AUTO_MERGE in sessions_def.py can name kinds, labels or paths that a person merges instead (labelled `merge-by-person`); it names none. `--no-merge` leaves every merge to a person. '
        'To stop new sessions from starting, stop `watch`; to keep one session from starting, label its issue `hold`. A paused session continues its own conversation when resumed, so nothing it had in hand is lost.', '',
        '**Usage limits.** All sessions draw on the one Claude plan of the account, with a five-hour and a weekly allowance. Every session runs on Opus, and the launcher keeps them within the allowance by running fewer at once rather than by changing model. '
        'Each session reports the account\'s usage through its status line ([usage_hooks.py](../tools/usage_hooks.py)), and the launcher starts no new session while the five-hour usage is at or above 80%, '
        'or while the weekly usage runs more than 10 points ahead of an even pace through the week (`--five-hour-hold`, `--weekly-margin`; `list` shows the figures and any hold). '
        'Sessions already running carry on. When one hits a limit, Claude Code waits and continues it after the reset; where it does not (after three hits in a row, or a wait of more than a day), '
        '`watch` continues it a few minutes after the reset. Sessions run with prompt suggestions and session recaps off, since those requests also count against the allowance.', '',
        '**Permissions.** An agent session runs without asking only the commands listed in SESSION_PERMISSIONS of [sessions_def.py](../tools/definitions/sessions_def.py): reading files, git on its own branch, '
        'and gh on its own issue and pull request. It may never force-push, push to main, merge, close issues or run the plan build. Every other command waits for a person in its window, '
        'so a session that needs, for example, Docker or a package manager asks before using it. Edit the list there to widen or narrow it; it applies to sessions started or resumed after the change.', '',
        '**Status.** [session-status.csv](session-status.csv) holds one row per session that has started: `session`, `status` (In progress, Blocked or Done), `pull_request`, `notes`. '
        'A session with no row is Not started. The file is written by the sync from the state of the issues, and the plan is rebuilt and committed with it; nobody edits it by hand, and sessions do not touch it, '
        'since every pull request would then change the same files. The build refuses a session marked In progress or Done while a session it comes after is not Done.', '',
        '**Fixes.** A gate evidence session files one issue for each failure it records:', '',
        '```text',
        'gh issue create --label kind:fix --title "RC-1-S27-F1 Fix: <the problem, in one sentence>" --body "Round: 1',
        'Owner session: RC-1-S08',
        'Gate line: <the done-when line or gate criterion that failed>"',
        '```', '',
        'The identifier is that of the first gate session of the slice followed by `-F` and a number; the round is 1 for failures of the first gate run, 2 for those of the second, and so on; '
        'the owner is the session of the slice whose work failed. The sync writes these issues into [session-fixes.csv](session-fixes.csv), and the build adds a fix session for each and a further gate evidence session, '
        '`<gate session>-G<n+1>`, for each round; each then has an issue of its own. Fixes of one round on the same unit, or on the screens of one domain, follow one another.', '',
        '<a id="people"></a>', '', '## 4. Where a person is needed', '',
        'A review agent reviews every pull request and the launcher merges what it approves; no person merges (rule 11). People still give the approvals, reviews and signatures below. '
        'They are given on work that is already merged, and a finding from them comes back as a fix session or a follow-up, not as a held merge:', '',
        '| Point | Who | Why |', '|---|---|---|',
        '| End of each contract session | Leads of the domains in the slice | The contracts bind every build session that follows; an error here is repeated in each |',
        '| A question raised under rule 3 | Owner of the specification | Clinical, financial and access behaviour is not for an agent to settle |',
        f'| After merge of a card with a safety duty ({sum(1 for s in S if s["review"])} cards) | As named on the card: the clinical safety officer, with a pharmacist, HIM or registration governance, the privacy officer, clinical engineering, AI governance or the SaMD design authority by area | '
        'Architecture section 13: safety-significant changes need a hazard review; the blood bank is a SaMD under design control |',
        '| A requirement that cites an open decision | Decision lead in the [decision plan](../decisions/decision-plan.md) | Marked "Needs a person" on the card |',
        '| After each readiness session | The departments that use the workflows, and the service owner | The downtime procedure is rehearsed by the people who will follow it (ACC-007); a session can only draft it |',
        '| After each gate evidence session | Clinical owner for a Tier 1 slice, business owner otherwise | The slice gate is passed by signature (ACC-002), on the evidence the session collected; a failure becomes a fix session |',
        '| Stage gates and go-live | As in [stage gates](stage-gates.md) | Not session work |', '',
        f'{sum(1 for s in S if s["human"] and s["kind"] in "BFU")} cards outside the readiness and gate sessions carry a "Needs a person" line: '
        + Ls([s['id'] for s in S if s['human'] and s['kind'] in 'BFU'], 1) + '.', '',
        '<a id="next"></a>', '', '## 5. Progress and what can start now', '',
        '| Group | Sessions | Done | In progress | Blocked |', '|---|---|---|---|---|']
for code, name, _ in GROUPS:
    mine = [s for s in S if s['group'] == code]
    c = collections.Counter(s['status'] for s in mine)
    out.append(f'| [{code} {name}](sessions/{page(code)}) | {len(mine)} | {c["Done"]} | {c["In progress"]} | {c["Blocked"]} |')
c = collections.Counter(s['status'] for s in S)
out += [f'| **All** | **{len(S)}** | **{c["Done"]}** | **{c["In progress"]}** | **{c["Blocked"]}** |', '',
        f'**Can start now** ({len(READY)}): every session they come after is Done.', '']
out += ['| Session | Kind | Scope |', '|---|---|---|'] if READY else []
for s in READY:
    out.append(f'| {L(s["id"], 1)} | {KIND[s["kind"]][1] if s["kind"] != "F" else "Foundation"} | {td(s["title"])} |')
out += ['', '<a id="index"></a>', '', '## 6. Sessions by slice', '',
        '| Slice | Title | Phase | After | Contract | Build | Screens | Integrate | Readiness | Gate | Fix | Sessions | Most side by side |', '|---|---|---|---|---|---|---|---|---|---|---|---|---|',
        f'| [{FN}](sessions/{page(FN)}) | Foundation for agent work | Before 1 | – | – | – | – | – | – | – | – | {nk["F"]} | {max(collections.Counter(s["step"] for s in S if s["group"] == FN).values())} |']
for sl in SLICES:
    ss = [s for s in S if s['slice'] == sl['id']]
    k = collections.Counter(s['kind'] for s in ss)
    out.append(f'| [{sl["id"]}](sessions/{page(sl["id"].split("-")[0])}#{sl["id"].lower()}) | {td(sl["title"])} | {sl["phase"]} | '
               f'{", ".join(slice_link(a, 1) for a in sl["after"]) or "Foundation"} | {k["C"]} | {k["B"]} | {k["U"]} | {k["I"]} | {k["R"]} | {k["G"]} | {k["X"]} | {len(ss)} | {max(collections.Counter(s["step"] for s in ss).values())} |')
longest = max(STEP.values())
out += ['', f'The longest chain of sessions that must follow one another is {longest} long. At its widest the plan has {max(width.values())} sessions with no order between them; '
        'how many actually run side by side is a matter of review capacity, since every session ends with a person (rule 11).', '',
        '<a id="checks"></a>', '', '## 7. Checks on this plan', '',
        f'- **Coverage.** All {len(BACK)} functional requirements are in exactly one build session and all {len(SCREENS)} screens in exactly one screen session; the build script fails otherwise.',
        '- **Order.** Every session comes after sessions that precede it in the plan, so there is no cycle. Within a slice, an upstream module named by a requirement is built first when it is in the same slice. '
        'Across slices, contracts come after contracts, integration after integration and gate after gate.',
        '- **No shared codebase side by side.** No two build sessions on one deployable unit can run side by side, anywhere in the plan; the build script fails otherwise. '
        'Every screen is in exactly one screen session and has a folder of its own, so no two screen sessions change the same files. '
        'Every module is in exactly one unit of [sessions_def.py](../tools/definitions/sessions_def.py).',
        f'- **Safety.** {sum(1 for s in S if s["safety"])} build sessions carry a "Safety" row from section 11.1 of the specifications, and {sum(1 for s in S if s["review"])} build or screen sessions a safety duty with a named review. '
        'Every identifier in SAFETY_REVIEW exists, and every non-functional category is placed in exactly one class; the build fails otherwise.',
        '- **Fixes.** Every row of session-fixes.csv, written from the fix issues, names a gate session and an owning session of the same slice; rounds run without a gap.',
        f'- **Tests.** {len({t for s in S for t in tests_of(s)})} test scenarios of section 15.2 are listed on the build session of the requirement they trace to; a scenario tracing to requirements in two sessions is listed on both. '
        'Tests of non-functional and cross-cutting requirements are run by the gate evidence sessions.',
        f'- **Screen design.** Every screen has design detail: {sum(1 for r in SCREENS if r["ui_id"].lower() in BRIEF)} have a design brief and '
        f'{sum(1 for r in SCREENS if r["ui_id"].lower() not in BRIEF and r["specification_detail"] == "Detailed")} a detailed entry in section 6.3 of their specification, which their cards link to instead. '
        + (f'{sum(1 for r in SCREENS if r["ui_id"].lower() not in BRIEF and r["specification_detail"] != "Detailed")} have neither and need a brief before their session starts.'
           if any(r['ui_id'].lower() not in BRIEF and r['specification_detail'] != 'Detailed' for r in SCREENS) else ''), '',
        '<a id="limits"></a>', '', '## 8. Limits', '',
        '- **Overlapping slices trade rework for speed.** A slice is built on contracts whose own slice has not passed its gate. A gate failure that changes a contract reaches every later session that used it (rule 12); '
        'a failure that leaves the contracts alone does not. Screens are built against stubs, so a stub that differs from the built service shows only at integration. '
        'Gates still pass in slice order, so nothing is released on an unchecked slice. To go back to strict order, make a slice start after the gate of the slices before it in build_sessions.py.',
        '- **Screen folders rest on the workspace layout.** Screen sessions run side by side only because foundation session FN-S06 lays out every domain workspace with one folder per screen and registration from that folder. '
        'If that layout is not accepted, put the screen sessions of a domain back one after another in build_sessions.py. Components built inside a screen folder can be duplicated between screens until the design system takes them up.',
        '- **Contract sessions side by side can disagree.** Two domains fixed at the same time can name a shared entity or event differently; the last contract session of the slice is where that is found and repaired, before any build session starts.',
        '- **Fix sessions are outside the side-by-side check.** A fix changes a unit or screen folder that a later slice may be working on at the same time. It is small and merges first; the open sessions on that unit rebase on it.',
        f'- **The cut is mechanical.** Sessions follow slice, module and the caps in [sessions_def.py](../tools/definitions/sessions_def.py) ({MAX_REQUIREMENTS} requirements, {MAX_SCREENS} screens). '
        'A requirement can be far larger or smaller than its neighbours. If a session proves too large, it stops clean (rule 9) and is run again; if a module is consistently too large, lower the cap.',
        '- **Session identifiers are positional.** Changing the slicing, the units, the caps or the screen inventory renumbers sessions. Do it between slices, and rename the issues and the handover files to match by hand: the sync recognises an issue by the session identifier at the start of its title.',
        '- **The unit grouping is the architecture\'s proposal.** Architecture section 5.2 says each unit\'s final shape is recorded in a decision record when its first slice is built. If a unit is split or merged there, change UNITS to match.',
        '- **Non-functional requirements** have no sessions of their own. Each is placed by its category, through NFR_CLASS in sessions_def.py. Code-level targets (security, interoperability, observability, localization, time integrity) go on every build card of the domain. '
        'Runtime targets (performance, latency, reliability, scalability, isolation, degraded operation, durability, recoverability) are checks of the integrate session. '
        'Availability, maintainability and portability are evidenced by the readiness session, or by the gate where a slice has none. Usability and accessibility go on screen cards. '
        'Section 10 does not say which module a target binds, so a card lists all of its domain\'s targets in the class.',
        '- **Safety rows are derived from section 11.1.** A requirement that section 11.1 cites as a safety control puts the function on the card of the session that builds it. A control the table states without citing a requirement is not found. '
        'Which areas need a person\'s safety review before merge is a hand-kept list (SAFETY_REVIEW in sessions_def.py).',
        '- **Enabling work** listed in the backlog of each domain (external integrations, data migration) is session work only where a slice requirement calls for it. Migration and rollout belong to the per-domain plans still to be written.',
        '- **Dependencies inside a slice** come from the "Upstream dependencies" line of each requirement. One the specifications do not state is not found; the contract session is where it should surface.', '',
        'Data: [data/sessions.csv](../data/sessions.csv). To change the cut, edit [tools/definitions/sessions_def.py](../tools/definitions/sessions_def.py) and run [tools/build.py](../tools/build.py).']
write('delivery/sessions.md', out)

# ------------------------------------------------------------------ data
with open(os.path.join(PLAN, 'data', 'sessions.csv'), 'w', newline='') as f:
    w = csv.writer(f, lineterminator='\n')
    w.writerow(['session', 'group', 'slice', 'phase', 'kind', 'step_in_slice', 'title', 'after', 'domain', 'unit', 'modules', 'builds_on', 'requirements', 'screens', 'test_scenarios', 'safety_functions', 'safety_review', 'nfrs', 'needs_a_person', 'status'])
    for s in S:
        w.writerow([s['id'], s['group'], s['slice'], BYSL[s['slice']]['phase'] if s['slice'] else 0, 'Foundation' if s['kind'] == 'F' else KIND[s['kind']][1], s['step'], s['title'],
                    ' '.join(s['after']), s['domain'], s['unit'], ' '.join(s['modules']), ' '.join(s['builds_on']), ' '.join(s['frs']), ' '.join(r['ui_id'] for r in s['screens']), ' '.join(tests_of(s)), '; '.join(f['function'] for f in s['safety']), '; '.join(a['area'] for a in s['review']),
                    ' '.join(n[0] for n in s['nfr'] + s['nfr_runtime']), '; '.join(s['human']), s['status']])
print(f'sessions: {len(S)}  ({", ".join(f"{k}: {v}" for k, v in sorted(nk.items()))})  ready: {len(READY)}  longest chain: {longest}')
