interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / tools / review-after-checks.py

116 lines · 7071 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Run caller-supplied checks and retain complete fresh-review evidence.
3
4This external verification instrument does not approve a change, authenticate a
5provider, sandbox tools, or count rounds. The operator reads the full record.
6"""
7import argparse
8import hashlib
9import json
10import os
11import pathlib
12import subprocess
13import sys
14
15
16def main():
17 parser = argparse.ArgumentParser(description=__doc__)
18 parser.add_argument('base')
19 parser.add_argument('task', type=pathlib.Path)
20 parser.add_argument('output', type=pathlib.Path)
21 parser.add_argument('check', nargs=argparse.REMAINDER)
22 args = parser.parse_args()
23 command = args.check[1:] if args.check[:1] == ['--'] else args.check
24 if not command:
25 raise ValueError('a check command is required')
26 git = lambda *a: subprocess.check_output(['git', *a], text=True).strip()
27 root = pathlib.Path(git('rev-parse', '--show-toplevel')).resolve()
28 head = git('rev-parse', 'HEAD')
29 base = git('rev-parse', '--verify', args.base + '^{commit}')
30 if head == base or subprocess.run(['git', 'merge-base', '--is-ancestor', base, head]).returncode:
31 raise ValueError('base must precede this head')
32 if git('status', '--porcelain'):
33 raise ValueError('use a checkout with clean Git porcelain status')
34 task = args.task.read_text(encoding='utf-8')
35 output = args.output.resolve()
36 if any(p.exists() and p.samefile(root) for p in (output, *output.parents)):
37 raise ValueError('evidence directory must be outside source')
38 output.mkdir(mode=0o700) # never reuse an earlier record
39 metadata = dict(head=head, base=base, check=command, stage='setup')
40 try:
41 verdict = output / 'verdict.txt'
42 prompt = (task + f'\n\nReview exact head {head}, base {base}. Do not change source or publish. '
43 f'Write the COMPLETE verdict to {verdict}; that evidence file is an allowed write. '
44 f'First line exactly, with no punctuation:\nHEAD {head}\nInclude program/model/requested effort, every finding and '
45 'its confidence percentage, and evidence limits. Give MERGE or REJECT. '
46 'Repeat the complete saved report in your final response.\n')
47 (output / 'task.txt').write_text(prompt, encoding='utf-8')
48 # Only this invocation is changed. Never edit the operator's persistent config.
49 overlay = dict(advisor=dict(enabled=False),
50 retry=dict(modelFallback=False, usageAwareFallback=False, waitForUsageReset=False),
51 contextPromotion=dict(enabled=False), prewalk=dict(enabled=False, auto='off'),
52 providers=dict(anthropic=dict(serverSideFallback=False)))
53 config = output / 'review-config.json'
54 config.write_text(json.dumps(overlay, indent=2) + '\n')
55 review_command = ['omp', '-p', '--auto-approve', '--config', str(config), '--no-prewalk',
56 '--thinking', 'medium', '--model', 'anthropic/claude-opus-5-5',
57 '--mode', 'json', '--session-dir', str(output / 'sessions')]
58 if os.environ.get('HOP_REVIEW_MAX_TIME'):
59 review_command += ['--max-time', os.environ['HOP_REVIEW_MAX_TIME']]
60 metadata.update(review_command=review_command, task_sha256=hashlib.sha256(prompt.encode()).hexdigest())
61 (output / 'launch.json').write_text(json.dumps(metadata, indent=2) + '\n')
62 env = dict(os.environ, PYTHONDONTWRITEBYTECODE='1')
63 metadata['stage'] = 'checks'
64 with (output / 'checks.log').open('wb') as log:
65 # Require the application verifier test suite before the caller check.
66 # Coverage still needs inspection; a passing suite is not proof of coverage.
67 if (root / 'tools/check-app-review.py').exists():
68 if not (root / 'tests/test_app_review.py').is_file():
69 raise ValueError('application evidence verifier requires its regression tests')
70 gate_tests = [sys.executable, '-m', 'unittest', 'discover', '-s', 'tests', '-p', 'test_app_review.py']
71 metadata['verifier_test_exit_code'] = subprocess.run(gate_tests, cwd=root, env=env,
72 stdout=log, stderr=subprocess.STDOUT).returncode
73 if metadata['verifier_test_exit_code']:
74 raise ValueError('application evidence verifier regression tests failed')
75 metadata['check_exit_code'] = subprocess.run(command, cwd=root, env=env, stdout=log,
76 stderr=subprocess.STDOUT).returncode
77 if metadata['check_exit_code']:
78 raise ValueError(f"checks failed ({metadata['check_exit_code']}); review was not started")
79 if git('rev-parse', 'HEAD') != head or git('status', '--porcelain'):
80 raise ValueError('checks changed source; review was not started')
81 metadata['stage'] = 'review'
82 with (output / 'transcript.jsonl').open('wb') as log, (output / 'stderr.log').open('wb') as err:
83 metadata['review_exit_code'] = subprocess.run(review_command + ['--', '@' + str(output / 'task.txt')], cwd=root,
84 env=env, stdout=log, stderr=err).returncode
85 if metadata['review_exit_code']:
86 raise ValueError(f"review command failed ({metadata['review_exit_code']})")
87 lines = verdict.read_text(encoding='utf-8').splitlines()
88 if not lines or lines[0] != 'HEAD ' + head or not '\n'.join(lines[1:]).strip():
89 raise ValueError('missing, empty or mismatched verdict')
90 if git('rev-parse', 'HEAD') != head or git('status', '--porcelain'):
91 raise ValueError('source differs after review')
92 metadata['stage'] = 'captured'
93 except BaseException as error:
94 metadata['failure'] = f'{type(error).__name__}: {error}'
95 raise
96 finally:
97 # Record the narrow Git boundary even for failed checks/review or bad reports.
98 # This does not inspect ignored files or promise a sandboxed reviewer.
99 try:
100 metadata['post_head'] = git('rev-parse', 'HEAD')
101 metadata['post_git_porcelain'] = git('status', '--porcelain')
102 except (OSError, subprocess.SubprocessError) as error:
103 metadata['post_git_error'] = str(error)
104 for name in ('checks.log', 'review-config.json', 'transcript.jsonl', 'stderr.log', 'verdict.txt'):
105 file = output / name
106 metadata[name + '_sha256'] = hashlib.sha256(file.read_bytes()).hexdigest() if file.is_file() else None
107 (output / 'result.json').write_text(json.dumps(metadata, indent=2) + '\n')
108 print(f'Captured {output}. Read the full verdict and transcript. Capture success is not MERGE.')
109
110
111if __name__ == '__main__':
112 try:
113 main()
114 except (OSError, ValueError, subprocess.SubprocessError, KeyboardInterrupt) as error:
115 print('Review capture stopped: ' + str(error), file=sys.stderr)
116 sys.exit(2)