Skip to content

MongLong0214/frontier-simplify / skills/frontier-simplify-review

frontier-simplify-review

Unverified

Review a change for concrete defects, check them with a refuter and a reproducer, then check repairs and their regressions against the preserved review. Use for substantial PR reviews or repeated review rounds. Stops automatic review after at most three attempts per PR and names the calling agent's next action; does not guarantee safe merge convergence.

scripts/lib/ledger.py

View on GitHub
"""Host receipts preserve evidence, not merge permission. Legacy outcomes remain historical."""
import json
import fcntl
import re
from pathlib import Path
import subprocess
import sys
from datetime import datetime, timezone
from protocol import digest, protocol_sha256, require, Rejected, MAX_ROUNDS, child_environment

HERE = Path(__file__).resolve().parent
SCRIPTS = HERE.parent
MODE = 'prose-review-v3'
PROSE_MODES = {'prose-review-v2', MODE}
VALIDATORS = ('refuter', 'reproducer')
# The only line the host reads from a finder's prose: a hint to skip validation, never a PASS.
NO_CANDIDATES = 'Validation candidates: NONE'
VALIDATION_VERSION = 1


def prose_mode(start):
    return start.get('mode') in PROSE_MODES


def scope_version(start):
    if 'scope_schema_version' not in start:
        return None
    version = start['scope_schema_version']
    require(type(version) is int and version == 1, 'scope-version',
            'unsupported declared scope schema version')
    return version


def validator_guard(name):
    return name.split('-', 1)[0] in VALIDATORS


def validator_outputs(role):
    return [f'{role}-{name}' for name in
            ('prompt.txt', 'events.jsonl', 'executor.err', 'executor-exit.txt', 'ARTIFACT.md')]


def validation(directory, start):
    """'skipped' or 'required' for one attempt's finder review; None before the validators existed.

    Only a first review, one that inherits no earlier review and so freezes no WITNESS_RESULTS.md,
    can skip, and only when the last nonblank line of its final answer is NO_CANDIDATES.
    """
    if 'validation_version' not in start:
        return None
    version = start['validation_version']
    require(type(version) is int and version == VALIDATION_VERSION, 'validation-version',
            'unsupported declared validation version')
    # Exact: a padded, quoted or punctuated marker runs both validators.
    lines = [line for line in (directory / 'ARTIFACT.md').read_text(
        encoding='utf-8', errors='replace').splitlines() if line.strip()]
    first = start['phase'] == 1 and 'WITNESS_RESULTS.md' not in start['inputs']
    return 'skipped' if first and lines and lines[-1] == NO_CANDIDATES else 'required'


def encode(value):
    return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode()


def append(root, event):
    path = root / 'ledger.jsonl'
    previous = path.read_bytes().splitlines()[-1] if path.exists() and path.stat().st_size else b''
    event = dict(event, previous_sha256=digest(previous), at=datetime.now(timezone.utc).isoformat())
    with path.open('ab') as f:
        f.write(encode(event) + b'\n')
        f.flush()
        import os
        os.fsync(f.fileno())
    return event


def read(root):
    path = root / 'ledger.jsonl'
    if not path.exists():
        return []
    events, previous = [], b''
    for raw in path.read_bytes().splitlines():
        e = json.loads(raw)
        require(e['previous_sha256'] == digest(previous), 'ledger-integrity', 'broken receipt chain')
        events.append(e)
        previous = raw
    return events


def hashes(directory, names):
    return {name: digest((directory / name).read_bytes()) for name in names}


def verify_hashes(directory, expected):
    for name, sha in expected.items():
        require(Path(name).name == name, 'ledger-integrity', 'invalid artifact path')
        p = directory / name
        require(p.is_file() and not p.is_symlink() and digest(p.read_bytes()) == sha,
                'ledger-integrity', f'{directory.name}/{name}: digest mismatch')


class MissingGuard(Exception):
    """A named check is not defined. That is a broken harness, not a finding about the review."""


def shell_guard(name, *args):
    # Ask whether the check exists before running it. A guard removed while a caller still names
    # it came back as `command not found` inside the guard's own failure text, and a check that
    # does not exist refused a round -- absence scored as a finding, in the harness that exists to
    # catch that. Reported by a consumer whose artifact was BLOCKed by a check nobody had written.
    p = subprocess.run(['bash', '-c', 'source "$1"; shift; declare -F "$1" >/dev/null || exit 127; '
                                      '"$@"', 'guards', str(HERE / 'guards.sh'), name,
                        *map(str, args)], capture_output=True, text=True, env=child_environment())
    if p.returncode == 127:
        raise MissingGuard(f'{name} is not defined in guards.sh; the harness is broken, and this '
                           'says nothing about the review')
    require(p.returncode == 0, name, p.stderr.strip().replace('\n', '; '))


def recompute(repo, directory, start, checkout=None):
    """Only facts about execution, target and bytes. No prose is scored."""
    checks = []
    def check(name, fn, label=''):
        try:
            fn()
            checks.append({'guard': name, 'ok': True})
        except (Rejected, OSError, ValueError, KeyError, subprocess.CalledProcessError) as e:
            checks.append({'guard': name, 'ok': False, 'reason': label + str(e).replace('\n', '; ')})
    def inputs():
        mandatory = {'SEAL.txt', 'inventory.txt', 'DIFF.patch', 'CHANGED.txt', 'prompt.txt'}
        if scope_version(start) == 1:
            mandatory.add('SCOPE.json')
        if start['phase'] == 2:
            mandatory |= {'ROUND1_INVENTORY.md', 'IMPLEMENTER_RESPONSE.md', 'REMEDIATION.patch',
                          'REMEDIATION_CHANGED.txt', 'REMEDIATION_HUNKS.md'}
            if prose_mode(start):
                mandatory.add('PREVIOUS_REVIEW.md')
            if 'validation_version' in start:
                mandatory.add('PRIOR_VALIDATION.md')
            require(digest((directory / 'ROUND1_INVENTORY.md').read_bytes()) == start['inventory_sha256'],
                    'inventory-integrity', 'original review copy differs from trusted digest')
        require(mandatory <= start['inputs'].keys(), 'input-digests', 'required input digest missing')
        verify_hashes(directory, start['inputs'])
        if scope_version(start) == 1:
            scope = json.loads((directory / 'SCOPE.json').read_bytes())
            require(isinstance(scope, dict), 'scope-target', 'frozen scope must be a JSON object')
            require(type(scope.get('schema_version')) is int and scope['schema_version'] == 1 and
                    scope.get('input_kind') == ('change' if start['phase'] == 1 else 'remediation') and
                    scope.get('from_sha') == (start['base_sha'] if start['phase'] == 1 else
                                              start['round1_head_sha']) and
                    scope.get('to_sha') == start['head_sha'], 'scope-target',
                    'frozen scope does not match the recorded exact commit pair')
    check('input-digests', inputs)
    check('executor-exit', lambda: require((directory / 'executor-exit.txt').read_text().strip() == '0',
                                          'executor-exit', 'executor failed; see executor.err'))
    for name in ('guard_turn_completed', 'guard_cmds_nonzero'):
        check(name, lambda name=name: shell_guard(name, directory / 'events.jsonl'))
    def extracted(prefix=''):
        marker = '--final' if prose_mode(start) else (
            '# Round 1 review inventory' if start['phase'] == 1 else '# Round 2 closure review')
        p = subprocess.run([sys.executable, str(HERE / 'extract.py'), str(directory / f'{prefix}events.jsonl'),
                            marker], capture_output=True, env=child_environment())
        require(p.returncode == 0 and p.stdout == (directory / f'{prefix}ARTIFACT.md').read_bytes(),
                prefix + 'last-message', 'no nonempty final message, or artifact differs from executor output')
    check('last-message', extracted)
    def target():
        p = subprocess.run([str(SCRIPTS / 'target-seal.sh'), 'verify', str(repo), str(directory), start['head_sha']],
                           capture_output=True, text=True, env=child_environment())
        require(p.returncode == 0, 'target', p.stderr.strip())
    check('target', target)
    check('checkout', lambda: require((directory / 'checkout-head.txt').read_text().strip() == start['head_sha'],
                                      'checkout', 'checkout did not match the reviewed head'))
    if all(c['ok'] for c in checks) and validation(directory, start) == 'required':
        # A required validator is checked like the finder: it ran, finished, used tools and
        # left a nonempty final answer. A validator that never started fails here too.
        for role in VALIDATORS:
            exit_file = directory / f'{role}-executor-exit.txt'
            def exited(role=role, exit_file=exit_file):
                require(exit_file.is_file(), f'{role}-executor-exit', f'the {role} did not run')
                code = exit_file.read_text().strip()
                require(code == '0', f'{role}-executor-exit', f'the {role} exited {code}; see {role}-executor.err')
            check(f'{role}-executor-exit', exited)
            if exit_file.is_file():
                for name in ('guard_turn_completed', 'guard_cmds_nonzero'):
                    check(f'{role}-{name}', lambda role=role, name=name:
                          shell_guard(name, directory / f'{role}-events.jsonl'), f'{role}: ')
                check(f'{role}-last-message', lambda role=role: extracted(role + '-'))
    return checks


def observations_state(start, end):
    version = start.get('checkout_checks_version')
    if version is None or not end.get('executed'):
        return 'NOT_OBSERVED'
    require(version == 1, 'ledger-observations', 'unknown checkout observation version')
    observed = end.get('checkout_observations')
    require(isinstance(observed, dict) and set(observed) == {'head', 'tracked', 'input_copies'},
            'ledger-observations', 'declared checkout observations are missing or incomplete')
    states = []
    for name in ('head', 'tracked', 'input_copies'):
        item = observed[name]
        require(isinstance(item, dict) and item.get('status') in {'unchanged', 'changed', 'error'},
                'ledger-observations', f'{name} has an unknown observation status')
        require(item['status'] == 'unchanged' or bool(item.get('reason')),
                'ledger-observations', f'{name} failure has no reason')
        if name == 'head' and item['status'] == 'unchanged':
            require(item.get('observed_sha') == start['head_sha'], 'ledger-observations',
                    'unchanged HEAD observation does not match the sealed target')
        states.append(item['status'])
    return 'ERROR' if 'error' in states else 'CHANGED' if 'changed' in states else 'UNCHANGED'


def evidence_available(checks, end, start):
    """Whether the finder's review is usable evidence. A validator that failed after it leaves the
    attempt failed, never complete, but the finder's answer still feeds the next follow-up."""
    # A removed checkout cannot be inspected again. Preserve its recorded head failure.
    return (bool(end.get('executed')) and not (end.get('reason') and not end.get('guards'))
            and observations_state(start, end) in {'UNCHANGED', 'NOT_OBSERVED'}
            and all(c['ok'] for c in checks if not validator_guard(c['guard'])) and all(
                c['ok'] for c in end.get('guards', []) if c['guard'] == 'checkout'))


def finder_recorded(start, end):
    """The same question from the receipt alone: every recorded review, and a fresh attempt whose
    finder passed every check while a required validator failed."""
    guards = end.get('guards') or []
    return bool(end.get('executed')) and (bool(end.get('recorded', end.get('accepted'))) or (
        any(validator_guard(c['guard']) for c in guards)
        and all(c['ok'] for c in guards if not validator_guard(c['guard']))
        and observations_state(start, end) in {'UNCHANGED', 'NOT_OBSERVED'}))


def validator_answers(directory, end):
    """Each validator's preserved, nonempty final answer in one finished attempt."""
    answers = {}
    for role in VALIDATORS:
        name = f'{role}-ARTIFACT.md'
        if name in end.get('outputs', {}) and (directory / name).is_file() and (directory / name).stat().st_size:
            answers[role] = directory / name
    return answers


def validators_state(directory, start, end, names=None):
    """What each validator did in one attempt, from its receipt. A status here is never a verdict.

    `names` maps a role to the file a reader should open instead of the preserved path.
    """
    if 'validation_version' not in start:
        return 'not run (the attempt predates the validators)'
    if not end:
        return 'not run (the attempt did not finish)'
    guards = end.get('guards') or []
    if not any(validator_guard(c['guard']) for c in guards):
        if guards and all(c['ok'] for c in guards):
            return f'skipped (the first review ended with "{NO_CANDIDATES}")'
        if end.get('reason') and not guards:
            return f"not completed ({end['reason']})"
        return "not run (the finder's review was not usable)"
    answers, names = validator_answers(directory, end), names or {}
    parts = []
    for role in VALIDATORS:
        failed = [c['reason'] for c in guards if c['guard'].startswith(role + '-') and not c['ok']]
        answer = f', answer {names.get(role, answers[role])}' if role in answers else ', no answer'
        parts.append(f'{role} ' + (f'FAILED: {failed[0]}' if failed else 'completed') + answer)
    return '; '.join(parts)


def budget(starts):
    """Automatic attempts and granted supplementary reviews, counted apart."""
    supplementary = [n for n, s in starts.items() if s.get('supplementary')]
    grant = starts[supplementary[-1]]['supplementary'] if supplementary else None
    return len(starts) - len(supplementary), len(supplementary), grant


def elapsed(root):
    """Seconds from each reservation to its finish. An unfinished attempt adds nothing."""
    started, total = {}, 0.0
    for e in read(root):
        try:
            at = datetime.fromisoformat(e['at'])
        except (KeyError, TypeError, ValueError):
            continue
        if e['event'] == 'started':
            started[e['round']] = at
        elif e['event'] == 'finished' and e['round'] in started:
            total += max(0.0, (at - started[e['round']]).total_seconds())
    return total


def cumulative(root, starts, grant=None):
    """One line a person can read before deciding whether another review is worth it."""
    automatic, supplementary, recorded_grant = budget(starts)
    grant = grant or recorded_grant
    granted = (f"{supplementary}/{grant['budget']} granted by {grant['granted_by']}" if grant
               else f'{supplementary}, none granted')
    seconds = int(elapsed(root))
    return (f'PR cumulative reviews {len(starts)} (automatic {automatic}/{MAX_ROUNDS}, '
            f'supplementary {granted}), cumulative time '
            f'{seconds // 3600}h{seconds // 60 % 60:02}m{seconds % 60:02}s')


def running(root):
    """Inspect the existing OS lock, without creating state or trusting a stale PID."""
    try:
        with (root / '.lock').open('r') as lock:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BlockingIOError:
                return True
    except FileNotFoundError:
        pass
    return False


def orphaned_rounds(root, starts):
    """Find unledgered round paths without adopting or removing them."""
    if not root.is_dir():
        return []
    return sorted(path for path in root.iterdir()
                  if re.fullmatch(r'round-[0-9]{4,}', path.name)
                  and int(path.name[6:]) not in starts)


def status(root, repo, head, base=None, context=None):
    if running(root):
        print(f'RUNNING: {root}; requested head {head}')
        return
    starts, ends, _ = audit(root, repo)
    orphans = orphaned_rounds(root, starts)
    if orphans:
        print('ORPHANED_PREPARATION: ' + ', '.join(map(str, orphans)) +
              '; preserve the evidence: no review can be recorded for this PR ID, so the review ends as failed')
    if not starts:
        print(f'NOT_REVIEWED: requested head {head}; 0/{MAX_ROUNDS} attempts')
        return
    n = max(starts)
    start, end = starts[n], ends.get(n, {})
    available = (evidence_available(recompute(repo, root / f'round-{n:04}', start), end, start)
                 and bool(end.get('recorded', end.get('accepted')))) if end else False
    state = 'INTERRUPTED' if not end else 'RECORDED' if available else 'FAILED'
    same = (start['head_sha'] == head and (base is None or start.get('base_sha') == base)
            and context is not None and start.get('context') == context)
    freshness = 'FRESH' if same and available and end.get('fresh_at_finish', True) else 'STALE'
    print(f'{state} {freshness}: reviewed head {start["head_sha"]}; requested head {head}; '
          f'{n}/{MAX_ROUNDS} attempts' + ('; HANDOFF' if n >= MAX_ROUNDS else ''))
    print(cumulative(root, starts))
    print(f'Artifact: {root / f"round-{n:04}" / "ARTIFACT.md"}')
    if end:
        print('Checkout observations: ' + observations_state(start, end))
        print('Validators: ' + validators_state(root / f'round-{n:04}', start, end))
    if end.get('freshness_reason') or end.get('reason'):
        print(end.get('freshness_reason') or end['reason'])
    import followup  # imports this module; loaded only when asked
    keys = followup.recurring(followup.recorded(root, starts, ends))
    if keys:
        print(followup.recurrence_note(keys))


def audit(root, repo, progress=False):
    starts, prepared, ends, originals = {}, {}, {}, []
    usable_rounds = []
    for e in read(root):
        n = e['round']
        if e['event'] == 'started':
            require(n == len(starts) + 1, 'ledger-rounds', 'round numbers were skipped or reset')
            require(e.get('mode') in {None, *PROSE_MODES}, 'ledger-version', 'unknown receipt mode')
            scope_version(e)
            starts[n] = e
        elif e['event'] == 'prepared':
            require(n in starts and n not in prepared and n not in ends and starts[n].get('mode') == MODE,
                    'ledger-prepared', 'prepared must follow one v3 reservation before finish')
            require(set(e) == {'event', 'round', 'inputs', 'previous_sha256', 'at'} and isinstance(e['inputs'], dict),
                    'ledger-prepared', 'prepared may declare only input hashes')
            prepared[n] = e
        else:
            require(e['event'] == 'finished' and n in starts and n not in ends,
                    'ledger-rounds', 'orphan or duplicate round result')
            require(e.get('executed') or not (e.get('accepted') or e.get('recorded')),
                    'ledger-guards', 'an unexecuted attempt cannot claim a recorded review')
            require(not e.get('executed') or starts[n].get('mode') != MODE or n in prepared,
                    'ledger-prepared', 'executed v3 attempt has no prepared input hashes')
            ends[n] = e
    for n, start in starts.items():
        if progress:
            print(f'review: checking stored evidence for attempt {n}/{len(starts)}',
                  file=sys.stderr, flush=True)
        d = root / f'round-{n:04}'
        if n in prepared:
            require(start['inputs'] == {}, 'ledger-prepared', 'v3 reservation changed its inputs before preparation')
            require(scope_version(start) != 1 or 'SCOPE.json' in prepared[n]['inputs'],
                    'input-digests', 'declared scope input digest missing from preparation')
            start = dict(start, inputs=prepared[n]['inputs'])
            starts[n] = start
        verify_hashes(d, start['inputs'])
        if start['phase'] == 2 and 'original_round' in start:
            require(originals and type(start['original_round']) is int and
                    start['original_round'] == originals[-1][0], 'ledger-handoff',
                    'original review round substituted')
            original = originals[-1]
            require(start.get('round1_head_sha') == original[2]['head_sha'] and
                    start['base_sha'] == original[2]['base_sha'] and
                    start.get('inventory_sha256') == digest((original[1] / 'ARTIFACT.md').read_bytes()),
                    'ledger-handoff', 'original review target or bytes substituted')
            prior = start.get('previous_round')
            require(type(prior) is int and prior < n and prior in ends and ends[prior].get('executed'),
                    'ledger-handoff', 'previous review is not an earlier executed attempt')
            require(prior == next((k for k in reversed(usable_rounds)
                                   if k >= start['original_round']), None), 'ledger-handoff',
                    'previous review does not name the latest usable attempt')
        end = ends.get(n)
        if not end:
            continue
        verify_hashes(d, end['outputs'])
        observed_state = observations_state(start, end)
        if not end['executed'] or (end.get('reason') and not end.get('guards')):
            continue
        mandatory = {'ARTIFACT.md', 'events.jsonl', 'executor.err', 'executor-exit.txt', 'checkout-head.txt'}
        for role in VALIDATORS:
            if any(c['guard'] == f'{role}-last-message' for c in end['guards']):
                mandatory.update(validator_outputs(role))
        require(mandatory <= end['outputs'].keys(), 'ledger-integrity', 'required output digest missing')
        fresh = prose_mode(start)
        result_key = 'recorded' if fresh else 'accepted'
        require(end[result_key] == (all(c['ok'] for c in end['guards'])
                                    and observed_state in {'UNCHANGED', 'NOT_OBSERVED'}),
                'ledger-guards', 'receipt result contradicts its recorded checks')
        require(not fresh or not end.get('accepted'), 'ledger-guards', 'a prose review cannot claim merge acceptance')
        checks = recompute(repo, d, start)
        if fresh and start.get('skill_sha256') == protocol_sha256(SCRIPTS):
            require(checks == end['guards'], 'ledger-guards', 'receipt checks differ from recomputation')
        usable = evidence_available(checks, end, start)
        if start['phase'] == 2 and start.get('inventory_sha256'):
            require(originals, 'ledger-handoff', 'no earlier original review')
            original = originals[-1]
            require(start['inventory_sha256'] == digest((original[1] / 'ARTIFACT.md').read_bytes()) and
                    start['round1_head_sha'] == original[2]['head_sha'] and
                    start['base_sha'] == original[2]['base_sha'], 'ledger-handoff', 'original review substituted')
            if fresh:
                prior = start['previous_round']
                require(prior < n and prior in ends and ends[prior].get('executed'),
                        'ledger-handoff', 'previous review is not an earlier executed attempt')
                require((d / 'PREVIOUS_REVIEW.md').read_bytes() ==
                        (root / f'round-{prior:04}' / 'ARTIFACT.md').read_bytes(),
                        'ledger-handoff', 'previous follow-up substituted')
                for label, k in (('ROUND1', start.get('original_round')), ('PREVIOUS', prior)):
                    if 'validation_version' not in start or k not in ends:
                        continue
                    answers = validator_answers(root / f'round-{k:04}', ends[k])
                    for role in VALIDATORS:
                        name = f'{label}_{role.upper()}.md'
                        require((name in start['inputs']) == (role in answers) and (
                            role not in answers or (d / name).read_bytes() == answers[role].read_bytes()),
                            'ledger-handoff', f'{name} is not the answer preserved in attempt {k}')
        expected_sha = digest((d / 'ARTIFACT.md').read_bytes()) if start['phase'] == 1 else start.get('inventory_sha256')
        require(end['inventory_sha256'] == expected_sha, 'ledger-digest', 'review digest differs')
        if start['phase'] == 1 and usable:
            # A historical rejected review can supply evidence; its acceptance stays false.
            # Neither the old nor the new outcome becomes merge authorization.
            originals.append((n, d, start, (d / 'ARTIFACT.md').read_text()))
        if usable:
            usable_rounds.append(n)
    return starts, ends, originals


def guard_rejections(ends):
    """Prefer recorded leaf reasons. Do not invent details absent from a legacy receipt."""
    tally = {}
    for e in ends.values():
        reasons = [(c['guard'], c.get('reason', '')) for c in e.get('guards', []) if not c['ok']]
        # A validator timeout's note sits beside the guards that already count it.
        if e.get('reason') and not e.get('guards'):
            reasons.append(('preflight', e['reason']))
        tags = set()
        for fallback, reason in reasons:
            found = re.findall(r'GUARD FAIL \[([a-z0-9_-]+)\]', reason)
            tags.add(found[-1] if found else fallback)
        for tag in tags:
            tally[tag] = tally.get(tag, 0) + 1
    return dict(sorted(tally.items(), key=lambda kv: (-kv[1], kv[0])))


def report(root, repo):
    print('Checking stored review evidence; use status to check for an active run.', flush=True)
    starts, ends, originals = audit(root, repo, progress=True)
    orphans = orphaned_rounds(root, starts)
    if orphans:
        print('ORPHANED_PREPARATION: ' + ', '.join(map(str, orphans)) +
              '; preserve the evidence: no review can be recorded for this PR ID, so the review ends as failed')
    print('Review evidence only; no row or exit status authorizes a merge.')
    print('attempt phase head outcome artifact')
    for n, s in starts.items():
        e = ends.get(n, {})
        if prose_mode(s):
            outcome = 'RECORDED' if e.get('recorded') else 'FAILED' if e else 'INTERRUPTED'
        else:
            outcome = 'LEGACY_ACCEPTED' if e.get('accepted') else 'LEGACY_REJECTED' if e else 'INTERRUPTED'
        print(n, s['phase'], s['head_sha'], outcome, root / f'round-{n:04}' / 'ARTIFACT.md')
        print('  checkout observations: ' + observations_state(s, e))
        print('  validators: ' + validators_state(root / f'round-{n:04}', s, e))
        for name, item in e.get('checkout_observations', {}).items():
            if item.get('status') != 'unchanged':
                print(f"  {name}: {item['status']} ({item.get('reason', 'unknown reason')})")
        print('  protocol SHA-256 at start: ' + s.get('skill_sha256',
              s.get('context', {}).get('protocol_sha256', 'unknown')))
        freshness = {True: 'FRESH', False: 'STALE'}.get(e.get('fresh_at_finish'), 'UNKNOWN')
        print(f'  freshness at finish: {freshness} (recorded observation, not current PR state)')
        if e.get('freshness_reason'):
            print('  ' + e['freshness_reason'])
        if 'item_count' in e:
            print(f"  legacy parser counts (not distinct confirmed defects): {e['item_count']} items, {e.get('fail_count', '?')} FAIL")
        if e.get('reason'):
            print('  ' + e['reason'])
        for c in e.get('guards', []):
            if not c['ok']:
                print('  ' + c['reason'])
    tally = guard_rejections(ends)
    if tally:
        print('recorded refusal reasons: ' + ', '.join(f'{g} x{c}' for g, c in tally.items()))
        if 'inventory' in tally:
            print('  Legacy inventory detail was not recorded; inspect its artifact. No reason is inferred.')
    print(f'{len(starts)} attempts; {sum(bool(e.get("executed")) for e in ends.values())} executed. '
          'Safe merge completion is not measured by these receipts.')
    automatic = budget(starts)[0]
    print(f'Automatic review budget: {automatic}/{MAX_ROUNDS} attempts used; '
          f'{max(0, MAX_ROUNDS - automatic)} remaining. Failures and interruptions count.')
    print(cumulative(root, starts))
    import followup  # imports this module; loaded only when asked
    followup.summary(root, starts, ends, originals)
    return starts, ends, originals


def handoff(root, repo, head, reason='automatic review has stopped'):
    """A human-readable handoff; the preserved prose, never extracted statuses, carries findings."""
    starts, ends, originals = report(root, repo)
    print(f'HANDOFF: requested head {head}; {reason}. No merge authorization.')
    matching = [n for n, s in starts.items() if s['head_sha'] == head]
    if not matching:
        print('This head has not been reviewed. Earlier evidence is not a review of this head.')
    print('The calling agent reads the artifacts above with their execution failures, validator answers '
          'and scope limitations, keeping unresolved findings, repair regressions and newly discovered '
          'original blockers. When the latest review covers this head and finished FRESH, its validators '
          'completed or were skipped, nothing blocking remains and the required product checks pass, it continues its '
          'existing completion path; otherwise it ends the task as failed, naming what remains. Nobody '
          'is asked to answer. A new head, phase-1 restart or changed response does not replenish this '
          'PR budget.')
    import followup  # imports this module; loaded only when asked
    print(f'Handoff document: {followup.write_handoff(root, head, starts, ends, originals, reason)}')
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall