@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,381 +0,0 @@
1
- """Capture once and save a sanitized report in the caller's Git worktree."""
2
-
3
- from contextlib import contextmanager
4
- from datetime import datetime, timezone
5
- import json
6
- import os
7
- from pathlib import Path
8
- from queue import Empty, Queue
9
- import re
10
- import runpy
11
- import secrets
12
- import shutil
13
- import stat
14
- import subprocess
15
- import sys
16
- from threading import Thread
17
- from time import monotonic
18
-
19
- SCRIPTS = Path(__file__).resolve().parent
20
- ARTIFACT = 'report.json'
21
- DESTINATION = 'Watcher counts destination unavailable; nothing saved.'
22
- FAILED = 'Watcher counts capture failed; nothing saved.'
23
- INVALID = 'Watcher counts capture requires a valid SSH alias and exact container name or ID.'
24
- HELP = ('Usage: python -I -B scripts/save-counts.py {live|sleuth|historical} <ssh-alias> <exact-container>\n'
25
- ' python -I -B scripts/save-counts.py --no-save historical <ssh-alias> <exact-container>\n'
26
- 'Run from the caller Git worktree with the script path pointing to the installed skill.\n'
27
- 'Save counts and coverage to ignored tmp_logs/<UTC>-<hash>/report.json.\n'
28
- '--no-save prints the same historical result and writes nothing (explicit no-save requests).\n'
29
- 'Only authorized sleuth mode prints and saves the bundled redactor’s detailed evidence.')
30
-
31
- # One bounded historical batch (ADR 0001). It keeps the controls of the retired
32
- # `timeout --kill-after=2s 15s ssh ... 2>&1 | summarize-logs.sh` pipeline: the same
33
- # SSH options and remote command, merged stdout+stderr, a 15 s deadline covering
34
- # setup and streaming, 2 s more before a forced kill, and a 32 KiB cap. Producer
35
- # status follows GNU timeout: 124 when the deadline is enforced, 137 when a kill
36
- # is needed, otherwise SSH's own status (128 + N for a signal).
37
- SSH_OPTIONS = ('-nT', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'UpdateHostKeys=no',
38
- '-o', 'ClearAllForwardings=yes', '-o', 'PermitLocalCommand=no', '-o', 'ControlPath=none')
39
- DEADLINE, KILL_GRACE, READ_SIZE = 15, 2, 4096
40
- SUMMARIZER = runpy.run_path(str(SCRIPTS / 'summarize-logs.py'))
41
- NUMBER = r'[0-9]{1,20}'
42
- WINDOW_ROW = re.compile(
43
- rf'window=([1-4]) error={NUMBER} warn={NUMBER} info={NUMBER} debug={NUMBER} '
44
- rf'unclassified={NUMBER} frames={NUMBER} dropped_bytes={NUMBER} top=(.+)')
45
- HIT = re.compile(rf'([A-Za-z_0-9]+):({NUMBER})')
46
-
47
-
48
- def capture_batch(alias, container):
49
- """Return (at most CAP bytes, producer status), or None when SSH is unavailable."""
50
- ssh = shutil.which('ssh')
51
- if not ssh:
52
- return None
53
- cap = SUMMARIZER['CAP']
54
- started = monotonic()
55
- process = subprocess.Popen([ssh, *SSH_OPTIONS, alias, 'docker', 'logs', '-f', '--tail=1000', '--', container],
56
- stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
57
- bufsize=0)
58
- chunks = Queue()
59
-
60
- def drain():
61
- # A thread, not select(): pipes are not selectable on Windows. After the cap
62
- # the data is still drained but discarded (see ADR 0001: closing a pipe that
63
- # another thread reads is unsafe), so memory stays bounded.
64
- with process.stdout as pipe:
65
- while True:
66
- try:
67
- data = pipe.read(READ_SIZE)
68
- except (OSError, ValueError):
69
- data = b''
70
- chunks.put(data)
71
- if not data:
72
- return
73
-
74
- Thread(target=drain, daemon=True).start()
75
- kept, size, expired = [], 0, False
76
- while True:
77
- remaining = started + DEADLINE - monotonic()
78
- try:
79
- data = chunks.get(timeout=remaining) if remaining > 0 else None
80
- except Empty:
81
- data = None
82
- if data is None:
83
- expired = True
84
- break
85
- if not data:
86
- break
87
- if size < cap:
88
- kept.append(data[:cap - size])
89
- size += len(kept[-1])
90
- if not expired:
91
- try:
92
- process.wait(timeout=max(0, started + DEADLINE - monotonic()))
93
- except subprocess.TimeoutExpired:
94
- expired = True
95
- if expired:
96
- process.terminate()
97
- try:
98
- process.wait(timeout=KILL_GRACE)
99
- status = 124
100
- except subprocess.TimeoutExpired:
101
- process.kill()
102
- process.wait()
103
- status = 137
104
- else:
105
- code = process.returncode
106
- status = 128 - code if code < 0 else code
107
- return b''.join(kept), status
108
-
109
-
110
- def historical(alias, container):
111
- captured = capture_batch(alias, container)
112
- if captured is None:
113
- return None
114
- data, producer = captured
115
- summary, consumer = SUMMARIZER['summarize'](data)
116
- # Same acceptance policy as the Bash batch: a deadline (124), a cap reached as
117
- # the pipe closed (141 with consumer 3) or a clean exit; an ambiguous kill (137)
118
- # or any other failure is not enough to save a report.
119
- if producer not in (0, 124) and (producer, consumer) != (141, 3):
120
- return None
121
- status = 'finished' if (producer, consumer) == (0, 0) else 'incomplete'
122
- severity, category, _ = summary.splitlines()
123
- return f'historical status={status}\n{summary}', {
124
- 'status': status, 'counts': {'severity': numeric_fields(severity.split()[1:]),
125
- 'category': numeric_fields(category.split()[1:])},
126
- 'coverage': {'cap': consumer == 3, 'partial': summary.rstrip('\n').endswith('partial=yes'),
127
- 'deadline': producer == 124},
128
- 'evidence': no_evidence(),
129
- }
130
-
131
-
132
- def numeric_fields(fields):
133
- return {name: int(value) for name, value in (field.split('=') for field in fields)}
134
-
135
-
136
- def no_evidence():
137
- return {'status': 'not_observed', 'message': 'No detailed evidence observed.', 'events': []}
138
-
139
-
140
- def live(watcher, sleuth, alias, container):
141
- result = watcher['capture'](alias, container, sleuth)
142
- if result is None:
143
- return None
144
- rows, evidence = result
145
- if len(rows) != watcher['WINDOWS'] or (evidence is not None) != sleuth:
146
- return None
147
- names = {name for name, _ in watcher['PATTERNS']}
148
- windows = []
149
- for index, row in enumerate(rows, start=1):
150
- match = WINDOW_ROW.fullmatch(row)
151
- if not match or int(match[1]) != index:
152
- return None
153
- hits = [HIT.fullmatch(hit) for hit in match[2].split(',')]
154
- if len(hits) != len(names) or not all(hits) or {hit[1] for hit in hits} != names:
155
- return None
156
- window = numeric_fields(row.split()[:-1])
157
- window['top'] = {hit[1]: int(hit[2]) for hit in hits}
158
- windows.append(window)
159
- return '\n'.join(watcher['live_output'](rows, evidence)) + '\n', {
160
- 'status': 'deadline', 'counts': {'windows': windows},
161
- 'coverage': {'window_seconds': watcher['WINDOW_SECONDS'],
162
- 'byte_limit_per_window': watcher['BYTE_LIMIT'],
163
- 'dropped_bytes': sum(row['dropped_bytes'] for row in windows)},
164
- 'evidence': evidence if sleuth else no_evidence(),
165
- }
166
-
167
-
168
- def git(args, cwd=None):
169
- # Resolve from the actual caller directory, not inherited Git repo overrides.
170
- env = {key: value for key, value in os.environ.items() if not key.upper().startswith('GIT_')}
171
- return subprocess.run(['git', *args], cwd=cwd, env=env, stdin=subprocess.DEVNULL,
172
- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=5)
173
-
174
-
175
- def worktree():
176
- result = git(['rev-parse', '--show-toplevel'])
177
- if result.returncode != 0 or not result.stdout.endswith(b'\n'):
178
- raise OSError('no worktree')
179
- return Path(result.stdout[:-1].decode('utf-8' if os.name == 'nt' else sys.getfilesystemencoding(),
180
- errors='surrogateescape')).resolve(strict=True)
181
-
182
-
183
- def require_ignore(root, session):
184
- require_root_rule(root)
185
- for path in ('tmp_logs/', f'tmp_logs/{session}/', f'tmp_logs/{session}/{ARTIFACT}'):
186
- if git(['check-ignore', '-q', '--', path], cwd=root).returncode != 0:
187
- raise OSError('destination not ignored')
188
-
189
-
190
- def is_reparse_point(info):
191
- return bool(getattr(info, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT)
192
-
193
-
194
- def real_directory(info):
195
- return stat.S_ISDIR(info.st_mode) and not is_reparse_point(info)
196
-
197
-
198
- def real_ignore_file(info):
199
- return stat.S_ISREG(info.st_mode) and not is_reparse_point(info) and info.st_nlink == 1
200
-
201
-
202
- def check_base(root):
203
- try:
204
- info = (root / 'tmp_logs').lstat()
205
- except FileNotFoundError:
206
- return
207
- if not real_directory(info):
208
- raise OSError('unsafe destination')
209
- if os.name == 'posix' and (info.st_uid != os.geteuid() or info.st_mode & 0o022):
210
- raise OSError('unsafe destination permissions')
211
-
212
-
213
- @contextmanager
214
- def pinned_windows_entry(path, valid):
215
- # Open the entry itself, not its reparse target, and hold a handle that
216
- # denies writes and deletion/rename until the caller has finished.
217
- import ctypes
218
- from ctypes import wintypes
219
-
220
- kernel = ctypes.WinDLL('kernel32', use_last_error=True)
221
- open_dir = kernel.CreateFileW
222
- open_dir.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID,
223
- wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE)
224
- open_dir.restype = wintypes.HANDLE
225
- close = kernel.CloseHandle
226
- close.argtypes = (wintypes.HANDLE,)
227
- read_attributes = 0x80
228
- share_read_only = 0x1 # Deny write-data handles and deletion/rename.
229
- open_existing = 3
230
- backup_semantics = 0x02000000 # Also allow opening directory handles.
231
- open_reparse_point = 0x00200000
232
- handle = open_dir(str(path), read_attributes, share_read_only, None, open_existing,
233
- backup_semantics | open_reparse_point, None)
234
- if handle == ctypes.c_void_p(-1).value:
235
- raise ctypes.WinError(ctypes.get_last_error())
236
- try:
237
- if not valid(path.lstat()):
238
- raise OSError('unsafe destination entry')
239
- yield
240
- finally:
241
- close(handle)
242
-
243
-
244
- def pinned_windows_directory(path):
245
- return pinned_windows_entry(path, real_directory)
246
-
247
-
248
- def create_base(path, **kwargs):
249
- try:
250
- os.mkdir(path, 0o700, **kwargs)
251
- except FileExistsError:
252
- pass # The actual directory is checked when opened below.
253
-
254
-
255
- def write_report(path, payload, **kwargs):
256
- flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_BINARY', 0)
257
- with os.fdopen(os.open(path, flags, 0o600, **kwargs), 'wb') as stream:
258
- stream.write(payload)
259
-
260
-
261
- @contextmanager
262
- def open_directory(path, **kwargs):
263
- fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, **kwargs)
264
- try:
265
- yield fd
266
- finally:
267
- os.close(fd)
268
-
269
-
270
- def check_root_rule(fd):
271
- with os.fdopen(fd, 'rb') as stream:
272
- if not real_ignore_file(os.fstat(stream.fileno())):
273
- raise OSError('unsafe root ignore file')
274
- if not any(line in (b'/tmp_logs/\n', b'/tmp_logs/\r\n', b'/tmp_logs/') for line in stream):
275
- raise OSError('missing exact root ignore rule')
276
-
277
-
278
- def require_root_rule(root):
279
- if os.name == 'nt':
280
- path = root / '.gitignore'
281
- with pinned_windows_directory(root), pinned_windows_entry(path, real_ignore_file):
282
- check_root_rule(os.open(path, os.O_RDONLY | os.O_BINARY))
283
- elif os.name == 'posix' and hasattr(os, 'O_NOFOLLOW') and hasattr(os, 'O_DIRECTORY') and (
284
- os.open in os.supports_dir_fd):
285
- with open_directory(root) as root_fd:
286
- # Do not follow a symlink or block opening a substituted FIFO.
287
- flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
288
- check_root_rule(os.open('.gitignore', flags, dir_fd=root_fd))
289
- else:
290
- raise OSError('secure root ignore check unavailable')
291
-
292
-
293
- def save(root, session, report):
294
- payload = (json.dumps(report, indent=2, allow_nan=False) + '\n').encode('ascii')
295
- check_base(root)
296
- require_ignore(root, session)
297
- if os.name == 'nt':
298
- base = root / 'tmp_logs'
299
- with pinned_windows_directory(root):
300
- create_base(base)
301
- with pinned_windows_directory(base):
302
- target = base / session
303
- os.mkdir(target, 0o700)
304
- with pinned_windows_directory(target):
305
- write_report(target / ARTIFACT, payload)
306
- elif os.name == 'posix' and hasattr(os, 'O_NOFOLLOW') and hasattr(os, 'O_DIRECTORY') and (
307
- {os.open, os.mkdir} <= os.supports_dir_fd):
308
- with open_directory(root) as root_fd:
309
- create_base('tmp_logs', dir_fd=root_fd)
310
- with open_directory('tmp_logs', dir_fd=root_fd) as base_fd:
311
- info = os.fstat(base_fd)
312
- if info.st_uid != os.geteuid() or info.st_mode & 0o022:
313
- raise OSError('unsafe destination permissions')
314
- os.mkdir(session, 0o700, dir_fd=base_fd)
315
- with open_directory(session, dir_fd=base_fd) as target_fd:
316
- write_report(ARTIFACT, payload, dir_fd=target_fd)
317
- else:
318
- raise OSError('secure directory creation unavailable')
319
-
320
-
321
- def main(args):
322
- if args == ['--help']:
323
- print(HELP)
324
- return 0
325
- # runpy, not import: `python -I` keeps this directory off sys.path. Read only names
326
- # listed in watch-live.py's SHARED_API (enforced by tests/error-scan.test.sh).
327
- watcher = runpy.run_path(str(SCRIPTS / 'watch-live.py'))
328
- try:
329
- alias_ok = watcher['alias_pattern']()
330
- except watcher['ConfigError'] as error:
331
- print(error, file=sys.stderr)
332
- return 1
333
- no_save = args[:1] == ['--no-save']
334
- if no_save:
335
- args = args[1:]
336
- if (len(args) != 3 or args[0] not in ('live', 'sleuth', 'historical')
337
- or (no_save and args[0] != 'historical')
338
- or not alias_ok.fullmatch(args[1]) or not watcher['CONTAINER'].fullmatch(args[2])):
339
- print(INVALID, file=sys.stderr)
340
- return 1
341
- mode, alias, container = args
342
- if no_save:
343
- # Explicit no-save request: the same bounded batch and status policy, printed
344
- # only. Replaces the hand-run Bash pipeline the agent had to interpret.
345
- try:
346
- result = historical(alias, container)
347
- except (OSError, ValueError, subprocess.SubprocessError):
348
- result = None
349
- if result is None:
350
- print(FAILED.replace('; nothing saved.', '.'), file=sys.stderr)
351
- return 1
352
- print(result[0], end='')
353
- return 0
354
- try:
355
- root = worktree()
356
- session = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') + '-' + secrets.token_hex(16)
357
- check_base(root)
358
- require_ignore(root, session)
359
- except (OSError, ValueError, subprocess.SubprocessError):
360
- print(DESTINATION, file=sys.stderr)
361
- return 1
362
- try:
363
- result = (historical(alias, container) if mode == 'historical'
364
- else live(watcher, mode == 'sleuth', alias, container))
365
- except (OSError, ValueError, subprocess.SubprocessError):
366
- result = None
367
- if result is None:
368
- print(FAILED, file=sys.stderr)
369
- return 1
370
- output, report = result
371
- try:
372
- save(root, session, dict(report, mode=mode, source={'container': container}))
373
- except (OSError, ValueError, subprocess.SubprocessError):
374
- print(DESTINATION, file=sys.stderr)
375
- return 1
376
- print(output, end='')
377
- return 0
378
-
379
-
380
- if __name__ == '__main__':
381
- sys.exit(main(sys.argv[1:]))
@@ -1,113 +0,0 @@
1
- #!/usr/bin/env python3
2
- """summarize-logs.py: bounded keyword counts for one batch of container logs.
3
-
4
- Reads at most 32 KiB from stdin and prints three fixed lines:
5
- severity error=N warn=N info=N debug=N unknown=N
6
- category timeout=N connection=N auth=N other=N
7
- input cap=<yes|no> partial=<yes|no>
8
-
9
- Exit status: 0 complete, 3 the 32 KiB cap was reached, 4 an unterminated final
10
- record was discarded, 1 bad usage. Never echoes input; stderr stays silent.
11
-
12
- Also used as a library by save-counts.py (`summarize(data)`). Standard library
13
- only, so it runs the same on Linux, macOS and Windows (ADR 0001).
14
- """
15
-
16
- import re
17
- import sys
18
-
19
- CAP = 32768
20
- LEVEL_WINDOW = 12
21
- SEVERITY = {'error': 'error', 'fatal': 'error', 'panic': 'error', 'warn': 'warn', 'warning': 'warn',
22
- 'info': 'info', 'debug': 'debug', 'trace': 'debug'}
23
- SEPARATORS = re.compile(rb'[^A-Za-z0-9_]+')
24
- SIGNATURE = re.compile(r' (typeerror|unhandledpromiserejection|econnrefused|etimedout|econnreset|epipe|'
25
- r'eai_again|getaddrinfo|out of memory) | http 5[0-9][0-9] ')
26
- TIMEOUT = re.compile(r' (timeout|timed out) ')
27
- CONNECTION = re.compile(r' (connection|connect|disconnect(ed)?) ')
28
- AUTH = re.compile(r' (auth|authentication|unauthorized|forbidden) ')
29
-
30
-
31
- def numeric_level(value):
32
- if value >= 50:
33
- return 'error'
34
- if value >= 40:
35
- return 'warn'
36
- if value >= 30:
37
- return 'info'
38
- if value >= 10:
39
- return 'debug'
40
- return ''
41
-
42
-
43
- def record_level(tokens):
44
- """First recognised level token near the start: tolerates a leading timestamp
45
- or host header and ignores a severity word buried later in the message."""
46
- for i, token in enumerate(tokens[:LEVEL_WINDOW]):
47
- level = SEVERITY.get(token, '')
48
- if level:
49
- return level
50
- if token in ('level', 'lvl') and i + 1 < len(tokens) and tokens[i + 1].isdigit():
51
- level = numeric_level(int(tokens[i + 1]))
52
- if level:
53
- return level
54
- # Only [A-Za-z0-9_] reach a record, so JSON quotes never survive: a JSON
55
- # level ("level":"error" or "level":50) is matched by the token loop above.
56
- return ''
57
-
58
-
59
- def summarize(data):
60
- """Return (three-line summary, exit status) for at most CAP bytes."""
61
- data = data[:CAP]
62
- severity = dict.fromkeys(('error', 'warn', 'info', 'debug', 'unknown'), 0)
63
- category = dict.fromkeys(('timeout', 'connection', 'auth', 'other'), 0)
64
- *records, tail = data.split(b'\n')
65
- for raw in records:
66
- # Non-word byte runs become one space; ASCII-only lowercase (C locale).
67
- line = SEPARATORS.sub(b' ', raw).lower().decode('ascii')
68
- rec = ' ' + line + ' '
69
- level = record_level(rec.split()) # like awk split(rec, a, " "): no empty tokens
70
- if not level and SIGNATURE.search(rec):
71
- level = 'error'
72
- severity[level or 'unknown'] += 1
73
- if TIMEOUT.search(rec):
74
- category['timeout'] += 1
75
- elif CONNECTION.search(rec):
76
- category['connection'] += 1
77
- elif AUTH.search(rec):
78
- category['auth'] += 1
79
- else:
80
- category['other'] += 1
81
- cap = len(data) == CAP
82
- partial = bool(tail)
83
- text = ('severity ' + ' '.join(f'{k}={v}' for k, v in severity.items()) + '\n'
84
- 'category ' + ' '.join(f'{k}={v}' for k, v in category.items()) + '\n'
85
- f'input cap={"yes" if cap else "no"} partial={"yes" if partial else "no"}\n')
86
- return text, 3 if cap else 4 if partial else 0
87
-
88
-
89
- def read_capped(stream):
90
- chunks, size = [], 0
91
- while size < CAP:
92
- chunk = stream.read(CAP - size)
93
- if not chunk:
94
- break
95
- chunks.append(chunk)
96
- size += len(chunk)
97
- return b''.join(chunks)
98
-
99
-
100
- def main(argv):
101
- if argv:
102
- return 1
103
- try:
104
- text, status = summarize(read_capped(sys.stdin.buffer))
105
- sys.stdout.write(text)
106
- sys.stdout.flush()
107
- except (OSError, ValueError):
108
- return 1
109
- return status
110
-
111
-
112
- if __name__ == '__main__':
113
- sys.exit(main(sys.argv[1:]))