@bbcsoftwarefactory/skills 0.1.1 → 1.1.3

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.
Files changed (71) hide show
  1. package/dist/index.json +2 -3
  2. package/dist/skills/code-quality-gate/SKILL.md +4 -5
  3. package/dist/skills/code-quality-gate/references/gate-bigo.md +1 -1
  4. package/dist/skills/delivery-coordinator/SKILL.md +7 -8
  5. package/dist/skills/delivery-coordinator/references/hud-output.md +1 -1
  6. package/dist/skills/delivery-coordinator/references/issue-claim.md +5 -5
  7. package/dist/skills/delivery-coordinator/references/issue-dedup.md +1 -1
  8. package/dist/skills/delivery-coordinator/references/worktree-isolation.md +2 -2
  9. package/dist/skills/greptile-review-loop/SKILL.md +3 -4
  10. package/dist/skills/greptile-review-loop/references/review-protocol.md +1 -1
  11. package/dist/skills/issue-reviewer/SKILL.md +10 -13
  12. package/dist/skills/issue-reviewer/references/review-format.md +1 -1
  13. package/dist/skills/issue-reviewer/references/triage.md +6 -6
  14. package/dist/skills/question-gate/SKILL.md +6 -8
  15. package/dist/skills/question-gate/references/client-hooks.md +10 -10
  16. package/dist/skills/question-gate/references/diagram-routing.md +3 -3
  17. package/dist/skills/skill-clean-architecture/SKILL.md +2 -3
  18. package/dist/skills/skill-clean-architecture/references/source-headers.md +2 -3
  19. package/dist/skills/tool-depot/references/readonly-access.md +1 -1
  20. package/dist/skills/tool-depot/references/tool-catalog.json +2 -2
  21. package/dist/skills/watcher-observability/SKILL.md +3 -4
  22. package/dist/skills/watcher-observability/references/batch-protocol.md +6 -6
  23. package/dist/skills/watcher-observability/references/configuration.md +1 -1
  24. package/dist/skills/watcher-observability/references/error-scan.md +1 -1
  25. package/dist/skills/watcher-observability/references/live-protocol.md +8 -8
  26. package/dist/skills/watcher-observability/references/server-account.md +8 -8
  27. package/dist/skills/watcher-observability/server/watcher-gate.sh +1 -1
  28. package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +10 -7
  29. package/dist/skills/workflow-auditor/SKILL.md +3 -5
  30. package/dist/skills/workflow-auditor/references/audit-protocol.md +3 -3
  31. package/dist/skills/workflow-auditor/references/ledger.md +1 -1
  32. package/package.json +26 -27
  33. package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +0 -225
  34. package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +0 -200
  35. package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +0 -363
  36. package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +0 -220
  37. package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +0 -263
  38. package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +0 -221
  39. package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +0 -123
  40. package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +0 -124
  41. package/dist/skills/greptile-review-loop/scripts/review-loop.py +0 -435
  42. package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +0 -331
  43. package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +0 -239
  44. package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +0 -311
  45. package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +0 -90
  46. package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +0 -168
  47. package/dist/skills/question-gate/scripts/triage-question.py +0 -713
  48. package/dist/skills/question-gate/tests/question-corpus.test.sh +0 -32
  49. package/dist/skills/question-gate/tests/triage-question.test.sh +0 -441
  50. package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +0 -427
  51. package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +0 -222
  52. package/dist/skills/watcher-observability/scripts/error-scan.py +0 -318
  53. package/dist/skills/watcher-observability/scripts/resolve-containers.py +0 -155
  54. package/dist/skills/watcher-observability/scripts/save-counts.py +0 -381
  55. package/dist/skills/watcher-observability/scripts/summarize-logs.py +0 -113
  56. package/dist/skills/watcher-observability/scripts/watch-live.py +0 -606
  57. package/dist/skills/watcher-observability/tests/error-scan.test.sh +0 -257
  58. package/dist/skills/watcher-observability/tests/live-windows.test.sh +0 -177
  59. package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +0 -87
  60. package/dist/skills/watcher-observability/tests/save-counts.test.sh +0 -338
  61. package/dist/skills/watcher-observability/tests/sleuth.test.sh +0 -176
  62. package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +0 -105
  63. package/dist/skills/watcher-observability/tests/watcher-config.test.sh +0 -70
  64. package/dist/skills/workflow-auditor/scripts/audit-ledger.py +0 -624
  65. package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +0 -183
  66. package/dist/skills/workflow-auditor/scripts/render-workflow.py +0 -201
  67. package/dist/skills/workflow-auditor/scripts/validate-skills.py +0 -444
  68. package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +0 -660
  69. package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +0 -93
  70. package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +0 -135
  71. package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +0 -190
@@ -1,331 +0,0 @@
1
- #!/usr/bin/env bash
2
- # review-loop.py against a fake gh and two fake subagents: no network, no LLM.
3
- set -euo pipefail
4
- cd -- "${BASH_SOURCE[0]%/*}/.."
5
- PYTHON_BIN=$(command -v python3 || command -v python)
6
- "$PYTHON_BIN" -I -B - <<'PY'
7
- import importlib.util
8
- import json
9
- import os
10
- from pathlib import Path
11
- import shutil
12
- import subprocess
13
- import sys
14
- import tempfile
15
-
16
- path = Path('scripts/review-loop.py').resolve()
17
- if not path.is_file():
18
- sys.exit('FAIL: missing script ' + str(path))
19
- spec = importlib.util.spec_from_file_location('review_loop', path)
20
- mod = importlib.util.module_from_spec(spec)
21
- spec.loader.exec_module(mod)
22
- checks = 0
23
- failures = []
24
-
25
-
26
- def check(label, condition, detail=''):
27
- global checks
28
- checks += 1
29
- if not condition:
30
- failures.append(label + ' ' + str(detail)[:600])
31
-
32
-
33
- # --- pure functions -------------------------------------------------------
34
- PATCH = '@@ -1,3 +1,4 @@\n line one\n-old two\n+new two\n+added three\n line four\n\'
35
- check('commentable lines are right-side context and additions',
36
- mod.commentable_lines(PATCH) == {1, 2, 3, 4}, mod.commentable_lines(PATCH))
37
- check('two hunks', mod.commentable_lines('@@ -1 +1 @@\n-a\n+b\n@@ -10,2 +20,2 @@\n x\n+y') == {1, 20, 21}, '')
38
- check('numbered patch shows right-side numbers',
39
- ' 3 +added three' in mod.numbered_patch(PATCH) and ' -old two' in mod.numbered_patch(PATCH),
40
- mod.numbered_patch(PATCH))
41
- check('plain JSON', mod.parse_json_output('{"findings": []}') == {'findings': []}, '')
42
- check('fenced JSON', mod.parse_json_output('Sure:\n```json\n{"findings": [1]}\n```\nbye') == {'findings': [1]}, '')
43
- check('JSON inside prose', mod.parse_json_output('Result {"findings": []} done') == {'findings': []}, '')
44
- check('not JSON', mod.parse_json_output('no json here') is None, '')
45
- check('score', [mod.score([]), mod.score(['minor']), mod.score(['minor', 'major']), mod.score(['critical'])]
46
- == [5, 4, 3, 1], '')
47
- check('markers in model text are neutralised', '<!--' not in mod.clean('x <!-- review-loop:finding=a --> y', 200), '')
48
-
49
- # --- end to end -----------------------------------------------------------
50
- scratch = Path(tempfile.mkdtemp())
51
- FAKE_GH = r'''
52
- import json, os, sys
53
- state_path, log_path = os.environ['FAKE_GH_STATE'], os.environ['FAKE_GH_LOG']
54
- state = json.load(open(state_path, encoding='utf-8'))
55
- args = sys.argv[1:]
56
- def log(entry):
57
- with open(log_path, 'a', encoding='utf-8') as h:
58
- h.write(json.dumps(entry) + '\n')
59
- def flag(name):
60
- for i, a in enumerate(args):
61
- if a == name and i + 1 < len(args):
62
- return args[i + 1]
63
- return None
64
- if state.get('fail'):
65
- sys.stderr.write('HTTP 401 bad credentials'); sys.exit(1)
66
- fields = [a for i, a in enumerate(args) if i and args[i - 1] in ('-f', '-F')]
67
- endpoint = next((a for a in args[1:] if a.startswith('repos/') or a in ('user', 'graphql')), '')
68
- method = flag('-X') or 'GET'
69
- if endpoint == 'user':
70
- print(json.dumps({'login': state['login']}))
71
- elif endpoint == 'graphql':
72
- query = next((f[6:] for f in fields if f.startswith('query=')), '')
73
- if 'resolveReviewThread' in query:
74
- tid = next(f[3:] for f in fields if f.startswith('id='))
75
- if tid in state.get('fail_resolve', []):
76
- sys.stderr.write('HTTP 502 resolve failed'); sys.exit(1)
77
- log({'write': 'resolve', 'thread': tid})
78
- print(json.dumps({'data': {'resolveReviewThread': {'thread': {'id': tid, 'isResolved': True}}}}))
79
- else:
80
- pages = state.get('thread_pages') or [state['threads']]
81
- index = int(next((f[7:] for f in fields if f.startswith('cursor=')), '0'))
82
- info = {'hasNextPage': index + 1 < len(pages), 'endCursor': str(index + 1)}
83
- print(json.dumps({'data': {'repository': {'pullRequest': {'reviewThreads': {
84
- 'pageInfo': info, 'nodes': pages[index]}}}}}))
85
- elif endpoint.endswith('/reviews') and method == 'POST':
86
- body = json.loads(sys.stdin.read())
87
- log({'write': 'review', 'body': body})
88
- print(json.dumps({'id': 1}))
89
- elif '--paginate' in args or '--slurp' in args:
90
- sys.stderr.write('unknown flag: --slurp'); sys.exit(1)
91
- elif '/reviews?' in endpoint or '/files?' in endpoint:
92
- items = state['reviews' if '/reviews?' in endpoint else 'files']
93
- for item in items:
94
- if 'review-loop:summary' in item.get('body', '') and 'commit_id' not in item:
95
- item['commit_id'] = item['body'].split('sha=')[1][:40]
96
- page, size = int(endpoint.split('page=')[-1]), int(endpoint.split('per_page=')[1].split('&')[0])
97
- print(json.dumps(items[(page - 1) * size:page * size]))
98
- elif endpoint.startswith('repos/'):
99
- print(json.dumps(state['pr']))
100
- else:
101
- sys.stderr.write('unexpected ' + ' '.join(args)); sys.exit(1)
102
- '''
103
- FAKE_RUNNER = r'''
104
- import json, os, sys, time
105
- role = sys.argv[1]
106
- prompt_path = sys.argv[2].split('file at ', 1)[1] if len(sys.argv) > 2 else None
107
- prompt = open(prompt_path, encoding='utf-8').read() if prompt_path else sys.stdin.read()
108
- with open(os.environ['FAKE_RUNNER_LOG'], 'a', encoding='utf-8') as h:
109
- h.write(json.dumps({'role': role, 'prompt_path': prompt_path, 'has_diff': 'src/app.py' in prompt,
110
- 'injection_wrapped': 'BEGIN UNTRUSTED DIFF' in prompt}) + '\n')
111
- if os.environ.get('FAKE_SLEEP'):
112
- time.sleep(float(os.environ['FAKE_SLEEP']))
113
- print(open(os.environ['FAKE_' + role.upper() + '_OUT'], encoding='utf-8').read())
114
- '''
115
- (scratch / 'fake_gh.py').write_text(FAKE_GH, encoding='utf-8')
116
- (scratch / 'fake_runner.py').write_text(FAKE_RUNNER, encoding='utf-8')
117
-
118
- HEAD = 'b' * 40
119
- FILES = [{'filename': 'src/app.py', 'status': 'modified',
120
- 'patch': '@@ -1,3 +1,4 @@\n def run(x):\n- return x\n+ if x is None:\n+ return 0\n return x'},
121
- {'filename': 'logo.png', 'status': 'added'}]
122
- MARK_OLD = '<!-- review-loop:finding=aaaaaaa-F1 severity=major -->'
123
-
124
-
125
- def base_state(**over):
126
- state = {'login': 'leifer', 'pr': {'state': 'open', 'head': {'sha': HEAD}, 'number': 7},
127
- 'files': FILES, 'reviews': [], 'threads': []}
128
- state.update(over)
129
- return state
130
-
131
-
132
- def run(state, reviewer, verifier, *extra, env_extra=None):
133
- case = Path(tempfile.mkdtemp(dir=scratch))
134
- (case / 'state.json').write_text(json.dumps(state), encoding='utf-8')
135
- (case / 'reviewer.txt').write_text(reviewer if isinstance(reviewer, str) else json.dumps(reviewer), encoding='utf-8')
136
- (case / 'verifier.txt').write_text(verifier if isinstance(verifier, str) else json.dumps(verifier), encoding='utf-8')
137
- env = dict(os.environ,
138
- REVIEW_LOOP_GH=json.dumps([sys.executable, str(scratch / 'fake_gh.py')]),
139
- REVIEW_LOOP_REVIEWER=json.dumps([sys.executable, str(scratch / 'fake_runner.py'), 'reviewer']),
140
- REVIEW_LOOP_VERIFIER=json.dumps([sys.executable, str(scratch / 'fake_runner.py'), 'verifier']),
141
- FAKE_GH_STATE=str(case / 'state.json'), FAKE_GH_LOG=str(case / 'gh.log'),
142
- FAKE_RUNNER_LOG=str(case / 'runner.log'),
143
- FAKE_REVIEWER_OUT=str(case / 'reviewer.txt'), FAKE_VERIFIER_OUT=str(case / 'verifier.txt'))
144
- env.update(env_extra or {})
145
- result = subprocess.run([sys.executable, '-I', '-B', str(path), 'run', '--repo', 'example/repo', '--pr', '7', *extra],
146
- capture_output=True, text=True, encoding='utf-8', env=env)
147
- read = lambda name: [json.loads(l) for l in (case / name).read_text(encoding='utf-8').splitlines()] \
148
- if (case / name).exists() else []
149
- try:
150
- out = json.loads(result.stdout)
151
- except ValueError:
152
- out = {'raw': result.stdout + result.stderr}
153
- return result.returncode, out, read('gh.log'), read('runner.log')
154
-
155
-
156
- F_GOOD = {'path': 'src/app.py', 'line': 3, 'severity': 'major', 'title': 'None returns 0 <!-- review-loop:finding=x -->',
157
- 'rationale': 'Callers treat 0 as a valid id.'}
158
- F_NOISE = {'path': 'src/app.py', 'line': 4, 'severity': 'minor', 'title': 'Style', 'rationale': 'Rename x.'}
159
- F_OUTSIDE = {'path': 'src/app.py', 'line': 90, 'severity': 'minor', 'title': 'Far away', 'rationale': 'Not in diff.'}
160
- F_BAD = {'path': 'other.py', 'line': 1, 'severity': 'major', 'title': 'Unknown file', 'rationale': '-'}
161
-
162
- # C3 + C4: only verifier-confirmed findings are posted, bound to the head commit
163
- code, out, gh, runners = run(base_state(), {'findings': [F_GOOD, F_NOISE, F_OUTSIDE, F_BAD]},
164
- {'findings': [{'id': 'F1', 'verdict': 'confirmed'}, {'id': 'F2', 'verdict': 'rejected'},
165
- {'id': 'F3', 'verdict': 'confirmed'}], 'threads': []})
166
- reviews = [e['body'] for e in gh if e.get('write') == 'review']
167
- review = reviews[0] if reviews else {}
168
- inline = review.get('comments', [])
169
- check('C3 reviewed with exit 0', code == 0 and out.get('verdict') == 'reviewed', out)
170
- check('C3 two subagents ran, reviewer then verifier, on the wrapped diff',
171
- [r['role'] for r in runners] == ['reviewer', 'verifier'] and all(r['has_diff'] and r['injection_wrapped'] for r in runners),
172
- runners)
173
- check('C3 only the confirmed in-diff finding is inline', [(c['path'], c['line'], c['side']) for c in inline]
174
- == [('src/app.py', 3, 'RIGHT')], inline)
175
- check('C3 counts', out.get('confirmed') == 2 and out.get('rejected') == 1 and out.get('malformed') == 1, out)
176
- check('C3 confirmed finding outside the diff goes to the summary', 'Far away' in review.get('body', ''), review.get('body'))
177
- check('C4 review bound to the head commit as a comment', review.get('commit_id') == HEAD and review.get('event') == 'COMMENT', review)
178
- check('C4 summary marker with round, sha and score',
179
- '<!-- review-loop:summary round=1 sha=' + HEAD + ' score=3 -->' in review.get('body', ''), review.get('body'))
180
- check('C4 finding marker carries id and severity',
181
- '<!-- review-loop:finding=bbbbbbb-F1 severity=major -->' in (inline[0]['body'] if inline else ''), inline)
182
- check('C4 forged marker from the model is neutralised',
183
- (inline[0]['body'] if inline else '').count('<!--') == 1, inline)
184
- check('C9 report has what the ledger needs', out.get('head_sha') == HEAD and out.get('score') == 3
185
- and out.get('round') == 1 and out.get('max_rounds') == 3, out)
186
- check('binary file listed as skipped', out.get('skipped_files') == ['logo.png'], out)
187
-
188
- # C5: resolve only the loop's own threads that the verifier marks fixed
189
- threads = [
190
- {'id': 'T_loop', 'isResolved': False, 'path': 'src/app.py', 'line': 3,
191
- 'comments': {'nodes': [{'author': {'login': 'leifer'}, 'body': 'Old bug ' + MARK_OLD}]}},
192
- {'id': 'T_human', 'isResolved': False, 'path': 'src/app.py', 'line': 4,
193
- 'comments': {'nodes': [{'author': {'login': 'ana'}, 'body': 'Please rename'}]}},
194
- {'id': 'T_copied', 'isResolved': False, 'path': 'src/app.py', 'line': 4,
195
- 'comments': {'nodes': [{'author': {'login': 'ana'}, 'body': 'copied ' + MARK_OLD}]}},
196
- {'id': 'T_done', 'isResolved': True, 'path': 'src/app.py', 'line': 1,
197
- 'comments': {'nodes': [{'author': {'login': 'leifer'}, 'body': 'x ' + MARK_OLD}]}},
198
- ]
199
- prior = [{'user': {'login': 'leifer'}, 'body': 'r <!-- review-loop:summary round=1 sha=' + 'a' * 40 + ' score=3 -->'}]
200
- code, out, gh, runners = run(base_state(threads=threads, reviews=prior), {'findings': []},
201
- {'findings': [], 'threads': [{'id': 'T1', 'verdict': 'fixed'}, {'id': 'T2', 'verdict': 'fixed'}]})
202
- resolved = [e['thread'] for e in gh if e.get('write') == 'resolve']
203
- check('C5 only the open loop thread is resolved', resolved == ['T_loop'], resolved)
204
- check('C5 round two, score 5 when nothing stays open', out.get('round') == 2 and out.get('score') == 5
205
- and out.get('threads_resolved') == 1 and out.get('threads_open') == 0, out)
206
-
207
- code, out, gh, runners = run(base_state(threads=threads[:1], reviews=prior), {'findings': []},
208
- {'findings': [], 'threads': [{'id': 'T1', 'verdict': 'open'}]})
209
- check('C5 a thread the verifier keeps open lowers the score by its severity',
210
- not [e for e in gh if e.get('write') == 'resolve'] and out.get('score') == 3 and out.get('threads_open') == 1, out)
211
- check('C9 open_findings includes loop threads still open',
212
- [f.get('key') for f in out.get('open_findings', [])] == ['aaaaaaa-F1'], out.get('open_findings'))
213
-
214
- second = dict(threads[0], id='T_loop2', path='src/app.py', line=4)
215
- code, out, gh, runners = run(base_state(threads=[threads[0], second], reviews=prior, fail_resolve=['T_loop']),
216
- {'findings': []},
217
- {'findings': [], 'threads': [{'id': 'T1', 'verdict': 'fixed'}, {'id': 'T2', 'verdict': 'fixed'}]})
218
- check('a failed resolve stops before the summary is posted, so no score claims it',
219
- code == 1 and not gh and [w.get('write') for w in out.get('not_attempted', [])] == ['resolve', 'review'], out)
220
- code, out, gh, runners = run(base_state(threads=[threads[0], second], reviews=prior, fail_resolve=['T_loop2']),
221
- {'findings': []},
222
- {'findings': [], 'threads': [{'id': 'T1', 'verdict': 'fixed'}, {'id': 'T2', 'verdict': 'fixed'}]})
223
- check('threads resolved before a failure stay resolved; the review is not posted',
224
- code == 1 and [e.get('thread') for e in gh] == ['T_loop'] and [w.get('write') for w in out.get('not_attempted', [])]
225
- == ['review'], out)
226
-
227
- code, out, gh, runners = run(base_state(thread_pages=[threads[1:2], threads[:1]], reviews=prior), {'findings': []},
228
- {'findings': [], 'threads': [{'id': 'T1', 'verdict': 'fixed'}]})
229
- check('C5 loop threads on a later GraphQL page are found and resolved',
230
- [e['thread'] for e in gh if e.get('write') == 'resolve'] == ['T_loop'], out)
231
-
232
- # C6: budget and freshness stop before any subagent runs
233
- three = [{'user': {'login': 'leifer'}, 'body': '<!-- review-loop:summary round=%d sha=%s score=%d -->' % (n, c * 40, n + 1)}
234
- for n, c in ((1, 'a'), (2, 'c'), (3, 'd'))]
235
- code, out, gh, runners = run(base_state(reviews=three, threads=threads[:1]), {'findings': []}, {'findings': []})
236
- check('C6 budget exhausted after three rounds, no subagent, no write',
237
- code == 0 and out.get('verdict') == 'budget-exhausted' and not runners and not gh, out)
238
- check('C6 budget exhausted reports the last score and the loop threads still open',
239
- out.get('score') == 4 and out.get('round') == 3 and out.get('threads_open') == 1
240
- and [f.get('path') for f in out.get('open_findings', [])] == ['src/app.py'], out)
241
- reordered = [three[0], dict(three[1], body='<!-- review-loop:summary round=2 sha=' + HEAD + ' score=4 -->'), three[2]]
242
- code, out, gh, runners = run(base_state(reviews=reordered), {'findings': []}, {'findings': []})
243
- check('C6 already-reviewed reports the round from its own marker', out.get('verdict') == 'already-reviewed'
244
- and out.get('round') == 2 and out.get('score') == 4, out)
245
- filler = [{'user': {'login': 'ana'}, 'body': 'LGTM'}] * 100
246
- code, out, gh, runners = run(base_state(reviews=filler + three), {'findings': []}, {'findings': []})
247
- check('C6 markers on the second page of reviews count, without gh --slurp',
248
- out.get('verdict') == 'budget-exhausted' and not runners, out)
249
- same = [{'user': {'login': 'leifer'}, 'body': '<!-- review-loop:summary round=1 sha=' + HEAD + ' score=4 -->'}]
250
- code, out, gh, runners = run(base_state(reviews=same), {'findings': []}, {'findings': []})
251
- check('C6 head already reviewed returns its score without rerunning',
252
- out.get('verdict') == 'already-reviewed' and out.get('score') == 4 and not runners, out)
253
- unbound = [dict(same[0], commit_id='c' * 40)]
254
- code, out, gh, runners = run(base_state(reviews=unbound), {'findings': []}, {'findings': [], 'threads': []})
255
- check('C4 a summary marker whose review is on another commit does not count',
256
- out.get('verdict') == 'reviewed' and out.get('round') == 1, out)
257
- someone = [{'user': {'login': 'ana'}, 'body': '<!-- review-loop:summary round=1 sha=' + HEAD + ' score=5 -->'}]
258
- code, out, gh, runners = run(base_state(reviews=someone), {'findings': []}, {'findings': [], 'threads': []})
259
- check('C6 a summary marker by someone else does not count', out.get('verdict') == 'reviewed' and out.get('round') == 1, out)
260
-
261
- # C7: dry run
262
- code, out, gh, runners = run(base_state(threads=threads[:1]), {'findings': [F_GOOD]},
263
- {'findings': [{'id': 'F1', 'verdict': 'confirmed'}], 'threads': [{'id': 'T1', 'verdict': 'fixed'}]},
264
- '--dry-run')
265
- check('C7 dry run writes nothing and lists the writes', code == 0 and out.get('dry_run') is True and not gh
266
- and [w['write'] for w in out.get('writes', [])] == ['resolve', 'review'], out)
267
-
268
- # subagent CLIs that take the prompt as an argument read it from a temporary file
269
- by_file = json.dumps([sys.executable, str(scratch / 'fake_runner.py'), 'reviewer', 'Follow the file at {prompt_file}'])
270
- code, out, gh, runners = run(base_state(), {'findings': []}, {'findings': [], 'threads': []}, '--dry-run',
271
- env_extra={'REVIEW_LOOP_REVIEWER': by_file})
272
- path_used = runners[0].get('prompt_path') if runners else None
273
- check('{prompt_file} inside an argument is replaced, read, and deleted afterwards',
274
- code == 0 and path_used and runners[0]['has_diff'] and not os.path.exists(path_used)
275
- and runners[1].get('prompt_path') is None, runners)
276
-
277
- # what was not reviewed cannot score 5/5
278
- big = {'filename': 'src/big.py', 'status': 'added',
279
- 'patch': '@@ -0,0 +1,20000 @@\n' + '\n'.join('+value_%05d = %d' % (n, n) for n in range(20000))}
280
- code, out, gh, runners = run(base_state(files=FILES + [big, {'status': 'added'}]), {'findings': []},
281
- {'findings': [], 'threads': []}, '--dry-run')
282
- check('a file cut by the diff budget caps the score at 4 and is reported',
283
- out.get('score') == 4 and out.get('truncated_files') == ['src/big.py'], out)
284
- check('skipped files never list a missing name', None not in out.get('skipped_files', [None]), out)
285
- check('the summary names the files that were not reviewed',
286
- 'src/big.py' in ((out.get('writes') or [{}])[0].get('payload') or {}).get('body', ''), out.get('writes'))
287
- code, out, gh, runners = run(base_state(files=[big]), {'findings': [dict(F_GOOD, path='src/big.py', line=12)]},
288
- {'findings': [{'id': 'F1', 'verdict': 'confirmed'}], 'threads': []}, '--dry-run')
289
- inline = ((out.get('writes') or [{}])[0].get('payload') or {}).get('comments', [])
290
- check('a PR whose only file exceeds the budget gets its first part reviewed, capped',
291
- out.get('verdict') == 'reviewed' and out.get('truncated_files') == ['src/big.py'] and out.get('score') == 3
292
- and [(c['path'], c['line']) for c in inline] == [('src/big.py', 12)], out)
293
- code, out, gh, runners = run(base_state(files=[{'filename': 'logo.png', 'status': 'added'}]), {'findings': []},
294
- {'findings': []})
295
- check('a PR with no reviewable text is unusable, no subagent', code == 2 and not runners and not gh, out)
296
- code, out, gh, runners = run(base_state(), {'findings': []}, {'findings': []},
297
- env_extra={'REVIEW_LOOP_REVIEWER': '[not json'})
298
- check('a malformed REVIEW_LOOP_* command is unusable, not a crash',
299
- code == 2 and out.get('verdict') == 'unusable' and 'REVIEW_LOOP_REVIEWER' in out.get('reason', ''), out)
300
-
301
- # C1 + C2: unusable inputs write nothing
302
- code, out, gh, runners = run(base_state(pr={'state': 'closed', 'head': {'sha': HEAD}}), {'findings': []}, {'findings': []})
303
- check('C1 closed PR is unusable', code == 2 and out.get('verdict') == 'unusable' and not runners and not gh, out)
304
- code, out, gh, runners = run(base_state(fail=True), {'findings': []}, {'findings': []})
305
- check('C1 gh failure is unusable', code == 2 and out.get('verdict') == 'unusable', out)
306
- code, out, gh, runners = run(base_state(login=None, threads=[dict(threads[0], comments={'nodes': [
307
- {'author': None, 'body': 'ghost ' + MARK_OLD}]})]), {'findings': []}, {'findings': []})
308
- check('C1 no authenticated login is unusable, so ghost threads are never taken as the loop\'s',
309
- code == 2 and not runners and not gh, out)
310
- code, out, gh, runners = run(base_state(), 'I could not review this.', {'findings': []})
311
- check('C2 reviewer without JSON is unusable, verifier not called, nothing written',
312
- code == 2 and [r['role'] for r in runners] == ['reviewer'] and not gh, out)
313
- code, out, gh, runners = run(base_state(), {'findings': [F_GOOD]}, '{"oops": 1}')
314
- check('C2 verifier without the expected JSON is unusable', code == 2 and not gh, out)
315
- code, out, gh, runners = run(base_state(), {'findings': []}, {'findings': []}, '--timeout', '1',
316
- env_extra={'FAKE_SLEEP': '5'})
317
- check('C2 subagent timeout is unusable', code == 2 and 'timed out' in out.get('reason', ''), out)
318
-
319
- result = subprocess.run([sys.executable, '-I', '-B', str(path), 'run', '--repo', 'bad repo', '--pr', '7'],
320
- capture_output=True, text=True, encoding='utf-8')
321
- check('C1 invalid --repo is unusable', result.returncode == 2, result.stdout)
322
- result = subprocess.run([sys.executable, '-I', '-B', str(path), '--help'], capture_output=True, text=True, encoding='utf-8')
323
- check('--help', result.returncode == 0 and 'Usage' in result.stdout, result.stdout)
324
-
325
- shutil.rmtree(scratch, ignore_errors=True)
326
- if failures:
327
- for item in failures:
328
- print('FAIL:', item, file=sys.stderr)
329
- sys.exit(1)
330
- print(f'PASS {checks} checks')
331
- PY
@@ -1,239 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Fetch and download visual attachments from a GitHub issue and its comments.
3
-
4
- Uses `gh api` with `Accept: application/vnd.github.full+json` so private-repo
5
- `github.com/user-attachments/assets/...` embeds resolve to short-lived signed URLs
6
- in `body_html`.
7
- """
8
-
9
- import argparse
10
- import html
11
- import json
12
- import mimetypes
13
- from pathlib import Path
14
- import re
15
- import subprocess
16
- import sys
17
- import tempfile
18
- import urllib.error
19
- import urllib.parse
20
- import urllib.request
21
-
22
- IMG_SRC_RE = re.compile(r'<img\b[^>]*\bsrc=["\']([^"\']+)["\']', re.IGNORECASE)
23
- LINK_HREF_RE = re.compile(r'<a\b[^>]*\bhref=["\']([^"\']+)["\']', re.IGNORECASE)
24
- MD_IMAGE_RE = re.compile(r'!\[[^\]]*\]\((https?://[^)\s]+)\)')
25
-
26
- IMAGE_EXTENSIONS = ('.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg')
27
- MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
28
- ALLOWED_HOSTS = (
29
- 'github.com',
30
- 'raw.githubusercontent.com',
31
- 'user-images.githubusercontent.com',
32
- 'private-user-images.githubusercontent.com',
33
- 'objects.githubusercontent.com',
34
- 'avatars.githubusercontent.com',
35
- )
36
- REPO_RE = re.compile(r'^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$')
37
-
38
-
39
- def is_allowed_attachment_url(url):
40
- parsed = urllib.parse.urlparse(url)
41
- if parsed.scheme.lower() != 'https':
42
- return False
43
- host = (parsed.hostname or '').lower()
44
- if not host:
45
- return False
46
- if host in ALLOWED_HOSTS or host.endswith('.githubusercontent.com'):
47
- return True
48
- return False
49
-
50
-
51
- def extract_urls_from_html(body_html, body_md=''):
52
- urls = []
53
- seen = set()
54
-
55
- for raw in IMG_SRC_RE.findall(body_html or ''):
56
- clean = html.unescape(raw).strip()
57
- if clean and clean not in seen:
58
- seen.add(clean)
59
- urls.append({'kind': 'image', 'url': clean})
60
-
61
- for raw in LINK_HREF_RE.findall(body_html or ''):
62
- clean = html.unescape(raw).strip()
63
- if not clean or clean in seen:
64
- continue
65
- parsed = urllib.parse.urlparse(clean)
66
- path_lower = parsed.path.lower()
67
- if (
68
- 'user-attachments' in parsed.path
69
- or 'private-user-images.githubusercontent.com' in parsed.netloc
70
- or 'objects.githubusercontent.com' in parsed.netloc
71
- or path_lower.endswith(IMAGE_EXTENSIONS)
72
- ):
73
- seen.add(clean)
74
- urls.append({'kind': 'attachment', 'url': clean})
75
-
76
- for raw in MD_IMAGE_RE.findall(body_md or ''):
77
- clean = html.unescape(raw).strip()
78
- if clean and clean not in seen and 'github.com/user-attachments/' not in clean:
79
- seen.add(clean)
80
- urls.append({'kind': 'image', 'url': clean})
81
-
82
- return urls
83
-
84
-
85
- def extension_for_content_type(content_type, url):
86
- ct = (content_type or '').split(';')[0].strip().lower()
87
- if ct:
88
- ext = mimetypes.guess_extension(ct)
89
- if ext == '.jpe':
90
- return '.jpg'
91
- if ext:
92
- return ext
93
- path_ext = Path(urllib.parse.urlparse(url).path).suffix.lower()
94
- if path_ext in IMAGE_EXTENSIONS:
95
- return path_ext
96
- return '.bin'
97
-
98
-
99
- class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
100
- def redirect_request(self, req, fp, code, msg, headers, newurl):
101
- if not is_allowed_attachment_url(newurl):
102
- raise urllib.error.URLError(f'Refusing untrusted redirect host: {newurl}')
103
- return super().redirect_request(req, fp, code, msg, headers, newurl)
104
-
105
-
106
- def download_attachment(url, dest_dir, index):
107
- if not is_allowed_attachment_url(url):
108
- return {
109
- 'url': url,
110
- 'local_path': None,
111
- 'content_type': None,
112
- 'bytes': 0,
113
- 'status': 'error',
114
- 'error': 'Untrusted attachment URL scheme or host',
115
- }
116
- req = urllib.request.Request(url, headers={'User-Agent': 'bbc-issue-reviewer/1.0'})
117
- opener = urllib.request.build_opener(_SafeRedirectHandler())
118
- try:
119
- with opener.open(req, timeout=20) as resp:
120
- content_type = resp.headers.get('Content-Type', '')
121
- chunks = []
122
- total = 0
123
- while True:
124
- chunk = resp.read(65536)
125
- if not chunk:
126
- break
127
- total += len(chunk)
128
- if total > MAX_ATTACHMENT_BYTES:
129
- raise ValueError(f'Attachment exceeds {MAX_ATTACHMENT_BYTES} byte limit')
130
- chunks.append(chunk)
131
- payload = b''.join(chunks)
132
- except (urllib.error.URLError, TimeoutError, OSError, ValueError) as err:
133
- return {
134
- 'url': url,
135
- 'local_path': None,
136
- 'content_type': None,
137
- 'bytes': 0,
138
- 'status': 'error',
139
- 'error': str(err),
140
- }
141
-
142
- ext = extension_for_content_type(content_type, url)
143
- is_image = content_type.lower().startswith('image/') or ext in IMAGE_EXTENSIONS
144
- out_path = Path(dest_dir) / f'attachment-{index}{ext}'
145
- out_path.write_bytes(payload)
146
- return {
147
- 'url': url,
148
- 'local_path': str(out_path),
149
- 'content_type': content_type or None,
150
- 'bytes': len(payload),
151
- 'status': 'downloaded' if is_image else 'downloaded_non_image',
152
- }
153
-
154
-
155
- def fetch_github_json(endpoint):
156
- proc = subprocess.run(
157
- ['gh', 'api', '-H', 'Accept: application/vnd.github.full+json', endpoint],
158
- capture_output=True,
159
- text=True,
160
- check=False,
161
- timeout=20,
162
- )
163
- if proc.returncode != 0:
164
- raise RuntimeError(proc.stderr.strip() or f'gh api failed for {endpoint}')
165
- return json.loads(proc.stdout)
166
-
167
-
168
- def process_issue_payload(issue_data, comments_data, out_dir, downloader=download_attachment):
169
- entries = []
170
- seen_urls = set()
171
-
172
- sources = [('body', issue_data)] + [
173
- (f'comment:{c.get("id", idx)}', c) for idx, c in enumerate(comments_data or [], start=1)
174
- ]
175
-
176
- counter = 0
177
- for source_name, item in sources:
178
- if not isinstance(item, dict):
179
- continue
180
- found = extract_urls_from_html(item.get('body_html', ''), item.get('body', ''))
181
- for entry in found:
182
- url = entry['url']
183
- if url in seen_urls:
184
- continue
185
- seen_urls.add(url)
186
- counter += 1
187
- dl = downloader(url, out_dir, counter)
188
- dl['source'] = source_name
189
- dl['kind'] = entry['kind']
190
- entries.append(dl)
191
-
192
- return {
193
- 'issue': issue_data.get('number'),
194
- 'title': issue_data.get('title'),
195
- 'url': issue_data.get('html_url'),
196
- 'out_dir': str(out_dir),
197
- 'attachments': entries,
198
- }
199
-
200
-
201
- def parse_args(argv):
202
- parser = argparse.ArgumentParser(
203
- description='Resolve and download attachments from a GitHub issue via gh api body_html.'
204
- )
205
- parser.add_argument('--repo', help='GitHub repository in owner/repo format.')
206
- parser.add_argument('--issue', type=int, help='Issue number.')
207
- parser.add_argument('--out', help='Output directory for downloaded attachments.')
208
- parser.add_argument('--stdin', action='store_true', help='Read {"issue": ..., "comments": ...} JSON from stdin.')
209
- return parser.parse_args(argv)
210
-
211
-
212
- def main(argv):
213
- args = parse_args(argv)
214
- out_dir = Path(args.out) if args.out else Path(tempfile.mkdtemp(prefix=f'bbc-issue-{args.issue or "stdin"}-'))
215
- out_dir.mkdir(parents=True, exist_ok=True)
216
-
217
- if args.stdin:
218
- payload = json.load(sys.stdin)
219
- issue_data = payload.get('issue', {})
220
- comments_data = payload.get('comments', [])
221
- report = process_issue_payload(issue_data, comments_data, out_dir)
222
- else:
223
- if not args.repo or not args.issue or not REPO_RE.fullmatch(args.repo) or args.issue <= 0:
224
- print(json.dumps({'error': 'Pass --repo owner/repo and positive --issue N (or --stdin).'}))
225
- return 2
226
- try:
227
- issue_data = fetch_github_json(f'repos/{args.repo}/issues/{args.issue}')
228
- comments_data = fetch_github_json(f'repos/{args.repo}/issues/{args.issue}/comments')
229
- except (RuntimeError, ValueError, OSError, subprocess.SubprocessError) as err:
230
- print(json.dumps({'error': str(err)}))
231
- return 1
232
- report = process_issue_payload(issue_data, comments_data, out_dir)
233
-
234
- print(json.dumps(report, indent=2, ensure_ascii=False))
235
- return 0
236
-
237
-
238
- if __name__ == '__main__':
239
- sys.exit(main(sys.argv[1:]))