spongebob-cli 0.3.2__py3-none-any.whl

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 (54) hide show
  1. spongebob/__init__.py +1 -0
  2. spongebob/__main__.py +375 -0
  3. spongebob/analyzer/__init__.py +9 -0
  4. spongebob/analyzer/__main__.py +39 -0
  5. spongebob/analyzer/analyzer.py +234 -0
  6. spongebob/bus/__init__.py +6 -0
  7. spongebob/bus/bus.py +38 -0
  8. spongebob/diagnose/__init__.py +29 -0
  9. spongebob/diagnose/__main__.py +111 -0
  10. spongebob/diagnose/adapter.py +82 -0
  11. spongebob/diagnose/models.py +79 -0
  12. spongebob/diagnose/probes.py +129 -0
  13. spongebob/engine/__init__.py +26 -0
  14. spongebob/engine/__main__.py +25 -0
  15. spongebob/engine/models.py +161 -0
  16. spongebob/engine/simulator.py +196 -0
  17. spongebob/export/__init__.py +25 -0
  18. spongebob/export/exporter.py +354 -0
  19. spongebob/meter/__init__.py +7 -0
  20. spongebob/meter/__main__.py +50 -0
  21. spongebob/meter/meter.py +140 -0
  22. spongebob/narrator/__init__.py +25 -0
  23. spongebob/narrator/narrator.py +352 -0
  24. spongebob/plugins/__init__.py +28 -0
  25. spongebob/plugins/loader.py +308 -0
  26. spongebob/plugins/models.py +47 -0
  27. spongebob/scenarios/__init__.py +25 -0
  28. spongebob/scenarios/builtin/__init__.py +1 -0
  29. spongebob/scenarios/builtin/control-line.toml +33 -0
  30. spongebob/scenarios/builtin/crowded-wifi.toml +33 -0
  31. spongebob/scenarios/builtin/flaky-last-mile.toml +33 -0
  32. spongebob/scenarios/builtin/long-haul-orbit.toml +33 -0
  33. spongebob/scenarios/builtin/overloaded-uplink.toml +35 -0
  34. spongebob/scenarios/builtin/tunnel-burst.toml +38 -0
  35. spongebob/scenarios/loader.py +205 -0
  36. spongebob/scenarios/models.py +55 -0
  37. spongebob/scenarios/runner.py +24 -0
  38. spongebob/ui/__init__.py +23 -0
  39. spongebob/ui/__main__.py +11 -0
  40. spongebob/ui/app.py +88 -0
  41. spongebob/ui/canvas.py +147 -0
  42. spongebob/ui/diagnose_screen.py +525 -0
  43. spongebob/ui/export_modal.py +158 -0
  44. spongebob/ui/menu_screen.py +159 -0
  45. spongebob/ui/replay.py +209 -0
  46. spongebob/ui/settings_screen.py +101 -0
  47. spongebob/ui/simulate_screen.py +566 -0
  48. spongebob/ui/theme.py +364 -0
  49. spongebob/ui/visualize_screen.py +411 -0
  50. spongebob_cli-0.3.2.dist-info/METADATA +78 -0
  51. spongebob_cli-0.3.2.dist-info/RECORD +54 -0
  52. spongebob_cli-0.3.2.dist-info/WHEEL +5 -0
  53. spongebob_cli-0.3.2.dist-info/entry_points.txt +2 -0
  54. spongebob_cli-0.3.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,140 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from dataclasses import dataclass
5
+ from typing import Iterable
6
+
7
+ from spongebob.engine.models import Event
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class LatencyStats:
12
+ """Summary statistics for one-way packet latency in milliseconds."""
13
+
14
+ min: float
15
+ avg: float
16
+ max: float
17
+ p95: float
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Metrics:
22
+ """Measured network impairment metrics computed from engine events."""
23
+
24
+ sent: int
25
+ delivered: int
26
+ lost: int
27
+ loss_pct: float
28
+ loss_by_hop: dict[str, int]
29
+ latency_ms: LatencyStats | None
30
+ jitter_ms: float | None
31
+ jitter_mean_abs_ms: float | None
32
+ reordered: int
33
+ throughput_kbps: float | None
34
+
35
+
36
+ def _percentile_95(sorted_values: list[float]) -> float:
37
+ n = len(sorted_values)
38
+ if n == 1:
39
+ return sorted_values[0]
40
+ pos = 0.95 * (n - 1)
41
+ lo = math.floor(pos)
42
+ hi = math.ceil(pos)
43
+ if lo == hi:
44
+ return sorted_values[lo]
45
+ return sorted_values[lo] + (sorted_values[hi] - sorted_values[lo]) * (pos - lo)
46
+
47
+
48
+ def measure(events: Iterable[Event], packet_size_bytes: int = 64) -> Metrics:
49
+ """Compute delivery, loss, latency, jitter, reordering, and throughput metrics."""
50
+ if isinstance(packet_size_bytes, bool) or not isinstance(packet_size_bytes, int) or packet_size_bytes < 0:
51
+ raise ValueError(f"packet_size_bytes must be a non-negative integer, got {packet_size_bytes}")
52
+
53
+ sent = 0
54
+ delivered_events: list[Event] = []
55
+ loss_by_hop: dict[str, int] = {}
56
+ first_send_time_ms: float | None = None
57
+
58
+ for event in events:
59
+ if event.type == "packet_sent":
60
+ sent += 1
61
+ if first_send_time_ms is None or event.time_ms < first_send_time_ms:
62
+ first_send_time_ms = event.time_ms
63
+ elif event.type == "packet_dropped":
64
+ if event.hop is not None:
65
+ loss_by_hop[event.hop] = loss_by_hop.get(event.hop, 0) + 1
66
+ elif event.type == "packet_delivered":
67
+ delivered_events.append(event)
68
+
69
+ delivered = len(delivered_events)
70
+ lost = sum(loss_by_hop.values()) if sent == 0 else max(0, sent - delivered)
71
+ loss_pct = (lost / sent * 100.0) if sent > 0 else 0.0
72
+
73
+ if delivered == 0:
74
+ return Metrics(
75
+ sent=sent,
76
+ delivered=0,
77
+ lost=lost,
78
+ loss_pct=loss_pct,
79
+ loss_by_hop=loss_by_hop,
80
+ latency_ms=None,
81
+ jitter_ms=None,
82
+ jitter_mean_abs_ms=None,
83
+ reordered=0,
84
+ throughput_kbps=None if packet_size_bytes == 0 else 0.0,
85
+ )
86
+
87
+ delivered_events.sort(key=lambda e: e.time_ms)
88
+
89
+ latencies = [
90
+ e.total_latency_ms if e.total_latency_ms is not None else 0.0
91
+ for e in delivered_events
92
+ ]
93
+ sorted_latencies = sorted(latencies)
94
+ latency_stats = LatencyStats(
95
+ min=sorted_latencies[0],
96
+ avg=sum(latencies) / delivered,
97
+ max=sorted_latencies[-1],
98
+ p95=_percentile_95(sorted_latencies),
99
+ )
100
+
101
+ jitter_ms = 0.0
102
+ if delivered >= 2:
103
+ abs_deltas: list[float] = []
104
+ for idx in range(1, delivered):
105
+ delta = abs(latencies[idx] - latencies[idx - 1])
106
+ jitter_ms += (delta - jitter_ms) / 16.0
107
+ abs_deltas.append(delta)
108
+ jitter_mean_abs_ms = sum(abs_deltas) / len(abs_deltas)
109
+ else:
110
+ jitter_mean_abs_ms = 0.0
111
+
112
+ reordered = 0
113
+ max_seq_seen = -1
114
+ for event in delivered_events:
115
+ if event.seq < max_seq_seen:
116
+ reordered += 1
117
+ else:
118
+ max_seq_seen = event.seq
119
+
120
+ last_delivery_time_ms = delivered_events[-1].time_ms
121
+ if packet_size_bytes == 0:
122
+ throughput_kbps: float | None = None
123
+ elif first_send_time_ms is not None and last_delivery_time_ms > first_send_time_ms:
124
+ duration_ms = last_delivery_time_ms - first_send_time_ms
125
+ throughput_kbps = (delivered * packet_size_bytes * 8.0) / duration_ms
126
+ else:
127
+ throughput_kbps = 0.0
128
+
129
+ return Metrics(
130
+ sent=sent,
131
+ delivered=delivered,
132
+ lost=lost,
133
+ loss_pct=loss_pct,
134
+ loss_by_hop=loss_by_hop,
135
+ latency_ms=latency_stats,
136
+ jitter_ms=jitter_ms,
137
+ jitter_mean_abs_ms=jitter_mean_abs_ms,
138
+ reordered=reordered,
139
+ throughput_kbps=throughput_kbps,
140
+ )
@@ -0,0 +1,25 @@
1
+ from .narrator import (
2
+ BANNED_NAMES,
3
+ DIAGNOSE_SUMMARY_POOL,
4
+ MASCOT_NAME,
5
+ DROP_REASON_POOLS,
6
+ FINDING_POOLS,
7
+ HEALTHY_POOL,
8
+ SUMMARY_POOL,
9
+ Line,
10
+ Narrator,
11
+ narrate,
12
+ )
13
+
14
+ __all__ = [
15
+ "BANNED_NAMES",
16
+ "DIAGNOSE_SUMMARY_POOL",
17
+ "DROP_REASON_POOLS",
18
+ "FINDING_POOLS",
19
+ "HEALTHY_POOL",
20
+ "MASCOT_NAME",
21
+ "SUMMARY_POOL",
22
+ "Line",
23
+ "Narrator",
24
+ "narrate",
25
+ ]
@@ -0,0 +1,352 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ from dataclasses import dataclass
5
+ from typing import Any, Mapping, Sequence
6
+
7
+ MASCOT_NAME = "Wobbles the Sea Cucumber"
8
+
9
+ BANNED_NAMES: tuple[str, ...] = (
10
+ "spongebob",
11
+ "bikini bottom",
12
+ "krusty krab",
13
+ "patrick",
14
+ "squidward",
15
+ "sandy cheeks",
16
+ "plankton",
17
+ "mr. krabs",
18
+ "gary",
19
+ "finding nemo",
20
+ "dory",
21
+ "ariel",
22
+ "sebastian",
23
+ "flounder",
24
+ )
25
+
26
+ HEALTHY_POOL: tuple[str, ...] = (
27
+ "Wiggle-tastic! Every packet glided through like a happy sea cucumber at {value}!",
28
+ "Zero drama on the reef today—{hop} is smoother than polished kelp!",
29
+ "All clear! Not a single dropped shell or wobbly current in sight!",
30
+ "Totally fine, probably—actually, no, it's genuinely pristine! Smooth sailing!",
31
+ "My antennae say: zero congestion, zero panic, 100% ocean breeze!",
32
+ "Packets arrived in neat little rows like synchronized krill!",
33
+ "No bumps, no tangles, no crabby queues—just pure aquatic zen!",
34
+ "If networks were tide pools, this one would win Best Behavior!",
35
+ "Everything arrived right on cue! Even the pickiest starfish would approve!",
36
+ "Smooth currents from end to end—my sea-cucumber heart is beaming!",
37
+ )
38
+
39
+ SUMMARY_POOL: tuple[str, ...] = (
40
+ "Run complete! {value} packets made it across the reef—every packet is an adventure!",
41
+ "Splashdown! {value} deliveries logged and counted by my squishy flippers!",
42
+ "That's a wrap on the tide! {value} packets reached the far shore!",
43
+ "Wiggle-tastic finish! {value} packets completed their underwater voyage!",
44
+ "End of the current! {value} packets checked in at the destination!",
45
+ "Bubbles up! The flow wrapped with {value} deliveries!",
46
+ )
47
+
48
+ DIAGNOSE_SUMMARY_POOL: tuple[str, ...] = (
49
+ "Live reef check done! {value} probes made the round trip without getting lost at sea!",
50
+ "Diagnose swim complete—{value} round-trip replies surfaced from the far shore!",
51
+ "Probe patrol reporting back: {value} handshakes came home safely!",
52
+ "My antennae tallied the live tide: {value} probes completed the round trip!",
53
+ "End of the live check! {value} probes bounced back across the reef!",
54
+ "Flipper-count complete! {value} probes answered the knock on the ocean floor!",
55
+ )
56
+
57
+ DROP_REASON_POOLS: dict[str, tuple[str, ...]] = {
58
+ "random": (
59
+ "Oops! A stray current at {hop} gently misplaced {value} packets—totally normal reef weather!",
60
+ "Random sea-foam ate {value} packets near {hop}, but the rest are swimming strong!",
61
+ "A passing jellyfish bumped {hop} and {value} packets drifted off course!",
62
+ "Mystery bubbles at {hop} vanished {value} packets into the deep blue!",
63
+ "Coin-flip currents at {hop} claimed {value} packets—keep paddling!",
64
+ "Just a tiny bit of ocean static at {hop}: {value} packets wandered off!",
65
+ ),
66
+ "burst": (
67
+ "Whoa! A whole school of {value} packets vanished together in a burst at {hop}!",
68
+ "A sudden riptide at {hop} swept away {value} packets in one big gulp!",
69
+ "Burst alert! {hop} blinked and {value} consecutive packets went sightseeing!",
70
+ "Hold onto your tentacles—{hop} hit a kelp-tangle burst and lost {value} packets!",
71
+ "A grumpy tide-wave at {hop} swallowed {value} packets back-to-back!",
72
+ "Clump-o-rama! {value} packets took an unscheduled detour together at {hop}!",
73
+ ),
74
+ "queue_full": (
75
+ "The waiting room at {hop} overflowed—{value} packets got bounced at the door!",
76
+ "Too many swimmers in the narrow tube at {hop}! {value} packets spilled out!",
77
+ "Queue jam at {hop}! {value} packets couldn't squeeze into the buffer!",
78
+ "Full house at {hop}! {value} latecomers had to turn around!",
79
+ "The bottle-neck at {hop} backed up and tail-dropped {value} packets!",
80
+ "No more standing room at {hop}—{value} packets were politely turned away!",
81
+ ),
82
+ "timeout": (
83
+ "Crickets on the reef! {hop} left {value} probes knocking with no reply before the bell!",
84
+ "Knock-knock at {hop}—{value} probes waited until the tide clock ran out!",
85
+ "No wave back from {hop}: {value} probes timed out in the deep blue!",
86
+ "The seashell phone at {hop} rang and rang—{value} probes timed out!",
87
+ "Radio silence near {hop}! {value} probes never heard a bubble back in time!",
88
+ "Sleepy currents at {hop} let {value} probes time out without a handshake!",
89
+ "Still waiting on {hop}—{value} probes swam past the timeout buoy!",
90
+ "Ghost town at {hop}! {value} probes got zero answer before the whistle blew!",
91
+ ),
92
+ }
93
+
94
+ FINDING_POOLS: dict[tuple[str, str], tuple[str, ...]] = {
95
+ ("HIGH_DELAY", "warn"): (
96
+ "Packets are taking a scenic {value} ms cruise across {hop}—maybe they stopped for kelp snacks!",
97
+ "A little sluggish at {value} ms on {hop}, like a sleepy sea turtle!",
98
+ "Delay is {value} ms across {hop}—not late, just fashionably unhurried!",
99
+ "The current is thick today: {value} ms average trip over {hop}!",
100
+ "Packets are paddling through molasses at {value} ms on {hop}!",
101
+ "Slow-motion swim! {hop} clocked {value} ms—plenty of time to admire the coral!",
102
+ "Warming up the flippers: {value} ms one-way delay across {hop}!",
103
+ "A leisurely {value} ms drift on {hop}—hope nobody is waiting for a snappy ping!",
104
+ ),
105
+ ("HIGH_DELAY", "critical"): (
106
+ "WHOA! {value} ms on {hop}?! Those packets are practically hibernating in a trench!",
107
+ "MAJOR LAG! {value} ms across {hop}—a glacier swims faster than this!",
108
+ "DEEP-SEA FREEZE! {hop} is dragging packets through {value} ms of mud!",
109
+ "ALERT! {value} ms delay on {hop}—even a barnacle could outrun that!",
110
+ "CRITICAL CRAWL! {value} ms on {hop}—packets are aging like driftwood!",
111
+ "SOS FROM THE TRENCH! {value} ms one-way latency on {hop}!",
112
+ "MEGA-STRETCH! {hop} is holding packets hostage for {value} ms!",
113
+ "TURTLE OVERDRIVE! {value} ms across {hop} is way past nap time!",
114
+ ),
115
+ ("HIGH_JITTER", "warn"): (
116
+ "Wobbly currents at {hop}! Delay std-dev is {value} ms—every packet has its own rhythm!",
117
+ "Chaotic wiggly waves at {hop} ({value} ms spread)—who needs steady timing anyway?",
118
+ "Jitterbugs spotted at {hop}! {value} ms wobble in the travel times!",
119
+ "Some packets sprint, some stroll at {hop}—{value} ms of pure unpredictability!",
120
+ "The metronome at {hop} is tipsy: {value} ms jitter!",
121
+ "Up, down, sideways—{hop} is bouncing packet delays by {value} ms!",
122
+ "Choppy surface at {hop} with {value} ms jitter—hold onto your shell!",
123
+ "A little sea-sick at {hop}: {value} ms delay variance!",
124
+ ),
125
+ ("HIGH_JITTER", "critical"): (
126
+ "WHIRLPOOL! {hop} is thrashing delays by {value} ms—total timing chaos!",
127
+ "CRITICAL WOBBLE! {value} ms jitter at {hop}—packets don't know which tide it is!",
128
+ "MAELSTROM AT {hop}! {value} ms std-dev is scrambling the whole stream!",
129
+ "EXTREME TURBULENCE! {hop} is tossing packets around with {value} ms jitter!",
130
+ "ABYSSALQUAKE! {value} ms jitter at {hop}—steady clocks need not apply!",
131
+ "WILD RIDE AT {hop}! {value} ms of pure, unfiltered delay whiplash!",
132
+ "PANIC IN THE KELP! {hop} jitter spiked to {value} ms!",
133
+ "SPIN CYCLE! {hop} is churning delays by {value} ms!",
134
+ ),
135
+ ("PACKET_LOSS", "warn"): (
136
+ "A few nibbles at {hop}: {value}% of packets went missing—probably fine!",
137
+ "Tiny leak in the hull at {hop}: {value}% packet loss!",
138
+ "{hop} misplaced {value}% of the swimmers—check under the rocks!",
139
+ "Gentle scatter at {hop}: {value}% loss, plenty still made it!",
140
+ "Sea-gulls got {value}% of the packets passing {hop}!",
141
+ "Mild packet evaporation at {hop}: {value}%!",
142
+ "{hop} has a {value}% drip—time to patch that coral pipe!",
143
+ "A cheeky {value}% loss rate at {hop}—keep swimming!",
144
+ ),
145
+ ("PACKET_LOSS", "critical"): (
146
+ "BLACK HOLE AT {hop}! {value}% of packets vanished into the abyss!",
147
+ "MAYDAY! {hop} is devouring {value}% of the flow!",
148
+ "CRITICAL LEAK! {value}% packet loss at {hop}—the pipe has a giant hole!",
149
+ "SINKING SHIP! {hop} dropped {value}% of everything that touched it!",
150
+ "ALARM! {hop} is eating {value}% of packets for breakfast!",
151
+ "TIDAL DISASTER! {value}% loss at {hop}—barely anything gets through!",
152
+ "RED ALERT AT {hop}! {value}% of the fleet is gone!",
153
+ "GIANT CRAB ON THE LINE! {hop} snipped {value}% of all packets!",
154
+ ),
155
+ ("BURST_LOSS", "warn"): (
156
+ "Consecutive {value}-packet hiccup at {hop}—a little clump went missing!",
157
+ "{hop} sneezed and dropped {value} packets in a row!",
158
+ "Mini-riptide at {hop}: {value} back-to-back packets vanished!",
159
+ "A {value}-packet gap appeared at {hop}—must've been a passing whale!",
160
+ "Clumpy loss at {hop}: {value} sequential packets took a break!",
161
+ "Burst-o-meter tingled at {hop} with {value} consecutive drops!",
162
+ "{hop} blinked for {value} packets straight!",
163
+ "A neat little {value}-packet hole punched out at {hop}!",
164
+ ),
165
+ ("BURST_LOSS", "critical"): (
166
+ "MASSIVE BLACKOUT AT {hop}! {value} packets in a row just disappeared!",
167
+ "CRITICAL BURST! {hop} went dark for {value} consecutive packets!",
168
+ "GIANT SQUID ATTACK! {value} back-to-back packets vanished at {hop}!",
169
+ "CHASM AT {hop}! {value} sequential packets fell into the trench!",
170
+ "SEVERE RIPTIDE! {hop} wiped out {value} packets in a single streak!",
171
+ "TOTAL BLINKOUT! {value} consecutive drops at {hop}!",
172
+ "MEGA-CLUMP LOSS! {hop} swallowed {value} packets without pausing!",
173
+ "EMERGENCY! {hop} lost {value} packets straight—check the reef!",
174
+ ),
175
+ ("BANDWIDTH_CHOKE", "warn"): (
176
+ "Squeeze play at {hop}! Queue is backing up ({value}) in the narrow pipe!",
177
+ "Traffic jam forming at {hop} ({value})—too many packets, tiny straw!",
178
+ "{hop} is puffing its cheeks—queue/drops hit {value}!",
179
+ "Bottleneck alert at {hop}: {value} piling up behind the cap!",
180
+ "Single-file swimming at {hop}—{value} waiting in line!",
181
+ "Narrow coral tunnel at {hop} caused {value} congestion!",
182
+ "A bit cramped at {hop}: {value} queued or bumped!",
183
+ "Slow-funnel at {hop} ({value})—packets are bumper-to-bumper!",
184
+ ),
185
+ ("BANDWIDTH_CHOKE", "critical"): (
186
+ "GRIDLOCK AT {hop}! {value}% queue-full drops—the pipe is bursting!",
187
+ "CRITICAL CHOKE! {hop} is overflowing with {value}% tail-drops!",
188
+ "TINY STRAW EXPLOSION! {hop} rejected {value}% of packets at the queue!",
189
+ "CLOGGED REEF! {hop} hit {value}% queue-full loss—nothing fits!",
190
+ "MEGA-BOTTLENECK! {value}% of packets bounced off {hop}'s full buffer!",
191
+ "OVERFLOW PANIC AT {hop}! {value}% dropped because the queue is packed!",
192
+ "TRAFFIC APOCALYPSE! {hop} spilled {value}% from an overstuffed queue!",
193
+ "NO ROOM IN THE OCEAN! {hop} tail-dropped {value}%!",
194
+ ),
195
+ ("REORDERING", "warn"): (
196
+ "Leapfrog! {value}% of packets arrived out of order across {hop}!",
197
+ "Musical chairs on {hop}: {value}% of packets overtook their friends!",
198
+ "A little queue-jumping ({value}%) along {hop}!",
199
+ "Fast swimmers passed slow swimmers: {value}% reordered on {hop}!",
200
+ "Sequence shuffle! {value}% of deliveries on {hop} swapped places!",
201
+ "Playful dolphins nudged {value}% of packets out of order on {hop}!",
202
+ "Mild scramble: {value}% reordering detected on {hop}!",
203
+ "Packets playing tag on {hop}—{value}% arrived ahead of earlier seqs!",
204
+ ),
205
+ ("REORDERING", "critical"): (
206
+ "TOTAL SCRAMBLE! {value}% of packets arrived out of order on {hop}!",
207
+ "CHAOS CONGA LINE! {value}% reordering across {hop}!",
208
+ "BLENDER MODE! {hop} tossed {value}% of packets into a salad!",
209
+ "CRITICAL SHUFFLE! {value}% of deliveries on {hop} overtook each other!",
210
+ "BACKWARDS SWIM! {value}% reordering on {hop}—sequence numbers are dizzy!",
211
+ "STAMPEDE! {value}% of packets scrambled past each other on {hop}!",
212
+ "ANARCHY IN THE PIPE! {value}% out-of-order arrivals on {hop}!",
213
+ "WHIRLPOOL SHUFFLE! {hop} scrambled {value}% of the stream!",
214
+ ),
215
+ }
216
+
217
+
218
+ @dataclass(frozen=True)
219
+ class Line:
220
+ """A single mascot narration line."""
221
+
222
+ text: str
223
+ tone: str
224
+ hop: str | None
225
+
226
+
227
+ class Narrator:
228
+ """Rule-based mascot narrator with weighted selection and no-repeat session memory."""
229
+
230
+ def __init__(
231
+ self,
232
+ extra_finding_pools: Mapping[tuple[str, str], Sequence[str]] | None = None,
233
+ extra_drop_pools: Mapping[str, Sequence[str]] | None = None,
234
+ ) -> None:
235
+ self._used: dict[str, set[int]] = {}
236
+ self._extra_finding_pools: dict[tuple[str, str], tuple[str, ...]] = (
237
+ {k: tuple(v) for k, v in extra_finding_pools.items()}
238
+ if extra_finding_pools
239
+ else {}
240
+ )
241
+ self._extra_drop_pools: dict[str, tuple[str, ...]] = (
242
+ {k: tuple(v) for k, v in extra_drop_pools.items()}
243
+ if extra_drop_pools
244
+ else {}
245
+ )
246
+
247
+ def reset(self) -> None:
248
+ """Clear no-repeat memory for a fresh session."""
249
+ self._used.clear()
250
+
251
+ def _pick(self, pool_key: str, pool: Sequence[str], rng: random.Random) -> str:
252
+ used = self._used.setdefault(pool_key, set())
253
+ available = [i for i in range(len(pool)) if i not in used]
254
+ if not available:
255
+ used.clear()
256
+ available = list(range(len(pool)))
257
+ # Weighted toward earlier (punchier) lines while still covering the whole pool
258
+ weights = [max(1, len(pool) - idx) for idx in available]
259
+ chosen_idx = rng.choices(available, weights=weights, k=1)[0]
260
+ used.add(chosen_idx)
261
+ return pool[chosen_idx]
262
+
263
+ def narrate(
264
+ self,
265
+ findings: Sequence[Any],
266
+ metrics: Any | None,
267
+ events: Sequence[Any] | None = None,
268
+ seed: int | None = None,
269
+ mode: str = "simulate",
270
+ ) -> list[Line]:
271
+ """Produce mascot narration lines for findings, drop reasons, and summary."""
272
+ rng = random.Random(seed)
273
+ lines: list[Line] = []
274
+
275
+ if not findings:
276
+ template = self._pick("healthy", HEALTHY_POOL, rng)
277
+ delivered = getattr(metrics, "delivered", 0) if metrics is not None else 0
278
+ lines.append(
279
+ Line(
280
+ text=template.format(hop="the path", value=f"{delivered} packets"),
281
+ tone="calm",
282
+ hop=None,
283
+ )
284
+ )
285
+ else:
286
+ for finding in findings:
287
+ code = getattr(finding, "code", "")
288
+ severity = getattr(finding, "severity", "warn")
289
+ hop = getattr(finding, "hop", None)
290
+ value = getattr(finding, "value", 0.0)
291
+ base_pool = FINDING_POOLS.get((code, severity))
292
+ extra_pool = self._extra_finding_pools.get((code, severity), ())
293
+ if base_pool is None and not extra_pool:
294
+ continue
295
+ pool = tuple(base_pool or ()) + extra_pool
296
+ template = self._pick(f"{code}:{severity}", pool, rng)
297
+ hop_label = hop if hop is not None else "the path"
298
+ tone = "frantic" if severity == "critical" else "worried"
299
+ lines.append(
300
+ Line(
301
+ text=template.format(hop=hop_label, value=f"{value:.1f}"),
302
+ tone=tone,
303
+ hop=hop,
304
+ )
305
+ )
306
+
307
+ if events:
308
+ drop_counts: dict[tuple[str, str | None], int] = {}
309
+ for ev in events:
310
+ if getattr(ev, "type", None) == "packet_dropped":
311
+ reason = getattr(ev, "reason", None)
312
+ if reason in DROP_REASON_POOLS:
313
+ key = (reason, getattr(ev, "hop", None))
314
+ drop_counts[key] = drop_counts.get(key, 0) + 1
315
+ for (reason, hop), count in drop_counts.items():
316
+ pool = DROP_REASON_POOLS[reason] + self._extra_drop_pools.get(reason, ())
317
+ template = self._pick(f"drop:{reason}", pool, rng)
318
+ lines.append(
319
+ Line(
320
+ text=template.format(hop=hop or "the path", value=str(count)),
321
+ tone="chaotic",
322
+ hop=hop,
323
+ )
324
+ )
325
+
326
+ if metrics is not None:
327
+ delivered = getattr(metrics, "delivered", 0)
328
+ sent = getattr(metrics, "sent", 0)
329
+ if mode == "diagnose":
330
+ summary_tmpl = self._pick("diagnose_summary", DIAGNOSE_SUMMARY_POOL, rng)
331
+ else:
332
+ summary_tmpl = self._pick("summary", SUMMARY_POOL, rng)
333
+ lines.append(
334
+ Line(
335
+ text=summary_tmpl.format(hop="the path", value=f"{delivered}/{sent}"),
336
+ tone="upbeat",
337
+ hop=None,
338
+ )
339
+ )
340
+
341
+ return lines
342
+
343
+
344
+ def narrate(
345
+ findings: Sequence[Any],
346
+ metrics: Any | None,
347
+ events: Sequence[Any] | None = None,
348
+ seed: int | None = None,
349
+ mode: str = "simulate",
350
+ ) -> list[Line]:
351
+ """Stateless convenience wrapper around Narrator.narrate()."""
352
+ return Narrator().narrate(findings, metrics, events, seed=seed, mode=mode)
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ from .loader import load_plugin, load_plugins_from_dir
4
+ from .models import (
5
+ MAX_JOKE_LEN,
6
+ MAX_PLUGIN_FILE_BYTES,
7
+ MAX_PLUGIN_FILES,
8
+ MAX_PLUGIN_TOTAL_BYTES,
9
+ MIN_CONTRAST_RATIO,
10
+ LoadedPlugin,
11
+ PluginKind,
12
+ PluginManifest,
13
+ PluginRegistry,
14
+ )
15
+
16
+ __all__ = [
17
+ "MAX_JOKE_LEN",
18
+ "MAX_PLUGIN_FILE_BYTES",
19
+ "MAX_PLUGIN_FILES",
20
+ "MAX_PLUGIN_TOTAL_BYTES",
21
+ "MIN_CONTRAST_RATIO",
22
+ "LoadedPlugin",
23
+ "PluginKind",
24
+ "PluginManifest",
25
+ "PluginRegistry",
26
+ "load_plugin",
27
+ "load_plugins_from_dir",
28
+ ]