@bbcsoftwarefactory/skills 0.0.0-stage → 0.1.1
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.
- package/dist/index.json +42 -0
- package/dist/skills/code-quality-gate/SKILL.md +59 -0
- package/dist/skills/code-quality-gate/references/gate-bigo.md +31 -0
- package/dist/skills/code-quality-gate/references/gate-earlyreturn.md +73 -0
- package/dist/skills/code-quality-gate/references/gate-typesafe.md +32 -0
- package/dist/skills/code-quality-gate/references/output-schema.yml +40 -0
- package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +225 -0
- package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +200 -0
- package/dist/skills/delivery-coordinator/SKILL.md +81 -0
- package/dist/skills/delivery-coordinator/references/hud-output.md +55 -0
- package/dist/skills/delivery-coordinator/references/intake.md +86 -0
- package/dist/skills/delivery-coordinator/references/issue-claim.md +143 -0
- package/dist/skills/delivery-coordinator/references/issue-dedup.md +38 -0
- package/dist/skills/delivery-coordinator/references/sleuth-regression-exercise.md +60 -0
- package/dist/skills/delivery-coordinator/references/visual-reference.md +45 -0
- package/dist/skills/delivery-coordinator/references/worktree-isolation.md +19 -0
- package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +363 -0
- package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +220 -0
- package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +263 -0
- package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +221 -0
- package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +123 -0
- package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +124 -0
- package/dist/skills/documentation-steward/SKILL.md +43 -0
- package/dist/skills/documentation-steward/references/discovery.md +17 -0
- package/dist/skills/documentation-steward/references/handoff.md +15 -0
- package/dist/skills/greptile-review-loop/SKILL.md +57 -0
- package/dist/skills/greptile-review-loop/references/review-protocol.md +37 -0
- package/dist/skills/greptile-review-loop/scripts/review-loop.py +435 -0
- package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +331 -0
- package/dist/skills/issue-reviewer/SKILL.md +87 -0
- package/dist/skills/issue-reviewer/references/review-format.md +100 -0
- package/dist/skills/issue-reviewer/references/triage.md +105 -0
- package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +239 -0
- package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +311 -0
- package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +90 -0
- package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +168 -0
- package/dist/skills/question-gate/SKILL.md +66 -0
- package/dist/skills/question-gate/references/client-hooks.md +111 -0
- package/dist/skills/question-gate/references/diagram-routing.md +58 -0
- package/dist/skills/question-gate/scripts/triage-question.py +713 -0
- package/dist/skills/question-gate/tests/fixtures/question-corpus.json +481 -0
- package/dist/skills/question-gate/tests/question-corpus.test.sh +32 -0
- package/dist/skills/question-gate/tests/triage-question.test.sh +441 -0
- package/dist/skills/regression-testing/SKILL.md +49 -0
- package/dist/skills/regression-testing/references/evidence-record.md +35 -0
- package/dist/skills/requirements-spec/SKILL.md +59 -0
- package/dist/skills/risk-scout/SKILL.md +53 -0
- package/dist/skills/risk-scout/references/risk-matrix.md +49 -0
- package/dist/skills/skill-clean-architecture/SKILL.md +54 -0
- package/dist/skills/skill-clean-architecture/references/layer-rules.md +22 -0
- package/dist/skills/skill-clean-architecture/references/source-headers.md +31 -0
- package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +427 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/bad-utf8.js +1 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-crlf.ts +6 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-mixed.ts +15 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/empty.js +0 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/no-newline.js +1 -0
- package/dist/skills/skill-clean-architecture/tests/fixtures/bigo.expected.yml +95 -0
- package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +222 -0
- package/dist/skills/tool-depot/SKILL.md +47 -0
- package/dist/skills/tool-depot/references/checkout.md +29 -0
- package/dist/skills/tool-depot/references/loki-read.md +41 -0
- package/dist/skills/tool-depot/references/readonly-access.md +84 -0
- package/dist/skills/tool-depot/references/tool-catalog.json +47 -0
- package/dist/skills/tool-depot/scripts/loki-runtime-logs.py +305 -0
- package/dist/skills/tool-depot/tests/loki-runtime-logs.test.sh +101 -0
- package/dist/skills/watcher-observability/SKILL.md +73 -0
- package/dist/skills/watcher-observability/references/batch-protocol.md +44 -0
- package/dist/skills/watcher-observability/references/configuration.md +31 -0
- package/dist/skills/watcher-observability/references/error-scan.md +102 -0
- package/dist/skills/watcher-observability/references/live-protocol.md +49 -0
- package/dist/skills/watcher-observability/references/server-account.md +72 -0
- package/dist/skills/watcher-observability/scripts/error-scan.py +318 -0
- package/dist/skills/watcher-observability/scripts/resolve-containers.py +155 -0
- package/dist/skills/watcher-observability/scripts/save-counts.py +381 -0
- package/dist/skills/watcher-observability/scripts/summarize-logs.py +113 -0
- package/dist/skills/watcher-observability/scripts/watch-live.py +606 -0
- package/dist/skills/watcher-observability/server/watcher-gate.sh +51 -0
- package/dist/skills/watcher-observability/tests/error-scan.test.sh +257 -0
- package/dist/skills/watcher-observability/tests/live-windows.test.sh +177 -0
- package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +87 -0
- package/dist/skills/watcher-observability/tests/save-counts.test.sh +338 -0
- package/dist/skills/watcher-observability/tests/sleuth.test.sh +176 -0
- package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +105 -0
- package/dist/skills/watcher-observability/tests/watcher-config.test.sh +70 -0
- package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +110 -0
- package/dist/skills/watcher-observability/watcher.json +1 -0
- package/dist/skills/workflow-auditor/SKILL.md +55 -0
- package/dist/skills/workflow-auditor/references/audit-protocol.md +49 -0
- package/dist/skills/workflow-auditor/references/ledger.md +122 -0
- package/dist/skills/workflow-auditor/scripts/audit-ledger.py +624 -0
- package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +183 -0
- package/dist/skills/workflow-auditor/scripts/render-workflow.py +201 -0
- package/dist/skills/workflow-auditor/scripts/validate-skills.py +444 -0
- package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +660 -0
- package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +93 -0
- package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +135 -0
- package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +190 -0
- package/package.json +27 -6
- package/README.md +0 -3
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
"""Opt-in live Docker log observation; no arguments configure the capture budget."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from queue import Empty, Full, Queue
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from threading import Event, Thread
|
|
11
|
+
from time import monotonic
|
|
12
|
+
|
|
13
|
+
WINDOW_SECONDS = 15
|
|
14
|
+
WINDOWS = 4
|
|
15
|
+
BYTE_LIMIT = 32_768
|
|
16
|
+
READ_SIZE = 4096
|
|
17
|
+
|
|
18
|
+
PATTERNS = (
|
|
19
|
+
('TypeError', r'\bTypeError\b'),
|
|
20
|
+
('UnhandledPromiseRejection', r'\bUnhandledPromiseRejection(?:Warning)?\b'),
|
|
21
|
+
('ECONNREFUSED', r'\bECONNREFUSED\b'),
|
|
22
|
+
('ETIMEDOUT', r'\bETIMEDOUT\b'),
|
|
23
|
+
('ECONNRESET', r'\bECONNRESET\b'),
|
|
24
|
+
('EPIPE', r'\bEPIPE\b'),
|
|
25
|
+
('ENOTFOUND', r'\bENOTFOUND\b|\bEAI_AGAIN\b|\bgetaddrinfo\b'),
|
|
26
|
+
('HTTP_5xx', r'\bHTTP(?:/\d+(?:\.\d+)?)?\s+5\d{2}\b'),
|
|
27
|
+
('OutOfMemory', r'\b(?:JavaScript )?[Hh]eap [Oo]ut [Oo]f [Mm]emory\b|\bOutOfMemory(?:Error)?\b'),
|
|
28
|
+
)
|
|
29
|
+
PLAIN_PATTERNS = tuple(re.compile(expr, re.ASCII | re.I) for _, expr in PATTERNS)
|
|
30
|
+
JSON_NAMES = {name.lower(): i for i, (name, _) in enumerate(PATTERNS)}
|
|
31
|
+
JSON_NAMES['unhandledpromiserejectionwarning'] = 1
|
|
32
|
+
LEVELS = {
|
|
33
|
+
'error': 'error', 'fatal': 'error', 'panic': 'error',
|
|
34
|
+
'warn': 'warn', 'warning': 'warn', 'info': 'info', 'debug': 'debug', 'trace': 'debug',
|
|
35
|
+
}
|
|
36
|
+
LEVEL_NAMES = '|'.join(LEVELS)
|
|
37
|
+
PLAIN_LEVEL = re.compile(rf'^({LEVEL_NAMES})(?=$|[\s:\]])|\[({LEVEL_NAMES})\]', re.ASCII | re.I)
|
|
38
|
+
# Most runtimes emit a structured header (timestamp, sometimes host/pid) before
|
|
39
|
+
# the level: "16:40:08 INFO ..." or "2026-11-26T16:40:08.123Z WARN ...".
|
|
40
|
+
# Without stripping it the level never matches and every record is unclassified.
|
|
41
|
+
TIMESTAMP = re.compile(
|
|
42
|
+
r'^(?:\[\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?\]'
|
|
43
|
+
r'|\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?'
|
|
44
|
+
r'|\d{1,2}:\d{2}:\d{2}(?:[.,]\d+)?'
|
|
45
|
+
r'|\d{4}/\d{2}/\d{2}[ T]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?)\s+', re.ASCII)
|
|
46
|
+
NUMERIC_LEVELS = ((60, 'error'), (50, 'error'), (40, 'warn'), (30, 'info'), (20, 'debug'), (10, 'debug'))
|
|
47
|
+
JSON_LEVEL_FIELDS = ('level', 'severity', 'severityText', 'severity_text', 'lvl', 'logLevel')
|
|
48
|
+
JSON_ERROR_FIELDS = ('error', 'err', 'exception')
|
|
49
|
+
# Common Node/Java/Python continuation lines, not independent incidents.
|
|
50
|
+
PYTHON_FILE = re.compile(r'^File "[^"\n]+", line \d+\b')
|
|
51
|
+
FRAME = re.compile(r'^(?:at\s+\S|Traceback \(most recent call last\):|'
|
|
52
|
+
r'Caused by:|\.\.\. \d+ more\b)')
|
|
53
|
+
CONTROL = re.compile(r'^(?:}\s*)?(?:try|catch)\s*(?:\(|\{|$)')
|
|
54
|
+
|
|
55
|
+
# #60: which SSH aliases the Watcher accepts is configuration, not code. The skill
|
|
56
|
+
# ships watcher.json with the default prefixes; a project overrides them with
|
|
57
|
+
# .watcher.json at the root of its Git repository. Every script validates the alias
|
|
58
|
+
# with alias_pattern() before any process starts, so a bad file never reaches SSH.
|
|
59
|
+
SKILL_CONFIG = Path(__file__).resolve().parent.parent / 'watcher.json'
|
|
60
|
+
PROJECT_CONFIG = '.watcher.json'
|
|
61
|
+
PREFIX = re.compile(r'[a-z0-9]{1,16}', re.ASCII)
|
|
62
|
+
MAX_PREFIXES = 8
|
|
63
|
+
MAX_CONFIG_BYTES = 4096
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ConfigError(ValueError):
|
|
67
|
+
"""The Watcher configuration is missing or invalid; nothing may connect."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def git_root(start):
|
|
71
|
+
for folder in (start, *start.parents):
|
|
72
|
+
if (folder / '.git').exists():
|
|
73
|
+
return folder
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def config_path(cwd=None):
|
|
78
|
+
root = git_root(Path(cwd or Path.cwd()).resolve())
|
|
79
|
+
override = root / PROJECT_CONFIG if root else None
|
|
80
|
+
return override if override is not None and override.is_file() else SKILL_CONFIG
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def alias_prefixes(cwd=None):
|
|
84
|
+
path = config_path(cwd)
|
|
85
|
+
try:
|
|
86
|
+
with open(path, 'rb') as handle:
|
|
87
|
+
raw = handle.read(MAX_CONFIG_BYTES + 1)
|
|
88
|
+
if len(raw) > MAX_CONFIG_BYTES:
|
|
89
|
+
raise ValueError('file too large')
|
|
90
|
+
data = json.loads(raw.decode('utf-8'), object_pairs_hook=unique_object,
|
|
91
|
+
parse_constant=reject_constant)
|
|
92
|
+
except (OSError, ValueError) as error:
|
|
93
|
+
raise ConfigError(f'Watcher configuration {path.name} is unreadable: {error}') from None
|
|
94
|
+
prefixes = data.get('alias_prefixes') if isinstance(data, dict) else None
|
|
95
|
+
if (not isinstance(data, dict) or set(data) != {'alias_prefixes'} or not isinstance(prefixes, list)
|
|
96
|
+
or not 1 <= len(prefixes) <= MAX_PREFIXES or len(set(map(str, prefixes))) != len(prefixes)
|
|
97
|
+
or not all(isinstance(p, str) and PREFIX.fullmatch(p) for p in prefixes)):
|
|
98
|
+
raise ConfigError(f'Watcher configuration {path.name} is invalid: it must be '
|
|
99
|
+
f'{{"alias_prefixes": [...]}} with 1-{MAX_PREFIXES} unique prefixes '
|
|
100
|
+
'of 1-16 characters a-z or 0-9.')
|
|
101
|
+
return tuple(prefixes)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def alias_pattern(cwd=None):
|
|
105
|
+
"""Return the compiled alias grammar for the active configuration."""
|
|
106
|
+
choices = '|'.join(re.escape(p) for p in alias_prefixes(cwd))
|
|
107
|
+
return re.compile(rf'(?:{choices})-[a-z0-9][a-z0-9-]*', re.ASCII)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
CONTAINER = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.-]*', re.ASCII)
|
|
111
|
+
|
|
112
|
+
INVALID = 'Watcher live mode requires a valid SSH alias and exact container name or ID.'
|
|
113
|
+
FAILED = 'Watcher live capture failed; no counts.'
|
|
114
|
+
HELP = ('Usage: python -I -B scripts/watch-live.py <ssh-alias> <exact-container>\n'
|
|
115
|
+
'Observe one authorized container for 60 seconds; report four 15-second windows.')
|
|
116
|
+
|
|
117
|
+
SLEUTH_HELP = ('Usage: python -I -B scripts/watch-live.py --sleuth <ssh-alias> <exact-container>\n'
|
|
118
|
+
'Add bounded, redacted evidence to the live summary; no raw IDs or logs.')
|
|
119
|
+
ID_FIELDS = {
|
|
120
|
+
'trace': ('traceId', 'trace_id'),
|
|
121
|
+
'request': ('requestId', 'request_id'),
|
|
122
|
+
'correlation': ('correlationId', 'correlation_id'),
|
|
123
|
+
}
|
|
124
|
+
EXCEPTIONS = {name: name for name in ('TypeError', 'ValueError', 'TimeoutError',
|
|
125
|
+
'ConnectionError', 'ReferenceError', 'RangeError',
|
|
126
|
+
'UnhandledPromiseRejection')}
|
|
127
|
+
EXCEPTIONS['UnhandledPromiseRejectionWarning'] = 'UnhandledPromiseRejection'
|
|
128
|
+
CODES = {name: name for name in ('ECONNREFUSED', 'ETIMEDOUT', 'ECONNRESET', 'EPIPE')}
|
|
129
|
+
WORDS = {word: word for word in ('connection', 'refused', 'timeout', 'timed', 'out',
|
|
130
|
+
'reset', 'upstream', 'unavailable', *CODES)}
|
|
131
|
+
REDACTED = '[redacted]'
|
|
132
|
+
SLEUTH_FRAMES = (
|
|
133
|
+
('python', re.compile(r'File "[^"\r\n]+", line ([0-9]{1,6})(?:, in [^\r\n]+)?')),
|
|
134
|
+
('node', re.compile(r'at [^\s()]+ \([^()\s]+:([0-9]{1,6}):[0-9]{1,6}\)')),
|
|
135
|
+
('java', re.compile(r'at [\w.$]+\([\w.$]+\.java:([0-9]{1,6})\)', re.ASCII)),
|
|
136
|
+
)
|
|
137
|
+
PLAIN_DIAGNOSTIC = re.compile(r'(?:(Caused by:) )?([A-Za-z]+)(?:: *(.*))?', re.ASCII)
|
|
138
|
+
EVENT_LIMIT, ID_LIMIT, FRAME_LIMIT, EXCERPT_LIMIT, WORD_LIMIT = 24, 16, 3, 4, 12
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def unique_object(pairs):
|
|
142
|
+
record = {}
|
|
143
|
+
for key, value in pairs:
|
|
144
|
+
if key in record:
|
|
145
|
+
raise ValueError('duplicate key')
|
|
146
|
+
record[key] = value
|
|
147
|
+
return record
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def reject_constant(_value):
|
|
151
|
+
raise ValueError('invalid JSON constant')
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def object_or_empty(value):
|
|
155
|
+
return value if isinstance(value, dict) else {}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def allowlisted(value, table):
|
|
159
|
+
return table.get(value) if isinstance(value, str) else None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def python_source_continuation(raw, after_file):
|
|
163
|
+
return after_file and raw.startswith(' ')
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def eligible_stack_lines(stack):
|
|
167
|
+
after_file = False
|
|
168
|
+
for raw in stack.split('\n'):
|
|
169
|
+
if python_source_continuation(raw, after_file):
|
|
170
|
+
continue
|
|
171
|
+
text = raw.strip()
|
|
172
|
+
after_file = bool(PYTHON_FILE.match(text))
|
|
173
|
+
yield text
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def frame_location(text):
|
|
177
|
+
for kind, pattern in SLEUTH_FRAMES:
|
|
178
|
+
match = pattern.fullmatch(text)
|
|
179
|
+
if match:
|
|
180
|
+
return {'kind': kind, 'line': int(match[1])}
|
|
181
|
+
return None
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def redacted_excerpt(message):
|
|
185
|
+
# Reconstruct from fixed strings only; punctuation, controls and composite
|
|
186
|
+
# tokens (URLs, paths, assignments, etc.) never supply output characters.
|
|
187
|
+
tokens = message.split() if isinstance(message, str) else []
|
|
188
|
+
fragment = []
|
|
189
|
+
for token in tokens[:WORD_LIMIT]:
|
|
190
|
+
word = WORDS.get(token, REDACTED)
|
|
191
|
+
if word != REDACTED or not fragment or fragment[-1] != REDACTED:
|
|
192
|
+
fragment.append(word)
|
|
193
|
+
truncated = len(tokens) > WORD_LIMIT
|
|
194
|
+
if not any(word != REDACTED for word in fragment):
|
|
195
|
+
return None, False
|
|
196
|
+
if truncated and fragment[-1] != REDACTED:
|
|
197
|
+
fragment.append(REDACTED)
|
|
198
|
+
return ' '.join(fragment), truncated
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class Sleuth:
|
|
202
|
+
def __init__(self):
|
|
203
|
+
self.window = 1
|
|
204
|
+
self.rows = []
|
|
205
|
+
self.labels = {}
|
|
206
|
+
self.excerpts = 0
|
|
207
|
+
self.limits = dict.fromkeys(('records', 'unselected_records', 'invalid_records',
|
|
208
|
+
'event_drops', 'id_drops', 'frame_drops', 'excerpt_drops',
|
|
209
|
+
'excerpt_truncations', 'dropped_bytes'), 0)
|
|
210
|
+
|
|
211
|
+
def label(self, kind, value):
|
|
212
|
+
key = (kind, value)
|
|
213
|
+
if key not in self.labels:
|
|
214
|
+
if len(self.labels) == ID_LIMIT:
|
|
215
|
+
self.limits['id_drops'] += 1
|
|
216
|
+
return None
|
|
217
|
+
self.labels[key] = f'id{len(self.labels) + 1}'
|
|
218
|
+
return self.labels[key]
|
|
219
|
+
|
|
220
|
+
def select(self, raw, source_line):
|
|
221
|
+
self.limits['records'] += 1
|
|
222
|
+
if source_line:
|
|
223
|
+
self.limits['unselected_records'] += 1
|
|
224
|
+
return
|
|
225
|
+
try:
|
|
226
|
+
body = strip_headers(raw.decode('utf-8').strip())
|
|
227
|
+
level_prefix = PLAIN_LEVEL.match(body)
|
|
228
|
+
plain = body[level_prefix.end():].strip() if level_prefix else body
|
|
229
|
+
brace = body.find('{')
|
|
230
|
+
is_object = brace >= 0 and body.rstrip().endswith('}')
|
|
231
|
+
record = (json.loads(body[brace:], object_pairs_hook=unique_object, parse_constant=reject_constant)
|
|
232
|
+
if is_object else {})
|
|
233
|
+
except (ValueError, RecursionError):
|
|
234
|
+
self.limits['invalid_records'] += 1
|
|
235
|
+
return
|
|
236
|
+
candidates = {}
|
|
237
|
+
for kind, keys in ID_FIELDS.items():
|
|
238
|
+
values = [record[key] for key in keys if key in record]
|
|
239
|
+
if values:
|
|
240
|
+
if (all(isinstance(value, str) and 0 < len(value) <= 128 for value in values)
|
|
241
|
+
and all(value == values[0] for value in values)):
|
|
242
|
+
candidates[kind] = values[0]
|
|
243
|
+
else:
|
|
244
|
+
self.limits['id_drops'] += 1
|
|
245
|
+
|
|
246
|
+
error = object_or_empty(record.get('error'))
|
|
247
|
+
cause = object_or_empty(error.get('cause'))
|
|
248
|
+
fields = {}
|
|
249
|
+
for key, value, table in (
|
|
250
|
+
('exception', error.get('name'), EXCEPTIONS), ('cause', cause.get('name'), EXCEPTIONS),
|
|
251
|
+
('code', error.get('code'), CODES), ('cause_code', cause.get('code'), CODES),
|
|
252
|
+
):
|
|
253
|
+
fixed = allowlisted(value, table)
|
|
254
|
+
if fixed:
|
|
255
|
+
fields[key] = fixed
|
|
256
|
+
status = record.get('status')
|
|
257
|
+
if type(status) is int and status == 503:
|
|
258
|
+
fields['status'] = 503
|
|
259
|
+
|
|
260
|
+
stack = error.get('stack')
|
|
261
|
+
frame_lines = eligible_stack_lines(stack) if isinstance(stack, str) else ()
|
|
262
|
+
message = record.get('message')
|
|
263
|
+
if not is_object:
|
|
264
|
+
frame_lines = [plain]
|
|
265
|
+
match = PLAIN_DIAGNOSTIC.fullmatch(plain)
|
|
266
|
+
if match:
|
|
267
|
+
cause_prefix, name, detail = match.groups()
|
|
268
|
+
if name in EXCEPTIONS:
|
|
269
|
+
fields['cause' if cause_prefix else 'exception'] = EXCEPTIONS[name]
|
|
270
|
+
message = detail
|
|
271
|
+
elif name in CODES and not cause_prefix:
|
|
272
|
+
fields['code'] = CODES[name]
|
|
273
|
+
message = detail
|
|
274
|
+
frames = [frame for line in frame_lines if (frame := frame_location(line))]
|
|
275
|
+
excerpt, truncated = redacted_excerpt(message)
|
|
276
|
+
if not (candidates or fields or frames or excerpt):
|
|
277
|
+
self.limits['unselected_records'] += 1
|
|
278
|
+
return
|
|
279
|
+
if len(self.rows) == EVENT_LIMIT:
|
|
280
|
+
self.limits['event_drops'] += 1
|
|
281
|
+
return
|
|
282
|
+
|
|
283
|
+
row = {'window': self.window, 'seq': self.limits['records']}
|
|
284
|
+
level = json_level(record) if is_object else None
|
|
285
|
+
if level is None:
|
|
286
|
+
match = PLAIN_LEVEL.search(body)
|
|
287
|
+
level = LEVELS[(match[1] or match[2]).lower()] if match else None
|
|
288
|
+
if frames:
|
|
289
|
+
fields['frames'] = frames[:FRAME_LIMIT]
|
|
290
|
+
self.limits['frame_drops'] += max(0, len(frames) - FRAME_LIMIT)
|
|
291
|
+
if excerpt:
|
|
292
|
+
if self.excerpts < EXCERPT_LIMIT:
|
|
293
|
+
fields['excerpt'] = excerpt
|
|
294
|
+
self.excerpts += 1
|
|
295
|
+
self.limits['excerpt_truncations'] += truncated
|
|
296
|
+
else:
|
|
297
|
+
self.limits['excerpt_drops'] += 1
|
|
298
|
+
# A bare request id on an INFO line is linkage, not evidence: only rows
|
|
299
|
+
# carrying signal fields or warn/error severity are worth emitting, or
|
|
300
|
+
# the event budget fills with chatter and the real signal is dropped.
|
|
301
|
+
if not fields and level not in ('error', 'warn'):
|
|
302
|
+
self.limits['unselected_records'] += 1
|
|
303
|
+
return
|
|
304
|
+
# Labels are allocated only for emitted evidence, so INFO chatter with
|
|
305
|
+
# request ids cannot consume the 16-label budget for the interesting rows.
|
|
306
|
+
ids = {kind: label for kind, value in candidates.items() if (label := self.label(kind, value))}
|
|
307
|
+
if ids:
|
|
308
|
+
row['ids'] = ids
|
|
309
|
+
if level:
|
|
310
|
+
row['level'] = level
|
|
311
|
+
row.update(fields)
|
|
312
|
+
self.rows.append(row)
|
|
313
|
+
|
|
314
|
+
def finish(self):
|
|
315
|
+
# Export selected rows and counters only, never the raw ID lookup.
|
|
316
|
+
return {'status': 'authorized_sleuth', 'events': self.rows,
|
|
317
|
+
'coverage': dict(self.limits, coverage='incomplete')}
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def live_output(rows, evidence):
|
|
321
|
+
yield 'live status=deadline'
|
|
322
|
+
yield from rows
|
|
323
|
+
if evidence is not None:
|
|
324
|
+
for row in (*evidence['events'], evidence['coverage']):
|
|
325
|
+
yield 'sleuth ' + json.dumps(row, separators=(',', ':'))
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def json_level(record):
|
|
329
|
+
"""Severity from common JSON shapes: string level, OTel severity, bunyan numbers."""
|
|
330
|
+
for field in JSON_LEVEL_FIELDS:
|
|
331
|
+
value = record.get(field)
|
|
332
|
+
if isinstance(value, str):
|
|
333
|
+
name = LEVELS.get(value.lower())
|
|
334
|
+
if name is not None:
|
|
335
|
+
return name
|
|
336
|
+
if value.isdigit():
|
|
337
|
+
value = int(value)
|
|
338
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
339
|
+
for threshold, name in NUMERIC_LEVELS:
|
|
340
|
+
if value >= threshold:
|
|
341
|
+
return name
|
|
342
|
+
return None
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def json_hit(record):
|
|
346
|
+
"""First recognised error name or code in common error field shapes."""
|
|
347
|
+
for field in JSON_ERROR_FIELDS:
|
|
348
|
+
value = record.get(field)
|
|
349
|
+
if isinstance(value, dict):
|
|
350
|
+
for key in ('name', 'code', 'type'):
|
|
351
|
+
candidate = value.get(key)
|
|
352
|
+
if isinstance(candidate, str) and candidate.lower() in JSON_NAMES:
|
|
353
|
+
return JSON_NAMES[candidate.lower()]
|
|
354
|
+
elif isinstance(value, str) and value.lower() in JSON_NAMES:
|
|
355
|
+
return JSON_NAMES[value.lower()]
|
|
356
|
+
return None
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def strip_headers(text, limit=3):
|
|
360
|
+
"""Remove up to `limit` leading structured headers (docker timestamp + app timestamp)."""
|
|
361
|
+
for _ in range(limit):
|
|
362
|
+
stripped = TIMESTAMP.sub('', text, count=1)
|
|
363
|
+
if stripped == text:
|
|
364
|
+
break
|
|
365
|
+
text = stripped
|
|
366
|
+
return text
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
class Window:
|
|
370
|
+
def __init__(self, continuing=False, python_frame=False, sleuth=None):
|
|
371
|
+
self.sleuth = sleuth
|
|
372
|
+
self.continuing = continuing
|
|
373
|
+
self.python_frame = python_frame
|
|
374
|
+
self.bytes = 0
|
|
375
|
+
self.dropped = 0
|
|
376
|
+
self.partial = bytearray()
|
|
377
|
+
self.counts = dict.fromkeys(('error', 'warn', 'info', 'debug', 'unclassified', 'frames'), 0)
|
|
378
|
+
self.hits = [0] * len(PATTERNS)
|
|
379
|
+
|
|
380
|
+
def classify(self):
|
|
381
|
+
raw = self.partial.decode('utf-8', errors='replace')
|
|
382
|
+
source_line = python_source_continuation(raw, self.python_frame)
|
|
383
|
+
if self.sleuth is not None:
|
|
384
|
+
self.sleuth.select(self.partial, source_line)
|
|
385
|
+
text = raw.strip()
|
|
386
|
+
# Indented source and caret lines belong to the preceding file frame.
|
|
387
|
+
if source_line:
|
|
388
|
+
self.counts['frames'] += 1
|
|
389
|
+
return
|
|
390
|
+
self.python_frame = bool(PYTHON_FILE.match(text))
|
|
391
|
+
if self.python_frame or FRAME.match(text):
|
|
392
|
+
self.counts['frames'] += 1
|
|
393
|
+
return
|
|
394
|
+
if CONTROL.match(text):
|
|
395
|
+
self.counts['unclassified'] += 1
|
|
396
|
+
return
|
|
397
|
+
|
|
398
|
+
body = strip_headers(text)
|
|
399
|
+
record = None
|
|
400
|
+
brace = body.find('{')
|
|
401
|
+
if brace >= 0 and body.rstrip().endswith('}'):
|
|
402
|
+
try:
|
|
403
|
+
record = json.loads(body[brace:])
|
|
404
|
+
except (ValueError, RecursionError):
|
|
405
|
+
record = None
|
|
406
|
+
|
|
407
|
+
level = json_level(record) if isinstance(record, dict) else None
|
|
408
|
+
hit = json_hit(record) if isinstance(record, dict) else None
|
|
409
|
+
if level is None:
|
|
410
|
+
match = PLAIN_LEVEL.search(body)
|
|
411
|
+
level = LEVELS[(match[1] or match[2]).lower()] if match else None
|
|
412
|
+
if hit is None:
|
|
413
|
+
hit = next((i for i, regex in enumerate(PLAIN_PATTERNS) if regex.search(body)), None)
|
|
414
|
+
|
|
415
|
+
self.counts[level or ('error' if hit is not None else 'unclassified')] += 1
|
|
416
|
+
if hit is not None:
|
|
417
|
+
self.hits[hit] += 1
|
|
418
|
+
|
|
419
|
+
def discard_partial(self):
|
|
420
|
+
if self.partial:
|
|
421
|
+
self.dropped += len(self.partial)
|
|
422
|
+
self.partial.clear()
|
|
423
|
+
self.continuing = True
|
|
424
|
+
self.python_frame = False
|
|
425
|
+
|
|
426
|
+
def feed(self, data):
|
|
427
|
+
# Drain over-budget input without parsing it or retaining a record suffix.
|
|
428
|
+
take = min(len(data), BYTE_LIMIT - self.bytes)
|
|
429
|
+
self.bytes += take
|
|
430
|
+
start = 0
|
|
431
|
+
while start < take:
|
|
432
|
+
lf = data.find(b'\n', start, take)
|
|
433
|
+
end = lf + 1 if lf >= 0 else take
|
|
434
|
+
if self.continuing:
|
|
435
|
+
self.dropped += end - start
|
|
436
|
+
else:
|
|
437
|
+
self.partial.extend(data[start:lf if lf >= 0 else end])
|
|
438
|
+
if lf >= 0:
|
|
439
|
+
self.classify()
|
|
440
|
+
self.partial.clear()
|
|
441
|
+
if lf >= 0:
|
|
442
|
+
self.continuing = False
|
|
443
|
+
start = end
|
|
444
|
+
if take < len(data):
|
|
445
|
+
self.discard_partial()
|
|
446
|
+
self.dropped += len(data) - take
|
|
447
|
+
self.continuing = not data.endswith(b'\n')
|
|
448
|
+
self.python_frame = False
|
|
449
|
+
|
|
450
|
+
def finish(self, idx):
|
|
451
|
+
self.discard_partial()
|
|
452
|
+
if self.sleuth is not None:
|
|
453
|
+
self.sleuth.limits['dropped_bytes'] += self.dropped
|
|
454
|
+
self.sleuth.window = idx + 1
|
|
455
|
+
counts = ' '.join(f'{name}={count}' for name, count in self.counts.items())
|
|
456
|
+
ranked = sorted(zip(PATTERNS, self.hits), key=lambda item: -item[1])
|
|
457
|
+
top = ','.join(f'{name}:{count}' for ((name, _), count) in ranked)
|
|
458
|
+
return f'window={idx} {counts} dropped_bytes={self.dropped} top={top}'
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
class Stream:
|
|
462
|
+
def __init__(self, argv):
|
|
463
|
+
self.process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
|
464
|
+
stderr=subprocess.STDOUT, bufsize=0)
|
|
465
|
+
self.queue = Queue(maxsize=1)
|
|
466
|
+
self.closed = Event()
|
|
467
|
+
self.reader = Thread(target=self._read, daemon=True)
|
|
468
|
+
try:
|
|
469
|
+
self.reader.start()
|
|
470
|
+
except RuntimeError:
|
|
471
|
+
with self.process.stdout:
|
|
472
|
+
self.process.kill()
|
|
473
|
+
self.process.wait(timeout=1)
|
|
474
|
+
raise
|
|
475
|
+
|
|
476
|
+
def _read(self):
|
|
477
|
+
with self.process.stdout as pipe:
|
|
478
|
+
while not self.closed.is_set():
|
|
479
|
+
try:
|
|
480
|
+
data = pipe.read(READ_SIZE)
|
|
481
|
+
except OSError:
|
|
482
|
+
data = b''
|
|
483
|
+
while not self.closed.is_set():
|
|
484
|
+
try:
|
|
485
|
+
self.queue.put(data, timeout=0.05)
|
|
486
|
+
break
|
|
487
|
+
except Full:
|
|
488
|
+
pass
|
|
489
|
+
if not data:
|
|
490
|
+
return
|
|
491
|
+
|
|
492
|
+
def read_until(self, deadline):
|
|
493
|
+
try:
|
|
494
|
+
return self.queue.get(timeout=max(0, deadline - monotonic()))
|
|
495
|
+
except Empty:
|
|
496
|
+
return None
|
|
497
|
+
|
|
498
|
+
def stop(self):
|
|
499
|
+
self.closed.set()
|
|
500
|
+
running = self.process.poll() is None
|
|
501
|
+
if running:
|
|
502
|
+
self.process.kill()
|
|
503
|
+
self.process.wait(timeout=1)
|
|
504
|
+
self.reader.join(timeout=1)
|
|
505
|
+
return running and not self.reader.is_alive()
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def start(argv):
|
|
509
|
+
return Stream(argv)
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def observe(argv, sleuth=None):
|
|
513
|
+
started = monotonic()
|
|
514
|
+
stream = start(argv)
|
|
515
|
+
rows = []
|
|
516
|
+
window = Window(sleuth=sleuth)
|
|
517
|
+
pending = None
|
|
518
|
+
try:
|
|
519
|
+
for idx in range(1, WINDOWS + 1):
|
|
520
|
+
deadline = started + idx * WINDOW_SECONDS
|
|
521
|
+
# Pending data sampled on/after a boundary belongs to the next window.
|
|
522
|
+
while monotonic() < deadline:
|
|
523
|
+
if pending is not None:
|
|
524
|
+
window.feed(pending)
|
|
525
|
+
pending = None
|
|
526
|
+
data = stream.read_until(deadline)
|
|
527
|
+
if data == b'':
|
|
528
|
+
return None # Unexpected EOF, including a clean early end.
|
|
529
|
+
if data is None:
|
|
530
|
+
break
|
|
531
|
+
pending = data
|
|
532
|
+
if idx == WINDOWS and pending is not None:
|
|
533
|
+
window.dropped += len(pending)
|
|
534
|
+
rows.append(window.finish(idx))
|
|
535
|
+
window = Window(window.continuing, window.python_frame, sleuth)
|
|
536
|
+
finally:
|
|
537
|
+
stopped = stream.stop()
|
|
538
|
+
return rows if stopped else None
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
class InvalidTarget(ValueError):
|
|
542
|
+
pass
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def capture(alias, container, sleuth_requested):
|
|
546
|
+
if not alias_pattern().fullmatch(alias) or not CONTAINER.fullmatch(container):
|
|
547
|
+
raise InvalidTarget
|
|
548
|
+
try:
|
|
549
|
+
# Only SSH is needed (ADR 0001). The exact target is already validated above
|
|
550
|
+
# with the same alias_pattern() and CONTAINER rules as resolve-containers.py; the old
|
|
551
|
+
# `bash -p resolve-containers.sh` call repeated them and made Bash mandatory.
|
|
552
|
+
ssh = shutil.which('ssh')
|
|
553
|
+
if ssh:
|
|
554
|
+
sleuth = Sleuth() if sleuth_requested else None
|
|
555
|
+
rows = observe([ssh, '-nT', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes',
|
|
556
|
+
'-o', 'UpdateHostKeys=no', '-o', 'ClearAllForwardings=yes', '-o',
|
|
557
|
+
'PermitLocalCommand=no', '-o', 'ControlPath=none', alias,
|
|
558
|
+
'docker', 'logs', '-f', '--tail=0', '--', container], sleuth)
|
|
559
|
+
if rows is not None:
|
|
560
|
+
return rows, sleuth.finish() if sleuth is not None else None
|
|
561
|
+
except (OSError, RuntimeError, subprocess.SubprocessError):
|
|
562
|
+
pass
|
|
563
|
+
return None
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def main(args):
|
|
567
|
+
if args == ['--help']:
|
|
568
|
+
print(HELP)
|
|
569
|
+
return 0
|
|
570
|
+
sleuth_requested = args[:1] == ['--sleuth']
|
|
571
|
+
if sleuth_requested:
|
|
572
|
+
args = args[1:]
|
|
573
|
+
if args == ['--help']:
|
|
574
|
+
print(SLEUTH_HELP)
|
|
575
|
+
return 0
|
|
576
|
+
try:
|
|
577
|
+
if len(args) != 2:
|
|
578
|
+
raise InvalidTarget
|
|
579
|
+
result = capture(args[0], args[1], sleuth_requested)
|
|
580
|
+
except ConfigError as error:
|
|
581
|
+
print(error, file=sys.stderr)
|
|
582
|
+
return 1
|
|
583
|
+
except InvalidTarget:
|
|
584
|
+
print(INVALID, file=sys.stderr)
|
|
585
|
+
return 1
|
|
586
|
+
if result is None:
|
|
587
|
+
print(FAILED, file=sys.stderr)
|
|
588
|
+
return 1
|
|
589
|
+
print(*live_output(*result), sep='\n')
|
|
590
|
+
return 0
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
# Names that error-scan.py and save-counts.py may read from this module. They load
|
|
594
|
+
# it with runpy.run_path because `python -I` keeps the script directory off
|
|
595
|
+
# sys.path, so a plain import cannot find a sibling file. Module level holds only
|
|
596
|
+
# definitions; main() runs under the __main__ guard. Renaming or removing any name
|
|
597
|
+
# here is a breaking change for those scripts; tests/error-scan.test.sh enforces it.
|
|
598
|
+
SHARED_API = (
|
|
599
|
+
'alias_pattern', 'ConfigError', 'CONTAINER', 'PATTERNS', 'PLAIN_PATTERNS', 'PLAIN_LEVEL', 'LEVELS', 'TIMESTAMP',
|
|
600
|
+
'CODES', 'EXCEPTIONS', 'WINDOWS', 'WINDOW_SECONDS', 'BYTE_LIMIT',
|
|
601
|
+
'strip_headers', 'json_level', 'json_hit', 'capture', 'live_output',
|
|
602
|
+
)
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
if __name__ == '__main__':
|
|
606
|
+
sys.exit(main(sys.argv[1:]))
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# watcher-gate.sh: SSH forced command for the Watcher's read-only server account.
|
|
3
|
+
#
|
|
4
|
+
# Install it on the server and bind it to the Watcher key in authorized_keys:
|
|
5
|
+
# restrict,command="/usr/local/bin/watcher-gate.sh" ssh-ed25519 AAAA... watcher
|
|
6
|
+
# See ../references/server-account.md for the full procedure.
|
|
7
|
+
#
|
|
8
|
+
# The Watcher scripts send exactly five remote command shapes. This gate allows
|
|
9
|
+
# only those, re-validates every value, runs docker with an argument array (never
|
|
10
|
+
# through a shell), and logs each decision to syslog (tag: watcher-gate) so the
|
|
11
|
+
# delivery ledger can be audited against what the server actually ran.
|
|
12
|
+
set -u
|
|
13
|
+
export LC_ALL=C
|
|
14
|
+
|
|
15
|
+
cmd=${SSH_ORIGINAL_COMMAND-}
|
|
16
|
+
name='[A-Za-z0-9][A-Za-z0-9_.-]*'
|
|
17
|
+
# Discovery prefix as resolve-containers.py sends it: literal dots escaped as "\.".
|
|
18
|
+
prefix='[A-Za-z0-9]([A-Za-z0-9_-]|\\\.)*'
|
|
19
|
+
|
|
20
|
+
log() {
|
|
21
|
+
local text=${1//[^[:print:]]/?}
|
|
22
|
+
command -v logger >/dev/null 2>&1 && logger -t watcher-gate -- "${text:0:300}"
|
|
23
|
+
return 0
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
deny() {
|
|
27
|
+
log "denied: $cmd"
|
|
28
|
+
printf '%s\n' 'watcher-gate: command not allowed' >&2
|
|
29
|
+
exit 126
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
allow() {
|
|
33
|
+
log "allowed: $cmd"
|
|
34
|
+
exec docker "$@"
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
re_follow="^docker logs -f --tail=(0|1000) -- ($name)\$"
|
|
38
|
+
re_since="^docker logs --since=([1-9][0-9]{0,2})m --timestamps -- ($name)\$"
|
|
39
|
+
re_tail="^docker logs --tail=([1-9][0-9]{0,4}) --timestamps -- ($name)\$"
|
|
40
|
+
re_ps="^docker ps --filter 'name=\\^/\\?($prefix)\\.\\*\\\$' --format '\\{\\{\\.Names\\}\\}'\$"
|
|
41
|
+
|
|
42
|
+
if [[ $cmd =~ $re_follow ]]; then
|
|
43
|
+
allow logs -f "--tail=${BASH_REMATCH[1]}" -- "${BASH_REMATCH[2]}"
|
|
44
|
+
elif [[ $cmd =~ $re_since ]] && (( BASH_REMATCH[1] <= 120 )); then
|
|
45
|
+
allow logs "--since=${BASH_REMATCH[1]}m" --timestamps -- "${BASH_REMATCH[2]}"
|
|
46
|
+
elif [[ $cmd =~ $re_tail ]] && (( BASH_REMATCH[1] <= 50000 )); then
|
|
47
|
+
allow logs "--tail=${BASH_REMATCH[1]}" --timestamps -- "${BASH_REMATCH[2]}"
|
|
48
|
+
elif [[ $cmd =~ $re_ps ]]; then
|
|
49
|
+
allow ps --filter "name=^/?${BASH_REMATCH[1]}.*\$" --format '{{.Names}}'
|
|
50
|
+
fi
|
|
51
|
+
deny
|