gitbills 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gitbills/preflight.py ADDED
@@ -0,0 +1,219 @@
1
+ """The preflight report (gitbills-preflight/1, src/preflight.js): one diff through the 14-rule security X-Ray, the slop
2
+ heuristics and the repository's AGENTS.md policy, offline, with a verdict, a grade and a two-line receipt."""
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import time
7
+
8
+ from .diff import MAX_DIFF_BYTES, parse_diff
9
+ from .policy import POLICY_REMEDIATIONS, evaluate_policy, parse_policy
10
+ from .scan import RULE_IDS, SEVERITY_POINTS, SEVERITY_RANK, risk_grade, scan_diff
11
+ from .slop import SLOP_POINTS, SLOP_REMEDIATIONS, evaluate_slop
12
+ from .text import display_text, fail, has_lone_surrogate, js_len, js_trim, md_code, sha256_hex
13
+ from .version import NPX_COMMAND, UVX_COMMAND
14
+ from .vouch import clean_repo
15
+
16
+ PREFLIGHT_PROTOCOL = 'gitbills-preflight/1'
17
+ DEFAULT_ORIGIN = 'https://gitbills.com'
18
+ VERDICTS = ('ready', 'review_recommended', 'blocked_policy', 'blocked_slop', 'blocked_security', 'empty_diff')
19
+ MAX_SIGNALS = 64
20
+ MAX_TITLE_CHARS = 1000
21
+ MAX_BODY_CHARS = 65_536
22
+ _SOURCE_RANK = {'security': 0, 'policy': 1, 'slop': 2, 'diff': 3}
23
+ _ORIGIN_RE = re.compile(r'^https://(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}(?::[1-9][0-9]{0,4})?\Z'
24
+ r'|^http://(?:localhost|127\.0\.0\.1|\[::1\])(?::[1-9][0-9]{0,4})?\Z', re.ASCII)
25
+ _PUNY_RE = re.compile(r'(?:^|[./])xn--', re.ASCII)
26
+
27
+
28
+ def _slop_severity(points):
29
+ return 'critical' if points >= 90 else 'high' if points >= 50 else 'medium' if points >= 30 else 'low'
30
+
31
+
32
+ def clean_origin(value, fallback: str = DEFAULT_ORIGIN) -> str:
33
+ """A clean origin for receipt links and API calls (https, or http on loopback, no path); else the fallback."""
34
+ if not isinstance(value, str):
35
+ return fallback
36
+ s = re.sub(r'/+$', '', js_trim(value).lower())
37
+ return s if len(s) <= 253 and _ORIGIN_RE.search(s) and not _PUNY_RE.search(s) else fallback
38
+
39
+
40
+ def _text(name, value, max_len):
41
+ s = '' if value is None else value
42
+ if not isinstance(s, str) or js_len(s) > max_len:
43
+ fail('invalid_field', '%s must be a string of at most %d characters.' % (name, max_len))
44
+ if has_lone_surrogate(s):
45
+ fail('invalid_field', '%s is not valid Unicode (a lone surrogate).' % name)
46
+ return s
47
+
48
+
49
+ def _compact_rules(rules):
50
+ return {k: v for k, v in rules.items() if v is not None and not (isinstance(v, list) and not v)}
51
+
52
+
53
+ def evaluate_preflight(diff=None, title='', body='', repo=None, pr_number=None, policy=None, policy_source=None,
54
+ known_ai_config_roots=(), origin=None, allow_empty: bool = False, policy_path=None) -> dict:
55
+ """The preflight report of one unified diff (see src/preflight.js evaluatePreflight for the fields)."""
56
+ started = time.perf_counter()
57
+ if diff is None:
58
+ diff = '' if allow_empty else None
59
+ if not isinstance(diff, str):
60
+ fail('invalid_diff', 'Provide the unified diff as a string.')
61
+ if len(diff.encode('utf-8', 'surrogatepass')) > MAX_DIFF_BYTES:
62
+ fail('diff_too_large', 'The diff is over %d bytes (UTF-8): check it in smaller parts.' % MAX_DIFF_BYTES)
63
+ if has_lone_surrogate(diff):
64
+ fail('invalid_diff', 'The diff is not valid Unicode (a lone surrogate).')
65
+ title = _text('title', title, MAX_TITLE_CHARS)
66
+ body = _text('body', body, MAX_BODY_CHARS)
67
+ policy_text = None if policy is None else _text('policy', policy, 262_144)
68
+ source = display_text(policy_source, 200) if isinstance(policy_source, str) else (None if policy_text is None else 'AGENTS.md')
69
+ policy_path = policy_path if isinstance(policy_path, str) and js_len(policy_path) <= 4096 else None
70
+ slug = None if repo is None else clean_repo(repo)
71
+ if pr_number is not None and (not isinstance(pr_number, int) or isinstance(pr_number, bool)
72
+ or pr_number < 1 or pr_number > 999_999_999):
73
+ fail('invalid_pr', 'prNumber must be a whole number from 1.')
74
+ roots = [r for r in (known_ai_config_roots or ()) if isinstance(r, str)][:256]
75
+ base = clean_origin(origin)
76
+ receipt_url = None if slug is None else ('%s/%s' % (base, slug) if pr_number is None else '%s/%s/pull/%d' % (base, slug, pr_number))
77
+ pol = None if policy_text is None else parse_policy(policy_text)
78
+ policy_info = {'source': source, 'found': bool(pol and pol['found']),
79
+ 'rules': _compact_rules(pol['rules']) if pol and pol['found'] else {}, 'violations': []}
80
+
81
+ if js_trim(diff) == '':
82
+ return _finish({'protocol': PREFLIGHT_PROTOCOL, 'verdict': 'empty_diff', 'ok': True, 'exit_code': 0,
83
+ 'risk_grade': 'A', 'risk_score': 0, 'slop_score': 0, 'rules_checked': len(RULE_IDS),
84
+ 'files_changed': 0, 'lines_added': 0, 'lines_removed': 0, 'signal_count': 0, 'signals': [],
85
+ 'slop_reasons': [], 'policy': policy_info, 'diff_sha256': '', 'repo': slug,
86
+ 'pr_number': pr_number, 'receipt_url': receipt_url}, started)
87
+ parsed = parse_diff(diff)
88
+ scan = scan_diff(parsed)
89
+ slop = evaluate_slop(parsed, title=title, body=body, known_ai_config_roots=roots)
90
+ findings = evaluate_policy(parsed, pol['rules'], title=title, body=body, policy_path=policy_path) if pol and pol['found'] else []
91
+ policy_info['violations'] = [f['rule'] for f in findings if f['severity'] != 'info']
92
+
93
+ found = list(scan['signals'])
94
+ for f in findings:
95
+ found.append({'source': 'policy', 'rule': f['rule'], 'detail': f['detail'], 'severity': f['severity'],
96
+ 'path': f['path'], 'line': None, 'remediation': POLICY_REMEDIATIONS[f['rule']]})
97
+ for code in slop['reasons']:
98
+ found.append({'source': 'slop', 'rule': code, 'detail': code, 'severity': _slop_severity(SLOP_POINTS.get(code, 50)),
99
+ 'path': None, 'line': None, 'remediation': SLOP_REMEDIATIONS[code]})
100
+ ranked = [s for _, s in sorted(enumerate(found), key=lambda e: (SEVERITY_RANK[e[1]['severity']], _SOURCE_RANK[e[1]['source']], e[0]))]
101
+ # A high diff signal is code nobody can read (binary, or padded past the scan cap): it blocks like a security finding.
102
+ security_blocked = any(s['source'] in ('security', 'diff') and s['severity'] in ('critical', 'high') for s in found)
103
+ if security_blocked:
104
+ verdict = 'blocked_security'
105
+ elif slop['slop_detected']:
106
+ verdict = 'blocked_slop'
107
+ elif policy_info['violations']:
108
+ verdict = 'blocked_policy'
109
+ elif any(s['severity'] != 'info' for s in found):
110
+ verdict = 'review_recommended'
111
+ else:
112
+ verdict = 'ready'
113
+ ok = not verdict.startswith('blocked_')
114
+ score = min(100, sum(SEVERITY_POINTS[s['severity']] for s in found if s['source'] in ('security', 'diff')))
115
+ return _finish({
116
+ 'protocol': PREFLIGHT_PROTOCOL,
117
+ 'verdict': verdict,
118
+ 'ok': ok,
119
+ 'exit_code': 0 if ok else 1,
120
+ 'risk_grade': risk_grade(score),
121
+ 'risk_score': score,
122
+ 'slop_score': slop['score'],
123
+ 'rules_checked': len(RULE_IDS),
124
+ 'files_changed': len(parsed['paths']),
125
+ 'lines_added': parsed['linesAdded'],
126
+ 'lines_removed': parsed['linesRemoved'],
127
+ 'signal_count': len(ranked),
128
+ 'signals': ranked[:MAX_SIGNALS],
129
+ 'slop_reasons': slop['reasons'],
130
+ 'policy': policy_info,
131
+ 'diff_sha256': sha256_hex(diff.replace('\r\n', '\n')),
132
+ 'repo': slug,
133
+ 'pr_number': pr_number,
134
+ 'receipt_url': receipt_url,
135
+ }, started)
136
+
137
+
138
+ def _finish(report, started):
139
+ report['markdown_receipt'] = receipt_markdown(report)
140
+ report['elapsed_ms'] = round((time.perf_counter() - started) * 1000, 2)
141
+ return report
142
+
143
+
144
+ def _policy_phrase(r):
145
+ if not r['policy']['found']:
146
+ return 'no AGENTS.md policy'
147
+ n = len(r['policy']['violations'])
148
+ return 'AGENTS.md policy: %d violation(s)' % n if n else 'AGENTS.md policy met'
149
+
150
+
151
+ def receipt_markdown(r) -> str:
152
+ """The two Markdown lines for a pull request description."""
153
+ if r['verdict'] == 'empty_diff':
154
+ first = '**GitBills preflight:** `empty_diff`: no changes to check.'
155
+ else:
156
+ first = ('**GitBills preflight:** %s, grade %s (security risk %d/100), slop %d/100, %s, %d signal(s), diff %s'
157
+ % (md_code(r['verdict']), md_code(r['risk_grade']), r['risk_score'], r['slop_score'], _policy_phrase(r),
158
+ r['signal_count'], md_code(r['diff_sha256'][:12])))
159
+ url = r['receipt_url']
160
+ link = '' if url is None else ' Receipt: [%s](%s)' % (re.sub(r'^https?://', '', url), url)
161
+ return '%s\nChecked offline with `%s preflight` (%s, %d security rules, nothing sent).%s' % (
162
+ first, NPX_COMMAND, PREFLIGHT_PROTOCOL, r['rules_checked'], link)
163
+
164
+
165
+ _ADVICE = {
166
+ 'blocked_security': 'Blocked: fix every critical and high security finding above, then run gitbills preflight again.',
167
+ 'blocked_slop': 'Blocked: fix the slop findings above, then run gitbills preflight again.',
168
+ 'blocked_policy': "Blocked: the change breaks this repository's AGENTS.md policy; fix it, then run gitbills preflight again.",
169
+ 'review_recommended': 'Review recommended: fix each finding above, or explain it in the pull request description.',
170
+ 'ready': 'Ready: paste the output of gitbills preflight --markdown into the pull request description.',
171
+ 'empty_diff': 'No changes to check: commit your work, or pass --base REF or --diff FILE.',
172
+ }
173
+ _SHOWN = 20
174
+
175
+
176
+ def _num(v):
177
+ return str(v) if isinstance(v, int) and not isinstance(v, bool) else '?'
178
+
179
+
180
+ def format_preflight_terminal(r) -> str:
181
+ def t(v, max_len=200):
182
+ return display_text('' if v is None else v, max_len)
183
+
184
+ ms = '%.2f' % r['elapsed_ms'] if isinstance(r.get('elapsed_ms'), (int, float)) else '?'
185
+ lines = ['GitBills preflight: %s (%s, %s ms, nothing sent)' % (t(r['verdict'], 40), PREFLIGHT_PROTOCOL, ms)]
186
+ if r['verdict'] != 'empty_diff':
187
+ lines.append(' Grade %s: security risk %s/100 from %s rules; slop %s/100; %s' % (
188
+ t(r['risk_grade'], 2), _num(r['risk_score']), _num(r['rules_checked']), _num(r['slop_score']), _policy_phrase(r)))
189
+ lines.append(' %s file(s), +%s -%s, diff sha256 %s' % (
190
+ _num(r['files_changed']), _num(r['lines_added']), _num(r['lines_removed']), t(r['diff_sha256'], 64)))
191
+ for s in r['signals'][:_SHOWN]:
192
+ where = (' in %s' % t(s['path']) if s['path'] else '') + (' line %d' % s['line'] if isinstance(s['line'], int) else '')
193
+ if not s['detail'] or s['detail'] == s['rule']:
194
+ detail = ''
195
+ elif s['source'] == 'policy':
196
+ detail = ' (%s)' % t(s['detail'], 120)
197
+ else:
198
+ detail = '/%s' % t(s['detail'], 60)
199
+ lines.append(' - %s %s %s%s%s: %s' % (s['severity'], s['source'], t(s['rule'], 60), detail, where, t(s['remediation'], 300)))
200
+ if r['signal_count'] > _SHOWN:
201
+ lines.append(' - %d more signal(s): gitbills preflight --json lists them' % (r['signal_count'] - _SHOWN))
202
+ lines.append(' %s' % _ADVICE.get(r['verdict'], ''))
203
+ if r['receipt_url']:
204
+ lines.append(' Receipt: %s' % r['receipt_url'])
205
+ return '\n'.join(lines)
206
+
207
+
208
+ def render_agent_rule(repo=None) -> str:
209
+ """The Markdown rule for CLAUDE.md or AGENTS.md that makes an agent run the preflight before every pull request."""
210
+ slug = None if repo is None else clean_repo(repo)
211
+ page = '' if slug is None else ' This repository on GitBills: %s/%s' % (DEFAULT_ORIGIN, slug)
212
+ return '\n'.join([
213
+ '## Pull request preflight (GitBills)',
214
+ 'Before you open or update a pull request, run `%s preflight --base origin/main` from the repository root '
215
+ '(`%s preflight` is the same check). It reads only the local diff and sends nothing.' % (NPX_COMMAND, UVX_COMMAND),
216
+ 'If it exits with any status but 0 (1: blocked_security, blocked_slop or blocked_policy; 2: it could not check '
217
+ 'the change), fix what it reports and run it again: never open a pull request until it exits 0.',
218
+ 'Paste what `%s preflight --markdown` prints into the pull request description.%s' % (NPX_COMMAND, page),
219
+ ])