sensorium-trace 0.18.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 (135) hide show
  1. sensorium/__init__.py +0 -0
  2. sensorium/__main__.py +4 -0
  3. sensorium/_c/rt/sensorium_c_rt.c +1446 -0
  4. sensorium/_typescript/package-lock.json +68 -0
  5. sensorium/_typescript/package.json +39 -0
  6. sensorium/_typescript/src/bindings.mjs +792 -0
  7. sensorium/_typescript/src/cap.mjs +227 -0
  8. sensorium/_typescript/src/capabilities.mjs +40 -0
  9. sensorium/_typescript/src/dbg.mjs +348 -0
  10. sensorium/_typescript/src/escape.mjs +351 -0
  11. sensorium/_typescript/src/focus.mjs +135 -0
  12. sensorium/_typescript/src/hook.mjs +127 -0
  13. sensorium/_typescript/src/index.mjs +1 -0
  14. sensorium/_typescript/src/naming.mjs +63 -0
  15. sensorium/_typescript/src/positions.mjs +37 -0
  16. sensorium/_typescript/src/probe.mjs +246 -0
  17. sensorium/_typescript/src/qualname.mjs +236 -0
  18. sensorium/_typescript/src/redact.mjs +711 -0
  19. sensorium/_typescript/src/register.mjs +15 -0
  20. sensorium/_typescript/src/resolve.mjs +260 -0
  21. sensorium/_typescript/src/rt.mjs +798 -0
  22. sensorium/_typescript/src/setup.mjs +11 -0
  23. sensorium/_typescript/src/tally.mjs +164 -0
  24. sensorium/_typescript/src/tasks.mjs +175 -0
  25. sensorium/_typescript/src/transform.mjs +800 -0
  26. sensorium/_typescript/src/vite.mjs +99 -0
  27. sensorium/c/__init__.py +8 -0
  28. sensorium/c/cc.py +612 -0
  29. sensorium/c/cli.py +60 -0
  30. sensorium/c/convert.py +669 -0
  31. sensorium/c/decode.py +300 -0
  32. sensorium/c/driver.py +365 -0
  33. sensorium/c/dwarf.py +706 -0
  34. sensorium/c/format.py +271 -0
  35. sensorium/c/pkg.py +187 -0
  36. sensorium/c/plan.py +277 -0
  37. sensorium/cli.py +140 -0
  38. sensorium/driver.py +47 -0
  39. sensorium/exit.py +33 -0
  40. sensorium/invocations.py +83 -0
  41. sensorium/limits.py +253 -0
  42. sensorium/mcp/__init__.py +0 -0
  43. sensorium/mcp/audit.py +162 -0
  44. sensorium/mcp/child.py +240 -0
  45. sensorium/mcp/cmd.py +101 -0
  46. sensorium/mcp/jsonrpc.py +172 -0
  47. sensorium/mcp/result.py +187 -0
  48. sensorium/mcp/schema.py +390 -0
  49. sensorium/mcp/server.py +493 -0
  50. sensorium/mcp/tools.py +299 -0
  51. sensorium/paths.py +80 -0
  52. sensorium/query/__init__.py +0 -0
  53. sensorium/query/caps.py +150 -0
  54. sensorium/query/dbg_dialects.py +64 -0
  55. sensorium/query/diff_cmd.py +748 -0
  56. sensorium/query/diff_notes.py +117 -0
  57. sensorium/query/exceptions_c.py +263 -0
  58. sensorium/query/exceptions_cmd.py +788 -0
  59. sensorium/query/exceptions_group.py +571 -0
  60. sensorium/query/exceptions_invocation.py +487 -0
  61. sensorium/query/exceptions_rust.py +683 -0
  62. sensorium/query/exceptions_typescript.py +688 -0
  63. sensorium/query/expr.py +606 -0
  64. sensorium/query/failures_cmd.py +306 -0
  65. sensorium/query/flow_cmd.py +778 -0
  66. sensorium/query/flow_report.py +128 -0
  67. sensorium/query/flow_values.py +195 -0
  68. sensorium/query/fmt.py +280 -0
  69. sensorium/query/frame_cmd.py +237 -0
  70. sensorium/query/grep_cmd.py +156 -0
  71. sensorium/query/help.py +18 -0
  72. sensorium/query/info_cmd.py +527 -0
  73. sensorium/query/info_rust.py +214 -0
  74. sensorium/query/info_typescript.py +261 -0
  75. sensorium/query/js_inspect.py +394 -0
  76. sensorium/query/moves.py +254 -0
  77. sensorium/query/redact_cmd.py +304 -0
  78. sensorium/query/refocus_cmd.py +661 -0
  79. sensorium/query/refocus_env.py +493 -0
  80. sensorium/query/refocus_facts.py +269 -0
  81. sensorium/query/refocus_licence.py +187 -0
  82. sensorium/query/refocus_report.py +327 -0
  83. sensorium/query/refocus_rust.py +537 -0
  84. sensorium/query/refocus_threads.py +197 -0
  85. sensorium/query/refocus_typescript.py +756 -0
  86. sensorium/query/refocus_world.py +666 -0
  87. sensorium/query/runs_cmd.py +213 -0
  88. sensorium/query/rust_debug.py +176 -0
  89. sensorium/query/sites.py +171 -0
  90. sensorium/query/tree_cmd.py +511 -0
  91. sensorium/query/tree_threads.py +168 -0
  92. sensorium/query/vocab.py +723 -0
  93. sensorium/query/watch_cmd.py +657 -0
  94. sensorium/record/__init__.py +0 -0
  95. sensorium/record/boot.py +797 -0
  96. sensorium/record/boot_io.py +141 -0
  97. sensorium/record/budget.py +135 -0
  98. sensorium/record/capture.py +433 -0
  99. sensorium/record/children.py +755 -0
  100. sensorium/record/children_merge.py +179 -0
  101. sensorium/record/elide.py +55 -0
  102. sensorium/record/fingerprint.py +26 -0
  103. sensorium/record/thread_starts.py +261 -0
  104. sensorium/record/tracer.py +798 -0
  105. sensorium/record/tracer_exc.py +199 -0
  106. sensorium/record/tracer_frames.py +618 -0
  107. sensorium/redact.py +304 -0
  108. sensorium/redact_content.py +156 -0
  109. sensorium/redact_key.py +317 -0
  110. sensorium/redact_store.py +502 -0
  111. sensorium/redact_values.py +433 -0
  112. sensorium/store/__init__.py +0 -0
  113. sensorium/store/db.py +284 -0
  114. sensorium/store/gc.py +360 -0
  115. sensorium/store/payloads.py +69 -0
  116. sensorium/store/reader.py +438 -0
  117. sensorium/store/writer.py +283 -0
  118. sensorium/ts/__init__.py +10 -0
  119. sensorium/ts/build.py +783 -0
  120. sensorium/ts/cli.py +130 -0
  121. sensorium/ts/driver.py +472 -0
  122. sensorium/ts/focus.py +146 -0
  123. sensorium/ts/harness.py +314 -0
  124. sensorium/ts/ingest.py +380 -0
  125. sensorium/ts/invocation.py +252 -0
  126. sensorium/ts/pkg.py +167 -0
  127. sensorium/ts/redaction.py +64 -0
  128. sensorium/ts/spool.py +168 -0
  129. sensorium/ts/truncation.py +81 -0
  130. sensorium/ts/wrapper.py +255 -0
  131. sensorium_trace-0.18.2.dist-info/METADATA +245 -0
  132. sensorium_trace-0.18.2.dist-info/RECORD +135 -0
  133. sensorium_trace-0.18.2.dist-info/WHEEL +4 -0
  134. sensorium_trace-0.18.2.dist-info/entry_points.txt +3 -0
  135. sensorium_trace-0.18.2.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,433 @@
1
+ """Structured value capture with hard caps and marked truncation.
2
+
3
+ Captures may be smaller than the real value; they are never silently so.
4
+ Anything cut carries "trunc": true; anything the object REFUSED to hand over
5
+ carries "unread": [names], naming which reads failed. Both bump
6
+ capture_stats["truncated"], which `info` reports as "truncated values".
7
+
8
+ Every read in this module is a call INTO the observed program. `__len__`,
9
+ `__iter__`, `items()`, `__str__`, `__repr__` -- and even `__class__`, which
10
+ `isinstance` consults, and the type's own `__name__` -- are all overridable,
11
+ and every one of them runs from inside a `sys.monitoring` callback. An
12
+ exception escaping one of them does not fail the capture: it propagates into
13
+ the observed program's frame, kills a program that runs clean standalone, and
14
+ is then reported by `exceptions` as that program's own bug, at the user's own
15
+ line, with a confident disposition. So every such read is guarded, and its
16
+ failure is RECORDED rather than invented around.
17
+ """
18
+ from itertools import islice
19
+
20
+ CAPS = {"str": 200, "repr": 200, "sample": 8, "depth": 3}
21
+
22
+ #: A default-repr object's field summary. Kept OUT of `CAPS`: `meta.caps`
23
+ #: and TRACE-FORMAT pin that four-key dict, and a field summary is a
24
+ #: display aid with its own tighter clip. Eight names, each value's text
25
+ #: clipped to 60 characters, and no nested field summary (a field that is
26
+ #: itself an object keeps a repr, not another `{...}`).
27
+ FIELD_KEYS = 8
28
+ FIELD_REPR = 60
29
+
30
+ capture_stats = {"truncated": 0}
31
+
32
+ #: Slot names that are not data. `__dict__` and `__weakref__` appear in
33
+ #: `__slots__` when a class asks for them; they are the machinery, not
34
+ #: fields a reader should see.
35
+ _SKIP_SLOTS = frozenset({"__dict__", "__weakref__"})
36
+
37
+
38
+ def _guarded(read, unread: list, name: str):
39
+ """One read against the observed object, which can never escape.
40
+
41
+ Returns None on failure and appends `name` to `unread`, so the capture
42
+ says which read it could not perform instead of inventing a value for it.
43
+ `BaseException` because a hostile dunder may raise anything at all, and
44
+ because letting anything out of a monitoring callback is strictly worse
45
+ than absorbing it here: the alternative is an exception attributed to the
46
+ program at a line that never raised.
47
+ """
48
+ try:
49
+ return read()
50
+ except BaseException:
51
+ unread.append(name)
52
+ capture_stats["truncated"] += 1
53
+ return None
54
+
55
+
56
+ def plain_str(s):
57
+ """`s` as an EXACT `str`; `s` unchanged if it is not a `str` at all.
58
+
59
+ A `str` subclass instance in a payload is a live object with live
60
+ dunders, and a payload outlives every guard in this module: `_on_line`
61
+ compares captures with `!=` (running `__eq__`) and `writer.add_event`
62
+ json-encodes them with `default=repr` (running `__repr__`), both on the
63
+ recorder's own thread and both outside anything here. Measured at
64
+ 6649bf0, on programs that run clean standalone: a `str` subclass with a
65
+ raising `__eq__` killed the traced program at `tracer.py:467`, and one
66
+ whose `__len__` overshot the cap while its `__getitem__` returned an
67
+ object with a raising `__repr__` killed it inside `json.dumps` -- the
68
+ latter in DEFAULT mode, through ordinary argument capture.
69
+
70
+ `str.__str__` rather than `str(s)`: `str()` honours a `__str__`
71
+ override, which can hand back another subclass instance (measured:
72
+ `str(ES("abc"))` returned an `ES`), while the unbound base slot reads
73
+ the underlying buffer and cannot be intercepted -- it also returns the
74
+ TRUE characters rather than whatever the override claims. Total by
75
+ construction: it can neither raise nor return a subclass.
76
+ """
77
+ if type(s) is str:
78
+ return s
79
+ try:
80
+ out = str.__str__(s)
81
+ except BaseException:
82
+ return s
83
+ return out if type(out) is str else s
84
+
85
+
86
+ def plain_num(n):
87
+ """An `int`/`float` subclass as its exact base type; `n` unchanged else.
88
+
89
+ Same hazard and same reasoning as `plain_str` -- `{"k": "num", "v": obj}`
90
+ embedded the live object -- with one addition: `int()` and `float()`
91
+ honour `__int__`/`__float__`, which can both LIE about the value and hand
92
+ back another subclass instance (measured: `int(EI(7))` returned 99). The
93
+ unbound base slots read the underlying value.
94
+
95
+ `issubclass(type(n), ...)`, NOT `isinstance(n, ...)`: isinstance consults
96
+ the INSTANCE's `__class__` when the type check is not an exact match, and a
97
+ `__class__` property can make that raise -- the very kind of program dunder
98
+ this normalisation exists to keep out of a payload. Dispatching on the type
99
+ touches no instance dunder, so like `plain_str` this is total by
100
+ construction: it can neither raise nor return a subclass.
101
+ """
102
+ t = type(n)
103
+ if t is int or t is float or t is bool:
104
+ return n
105
+ try:
106
+ if issubclass(t, int):
107
+ out = int.__int__(n)
108
+ elif issubclass(t, float):
109
+ out = float.__float__(n)
110
+ else:
111
+ return n
112
+ except BaseException:
113
+ return n
114
+ return out if type(out) in (int, float) else n
115
+
116
+
117
+ def type_name(obj) -> str:
118
+ """`type(obj).__name__` -- which a metaclass property can make raise,
119
+ and which it can also make return a live `str` subclass instance."""
120
+ try:
121
+ return plain_str(type(obj).__name__)
122
+ except BaseException:
123
+ return "?"
124
+
125
+
126
+ def _trunc_str(s: str, cap: int) -> tuple[str, bool]:
127
+ """Clip a string to `cap`, and NORMALISE it on the way through.
128
+
129
+ The single funnel every string in a payload passes: the `str` branch of
130
+ `_capture`, `_capture_obj`'s repr, and `capture_exc`'s message. `repr()`
131
+ and `str()` are both free to return a `str` SUBCLASS, so normalising
132
+ here rather than at each call site is what makes "no payload holds a
133
+ live object" a property of the module instead of a habit -- and it also
134
+ means `len(s)` and `s[:cap]` below run against a plain string rather
135
+ than against the observed program's `__len__` and `__getitem__`.
136
+ """
137
+ s = plain_str(s)
138
+ if len(s) <= cap:
139
+ return s, False
140
+ capture_stats["truncated"] += 1
141
+ return s[:cap], True
142
+
143
+
144
+ def capture_value(obj, depth: int = 0, *, summarize: bool = True) -> dict:
145
+ """Capture one value. Never raises -- see the module docstring.
146
+
147
+ The outer guard is not belt-and-braces over the inner ones: `isinstance`
148
+ consults `obj.__class__`, so the very first branch of `_capture` is
149
+ already a call into user code, as is `_trunc_str`'s `len()` on a `str`
150
+ subclass. Whatever gets past the specific guards still may not reach the
151
+ program.
152
+
153
+ `summarize` is true for a value captured as an argument, a local, a
154
+ return, or a member of one of those. Field values pass False, so a
155
+ field that is itself an object keeps a repr and does not grow another
156
+ field summary. Container members keep the flag: a list of plain
157
+ objects still shows each object's fields.
158
+ """
159
+ try:
160
+ return _capture(obj, depth, summarize=summarize)
161
+ except BaseException:
162
+ capture_stats["truncated"] += 1
163
+ return {"k": "unread", "type": type_name(obj), "oid": id(obj),
164
+ "unread": ["value"]}
165
+
166
+
167
+ def _capture(obj, depth: int, *, summarize: bool) -> dict:
168
+ if obj is None:
169
+ return {"k": "none"}
170
+ if isinstance(obj, bool):
171
+ return {"k": "bool", "v": obj} # `bool` cannot be subclassed
172
+ if isinstance(obj, (int, float)):
173
+ return {"k": "num", "v": plain_num(obj)}
174
+ if isinstance(obj, str):
175
+ s, t = _trunc_str(obj, CAPS["str"])
176
+ out = {"k": "str", "v": s}
177
+ if t:
178
+ out["trunc"] = True
179
+ return out
180
+ if isinstance(obj, (list, tuple, set, frozenset)):
181
+ return _capture_sized(obj, depth, "seq",
182
+ lambda o, d: [capture_value(x, d, summarize=summarize)
183
+ for x in islice(iter(o), CAPS["sample"])])
184
+ if isinstance(obj, dict):
185
+ return _capture_sized(obj, depth, "map",
186
+ lambda o, d: [[capture_value(k, d, summarize=summarize),
187
+ capture_value(v, d, summarize=summarize)]
188
+ for k, v in islice(o.items(), CAPS["sample"])])
189
+ return _capture_obj(obj, summarize=summarize)
190
+
191
+
192
+ def _capture_sized(obj, depth, kind, sampler) -> dict:
193
+ """A container's size and a sample of it, each read separately.
194
+
195
+ `len` and the sample are two independent calls into the object and fail
196
+ independently: a `list` subclass with a raising `__iter__` still has a
197
+ readable length, and a `dict` subclass with a raising `__len__` can still
198
+ be sampled. `len` is None when it could not be read -- never 0, which
199
+ `watch` would compare against as a fact -- and "sample" is absent rather
200
+ than partial, because half a materialised sample is not a sample of
201
+ anything.
202
+ """
203
+ unread: list = []
204
+ n = _guarded(lambda: len(obj), unread, "len")
205
+ out = {"k": kind, "type": type_name(obj), "len": n, "oid": id(obj)}
206
+ if depth >= CAPS["depth"]:
207
+ out["trunc"] = True
208
+ capture_stats["truncated"] += 1
209
+ else:
210
+ sample = _guarded(lambda: sampler(obj, depth + 1), unread, "sample")
211
+ if sample is not None:
212
+ out["sample"] = sample
213
+ # Only a length that was actually read can say the sample fell short.
214
+ if n is not None and n > CAPS["sample"]:
215
+ out["trunc"] = True
216
+ capture_stats["truncated"] += 1
217
+ if unread:
218
+ out["unread"] = unread
219
+ return out
220
+
221
+
222
+ def _capture_obj(obj, *, summarize: bool = True) -> dict:
223
+ out = {"k": "obj", "type": type_name(obj), "oid": id(obj)}
224
+ try:
225
+ r = repr(obj)
226
+ except BaseException:
227
+ r = f"<{type_name(obj)} repr-raised>"
228
+ out["trunc"] = True
229
+ out["unread"] = ["repr"]
230
+ capture_stats["truncated"] += 1
231
+ s, t = _trunc_str(r, CAPS["repr"])
232
+ out["repr"] = s
233
+ if t:
234
+ out["trunc"] = True
235
+ if summarize:
236
+ _attach_fields(obj, out)
237
+ return out
238
+
239
+
240
+ def _uses_default_repr(obj) -> bool:
241
+ """True when the first `__repr__` on the type's MRO is `object.__repr__`.
242
+
243
+ Walks class dicts, never the instance. A class that defines no
244
+ `__repr__` inherits `object`'s, whose text is `<Name object at 0x...>`
245
+ and names no field. Anything that cannot be read is treated as custom,
246
+ so a type that refuses the question does not grow an invented summary.
247
+ """
248
+ try:
249
+ default = object.__dict__.get("__repr__")
250
+ for cls in type(obj).__mro__:
251
+ found = cls.__dict__.get("__repr__")
252
+ if found is not None:
253
+ return found is default
254
+ except BaseException:
255
+ return False
256
+ return False
257
+
258
+
259
+ def _as_field_name(raw):
260
+ """A field name as an exact `str`, or None when it is not a name."""
261
+ if type(raw) is str:
262
+ name = raw
263
+ elif isinstance(raw, str):
264
+ coerced = plain_str(raw)
265
+ name = coerced if type(coerced) is str else None
266
+ else:
267
+ return None
268
+ if name is None or name in _SKIP_SLOTS or name == "_":
269
+ return None
270
+ return name
271
+
272
+
273
+ def _slot_items(raw):
274
+ """Names in a `__slots__` declaration: a string, or a list/tuple of them.
275
+
276
+ Anything else is ignored. A custom iterable would run the program's
277
+ `__iter__` from inside the callback, which this summary does not need.
278
+ """
279
+ if isinstance(raw, str):
280
+ return (raw,)
281
+ if type(raw) in (list, tuple):
282
+ return tuple(raw)
283
+ return ()
284
+
285
+
286
+ def _collect_names(obj) -> list:
287
+ """`__dict__` keys in insertion order, then `__slots__` along the MRO."""
288
+ names = []
289
+ seen = set()
290
+
291
+ def add(raw) -> None:
292
+ try:
293
+ name = _as_field_name(raw)
294
+ except BaseException:
295
+ return
296
+ if name is None or name in seen:
297
+ return
298
+ seen.add(name)
299
+ names.append(name)
300
+
301
+ try:
302
+ d = object.__getattribute__(obj, "__dict__")
303
+ except BaseException:
304
+ d = None
305
+ if type(d) is dict:
306
+ for key in d:
307
+ add(key)
308
+ elif isinstance(d, dict):
309
+ try:
310
+ keys = list(d)
311
+ except BaseException:
312
+ keys = []
313
+ for key in keys:
314
+ add(key)
315
+
316
+ try:
317
+ mro = type(obj).__mro__
318
+ except BaseException:
319
+ return names
320
+ for cls in mro:
321
+ try:
322
+ raw = cls.__dict__.get("__slots__")
323
+ except BaseException:
324
+ continue
325
+ if raw is None:
326
+ continue
327
+ try:
328
+ slots = _slot_items(raw)
329
+ except BaseException:
330
+ continue
331
+ for slot in slots:
332
+ add(slot)
333
+ return names
334
+
335
+
336
+ def _field_value(val) -> dict:
337
+ """One field, clipped tighter than a normal capture and not re-summarised.
338
+
339
+ Containers are captured at the depth cap, so they keep a type and a
340
+ length and no sample. Strings clip once, at `FIELD_REPR`, rather than
341
+ at `CAPS["str"]` and then again.
342
+ """
343
+ if isinstance(val, str):
344
+ s, t = _trunc_str(val, FIELD_REPR)
345
+ out = {"k": "str", "v": s}
346
+ if t:
347
+ out["trunc"] = True
348
+ return out
349
+ cap = capture_value(val, depth=CAPS["depth"], summarize=False)
350
+ if cap.get("k") == "obj" and isinstance(cap.get("repr"), str):
351
+ text = cap["repr"]
352
+ if len(text) > FIELD_REPR:
353
+ cap = dict(cap)
354
+ cap["repr"] = text[:FIELD_REPR]
355
+ if not cap.get("trunc"):
356
+ capture_stats["truncated"] += 1
357
+ cap["trunc"] = True
358
+ return cap
359
+
360
+
361
+ def _read_field(obj, name: str) -> dict:
362
+ """The value of one field. A failed read is `unread`, never a captured None."""
363
+ try:
364
+ d = object.__getattribute__(obj, "__dict__")
365
+ except BaseException:
366
+ d = None
367
+ if type(d) is dict and name in d:
368
+ try:
369
+ return _field_value(d[name])
370
+ except BaseException:
371
+ capture_stats["truncated"] += 1
372
+ return {"k": "unread", "unread": ["value"]}
373
+ try:
374
+ return _field_value(object.__getattribute__(obj, name))
375
+ except BaseException:
376
+ capture_stats["truncated"] += 1
377
+ return {"k": "unread", "unread": ["value"]}
378
+
379
+
380
+ def _attach_fields(obj, out: dict) -> None:
381
+ """A shallow `{name: capture}` on `out` when `obj` uses `object.__repr__`.
382
+
383
+ Absent when the class defines its own repr (that text is the summary)
384
+ and absent when the instance has no fields. `fields_trunc` means more
385
+ names existed than `FIELD_KEYS`. A summary that itself fails is
386
+ `unread: ["fields"]` on the object, and the repr already stored stays.
387
+ """
388
+ if not _uses_default_repr(obj):
389
+ return
390
+ try:
391
+ names = _collect_names(obj)
392
+ except BaseException:
393
+ out.setdefault("unread", []).append("fields")
394
+ capture_stats["truncated"] += 1
395
+ return
396
+ if not names:
397
+ return
398
+ kept = names[:FIELD_KEYS]
399
+ fields = {name: _read_field(obj, name) for name in kept}
400
+ if fields:
401
+ out["fields"] = fields
402
+ if len(names) > FIELD_KEYS:
403
+ out["fields_trunc"] = True
404
+ capture_stats["truncated"] += 1
405
+
406
+
407
+ def capture_exc(exc: BaseException, serial: int | None = None) -> dict:
408
+ """Capture one exception.
409
+
410
+ `oid` is `id(exc)` and is NOT an identity: CPython recycles addresses, so
411
+ two distinct exceptions routinely share one -- measured, in a plain retry
412
+ loop. `serial` is the exact identity, minted by the tracer's exception
413
+ state machine while it holds a strong reference to the object, and is
414
+ absent only where the recorder genuinely does not know it (and in traces
415
+ recorded before serials existed).
416
+
417
+ `str(exc)` is the observed program's `__str__`, guarded like every other
418
+ read here: an exception whose message cannot be read is reported as
419
+ exactly that, never as an exception with an empty message.
420
+ """
421
+ unread: list = []
422
+ # The clip is INSIDE the guard: `str(exc)` may return a `str` subclass,
423
+ # and normalising one runs no user code but reading a hostile `__len__`
424
+ # would -- see `_trunc_str`. `capture_exc` is its own entry point, with
425
+ # no outer guard above it, so nothing here may raise.
426
+ msg = _guarded(lambda: _trunc_str(str(exc), CAPS["str"])[0], unread, "msg")
427
+ out = {"type": type_name(exc), "msg": "" if msg is None else msg,
428
+ "oid": id(exc)}
429
+ if unread:
430
+ out["unread"] = unread
431
+ if serial is not None:
432
+ out["serial"] = serial
433
+ return out