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/__init__.py +29 -0
- gitbills/__main__.py +3 -0
- gitbills/cli.py +417 -0
- gitbills/diff.py +268 -0
- gitbills/local.py +436 -0
- gitbills/policy.py +449 -0
- gitbills/preflight.py +219 -0
- gitbills/remote.py +676 -0
- gitbills/scan.py +392 -0
- gitbills/slop.py +423 -0
- gitbills/text.py +103 -0
- gitbills/version.py +4 -0
- gitbills/vouch.py +161 -0
- gitbills-0.1.2.dist-info/METADATA +82 -0
- gitbills-0.1.2.dist-info/RECORD +19 -0
- gitbills-0.1.2.dist-info/WHEEL +5 -0
- gitbills-0.1.2.dist-info/entry_points.txt +2 -0
- gitbills-0.1.2.dist-info/licenses/LICENSE +21 -0
- gitbills-0.1.2.dist-info/top_level.txt +1 -0
gitbills/policy.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""Executable AGENTS.md policy (src/policy.js): the policy section, read as `- Key: value` bullets or plain
|
|
2
|
+
`key: value` lines, in this tool's words or gitbills.com's (docs/agents-md.md)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from .slop import is_code_file, is_test_file
|
|
8
|
+
from .text import display_text, js_len, js_trim
|
|
9
|
+
from .version import NPX_COMMAND
|
|
10
|
+
|
|
11
|
+
POLICY_PROTOCOL = 'gitbills-policy/1'
|
|
12
|
+
POLICY_HEADING = '## Pull requests from agents'
|
|
13
|
+
POLICY_MAX_BYTES = 262_144
|
|
14
|
+
# The files a change must not rewrite under the policy they set: the policy itself and the trust lists.
|
|
15
|
+
POLICY_FILES = ('AGENTS.md', '.github/AGENTS.md', 'VOUCHED.td', '.github/VOUCHED.td')
|
|
16
|
+
POLICY_BLOCK = '\n'.join([
|
|
17
|
+
POLICY_HEADING,
|
|
18
|
+
'- Preflight: run `%s preflight --markdown` and paste its receipt into the PR body.' % NPX_COMMAND,
|
|
19
|
+
'- Max files changed: 25',
|
|
20
|
+
'- Max lines changed: 800',
|
|
21
|
+
'- Tests: required for code changes',
|
|
22
|
+
'- Protected paths: .github/workflows/, LICENSE',
|
|
23
|
+
])
|
|
24
|
+
POLICY_RULE_KEYS = ('preflight', 'max_files_changed', 'max_lines_changed', 'tests', 'protected_paths', 'issue_link',
|
|
25
|
+
'ai_disclosure', 'dependencies', 'vouch', 'agents', 'max_open_prs_per_author', 'commercial_vendor_prs',
|
|
26
|
+
'scout_vouches')
|
|
27
|
+
|
|
28
|
+
_A = re.ASCII
|
|
29
|
+
_I = re.IGNORECASE | re.ASCII
|
|
30
|
+
_HEADING_RE = re.compile(r'^(#{2,3})[ \t]+(?:pull[ \t]+requests?[ \t]+from[ \t]+(?:ai[ \t]+)?agents|'
|
|
31
|
+
r'(?:ai[ \t]+)?agent[ \t]+pull[ \t]+requests?|gitbills(?:[ \t]+policy)?)[ \t]*(?::[ \t]*)?(?:#+[ \t]*)?$', _I)
|
|
32
|
+
_BULLET_RE = re.compile(r'^[ \t]*[-*+][ \t]+([^\n]+)$', _A)
|
|
33
|
+
# A plain `key: value` line (4 spaces in is code).
|
|
34
|
+
_DIRECTIVE_RE = re.compile(r"^ {0,3}[A-Za-z*`_][A-Za-z0-9_ `*'-]{0,60}:", _A)
|
|
35
|
+
_FENCE_RE = re.compile(r'^[ \t]*(?:```|~~~)', _A)
|
|
36
|
+
_COMMENT_RE = re.compile(r'^ {0,3}<!--', _A)
|
|
37
|
+
_NEXT_HEADING_RE = re.compile(r'^(#{1,6})[ \t]', _A)
|
|
38
|
+
_KEYS = {
|
|
39
|
+
'preflight': 'preflight',
|
|
40
|
+
'max-files-changed': 'max_files_changed', 'max-changed-files': 'max_files_changed', 'max-files': 'max_files_changed',
|
|
41
|
+
'max-lines-changed': 'max_lines_changed', 'max-changed-lines': 'max_lines_changed', 'max-lines': 'max_lines_changed',
|
|
42
|
+
'max-diff-lines': 'max_lines_changed',
|
|
43
|
+
'tests': 'tests', 'tests-required': 'tests', 'require-tests': 'tests', 'require-tests-for-code': 'tests',
|
|
44
|
+
'protected-paths': 'protected_paths', 'forbidden-paths': 'protected_paths', 'do-not-touch': 'protected_paths',
|
|
45
|
+
'issue-link': 'issue_link', 'linked-issue': 'issue_link', 'require-linked-issue': 'issue_link',
|
|
46
|
+
'ai-disclosure': 'ai_disclosure', 'disclose-ai': 'ai_disclosure', 'disclosure': 'ai_disclosure',
|
|
47
|
+
'require-disclosure': 'ai_disclosure',
|
|
48
|
+
'dependencies': 'dependencies', 'new-dependencies': 'dependencies', 'runtime-dependencies': 'dependencies',
|
|
49
|
+
'vouch': 'vouch', 'first-time-contributors': 'vouch',
|
|
50
|
+
'agents': 'agents', 'agent-prs': 'agents', 'ai-prs': 'agents',
|
|
51
|
+
'max-open-prs-per-author': 'max_open_prs_per_author', 'max-open-prs': 'max_open_prs_per_author',
|
|
52
|
+
'commercial-vendor-prs': 'commercial_vendor_prs', 'vendor-prs': 'commercial_vendor_prs', 'scout-vouches': 'scout_vouches',
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _choices(spec):
|
|
57
|
+
"""value: other words for it."""
|
|
58
|
+
return {w: v for v, words in spec.items() for w in [v] + words.split(' ')}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_CHOICES = {
|
|
62
|
+
'agents': _choices({'allowed': 'open allow welcome yes true',
|
|
63
|
+
'allowed_with_preflight': 'preflight with_preflight require_preflight',
|
|
64
|
+
'vouched_only': 'vouched require_vouch vouch_required',
|
|
65
|
+
'maintainers_only': 'none closed no false disallow forbidden'}),
|
|
66
|
+
'commercial_vendor_prs': _choices({'allow': 'allowed', 'require_vouch': 'vouch_required', 'require_bond': 'bond_required',
|
|
67
|
+
'reject': 'rejected'}),
|
|
68
|
+
'scout_vouches': _choices({'allow': 'allowed', 'maintainers_only': 'disabled'}),
|
|
69
|
+
}
|
|
70
|
+
_UNLIMITED_RE = re.compile(r'^(?:null|none|unlimited|~)$', _I)
|
|
71
|
+
_REQUIRED_RE = re.compile(r'\b(?:required|require|must|yes|always|on|true)\b', _I)
|
|
72
|
+
_NEGATIVE_RE = re.compile(r'^(?:optional|not[ \t]+required|no|never|off|false)\b', _I)
|
|
73
|
+
_PATH_PATTERN_RE = re.compile(r'^[A-Za-z0-9_.*/ -]{1,200}$', _A)
|
|
74
|
+
_NUMBER_RE = re.compile(r'(?:^|[^0-9])([0-9]{1,9})(?![0-9])', _A)
|
|
75
|
+
_NONE_DEPS_RE = re.compile(r'\b(?:none|no[ \t]+new|not[ \t]+allowed|forbidden|zero|never)\b', _I)
|
|
76
|
+
_BOLD_CLOSE_RE = re.compile(r'^[ \t]*(?:\*\*|__)(?=[ \t])', _A)
|
|
77
|
+
_CHOICE_CUT_RE = re.compile(r'[ \t]#|\(', _A)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _key_of(s):
|
|
81
|
+
"""Keys lose Markdown emphasis and read _ as -."""
|
|
82
|
+
s = re.sub(r'[`*]', '', s).lower()
|
|
83
|
+
return re.sub(r'^-+|-+$', '', re.sub(r'[^a-z0-9]+', '-', s, flags=_A))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _plain(s):
|
|
87
|
+
"""Values lose backticks and the closing ** of a bold key, but keep * and _ (globs and paths need them)."""
|
|
88
|
+
return _BOLD_CLOSE_RE.sub('', s.replace('`', ''), count=1).strip(' \t')
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _choice_of(table, value):
|
|
92
|
+
"""A choice as written (lowercase, before any (note) or # comment), else None."""
|
|
93
|
+
v = '' if js_len(value) > 200 else re.sub(r'[`*"\']', '', value.lower())
|
|
94
|
+
cut = _CHOICE_CUT_RE.search(v)
|
|
95
|
+
v = (v if cut is None else v[:cut.start()]).strip(' \t')
|
|
96
|
+
v = re.sub(r'^_+|_+$', '', re.sub(r'[ \t-]+', '_', v[:-1] if v.endswith('.') else v))
|
|
97
|
+
return table.get(v)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def parse_policy(text) -> dict:
|
|
101
|
+
"""Read the policy section of an AGENTS.md text: protocol, found, heading_line, rules, unrecognized."""
|
|
102
|
+
rules = {k: ([] if k == 'protected_paths' else None) for k in POLICY_RULE_KEYS}
|
|
103
|
+
result = {'protocol': POLICY_PROTOCOL, 'found': False, 'heading_line': None, 'rules': rules, 'unrecognized': []}
|
|
104
|
+
lines = [ln[:-1] if ln.endswith('\r') else ln for ln in ('' if text is None else str(text)).split('\n')]
|
|
105
|
+
level = 0
|
|
106
|
+
in_fence = False
|
|
107
|
+
in_comment = False
|
|
108
|
+
for i, line in enumerate(lines):
|
|
109
|
+
if in_comment:
|
|
110
|
+
in_comment = '-->' not in line
|
|
111
|
+
continue
|
|
112
|
+
if _FENCE_RE.search(line):
|
|
113
|
+
in_fence = not in_fence
|
|
114
|
+
continue
|
|
115
|
+
if in_fence:
|
|
116
|
+
continue
|
|
117
|
+
if _COMMENT_RE.search(line): # commented out
|
|
118
|
+
in_comment = line.find('-->', line.find('<!--') + 4) < 0
|
|
119
|
+
continue
|
|
120
|
+
if not result['found']:
|
|
121
|
+
h = _HEADING_RE.search(line)
|
|
122
|
+
if h:
|
|
123
|
+
result['found'], result['heading_line'], level = True, i + 1, len(h.group(1))
|
|
124
|
+
continue
|
|
125
|
+
nxt = _NEXT_HEADING_RE.search(line)
|
|
126
|
+
if nxt and len(nxt.group(1)) <= level:
|
|
127
|
+
break
|
|
128
|
+
bullet = _BULLET_RE.search(line)
|
|
129
|
+
item = bullet.group(1) if bullet else line.lstrip(' ') if _DIRECTIVE_RE.search(line) else None
|
|
130
|
+
if item is None:
|
|
131
|
+
continue
|
|
132
|
+
colon = item.find(':')
|
|
133
|
+
if not bullet and item.startswith('//', colon + 1):
|
|
134
|
+
continue # a link (https://...), not a rule
|
|
135
|
+
key = _KEYS.get(_key_of(item[:colon])) if colon > 0 else None
|
|
136
|
+
value = _plain(item[colon + 1:]) if colon > 0 else ''
|
|
137
|
+
if not key or not _read_rule(rules, key, value):
|
|
138
|
+
if len(result['unrecognized']) < 20:
|
|
139
|
+
result['unrecognized'].append(display_text(item, 160))
|
|
140
|
+
# What agents implies, unless the section says otherwise.
|
|
141
|
+
if rules['agents'] == 'allowed_with_preflight' and rules['preflight'] is None:
|
|
142
|
+
rules['preflight'] = True
|
|
143
|
+
if rules['agents'] == 'vouched_only' and rules['vouch'] is None:
|
|
144
|
+
rules['vouch'] = 'required'
|
|
145
|
+
return result
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _read_rule(rules, key, value):
|
|
149
|
+
if key == 'preflight':
|
|
150
|
+
rules['preflight'] = not _NEGATIVE_RE.search(value)
|
|
151
|
+
return True
|
|
152
|
+
if key.startswith('max_'):
|
|
153
|
+
n = _NUMBER_RE.search(value)
|
|
154
|
+
if not n and _UNLIMITED_RE.search(value):
|
|
155
|
+
rules[key] = None
|
|
156
|
+
return True
|
|
157
|
+
if not n or int(n.group(1)) < 1:
|
|
158
|
+
return False
|
|
159
|
+
rules[key] = int(n.group(1))
|
|
160
|
+
return True
|
|
161
|
+
if key in _CHOICES:
|
|
162
|
+
c = _choice_of(_CHOICES[key], value)
|
|
163
|
+
if c is not None:
|
|
164
|
+
rules[key] = c
|
|
165
|
+
return c is not None
|
|
166
|
+
if key == 'protected_paths':
|
|
167
|
+
items = [re.sub(r'^/+', '', re.sub(r'^\./', '', p.strip(' \t'), count=1), count=1) for p in value.split(',')]
|
|
168
|
+
items = [p for p in items if p and _PATH_PATTERN_RE.search(p) and '..' not in p.split('/')]
|
|
169
|
+
for p in items:
|
|
170
|
+
if p not in rules['protected_paths'] and len(rules['protected_paths']) < 50:
|
|
171
|
+
rules['protected_paths'].append(p)
|
|
172
|
+
return bool(items)
|
|
173
|
+
if key == 'dependencies':
|
|
174
|
+
rules['dependencies'] = 'none' if _NONE_DEPS_RE.search(value) else 'allowed'
|
|
175
|
+
return True
|
|
176
|
+
rules[key] = 'optional' if _NEGATIVE_RE.search(value) else 'required' if _REQUIRED_RE.search(value) else 'optional'
|
|
177
|
+
return True
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _glob_to_re(pattern):
|
|
181
|
+
out = []
|
|
182
|
+
i = 0
|
|
183
|
+
while i < len(pattern):
|
|
184
|
+
c = pattern[i]
|
|
185
|
+
if c == '*':
|
|
186
|
+
if i + 1 < len(pattern) and pattern[i + 1] == '*':
|
|
187
|
+
out.append('[^\\n\\r]*')
|
|
188
|
+
i += 1
|
|
189
|
+
else:
|
|
190
|
+
out.append('[^/]*')
|
|
191
|
+
else:
|
|
192
|
+
out.append(c if re.match(r'[A-Za-z0-9_/ -]', c, _A) else '\\' + c)
|
|
193
|
+
i += 1
|
|
194
|
+
return re.compile(r'^%s\Z' % ''.join(out))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _protected_matcher(pattern):
|
|
198
|
+
"""A matcher for one protected-path pattern: `dir/`, an exact path (or folder), or a * / ** glob."""
|
|
199
|
+
if '*' in pattern:
|
|
200
|
+
a, b = _glob_to_re(pattern), _glob_to_re(re.sub(r'/+$', '', pattern) + '/**')
|
|
201
|
+
return lambda path: bool(a.search(path) or b.search(path))
|
|
202
|
+
if pattern.endswith('/'):
|
|
203
|
+
return lambda path: path.startswith(pattern)
|
|
204
|
+
return lambda path: path == pattern or path.startswith(pattern + '/')
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def matches_protected(path: str, pattern: str) -> bool:
|
|
208
|
+
"""Whether a changed path falls under a protected-path pattern: `dir/`, an exact path (or folder), or a glob."""
|
|
209
|
+
return _protected_matcher(pattern)(path)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _new_file_view(f):
|
|
213
|
+
rows = [{'text': c['text'], 'line': c['line'], 'added': False} for c in f['context']]
|
|
214
|
+
rows += [{'text': a['text'], 'line': a['line'], 'added': True} for a in f['added'] if a['line'] is not None]
|
|
215
|
+
return sorted(rows, key=lambda r: (r['line'], 1 if r['added'] else 0))
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
_PKG_SECTION_RE = re.compile(r'^[ \t]*"((?:dev|peer|optional|bundled?)?[Dd]ependencies|overrides|resolutions)"[ \t]*:[ \t]*\{', _A)
|
|
219
|
+
_PKG_RUNTIME = {'dependencies', 'peerDependencies', 'optionalDependencies', 'overrides', 'resolutions'}
|
|
220
|
+
_TOML_TABLE_RE = re.compile(r'^[ \t]*\[([^\]\n]+)\][ \t]*(?:#[^\n]*)?$', _A)
|
|
221
|
+
_PY_DEPS_OPEN_RE = re.compile(r'^[ \t]*dependencies[ \t]*=[ \t]*\[([^\n]*)$', _A)
|
|
222
|
+
_REQ_FILE_RE = re.compile(r'(?:^|/)requirements(?:[^/]*\.txt|/[^/]+\.txt)\Z', re.I | _A)
|
|
223
|
+
# A requirement, an editable, VCS, URL or path install, an included file, or another package index.
|
|
224
|
+
_REQ_LINE_RE = re.compile(r'^[ \t]*(?:[A-Za-z0-9][A-Za-z0-9_.-]*[ \t]*(?:\[[A-Za-z0-9_,. -]*\][ \t]*)?(?:[=<>!~]=|[<>@;]|$)|-[eirf](?:[ \t]|$)|--(?:editable|requirement|index-url|extra-index-url|find-links|trusted-host)\b|(?:git|hg|svn|bzr)\+|(?:https?|file)://|\.{0,2}/)', _A)
|
|
225
|
+
_QUOTED_NAME_RE = re.compile(r'''["'][A-Za-z0-9]''', _A)
|
|
226
|
+
_CFG_SECTION_RE = re.compile(r'^[ \t]*\[([^\]\n]+)\][ \t]*$', _A)
|
|
227
|
+
_CFG_KV_RE = re.compile(r'^([A-Za-z0-9_.-]+)[ \t]*[=:][ \t]*([^\n]*)$', _A)
|
|
228
|
+
_SETUP_REQ_RE = re.compile(r'\b(?:install_requires|extras_require)[ \t]*=', _A)
|
|
229
|
+
_NPM_RESOLVED_RE = re.compile(r'"resolved"[ \t]*:[ \t]*"([^"]*)"', _A)
|
|
230
|
+
_YARN_RESOLVED_RE = re.compile(r'''^[ \t]+resolved:?[ \t]+"?([^" \t]+)''', _A)
|
|
231
|
+
_YARN_REGISTRY_RE = re.compile(r'^https://registry\.(?:yarnpkg\.com|npmjs\.org)/', _A)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _depth(s, opening, closing):
|
|
235
|
+
return sum(1 if c in opening else -1 if c in closing else 0 for c in s)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def adds_runtime_dependency(f) -> bool:
|
|
239
|
+
"""Whether a changed file adds a runtime dependency: package.json (runtime sections, overrides, resolutions),
|
|
240
|
+
requirements*.txt, pyproject.toml, setup.cfg, setup.py, or a lockfile entry resolved outside the registry."""
|
|
241
|
+
full = f['path'] or ''
|
|
242
|
+
name = full.split('/')[-1].lower()
|
|
243
|
+
if _REQ_FILE_RE.search(full):
|
|
244
|
+
return any(_REQ_LINE_RE.search(a['text']) for a in f['added'])
|
|
245
|
+
if name == 'package.json':
|
|
246
|
+
section, depth = None, 0
|
|
247
|
+
for row in _new_file_view(f):
|
|
248
|
+
if section is None:
|
|
249
|
+
head = _PKG_SECTION_RE.search(row['text'])
|
|
250
|
+
if not head:
|
|
251
|
+
continue
|
|
252
|
+
rest = row['text'][head.end():]
|
|
253
|
+
if row['added'] and head.group(1) in _PKG_RUNTIME and '"' in rest:
|
|
254
|
+
return True
|
|
255
|
+
depth = 1 + _depth(rest, '{', '}')
|
|
256
|
+
section = head.group(1) if depth > 0 else None
|
|
257
|
+
continue
|
|
258
|
+
if row['added'] and section in _PKG_RUNTIME and re.match(r'^[ \t]*"', row['text']):
|
|
259
|
+
return True
|
|
260
|
+
depth += _depth(row['text'], '{', '}')
|
|
261
|
+
if depth <= 0:
|
|
262
|
+
section = None
|
|
263
|
+
return False
|
|
264
|
+
if name == 'pyproject.toml':
|
|
265
|
+
table, in_list = None, False
|
|
266
|
+
for row in _new_file_view(f):
|
|
267
|
+
t = _TOML_TABLE_RE.search(row['text'])
|
|
268
|
+
if t:
|
|
269
|
+
table, in_list = js_trim(t.group(1)), False
|
|
270
|
+
continue
|
|
271
|
+
if table == 'project':
|
|
272
|
+
opened = _PY_DEPS_OPEN_RE.search(row['text'])
|
|
273
|
+
if opened:
|
|
274
|
+
if row['added'] and _QUOTED_NAME_RE.search(opened.group(1)):
|
|
275
|
+
return True
|
|
276
|
+
in_list = ']' not in opened.group(1)
|
|
277
|
+
continue
|
|
278
|
+
if in_list:
|
|
279
|
+
if re.match(r'^[ \t]*\]', row['text']):
|
|
280
|
+
in_list = False
|
|
281
|
+
continue
|
|
282
|
+
if row['added'] and re.match(r'''^[ \t]*["'][A-Za-z0-9]''', row['text']):
|
|
283
|
+
return True
|
|
284
|
+
elif table == 'project.optional-dependencies':
|
|
285
|
+
if row['added'] and _QUOTED_NAME_RE.search(row['text']):
|
|
286
|
+
return True
|
|
287
|
+
elif table == 'tool.poetry.dependencies':
|
|
288
|
+
if (row['added'] and re.match(r'^[ \t]*[A-Za-z0-9][A-Za-z0-9_.-]*[ \t]*=', row['text'])
|
|
289
|
+
and not re.match(r'^[ \t]*python[ \t]*=', row['text'])):
|
|
290
|
+
return True
|
|
291
|
+
return False
|
|
292
|
+
if name == 'setup.cfg':
|
|
293
|
+
section, in_list = None, False
|
|
294
|
+
for row in _new_file_view(f):
|
|
295
|
+
s = _CFG_SECTION_RE.search(row['text'])
|
|
296
|
+
if s:
|
|
297
|
+
section, in_list = js_trim(s.group(1)).lower(), False
|
|
298
|
+
continue
|
|
299
|
+
if section not in ('options', 'options.extras_require'):
|
|
300
|
+
continue
|
|
301
|
+
kv = _CFG_KV_RE.search(row['text'])
|
|
302
|
+
if kv:
|
|
303
|
+
in_list = section == 'options.extras_require' or kv.group(1).lower() == 'install_requires'
|
|
304
|
+
if in_list and row['added'] and re.search(r'[A-Za-z0-9]', kv.group(2)):
|
|
305
|
+
return True
|
|
306
|
+
elif in_list and row['added'] and re.match(r'^[ \t]+[^ \t#;]', row['text'], _A):
|
|
307
|
+
return True
|
|
308
|
+
return False
|
|
309
|
+
if name == 'setup.py':
|
|
310
|
+
depth = 0
|
|
311
|
+
for row in _new_file_view(f):
|
|
312
|
+
if depth <= 0:
|
|
313
|
+
m = _SETUP_REQ_RE.search(row['text'])
|
|
314
|
+
if not m:
|
|
315
|
+
continue
|
|
316
|
+
rest = row['text'][m.end():]
|
|
317
|
+
if row['added'] and _QUOTED_NAME_RE.search(rest):
|
|
318
|
+
return True
|
|
319
|
+
depth = _depth(rest, '[{(', ']})')
|
|
320
|
+
continue
|
|
321
|
+
if row['added'] and _QUOTED_NAME_RE.search(row['text']):
|
|
322
|
+
return True
|
|
323
|
+
depth += _depth(row['text'], '[{(', ']})')
|
|
324
|
+
return False
|
|
325
|
+
if name in ('package-lock.json', 'npm-shrinkwrap.json'):
|
|
326
|
+
return any((m := _NPM_RESOLVED_RE.search(a['text'])) is not None and not m.group(1).startswith('https://registry.npmjs.org/')
|
|
327
|
+
for a in f['added'])
|
|
328
|
+
if name == 'yarn.lock':
|
|
329
|
+
return any((m := _YARN_RESOLVED_RE.search(a['text'])) is not None and not _YARN_REGISTRY_RE.search(m.group(1))
|
|
330
|
+
for a in f['added'])
|
|
331
|
+
return False
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
_ISSUE_LINK_RE = re.compile(r'(?:^|[^A-Za-z0-9_&])#[0-9]+\b|https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/issues/[0-9]+|\b[A-Z][A-Z0-9]{1,9}-[0-9]+\b', _A)
|
|
335
|
+
_DISCLOSURE_RE = re.compile(r'\b(?:ai|llm|agent|agents|copilot|claude|codex|cursor|gpt|gemini|generated|assisted|co-authored-by)\b', _I)
|
|
336
|
+
|
|
337
|
+
POLICY_REMEDIATIONS = {
|
|
338
|
+
'agents_maintainers_only': 'AGENTS.md takes agent pull requests only from maintainers: ask one to make this change, or to vouch for its commit.',
|
|
339
|
+
'max_files_changed_exceeded': 'Split the change into smaller pull requests: AGENTS.md caps the files one may change.',
|
|
340
|
+
'max_lines_changed_exceeded': 'Split the change into smaller pull requests: AGENTS.md caps the lines one may change.',
|
|
341
|
+
'tests_required': 'Add or update tests for the code you changed: AGENTS.md requires tests for code changes.',
|
|
342
|
+
'protected_path_touched': 'Leave protected paths alone (AGENTS.md lists them), or ask a maintainer to make that change.',
|
|
343
|
+
'issue_link_missing': 'Link the issue this fixes in the pull request body (for example: Fixes #123).',
|
|
344
|
+
'ai_disclosure_missing': 'Say in the pull request body that an AI agent wrote or assisted with this change.',
|
|
345
|
+
'new_runtime_dependency': 'This repository takes no new runtime dependencies (AGENTS.md): use the standard library instead.',
|
|
346
|
+
'issue_link_unchecked': 'Pass --body (or --body-file) so the issue-link rule can be checked before the pull request opens.',
|
|
347
|
+
'ai_disclosure_unchecked': 'Pass --body (or --body-file) so the AI-disclosure rule can be checked before the pull request opens.',
|
|
348
|
+
'policy_file_modified': 'Change AGENTS.md and VOUCHED.td in a pull request of their own that a maintainer reviews: a change never rewrites its own rules.',
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def evaluate_policy(parsed, rules, title='', body='', policy_path=None) -> list:
|
|
353
|
+
"""Check a parsed diff against policy rules: [{rule, detail, severity, path}] (high, or info when unchecked).
|
|
354
|
+
policy_path names the policy file's repository path when it is not one of POLICY_FILES."""
|
|
355
|
+
out = []
|
|
356
|
+
|
|
357
|
+
def v(rule, detail, path=None, severity='high'):
|
|
358
|
+
out.append({'rule': rule, 'detail': detail, 'severity': severity, 'path': path})
|
|
359
|
+
|
|
360
|
+
changed = len(parsed['paths'])
|
|
361
|
+
lines = parsed['linesAdded'] + parsed['linesRemoved']
|
|
362
|
+
# Offline nobody knows who opens it; the Action exempts maintainers.
|
|
363
|
+
if rules.get('agents') == 'maintainers_only':
|
|
364
|
+
v('agents_maintainers_only', 'AGENTS.md restricts agent pull requests to repository maintainers')
|
|
365
|
+
if rules['max_files_changed'] is not None and changed > rules['max_files_changed']:
|
|
366
|
+
v('max_files_changed_exceeded', '%d files changed, at most %d allowed' % (changed, rules['max_files_changed']))
|
|
367
|
+
if rules['max_lines_changed'] is not None and lines > rules['max_lines_changed']:
|
|
368
|
+
v('max_lines_changed_exceeded', '%d lines changed, at most %d allowed' % (lines, rules['max_lines_changed']))
|
|
369
|
+
if rules['tests'] == 'required':
|
|
370
|
+
code = any(f['path'] and not f['isDeleted'] and is_code_file(f['path']) and not is_test_file(f['path'])
|
|
371
|
+
for f in parsed['files'])
|
|
372
|
+
if code and not any(is_test_file(p) for p in parsed['paths']):
|
|
373
|
+
v('tests_required', 'code changed without a test change')
|
|
374
|
+
if rules['protected_paths']:
|
|
375
|
+
seen = set()
|
|
376
|
+
matchers = [(pat, _protected_matcher(pat)) for pat in rules['protected_paths']]
|
|
377
|
+
for f in parsed['files']:
|
|
378
|
+
for p in (f['oldPath'], f['newPath']):
|
|
379
|
+
if not isinstance(p, str) or p in seen:
|
|
380
|
+
continue
|
|
381
|
+
hit = next((pat for pat, match in matchers if match(p)), None)
|
|
382
|
+
if hit is not None:
|
|
383
|
+
seen.add(p)
|
|
384
|
+
v('protected_path_touched', 'matches %s' % hit, display_text(p, 300))
|
|
385
|
+
watched = set(POLICY_FILES)
|
|
386
|
+
if isinstance(policy_path, str) and policy_path:
|
|
387
|
+
watched.add(policy_path)
|
|
388
|
+
touched = set()
|
|
389
|
+
for f in parsed['files']:
|
|
390
|
+
for p in (f['oldPath'], f['newPath']):
|
|
391
|
+
if isinstance(p, str) and p in watched and p not in touched:
|
|
392
|
+
touched.add(p)
|
|
393
|
+
v('policy_file_modified', 'a policy or trust file changes', display_text(p, 300))
|
|
394
|
+
text = title + '\n' + body
|
|
395
|
+
has_text = js_trim(text) != ''
|
|
396
|
+
if rules['issue_link'] == 'required':
|
|
397
|
+
if not has_text:
|
|
398
|
+
v('issue_link_unchecked', 'no title or body given', None, 'info')
|
|
399
|
+
elif not _ISSUE_LINK_RE.search(text):
|
|
400
|
+
v('issue_link_missing', 'no issue reference in the title or body')
|
|
401
|
+
if rules['ai_disclosure'] == 'required':
|
|
402
|
+
if not js_trim(body):
|
|
403
|
+
v('ai_disclosure_unchecked', 'no body given', None, 'info')
|
|
404
|
+
elif not _DISCLOSURE_RE.search(body):
|
|
405
|
+
v('ai_disclosure_missing', 'the body does not disclose AI assistance')
|
|
406
|
+
if rules['dependencies'] == 'none':
|
|
407
|
+
dep = next((f for f in parsed['files'] if adds_runtime_dependency(f)), None)
|
|
408
|
+
if dep:
|
|
409
|
+
v('new_runtime_dependency', 'a runtime dependency is added', display_text(dep['path'], 300))
|
|
410
|
+
return out
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def append_policy_block(existing) -> str:
|
|
414
|
+
"""AGENTS.md text with the policy block appended; raises ValueError when the section already exists."""
|
|
415
|
+
text = existing or ''
|
|
416
|
+
if parse_policy(text)['found']:
|
|
417
|
+
raise ValueError('AGENTS.md already has a policy section; edit it instead.')
|
|
418
|
+
if not text:
|
|
419
|
+
return POLICY_BLOCK + '\n'
|
|
420
|
+
sep = '' if text.endswith('\n\n') else '\n' if text.endswith('\n') else '\n\n'
|
|
421
|
+
return text + sep + POLICY_BLOCK + '\n'
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def format_policy_terminal(p, source) -> str:
|
|
425
|
+
lines = ['AGENTS.md policy (%s): %s' % (POLICY_PROTOCOL, display_text(source if source is not None else 'AGENTS.md', 200))]
|
|
426
|
+
if not p['found']:
|
|
427
|
+
lines.append(' No "%s" section: gitbills policy --init prints one, --init --write adds it.' % POLICY_HEADING)
|
|
428
|
+
return '\n'.join(lines)
|
|
429
|
+
lines.append(' Section at line %d' % p['heading_line'])
|
|
430
|
+
shown = False
|
|
431
|
+
for k in POLICY_RULE_KEYS:
|
|
432
|
+
v = p['rules'][k]
|
|
433
|
+
if v is None or (isinstance(v, list) and not v):
|
|
434
|
+
continue
|
|
435
|
+
shown = True
|
|
436
|
+
if isinstance(v, list):
|
|
437
|
+
text = ', '.join(display_text(x, 100) for x in v)
|
|
438
|
+
elif v is True:
|
|
439
|
+
text = 'required'
|
|
440
|
+
elif v is False:
|
|
441
|
+
text = 'optional'
|
|
442
|
+
else:
|
|
443
|
+
text = str(v)
|
|
444
|
+
lines.append(' - %s: %s' % (k, text))
|
|
445
|
+
if not shown:
|
|
446
|
+
lines.append(' (no rule this version reads)')
|
|
447
|
+
for u in p['unrecognized']:
|
|
448
|
+
lines.append(' Not read: "%s" (shown, not enforced)' % u)
|
|
449
|
+
return '\n'.join(lines)
|