@bbcsoftwarefactory/skills 0.1.1 → 1.1.2

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,624 +0,0 @@
1
- """Check a delivery ledger against the skill workflow and the Tool Depot catalog.
2
-
3
- Read-only: it reads the ledger and the catalog and prints a JSON verdict.
4
- Findings name rule IDs, stages and record IDs; they never echo free-text evidence.
5
- """
6
-
7
- import json
8
- from pathlib import Path
9
- import re
10
- import subprocess
11
- import sys
12
-
13
- LEDGER_NAME = 'bbc-delivery-ledger.json'
14
- DEFAULT_CATALOG = Path(__file__).resolve().parents[2] / 'tool-depot' / 'references' / 'tool-catalog.json'
15
- HELP = ('Usage: python -I -B scripts/audit-ledger.py [ledger.json] [--catalog tool-catalog.json]'
16
- ' [--server-log watcher-gate.log]\n'
17
- 'Without a ledger path, read bbc-delivery-ledger.json from the current Git worktree\n'
18
- '(git rev-parse --git-path). Exit 0: conforms or gaps only; 1: violations; 2: unusable input.')
19
-
20
- STAGES = ('observe', 'specify', 'claim', 'reproduce', 'implement', 'verify', 'quality', 'docs',
21
- 'commit_pr', 'review', 'residual_risk', 'code_owner', 'release_owner')
22
- ORDER = {stage: index for index, stage in enumerate(STAGES)}
23
- KINDS = ('change', 'issue-only', 'read-only')
24
- LANES = ('trivial', 'standard', 'high-risk')
25
- STATUSES = ('done', 'reused', 'gap')
26
- REQUIRED_FOR_CHANGE = ('specify', 'reproduce', 'implement', 'verify', 'quality', 'commit_pr', 'review')
27
- WRITE_STAGES = ('claim', 'implement', 'verify', 'quality', 'commit_pr', 'review')
28
- RERUN_AFTER_CHANGE = ('verify', 'quality', 'commit_pr', 'review')
29
- LOOP_TARGETS = ('reproduce', 'implement')
30
- AUTHORIZED_STAGES = ('claim', 'implement', 'commit_pr')
31
- # Claiming the issue is part of implementing it, so an `implement` authorization covers it.
32
- COVERED_BY = {'claim': ('claim', 'implement')}
33
- HUMAN_STAGES = ('code_owner', 'release_owner')
34
- GAP_ALLOWED = ('observe', 'claim', 'reproduce', 'verify', 'docs', 'review', 'residual_risk')
35
- QUALITY_CHECKS = ('typesafe', 'earlyreturn', 'bigo')
36
- GAP_TYPES = ('not-reproducible', 'no-runnable-test')
37
- WRITE_TOOLS = ('github-write',)
38
- SHA = re.compile(r'[0-9a-fA-F]{7,40}')
39
-
40
-
41
- class Unusable(Exception):
42
- """The ledger or catalog cannot be audited."""
43
-
44
-
45
- class Audit:
46
- def __init__(self):
47
- self.violations = []
48
- self.gaps = []
49
-
50
- def violation(self, rule, detail, where=None):
51
- self.violations.append(_finding(rule, detail, where))
52
-
53
- def gap(self, rule, detail, where=None):
54
- self.gaps.append(_finding(rule, detail, where))
55
-
56
-
57
- def _finding(rule, detail, where):
58
- finding = {'rule': rule, 'detail': detail}
59
- if where is not None:
60
- finding['at'] = where
61
- return finding
62
-
63
-
64
- def _text(value):
65
- return isinstance(value, str) and value.strip() != ''
66
-
67
-
68
- def _sha(value):
69
- return isinstance(value, str) and SHA.fullmatch(value) is not None
70
-
71
-
72
- def load_json(path, label):
73
- try:
74
- with open(path, encoding='utf-8') as handle:
75
- return json.load(handle)
76
- except (OSError, ValueError):
77
- raise Unusable(label + ' is missing or is not valid JSON.')
78
-
79
-
80
- def load_catalog(path):
81
- catalog = load_json(path, 'Tool Depot catalog')
82
- tools = catalog.get('tools') if isinstance(catalog, dict) else None
83
- if not isinstance(tools, list):
84
- raise Unusable('Tool Depot catalog has no tools array.')
85
- purposes = {}
86
- for tool in tools:
87
- if isinstance(tool, dict) and _text(tool.get('id')) and isinstance(tool.get('purposes'), list):
88
- purposes[tool['id']] = set(tool['purposes'])
89
- if not purposes:
90
- raise Unusable('Tool Depot catalog lists no usable tools.')
91
- return purposes
92
-
93
-
94
- def records(ledger, key):
95
- value = ledger.get(key, [])
96
- if not isinstance(value, list) or not all(isinstance(item, dict) for item in value):
97
- raise Unusable('Ledger field "' + key + '" must be an array of objects.')
98
- return value
99
-
100
-
101
- def validate_shape(ledger):
102
- if not isinstance(ledger, dict):
103
- raise Unusable('Ledger must be a JSON object.')
104
- if ledger.get('version') != 1:
105
- raise Unusable('Unsupported ledger version; expected 1.')
106
- if ledger.get('kind') not in KINDS:
107
- raise Unusable('Ledger kind must be one of: ' + ', '.join(KINDS) + '.')
108
- lane = ledger.get('lane')
109
- if lane is not None and lane not in LANES:
110
- raise Unusable('Ledger lane must be one of: ' + ', '.join(LANES) + '.')
111
- for index, stage in enumerate(records(ledger, 'stages')):
112
- if stage.get('stage') not in ORDER:
113
- raise Unusable('stages[' + str(index) + '] has an unknown stage.')
114
- if stage.get('status') not in STATUSES:
115
- raise Unusable('stages[' + str(index) + '] has an unknown status.')
116
-
117
-
118
- def check_people(ledger, audit):
119
- people = {}
120
- for auth in records(ledger, 'authorizations'):
121
- auth_id = auth.get('id')
122
- if not _text(auth_id):
123
- audit.violation('A2', 'An authorization has no id.')
124
- continue
125
- if auth.get('by') != 'person':
126
- audit.violation('A2', 'Only people approve; this authorization was not granted by a person.', auth_id)
127
- continue
128
- covers = auth.get('covers')
129
- people[auth_id] = set(covers) if isinstance(covers, list) else set()
130
- return people
131
-
132
-
133
- def check_worktree(ledger, audit):
134
- if ledger['kind'] != 'change':
135
- return
136
- worktree = ledger.get('worktree')
137
- if not isinstance(worktree, dict):
138
- audit.violation('W1', 'Change work needs a dedicated worktree record.')
139
- return
140
- if not _text(worktree.get('path')):
141
- audit.violation('W1', 'Worktree path is missing.')
142
- branch = worktree.get('branch')
143
- if not (isinstance(branch, str) and branch.startswith('feat/') and len(branch) > len('feat/')):
144
- audit.violation('W1', 'Branch must be a unique feat/<task> branch.')
145
- if not _sha(worktree.get('base_sha')):
146
- audit.violation('W1', 'Default-branch base SHA is missing or not a hex SHA.')
147
-
148
-
149
- def check_kind(ledger, stages, audit):
150
- if ledger['kind'] == 'change':
151
- return
152
- for index, stage in enumerate(stages):
153
- if stage['stage'] in WRITE_STAGES:
154
- audit.violation('K1', ledger['kind'] + ' work cannot include write stages.', 'stages[' + str(index) + ']')
155
-
156
-
157
- def check_order(stages, audit):
158
- for index in range(1, len(stages)):
159
- before, after = stages[index - 1]['stage'], stages[index]['stage']
160
- if ORDER[after] >= ORDER[before] or after in LOOP_TARGETS:
161
- continue
162
- audit.violation('S2', 'Stage "' + after + '" runs after "' + before + '"; loops may only return to reproduce or implement.',
163
- 'stages[' + str(index) + ']')
164
-
165
-
166
- def check_required(ledger, stages, audit):
167
- if ledger['kind'] != 'change':
168
- return
169
- names = [stage['stage'] for stage in stages]
170
- for required in REQUIRED_FOR_CHANGE:
171
- if required not in names:
172
- audit.violation('S1', 'Required stage "' + required + '" is missing.')
173
- if 'implement' not in names:
174
- return
175
- first_change = names.index('implement')
176
- for prerequisite in ('specify', 'reproduce'):
177
- if prerequisite not in names[:first_change]:
178
- audit.violation('S3', 'Stage "' + prerequisite + '" must come before the first implementation.')
179
- last_change = len(names) - 1 - names[::-1].index('implement')
180
- for rerun in RERUN_AFTER_CHANGE:
181
- if rerun not in names[last_change + 1:]:
182
- audit.violation('S4', 'Stage "' + rerun + '" was not rerun after the last implementation.')
183
-
184
-
185
- def last(stages, name):
186
- for stage in reversed(stages):
187
- if stage['stage'] == name:
188
- return stage
189
- return None
190
-
191
-
192
- def evidence(stage):
193
- value = stage.get('evidence')
194
- return value if isinstance(value, dict) else {}
195
-
196
-
197
- def check_statuses(stages, audit):
198
- for index, stage in enumerate(stages):
199
- where = 'stages[' + str(index) + ']'
200
- status, name = stage['status'], stage['stage']
201
- if status == 'reused' and not _text(stage.get('reason')):
202
- audit.violation('S5', 'Reused evidence needs a reason naming its source.', where)
203
- if status != 'gap':
204
- continue
205
- if not _text(stage.get('reason')):
206
- audit.violation('S5', 'A gap needs a stated reason.', where)
207
- if name not in GAP_ALLOWED:
208
- audit.violation('S5', 'Stage "' + name + '" cannot be closed as a gap.', where)
209
- continue
210
- audit.gap('G1', 'Stage "' + name + '" closed as a gap; tell the Code Owner.', where)
211
-
212
-
213
- def check_reproduction(stages, audit):
214
- names = [stage['stage'] for stage in stages]
215
- for index, stage in enumerate(stages):
216
- if stage['stage'] != 'reproduce':
217
- continue
218
- where = 'stages[' + str(index) + ']'
219
- if stage['status'] == 'done':
220
- facts = evidence(stage)
221
- if not _text(facts.get('command')) or facts.get('result') != 'fail':
222
- audit.violation('E1', 'RED needs the test command and an observed failing result.', where)
223
- continue
224
- if stage['status'] != 'gap':
225
- continue
226
- gap_type = stage.get('gap_type')
227
- if gap_type not in GAP_TYPES:
228
- audit.violation('E1', 'A reproduction gap needs gap_type: ' + ' or '.join(GAP_TYPES) + '.', where)
229
- elif gap_type == 'not-reproducible' and 'implement' in names[index + 1:]:
230
- audit.violation('E1', 'Implemented after an unreproduced bug; document the gap and stop.', where)
231
-
232
-
233
- def check_results(stages, audit):
234
- verify = last(stages, 'verify')
235
- reproduce = last(stages, 'reproduce')
236
- if verify is not None and verify['status'] == 'gap':
237
- if reproduce is None or reproduce.get('gap_type') != 'no-runnable-test':
238
- audit.violation('E2', 'Verification can be a gap only when no runnable test applies.')
239
- elif verify is not None:
240
- facts = evidence(verify)
241
- if not _text(facts.get('command')) or facts.get('result') != 'pass':
242
- audit.violation('E2', 'The last verification needs its command and a passing result.')
243
- quality = last(stages, 'quality')
244
- if quality is not None:
245
- facts = {} if quality['status'] == 'gap' else evidence(quality)
246
- failing = [check for check in QUALITY_CHECKS if facts.get(check) != 'pass']
247
- if failing:
248
- audit.violation('Q1', 'The last quality gate did not pass: ' + ', '.join(failing) + '.')
249
-
250
-
251
- def check_review(stages, audit):
252
- pull = last(stages, 'commit_pr')
253
- review = last(stages, 'review')
254
- if pull is not None:
255
- facts = evidence(pull)
256
- if not _text(facts.get('pr')) or not _sha(facts.get('head_sha')):
257
- audit.violation('R1', 'Commit & PR needs the PR reference and the exact head SHA.')
258
- if review is None or review['status'] == 'gap' or pull is None:
259
- return
260
- facts = evidence(review)
261
- if not _text(facts.get('score')):
262
- audit.violation('R1', 'The Greptile review needs the observed score.')
263
- if facts.get('head_sha') != evidence(pull).get('head_sha'):
264
- audit.violation('R1', 'The Greptile review is not for the current PR head.')
265
-
266
-
267
- ISSUE_LINK_PURPOSES = ('comment-approved-issue', 'update-approved-issue')
268
-
269
-
270
- def check_issue_link(ledger, stages, audit):
271
- pull = last(stages, 'commit_pr')
272
- if pull is None or pull.get('status') == 'gap':
273
- return
274
- issue = evidence(pull).get('issue')
275
- if not _text(issue):
276
- return
277
- if evidence(pull).get('issue_linked') is not True:
278
- audit.violation('R2', 'PR opened for a canonical issue must record issue_linked: true.')
279
- return
280
- requests = {req.get('id'): req for req in records(ledger, 'tool_requests') if _text(req.get('id'))}
281
- has_use = any(
282
- use.get('tool') == 'github-write'
283
- and use.get('target') == issue
284
- and (req := requests.get(use.get('request'))) is not None
285
- and req.get('disposition') == 'eligible'
286
- and req.get('purpose') in ISSUE_LINK_PURPOSES
287
- for use in records(ledger, 'tool_uses')
288
- )
289
- if not has_use:
290
- audit.violation('R2', 'PR opened for a canonical issue must link the PR back on that issue via Tool Depot.')
291
-
292
-
293
- ISSUE_WRITE_PURPOSES = ('publish-approved-issue', 'update-approved-issue', 'comment-approved-issue')
294
-
295
-
296
- def check_visuals(ledger, audit):
297
- requests = {req.get('id'): req for req in records(ledger, 'tool_requests') if _text(req.get('id'))}
298
- for index, use in enumerate(records(ledger, 'tool_uses')):
299
- request = requests.get(use.get('request'))
300
- if request is None or request.get('purpose') not in ISSUE_WRITE_PURPOSES:
301
- continue
302
- where = 'tool_uses[' + str(index) + ']'
303
- visual = use.get('visual')
304
- if isinstance(visual, str) and visual.startswith('https://'):
305
- continue
306
- if isinstance(visual, dict) and _text(visual.get('gap')):
307
- audit.gap('G2', 'Issue write has no visual reference; the stated gap travels with the PR.', where)
308
- continue
309
- audit.violation('V1', 'Issue write needs a visual reference URL or a stated visual gap.', where)
310
-
311
-
312
- DEDUP_GUARDED_PURPOSES = ('publish-approved-issue', 'reopen-approved-issue')
313
-
314
-
315
- def _repository(target):
316
- return target.split('#', 1)[0].strip() if isinstance(target, str) else ''
317
-
318
-
319
- def check_dedup(ledger, audit):
320
- requests = {req.get('id'): req for req in records(ledger, 'tool_requests') if _text(req.get('id'))}
321
- searched = set()
322
- for index, use in enumerate(records(ledger, 'tool_uses')):
323
- request = requests.get(use.get('request'))
324
- if request is None or request.get('disposition') != 'eligible':
325
- continue
326
- repository = _repository(use.get('target'))
327
- if request.get('purpose') == 'check-duplicate-issues' and repository:
328
- searched.add(repository)
329
- continue
330
- if request.get('purpose') in DEDUP_GUARDED_PURPOSES and repository not in searched:
331
- audit.violation('D1', 'Issue filed or reopened without an earlier duplicate search of the same repository.',
332
- 'tool_uses[' + str(index) + ']')
333
-
334
-
335
- def check_triage(ledger, audit):
336
- """I1-I2: issue-reviewer triage is read first and stated in a comment (issue-reviewer/references/triage.md)."""
337
- requests = {req.get('id'): req for req in records(ledger, 'tool_requests') if _text(req.get('id'))}
338
- read, pending = set(), {}
339
- for index, use in enumerate(records(ledger, 'tool_uses')):
340
- request = requests.get(use.get('request'))
341
- if request is None or request.get('disposition') != 'eligible':
342
- continue
343
- target, purpose = use.get('target'), request.get('purpose')
344
- if purpose == 'check-issue-triage':
345
- read.add(target)
346
- elif purpose == 'triage-approved-issue':
347
- if target not in read:
348
- audit.violation('I1', 'Issue triaged without an earlier check-issue-triage read of the same issue.',
349
- 'tool_uses[' + str(index) + ']')
350
- pending[target] = index
351
- elif purpose == 'comment-approved-issue':
352
- pending.pop(target, None)
353
- for index in sorted(pending.values()):
354
- audit.violation('I2', 'Triage applied without a later comment on the issue that states it.',
355
- 'tool_uses[' + str(index) + ']')
356
-
357
-
358
- CLAIM_FREE = ('free', 'claimed-by-you')
359
- CLAIM_HELD = ('claimed-by-other', 'orphan-claim')
360
- CLAIM_BRANCH = re.compile(r'feat/(\d+)-[a-z0-9][a-z0-9._-]*')
361
- ISSUE_NUMBER = re.compile(r'#(\d+)$')
362
-
363
-
364
- def canonical_issue(ledger, stages):
365
- if _text(ledger.get('issue')):
366
- return ledger['issue'].strip()
367
- pull = last(stages, 'commit_pr')
368
- issue = evidence(pull).get('issue') if pull is not None else None
369
- return issue.strip() if _text(issue) else None
370
-
371
-
372
- def _first_use(ledger, purpose, target):
373
- requests = {req.get('id'): req for req in records(ledger, 'tool_requests') if _text(req.get('id'))}
374
- for index, use in enumerate(records(ledger, 'tool_uses')):
375
- request = requests.get(use.get('request'))
376
- if (request is not None and request.get('disposition') == 'eligible'
377
- and request.get('purpose') == purpose and use.get('target') == target):
378
- return index
379
- return None
380
-
381
-
382
- def check_claim(ledger, stages, people, audit):
383
- """C1-C4: one person per canonical issue (delivery-coordinator/references/issue-claim.md)."""
384
- if ledger['kind'] != 'change':
385
- return
386
- issue = canonical_issue(ledger, stages)
387
- if issue is None:
388
- return
389
- names = [stage['stage'] for stage in stages]
390
- if 'claim' not in names:
391
- audit.violation('C1', 'Work on a canonical issue needs a claim stage before RED.')
392
- return
393
- index = len(names) - 1 - names[::-1].index('claim')
394
- claim, where = stages[index], 'stages[' + str(index) + ']'
395
- if claim['status'] == 'gap':
396
- return
397
- facts = evidence(claim)
398
- if facts.get('issue') != issue:
399
- audit.violation('C2', 'The claim is not for the canonical issue of this delivery.', where)
400
- if not _text(facts.get('claimant')):
401
- audit.violation('C2', 'The claim must name the claimant login.', where)
402
- check = facts.get('check')
403
- if check in CLAIM_HELD:
404
- handover = facts.get('handover')
405
- if handover not in people or 'claim' not in people[handover]:
406
- audit.violation('C2', 'The issue was held by someone else; a handover needs a person authorization '
407
- 'that covers claim.', where)
408
- elif check not in CLAIM_FREE:
409
- audit.violation('C2', 'The check verdict must be free or claimed-by-you (or a handover).', where)
410
- if facts.get('verify') != 'claimed-by-you':
411
- audit.violation('C2', 'The recheck after claiming must be claimed-by-you.', where)
412
- read_at = _first_use(ledger, 'check-issue-claim', issue)
413
- write_at = _first_use(ledger, 'claim-approved-issue', issue)
414
- if read_at is None:
415
- audit.violation('C3', 'No eligible check-issue-claim read of the canonical issue.', where)
416
- if write_at is None and check != 'claimed-by-you':
417
- audit.violation('C3', 'The claim was never recorded on GitHub through claim-approved-issue.', where)
418
- if write_at is not None and read_at is not None and write_at < read_at:
419
- audit.violation('C3', 'The claim was written before the issue was checked.', where)
420
- number = ISSUE_NUMBER.search(issue)
421
- branch = CLAIM_BRANCH.fullmatch(str((ledger.get('worktree') or {}).get('branch', '')))
422
- if number is None or branch is None or branch.group(1) != number.group(1):
423
- audit.violation('C4', 'The worktree branch must be feat/<issue-number>-<slug> for the canonical issue.')
424
-
425
-
426
- def check_authorizations(stages, people, audit):
427
- for index, stage in enumerate(stages):
428
- name = stage['stage']
429
- where = 'stages[' + str(index) + ']'
430
- if name in HUMAN_STAGES and stage.get('actor') != 'person':
431
- audit.violation('H1', 'Stage "' + name + '" belongs to a person, not an agent.', where)
432
- if name not in AUTHORIZED_STAGES or stage['status'] == 'gap':
433
- continue
434
- auth_id = stage.get('authorization')
435
- if auth_id not in people:
436
- audit.violation('A1', 'Stage "' + name + '" has no authorization granted by a person.', where)
437
- elif people[auth_id].isdisjoint(COVERED_BY.get(name, (name,))):
438
- audit.violation('A1', 'The cited authorization does not cover "' + name + '".', where)
439
- names = [stage['stage'] for stage in stages]
440
- if 'release_owner' in names and 'code_owner' not in names[:names.index('release_owner')]:
441
- audit.violation('H2', 'A deployment decision needs a prior Code Owner review.')
442
-
443
-
444
- def check_tools(ledger, catalog, people, audit):
445
- requests = {}
446
- for request in records(ledger, 'tool_requests'):
447
- request_id = request.get('id')
448
- if not _text(request_id):
449
- audit.violation('T6', 'A Tool Depot request has no id.')
450
- continue
451
- requests[request_id] = request
452
- missing = [key for key in ('requester', 'tool', 'purpose', 'target', 'operation', 'disposition')
453
- if not _text(request.get(key))]
454
- if missing:
455
- audit.violation('T6', 'Tool Depot request is incomplete: ' + ', '.join(missing) + '.', request_id)
456
- if request.get('disposition') != 'eligible':
457
- continue
458
- tool = request.get('tool')
459
- if request.get('purpose') not in catalog.get(tool, set()):
460
- audit.violation('T3', 'Eligible request uses a tool or purpose that is not in the catalog.', request_id)
461
- if tool in WRITE_TOOLS and request.get('authorization') not in people:
462
- audit.violation('T5', 'A GitHub write needs an authorization granted by a person.', request_id)
463
- for index, use in enumerate(records(ledger, 'tool_uses')):
464
- where = 'tool_uses[' + str(index) + ']'
465
- request = requests.get(use.get('request'))
466
- if request is None:
467
- audit.violation('T1', 'External tool used without a Tool Depot request.', where)
468
- continue
469
- if request.get('disposition') != 'eligible':
470
- audit.violation('T2', 'Tool used although the Depot did not return eligible.', where)
471
- if use.get('tool') != request.get('tool') or use.get('target') != request.get('target'):
472
- audit.violation('T4', 'Tool or target differs from the eligible request.', where)
473
-
474
-
475
- def check_lane(ledger, stages, audit):
476
- if ledger.get('lane') != 'high-risk':
477
- return
478
- residual = last(stages, 'residual_risk')
479
- if residual is None or residual.get('status') != 'done':
480
- audit.violation('L1', 'High-risk lane requires a completed residual_risk assessment.')
481
-
482
-
483
- def audit_ledger(ledger, catalog, server_commands=None):
484
- validate_shape(ledger)
485
- audit = Audit()
486
- stages = records(ledger, 'stages')
487
- people = check_people(ledger, audit)
488
- check_worktree(ledger, audit)
489
- check_kind(ledger, stages, audit)
490
- check_order(stages, audit)
491
- check_required(ledger, stages, audit)
492
- check_statuses(stages, audit)
493
- check_reproduction(stages, audit)
494
- check_results(stages, audit)
495
- check_review(stages, audit)
496
- check_lane(ledger, stages, audit)
497
- check_issue_link(ledger, stages, audit)
498
- check_visuals(ledger, audit)
499
- check_dedup(ledger, audit)
500
- check_triage(ledger, audit)
501
- check_claim(ledger, stages, people, audit)
502
- check_authorizations(stages, people, audit)
503
- check_tools(ledger, catalog, people, audit)
504
- if server_commands is not None:
505
- check_server_log(ledger, server_commands, audit)
506
- verdict = 'violations' if audit.violations else 'gaps' if audit.gaps else 'conforms'
507
- return {
508
- 'verdict': verdict,
509
- 'violations': audit.violations,
510
- 'gaps': audit.gaps,
511
- 'checked': {
512
- 'stages': len(stages),
513
- 'tool_requests': len(records(ledger, 'tool_requests')),
514
- 'tool_uses': len(records(ledger, 'tool_uses')),
515
- },
516
- }
517
-
518
-
519
- def default_ledger():
520
- try:
521
- result = subprocess.run(['git', 'rev-parse', '--git-path', LEDGER_NAME],
522
- capture_output=True, text=True, check=True, timeout=10)
523
- except (OSError, subprocess.SubprocessError):
524
- raise Unusable('No ledger path given and the current directory is not a Git worktree.')
525
- return Path(result.stdout.strip())
526
-
527
-
528
- def parse_args(argv):
529
- ledger, catalog, server_log = None, DEFAULT_CATALOG, None
530
- args = list(argv)
531
- while args:
532
- arg = args.pop(0)
533
- if arg in ('-h', '--help'):
534
- return None
535
- if arg == '--catalog' and args:
536
- catalog = Path(args.pop(0))
537
- elif arg == '--server-log' and args:
538
- server_log = Path(args.pop(0))
539
- elif ledger is None and not arg.startswith('-'):
540
- ledger = Path(arg)
541
- else:
542
- raise Unusable('Unexpected argument; see --help.')
543
- return ledger, catalog, server_log
544
-
545
-
546
- # #40: what the server actually ran. watcher-gate.sh logs every decision to syslog
547
- # (tag watcher-gate) as `allowed: <command>` or `denied: <command>`; only allowed
548
- # commands ran. Accepts `journalctl -t watcher-gate -o json` or plain syslog text.
549
- GATE_ENTRY = re.compile(r'(?:^|\swatcher-gate(?:\[\d+\])?:\s)(allowed|denied): (.*)$')
550
- GATE_LOGS = re.compile(r'^docker logs .* -- ([A-Za-z0-9][A-Za-z0-9_.-]*)$')
551
- GATE_PS = re.compile(r"^docker ps --filter 'name=\^/\?((?:[A-Za-z0-9_-]|\\\.)+)\.\*\$' --format")
552
- TARGET_TOKEN = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.*-]*')
553
-
554
-
555
- def load_server_log(path):
556
- try:
557
- lines = path.read_text(encoding='utf-8', errors='replace').splitlines()
558
- except OSError:
559
- raise Unusable('Server log cannot be read.')
560
- entries = []
561
- for line in lines:
562
- message = line
563
- if line.lstrip().startswith('{'):
564
- try:
565
- record = json.loads(line)
566
- except ValueError:
567
- continue
568
- if not isinstance(record, dict) or record.get('SYSLOG_IDENTIFIER') != 'watcher-gate':
569
- continue
570
- message = str(record.get('MESSAGE', ''))
571
- elif 'watcher-gate' not in line:
572
- continue
573
- match = GATE_ENTRY.search(message)
574
- if match:
575
- entries.append((match.group(1), match.group(2)))
576
- if not entries:
577
- raise Unusable('Server log has no watcher-gate entries; export it with journalctl -t watcher-gate -o json.')
578
- return [command for decision, command in entries if decision == 'allowed']
579
-
580
-
581
- def server_target(command):
582
- logs = GATE_LOGS.match(command)
583
- if logs:
584
- return logs.group(1), False
585
- ps = GATE_PS.match(command)
586
- if ps:
587
- return ps.group(1).replace('\\.', '.'), True
588
- return None, False
589
-
590
-
591
- def check_server_log(ledger, commands, audit):
592
- """T7: every command the server allowed must consume one recorded ssh use."""
593
- uses = [set(TARGET_TOKEN.findall(use.get('target') if isinstance(use.get('target'), str) else ''))
594
- for use in records(ledger, 'tool_uses') if use.get('tool') == 'ssh']
595
- for index, command in enumerate(commands):
596
- name, is_prefix = server_target(command)
597
- wanted = {name + '*', name} if is_prefix else {name}
598
- match = next((i for i, tokens in enumerate(uses) if name and tokens & wanted), None)
599
- if match is None:
600
- audit.violation('T7', 'The server ran an SSH command with no matching ssh tool_use in the ledger: '
601
- + command[:160], f'server_log[{index}]')
602
- else:
603
- uses.pop(match)
604
-
605
-
606
- def main(argv):
607
- try:
608
- parsed = parse_args(argv)
609
- if parsed is None:
610
- print(HELP)
611
- return 0
612
- ledger_path, catalog_path, server_log = parsed
613
- catalog = load_catalog(catalog_path)
614
- commands = load_server_log(server_log) if server_log else None
615
- report = audit_ledger(load_json(ledger_path or default_ledger(), 'Delivery ledger'), catalog, commands)
616
- except Unusable as error:
617
- print(json.dumps({'verdict': 'unusable', 'detail': str(error)}))
618
- return 2
619
- print(json.dumps(report, indent=2))
620
- return 1 if report['violations'] else 0
621
-
622
-
623
- if __name__ == '__main__':
624
- sys.exit(main(sys.argv[1:]))