@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,257 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -eu
3
- cd -- "${BASH_SOURCE[0]%/*}/.."
4
- PYTHON_BIN=$(command -v python3 || command -v python)
5
- "$PYTHON_BIN" -I -B - <<'PY'
6
- import contextlib
7
- import io
8
- import json
9
- import os
10
- from pathlib import Path
11
- import runpy
12
- import subprocess
13
- import sys
14
- import tempfile
15
- from unittest.mock import patch
16
-
17
- scripts = Path('scripts').resolve()
18
- entry = scripts / 'error-scan.py'
19
- mod = runpy.run_path(str(entry))
20
-
21
- checks = 0
22
-
23
- # A fake SSH on PATH (#52): scan() streams from a real child process, so the
24
- # tests drive it through an executable instead of mocking subprocess.run.
25
- fake_dir = Path(tempfile.mkdtemp())
26
- (fake_dir / 'ssh').write_text(f"""#!{sys.executable} -I
27
- import os, sys, time
28
- mode = os.environ.get('FAKE_MODE', 'file')
29
- out = sys.stdout.buffer
30
- if mode == 'file':
31
- out.write(open(os.environ['FAKE_FILE'], 'rb').read())
32
- elif mode == 'flood':
33
- block = b'x' * 65536 + b'\\n'
34
- for _ in range(int(os.environ['FAKE_MB']) * 16):
35
- out.write(block)
36
- elif mode == 'hang':
37
- out.write(b'ERROR first\\n'); out.flush(); time.sleep(30)
38
- elif mode == 'fail':
39
- sys.exit(255)
40
- """, encoding='utf-8')
41
- (fake_dir / 'ssh').chmod(0o700)
42
- fake_env = {'PATH': str(fake_dir) + os.pathsep + os.environ['PATH']}
43
-
44
-
45
- def scan_with(mode, data=None, **extra):
46
- env = dict(fake_env, FAKE_MODE=mode, **extra)
47
- if data is not None:
48
- path = fake_dir / 'input.log'
49
- path.write_bytes(data)
50
- env['FAKE_FILE'] = str(path)
51
- with patch.dict(os.environ, env):
52
- return mod['scan']('bbc-test', 'app-1', ('since', 15))
53
-
54
-
55
- # 1. digest drops UUIDs, URLs, emails, paths, and Bearer tokens (allowlist, #39)
56
- sample = (
57
- 'ERROR user alice@example.com hit https://secret.internal/api?token=abc '
58
- 'at /srv/app/auth.ts Bearer eyJhbGciOiJIUzI1NiJ9 123e4567-e89b-12d3-a456-426614174000 5551234567'
59
- )
60
- norm = mod['digest'](sample)
61
- for forbidden in ('alice@example.com', 'https://secret.internal', '/srv/app/auth.ts', 'eyJhbGciOiJIUzI1NiJ9', '123e4567', '5551234567'):
62
- assert forbidden not in norm, (forbidden, norm)
63
- checks += 1
64
-
65
- # 2. 16 MiB ceiling rejects oversized output
66
- try:
67
- scan_with('file', b'x' * (mod['MAX_BYTES'] + 1))
68
- raise AssertionError('Expected SystemExit on oversized output')
69
- except SystemExit as exc:
70
- assert 'ceiling' in str(exc), exc
71
- checks += 1
72
-
73
- # 2b. #52: the ceiling bounds memory. 200 MB of output is refused without being
74
- # held: the scan runs in its own process and its peak RSS stays below 64 MB.
75
- probe = subprocess.run([sys.executable, '-I', '-c', f"""
76
- import os, resource, subprocess, sys
77
- p = subprocess.run([sys.executable, '-I', '-B', {str(entry)!r}, 'bbc-test', 'app-1', '5'],
78
- capture_output=True, text=True)
79
- print(p.returncode, resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss, p.stderr.strip())
80
- """], env=dict(os.environ, **fake_env, FAKE_MODE='flood', FAKE_MB='200'), capture_output=True, text=True, timeout=120)
81
- code, rss_kb, message = probe.stdout.split(' ', 2)
82
- rss_mb = int(rss_kb) / 1024 if sys.platform != 'darwin' else int(rss_kb) / 1024 / 1024
83
- assert code == '1' and 'ceiling' in message, probe.stdout + probe.stderr
84
- assert rss_mb < 64, f'peak RSS {rss_mb:.0f} MB for 200 MB of output'
85
- checks += 1
86
-
87
- # 2c. #52: a missed deadline is a clean failure, not an uncaught TimeoutExpired.
88
- # runpy.run_path returns a copy of the globals: patch the function's own dict.
89
- with patch.dict(mod['scan'].__globals__, {'DEADLINE': 1}):
90
- try:
91
- scan_with('hang')
92
- raise AssertionError('Expected SystemExit on deadline')
93
- except SystemExit as exc:
94
- assert 'no counts' in str(exc), exc
95
- checks += 1
96
-
97
- # 2d. A failing SSH is still a clean failure.
98
- try:
99
- scan_with('fail')
100
- raise AssertionError('Expected SystemExit on SSH failure')
101
- except SystemExit as exc:
102
- assert str(exc) == 'Watcher scan failed; no counts.', exc
103
- checks += 1
104
-
105
- # 3. Clean window creates no saved file; signal window saves safely only with anchored /tmp_logs/
106
- with tempfile.TemporaryDirectory() as tmp:
107
- project = Path(tmp)
108
- subprocess.run(['git', 'init', '-q', str(project)], check=True)
109
- (project / '.gitignore').write_text('tmp_logs/\n', encoding='utf-8') # unanchored: must NOT save!
110
- saved_unanchored = mod['save'](
111
- 'bbc-test', 'app-1', ('since', 15),
112
- {'error': 1, 'warn': 0, 'info': 0, 'debug': 0, 'unclassified': 0},
113
- [0] * len(mod['PATTERNS']), {}, [{'level': 'error', 'signature': None, 'digest': 'boom'}], 100,
114
- )
115
- # Run inside project
116
- old_cwd = os.getcwd()
117
- try:
118
- os.chdir(project)
119
- saved_unanchored = mod['save'](
120
- 'bbc-test', 'app-1', ('since', 15),
121
- {'error': 1, 'warn': 0, 'info': 0, 'debug': 0, 'unclassified': 0},
122
- [0] * len(mod['PATTERNS']), {}, [{'level': 'error', 'signature': None, 'digest': 'boom'}], 100,
123
- )
124
- assert saved_unanchored is None, saved_unanchored
125
-
126
- # Anchored /tmp_logs/ with symlink tmp_logs must be refused
127
- (project / '.gitignore').write_text('/tmp_logs/\n', encoding='utf-8')
128
- outside = project / 'outside'
129
- outside.mkdir()
130
- try:
131
- os.symlink(outside, project / 'tmp_logs')
132
- saved_sym = mod['save'](
133
- 'bbc-test', 'app-1', ('since', 15),
134
- {'error': 1, 'warn': 0, 'info': 0, 'debug': 0, 'unclassified': 0},
135
- [0] * len(mod['PATTERNS']), {}, [{'level': 'error', 'signature': None, 'digest': 'boom'}], 100,
136
- )
137
- assert saved_sym is None, saved_sym
138
- os.unlink(project / 'tmp_logs')
139
- except OSError:
140
- pass
141
-
142
- # Valid anchored /tmp_logs/ saves artifact
143
- saved_ok = mod['save'](
144
- 'bbc-test', 'app-1', ('since', 15),
145
- {'error': 1, 'warn': 0, 'info': 0, 'debug': 0, 'unclassified': 0},
146
- [0] * len(mod['PATTERNS']), {}, [{'level': 'error', 'signature': None, 'digest': 'boom'}], 100,
147
- )
148
- assert saved_ok is not None and saved_ok.is_file(), saved_ok
149
- finally:
150
- os.chdir(old_cwd)
151
- checks += 1
152
-
153
- # 4. Digests are built from an allowlist (#39): no character of a secret value,
154
- # host, email, phone or JWT may reach stdout rows or the saved JSON.
155
- secret_log = '\n'.join((
156
- '2026-11-27T10:00:01.000Z {"level":"error","msg":"payment failed","password":"hunter2-secret","api_key":"sk_live_ABCDEF123456"}',
157
- '2026-11-27T10:00:02.000Z ERROR charge for maria.lopez@example.com failed: connection refused to db-prod-07.internal',
158
- '2026-11-27T10:00:03.000Z WARN retry with session=9f8e7d6c-1111-2222-3333-444455556666 cookie=abc123xyz',
159
- '2026-11-27T10:00:04.000Z ERROR auth failed Authorization: Basic dXNlcjpwYXNz jwt=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig phone=+1 555 0100 123',
160
- '2026-11-27T10:00:05.000Z ERROR ECONNREFUSED TimeoutError: upstream unavailable for tenant acme-corp',
161
- )).encode()
162
- _, _, _, rows, _, _ = scan_with('file', secret_log)
163
- digests = ' || '.join(str(row['digest']) for row in rows)
164
- for forbidden in ('hunter', 'secret', 'sk_live', 'ABCDEF', 'password', 'api_key', 'maria', 'example.com',
165
- 'db-prod', 'internal', 'abc', 'xyz', 'cookie', 'session', 'dXNlcjpwYXNz', 'eyJ', 'sig',
166
- '0100', '555', 'acme', 'tenant'):
167
- assert forbidden not in digests, (forbidden, digests)
168
- for expected in ('payment failed', 'connection refused', 'ECONNREFUSED', 'TimeoutError', 'upstream unavailable'):
169
- assert expected in digests, (expected, digests)
170
- assert len(rows) == 5, rows
171
- checks += 1
172
-
173
- # 5. Explicit shared contract (#48): error-scan.py and save-counts.py load watch-live.py
174
- # with runpy (python -I keeps the script directory off sys.path), so every name they
175
- # read from it must be declared in watch-live's SHARED_API and must exist.
176
- import re as _re
177
- live = runpy.run_path(str(scripts / 'watch-live.py'))
178
- shared = live.get('SHARED_API')
179
- assert isinstance(shared, tuple) and shared, 'watch-live.py must declare SHARED_API'
180
- missing = [name for name in shared if name not in live]
181
- assert not missing, ('SHARED_API names not defined in watch-live.py', missing)
182
- for consumer, var in (('error-scan.py', 'W'), ('save-counts.py', 'watcher'), ('resolve-containers.py', 'W')):
183
- used = set(_re.findall(var + r"\['([A-Za-z_]+)'\]", (scripts / consumer).read_text(encoding='utf-8')))
184
- assert used, (consumer, 'no shared names found; update this check')
185
- undeclared = sorted(used - set(shared))
186
- assert not undeclared, (consumer, 'uses names outside SHARED_API', undeclared)
187
- checks += 1
188
-
189
- # 6. #45: --project <uuid> keeps only lines that mention the project, so other
190
- # customers' records sharing the container never reach the counts, digests or
191
- # saved report. Matching is on the uuid string, whatever the field is called.
192
- project = '3f2b9c1e-7a4d-4e8b-9c2f-1a2b3c4d5e6f'
193
- other = '9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d'
194
- shared = '\n'.join((
195
- f'2026-11-29T10:00:01Z {{"level":"error","msg":"payment failed","projectId":"{project}"}}',
196
- f'2026-11-29T10:00:02Z {{"level":"error","msg":"connection refused","projectId":"{other}"}}',
197
- f'2026-11-29T10:00:03Z ERROR timeout for project_id={project.upper()}',
198
- f'2026-11-29T10:00:04Z WARN retry for project {other}',
199
- '2026-11-29T10:00:05Z ERROR upstream unavailable (no project in context)',
200
- )).encode()
201
- log_file = fake_dir / 'shared.log'
202
- log_file.write_bytes(shared)
203
-
204
-
205
- def run_main(args, data_file):
206
- out = io.StringIO()
207
- with patch.dict(os.environ, dict(fake_env, FAKE_MODE='file', FAKE_FILE=str(data_file))), \
208
- contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()) as err:
209
- try:
210
- code = mod['main'](args)
211
- except SystemExit as exc:
212
- code = exc.code
213
- return code, out.getvalue(), err.getvalue()
214
-
215
-
216
- with tempfile.TemporaryDirectory() as tmp:
217
- old_cwd = os.getcwd()
218
- os.chdir(tmp) # not a Git worktree: nothing is saved here
219
- try:
220
- code, out, _ = run_main(['--project', project, 'bbc-test', 'app-1', '15'], log_file)
221
- assert code == 0, (code, out)
222
- assert f'project={project} filtered_out=3' in out, out
223
- assert 'severity error=2 warn=0' in out, out # only this project's two lines
224
- assert 'payment failed' in out and 'timeout' in out, out
225
- assert 'connection refused' not in out and 'retry' not in out and 'upstream' not in out, out
226
- checks += 1
227
- # Without --project the output keeps its previous shape (no project field).
228
- code, out, _ = run_main(['bbc-test', 'app-1', '15'], log_file)
229
- assert code == 0 and 'project=' not in out and 'severity error=4 warn=1' in out, out
230
- checks += 1
231
- # An invalid uuid is a usage error before any connection.
232
- marker = fake_dir / 'called'
233
- code, out, err = run_main(['--project', 'acme-corp', 'bbc-test', 'app-1', '15'], log_file)
234
- assert code == 1 and 'Usage' in err, (code, err)
235
- checks += 1
236
- finally:
237
- os.chdir(old_cwd)
238
-
239
- # The saved report records the filter, so an audit can tell filtered scans apart.
240
- with tempfile.TemporaryDirectory() as tmp:
241
- proj = Path(tmp)
242
- subprocess.run(['git', 'init', '-q', str(proj)], check=True)
243
- (proj / '.gitignore').write_text('/tmp_logs/\n', encoding='utf-8')
244
- old_cwd = os.getcwd()
245
- os.chdir(proj)
246
- try:
247
- code, out, _ = run_main(['--project', project, 'bbc-test', 'app-1', '15'], log_file)
248
- saved = Path(out.split('saved=')[1].strip())
249
- report = json.loads(saved.read_text(encoding='utf-8'))
250
- assert report['project'] == project and report['filtered_out'] == 3, report
251
- assert other not in saved.read_text(encoding='utf-8'), 'another customer leaked into the report'
252
- checks += 1
253
- finally:
254
- os.chdir(old_cwd)
255
-
256
- print(f'PASS {checks} checks')
257
- PY
@@ -1,177 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -eu
3
- cd -- "${BASH_SOURCE[0]%/*}/.."
4
- # No live SSH: replace the process boundary with a synthetic transport.
5
- python -I -B - "$BASH" <<'PY'
6
- import contextlib
7
- import io
8
- from pathlib import Path
9
- import runpy
10
- import sys
11
- from unittest.mock import patch
12
-
13
- path = Path('scripts/watch-live.py')
14
- if not path.is_file():
15
- sys.exit('RED: live watcher entry point is missing')
16
- main = runpy.run_path(str(path))['main']
17
- controls = main.__globals__
18
- bash = sys.argv[1]
19
- failed = checks = 0
20
- failure = 'Watcher live capture failed; no counts.\n'
21
- invalid = 'Watcher live mode requires a valid SSH alias and exact container name or ID.\n'
22
- # The nine fixed signatures, in the documented order (SKILL.md "Parsing Notes").
23
- patterns = ('TypeError', 'UnhandledPromiseRejection', 'ECONNREFUSED', 'ETIMEDOUT', 'ECONNRESET',
24
- 'EPIPE', 'ENOTFOUND', 'HTTP_5xx', 'OutOfMemory')
25
-
26
-
27
- def row(i, *, error=0, warn=0, info=0, debug=0, unclassified=0, frames=0,
28
- dropped=0, hits=None):
29
- counts = dict.fromkeys(patterns, 0)
30
- for name, count in (hits or {}).items():
31
- counts[name] = count
32
- ranked = sorted(counts.items(), key=lambda pair: -pair[1])
33
- top = ','.join(f'{name}:{count}' for name, count in ranked)
34
- return (f'window={i} error={error} warn={warn} info={info} debug={debug} '
35
- f'unclassified={unclassified} frames={frames} dropped_bytes={dropped} top={top}\n')
36
-
37
-
38
- def check(label, events, expected, args=('bbc-test', 'app.test'), calls=1,
39
- launch_error=False, validation_calls=None, deadline_race=False, no_bash=False):
40
- global failed, checks
41
- # Include SSH setup in the same budget; no log is read before second 2.
42
- now = 100.0
43
- launches = []
44
- closed = []
45
- queue = iter(events)
46
- pending = next(queue, None)
47
-
48
- class FakeStream:
49
- def read_until(self, end):
50
- nonlocal now, pending
51
- if (pending is None or (100 + pending[0] >= end and not
52
- (deadline_race and end == 160 and pending[0] == 60))):
53
- now = end
54
- return None
55
- at, data = pending
56
- now = 100 + at
57
- pending = next(queue, None)
58
- return data
59
-
60
- def stop(self):
61
- closed.append(now)
62
- return True
63
-
64
- def start(argv):
65
- nonlocal now
66
- launches.append(argv)
67
- if launch_error:
68
- raise OSError('private diagnostic')
69
- now += 2
70
- return FakeStream()
71
-
72
- def which(name):
73
- return {'bash': None if no_bash else bash, 'ssh': 'fake-ssh'}.get(name)
74
-
75
- out, err = io.StringIO(), io.StringIO()
76
- with patch.dict(controls, {'start': start, 'monotonic': lambda: now}), \
77
- patch.object(controls['shutil'], 'which', which), \
78
- patch.object(controls['subprocess'], 'run', wraps=controls['subprocess'].run) as validate, \
79
- contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
80
- status = main(list(args))
81
- wanted_argv = ['fake-ssh', '-nT', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes',
82
- '-o', 'UpdateHostKeys=no', '-o', 'ClearAllForwardings=yes', '-o',
83
- 'PermitLocalCommand=no', '-o', 'ControlPath=none', args[0] if args else '',
84
- 'docker', 'logs', '-f', '--tail=0', '--', args[-1] if args else '']
85
- checks += 1
86
- expected_closed = ([] if not calls or launch_error else
87
- [160.0 if expected[0] == 0 else now])
88
- if (status, out.getvalue(), err.getvalue()) != expected or \
89
- launches != [wanted_argv] * calls or closed != expected_closed or \
90
- (validation_calls is not None and validate.call_count != validation_calls):
91
- failed += 1
92
- print(f'FAIL {label}: exit={status} stdout={out.getvalue()!r} '
93
- f'stderr={err.getvalue()!r} launches={launches!r} closed={closed!r} '
94
- f'validation_calls={validate.call_count}', file=sys.stderr)
95
-
96
-
97
- def success(*windows):
98
- return (0, 'live status=deadline\n' + ''.join(windows), '')
99
-
100
-
101
- check('classification-boundary-and-idle', [
102
- (3, b'{"level":"error","error":{"name":"TypeError"},"message":"secret"}\n'
103
- b'{"level":"warning","message":"ECONNREFUSED"}\n'
104
- b'[INFO] ready\nDEBUG ready\ntry {\n} catch (TypeError) {\n'
105
- b' at private (secret.js:1:1)\n'),
106
- (15, b'UnhandledPromiseRejection: hidden\nECONNREFUSED private\nETIMEDOUT private\n'
107
- b'HTTP/1.1 503 private\nHTTP 503 private\nERROR private\n'),
108
- (59, b'INFO incomplete'),
109
- (60, b'TypeError: past deadline\n'),
110
- ], success(row(1, error=1, warn=1, info=1, debug=1, unclassified=2, frames=1,
111
- hits={'TypeError': 1, 'ECONNREFUSED': 1}), row(2, error=6, hits={'UnhandledPromiseRejection': 1, 'ECONNREFUSED': 1,
112
- 'ETIMEDOUT': 1, 'HTTP_5xx': 2}),
113
- row(3), row(4, dropped=15)))
114
- check('empty-idle', [], success(*(row(i) for i in range(1, 5))), args=('bb-test', 'abc123'))
115
- check('budget-and-partial-continuation', [
116
- (4, b'x' * 32766 + b'\nI'), (5, b'NFO ignored\nERROR ignored\n'),
117
- (14, b'TypeError: no newline'), (16, b'\nINFO fresh\nERR'),
118
- (31, b'OR continuation\nWARN fresh\n'),
119
- ], success(row(1, unclassified=1, dropped=48), row(2, info=1, dropped=4),
120
- row(3, warn=1, dropped=16), row(4)))
121
- check('actual-cross-window-fragment', [(14, b'ERR'), (15, b'OR hidden\nDEBUG fresh\n')],
122
- success(row(1, dropped=3), row(2, debug=1, dropped=10), row(3), row(4)))
123
- for args in [('bbc-test\r\n', 'app.test'), ('bbc-test', 'app.test\r\n'),
124
- ('bbc-test\n', 'app.test'), ('bbc-test', 'app.test\n'),
125
- ('bbc-tést', 'app.test'), ('bbc-test', 'app.tést')]:
126
- check('reject-original-before-process', [], (1, '', invalid), args=args,
127
- calls=0, validation_calls=0)
128
- # ADR 0001: live mode needs only SSH. Without bash on PATH (native Windows) an exact,
129
- # validated target still captures, and no validation subprocess runs.
130
- check('no-bash-needed', [(3, b'INFO ready\n')], success(row(1, info=1), row(2), row(3), row(4)),
131
- no_bash=True, validation_calls=0)
132
- check('dequeued-at-deadline', [(59, b'INFO kept\nERR'), (60, b'TypeError: late\n')],
133
- success(row(1), row(2), row(3), row(4, info=1, dropped=19)), deadline_race=True)
134
- check('python-traceback', [(3, b'Traceback (most recent call last):\n'
135
- b' File "private.py", line 1, in run\n'
136
- b' operation()\n'
137
- b' ^^^^^^^^^^^\n'
138
- b' File "private.py", line 2, in operation\n'
139
- b' raise TypeError("secret")\n'
140
- b'TypeError: secret\n')],
141
- success(row(1, error=1, frames=6, hits={'TypeError': 1}), row(2), row(3), row(4)))
142
- check('exact-bracketed-level', [(3, b'[ERROR CODES] ok\n[ERROR] private\n')],
143
- success(row(1, error=1, unclassified=1), row(2), row(3), row(4)))
144
- check('early-eof-discards-counts', [(3, b'ERROR hidden\n'), (19, b'')], (1, '', failure))
145
- check('launch-failure', [], (1, '', failure), launch_error=True)
146
- for args in [(), ('bbc-test',), ('wrong-host', 'app'), ('bbc-test', 'app*'),
147
- ('bbc-test', 'app;id'), ('bbc-test', '-app'), ('bbc-test', 'app', 'next')]:
148
- check('reject-invalid-target', [], (1, '', invalid), args=args, calls=0)
149
-
150
- check('help', [], (0, 'Usage: python -I -B scripts/watch-live.py <ssh-alias> <exact-container>\n'
151
- 'Observe one authorized container for 60 seconds; report four 15-second windows.\n', ''),
152
- args=('--help',), calls=0)
153
-
154
- # Exercise the real bounded local pipe and cleanup, with a Python child in
155
- # place of SSH. No synthetic clock is used for this transport check.
156
- stream = controls['start']([sys.executable, '-I', '-B', '-u', '-c',
157
- 'import sys,time; sys.stdout.buffer.write(b"out\\n"); '
158
- 'sys.stderr.buffer.write(b"err\\n"); time.sleep(60)'])
159
- data = b''
160
- try:
161
- until = controls['monotonic']() + 5
162
- while data != b'out\nerr\n' and len(data) < 8:
163
- part = stream.read_until(until)
164
- if not part:
165
- break
166
- data += part
167
- idle = stream.read_until(controls['monotonic']() + 0.02)
168
- finally:
169
- stopped = stream.stop()
170
- checks += 1
171
- if data != b'out\nerr\n' or idle is not None or not stopped:
172
- failed += 1
173
- print(f'FAIL local transport: data={data!r} idle={idle!r} stopped={stopped}', file=sys.stderr)
174
-
175
- print(f'{checks} checks, {failed} failed')
176
- sys.exit(bool(failed))
177
- PY
@@ -1,87 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -eu
3
- cd -- "${BASH_SOURCE[0]%/*}/.."
4
-
5
- scratch=$(mktemp -d)
6
- trap 'rm -rf -- "$scratch"' EXIT
7
- failures=0
8
- checks=0
9
- PYTHON_BIN=$(command -v python3 || command -v python)
10
- PYTHON_BIN=$("$PYTHON_BIN" -c 'import sys; print(sys.executable)')
11
-
12
- # ADR 0001: the resolver runs with a PATH that holds only the fake SSH, so it
13
- # cannot depend on bash, timeout, head, od or awk.
14
- printf '#!%s -p\n' "$BASH" >"$scratch/ssh"
15
- printf '%s\n' '
16
- printf "called\n" >>"$MARKER"
17
- expected=(-nT -o BatchMode=yes -o StrictHostKeyChecking=yes -o UpdateHostKeys=no
18
- -o ClearAllForwardings=yes -o PermitLocalCommand=no -o ControlPath=none
19
- bbc-test "docker ps --filter '\''name=^/?shop-app-.*$'\'' --format '\''{{.Names}}'\''")
20
- if [[ $FIXTURE == dots ]]; then
21
- expected[${#expected[@]}-2]=bb-test
22
- expected[${#expected[@]}-1]="docker ps --filter '\''name=^/?app\.test-.*$'\'' --format '\''{{.Names}}'\''"
23
- fi
24
- [[ $# == ${#expected[@]} ]] || exit 90
25
- for word in "${expected[@]}"; do
26
- [[ $1 == "$word" ]] || exit 91
27
- shift
28
- done
29
- case $FIXTURE in
30
- names) printf "shop-app-b\nshop-app-a\nshop-app-b\n" ;;
31
- dots) printf "app.test-west\n" ;;
32
- empty) ;;
33
- foreign) printf "shop-app-ok\nother-shop-app-x\n" ;;
34
- malformed) printf "shop-app-ok\nshop-app-x extra\n" ;;
35
- nul) printf "shop-app-x\000y\n" ;;
36
- partial) printf "shop-app-ok\nshop-app-x" ;;
37
- many) for ((i=1; i<=17; i++)); do printf "shop-app-%s\n" "$i"; done ;;
38
- limit) printf "shop-app-%08182d\n" 0 ;;
39
- oversized) printf "shop-app-%09000d\n" 0 ;;
40
- error) printf "shop-app-ok\n"; printf "private diagnostic\n" >&2; exit 255 ;;
41
- deadline) printf "shop-app-ok\n"; exit 124 ;;
42
- *) exit 92 ;;
43
- esac
44
- ' >>"$scratch/ssh"
45
- chmod +x "$scratch/ssh"
46
-
47
- check() {
48
- local label=$1 fixture=$2 want_rc=$3 want_out=$4 want_err=$5 want_calls=$6
49
- shift 6
50
- local rc=0 output error_output calls end=$'\037'
51
- : >"$scratch/calls"
52
- output=$(rc=0
53
- PATH="$scratch" FIXTURE="$fixture" MARKER="$scratch/calls" \
54
- "$PYTHON_BIN" -I -B scripts/resolve-containers.py "$@" 2>"$scratch/stderr" || rc=$?
55
- printf '%s' "$end"
56
- exit "$rc"
57
- ) || rc=$?
58
- output=${output%"$end"}
59
- IFS= read -r -d '' error_output <"$scratch/stderr" || :
60
- IFS= read -r -d '' calls <"$scratch/calls" || :
61
- checks=$((checks + 1))
62
- if [[ $rc != "$want_rc" || $output != "$want_out" || $error_output != "$want_err" || $calls != "$want_calls" ]]; then
63
- printf 'FAIL %s: exit=%s stdout=%q stderr=%q calls=%q\n' "$label" "$rc" "$output" "$error_output" "$calls" >&2
64
- failures=$((failures + 1))
65
- fi
66
- }
67
-
68
- selector='shop-app-*'
69
- called=$'called\n'
70
- invalid=$'Watcher requires a valid SSH alias and container name, ID, or literal prefix followed by *.\n'
71
- failed=$'Watcher container discovery failed; no snapshot.\n'
72
- check exact-id unused 0 $'abc123\n' '' '' bbc-test abc123
73
- check exact-name unused 0 $'app.test\n' '' '' bb-test app.test
74
- check missing unused 1 '' "$invalid" '' bbc-test
75
- check invalid-alias unused 1 '' "$invalid" '' other-host "$selector"
76
- for bad in '*' 'app**' 'app*x' '*app' 'app[0-9]*' 'app|x*' 'app *' 'app+*' 'app\.*' 'app;id*' '/app*' $'app\n*' '-app*'; do
77
- check "reject-$bad" unused 1 '' "$invalid" '' bbc-test "$bad"
78
- done
79
- check snapshot names 0 $'shop-app-b\nshop-app-a\n' '' "$called" bbc-test "$selector"
80
- check literal-dot dots 0 $'app.test-west\n' '' "$called" bb-test 'app.test-*'
81
- check no-matches empty 0 '' '' "$called" bbc-test "$selector"
82
- for fixture in foreign malformed nul partial many limit oversized error deadline; do
83
- check "$fixture" "$fixture" 1 '' "$failed" "$called" bbc-test "$selector"
84
- done
85
-
86
- printf '%s checks, %s failed\n' "$checks" "$failures"
87
- [[ $failures == 0 ]]