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,798 @@
1
+ // The runtime. Every instrumented file imports this module and calls into it,
2
+ // so it imports `node:` builtins and nothing else, boots lazily on its first
3
+ // record, and is a complete no-op when the tier is not `call` — the whole cost
4
+ // of `off` is the transform (E1, 1.058).
5
+ //
6
+ // What it holds: the tasks a test callback opens, the frame stack each task
7
+ // owns, the values it is allowed to read, and the JSONL spool it appends to.
8
+ // One spool per container `(pid, threadId)`; one JSON object per line; the
9
+ // converter (`sensorium ts ingest`) is the only reader.
10
+ import { AsyncLocalStorage } from 'node:async_hooks';
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { isMainThread, threadId } from 'node:worker_threads';
14
+
15
+ import { budget } from './cap.mjs';
16
+ import { capabilities } from './capabilities.mjs';
17
+ import { cap, captures, dbg, exc } from './dbg.mjs';
18
+ import { VERSION } from './index.mjs';
19
+ import { nameFor, setProvider, titleOf } from './naming.mjs';
20
+ import { bootEnv, redactReturn } from './redact.mjs';
21
+
22
+ /** @typedef {{id: number, name: string, stack: Frame[]}} Task */
23
+ /** @typedef {{id: number, task: Task|null, q: string, open: boolean, mark: Record<string, unknown>|null, pending?: Captured, elided?: boolean, reason?: string|null, file?: number, c?: number}} Frame */
24
+ /** @typedef {Record<string, unknown>} Record_ */
25
+ /** @typedef {import('./dbg.mjs').Captured} Captured */
26
+
27
+ /** The tier is read ONCE, at module load: a run does not change instrument. */
28
+ const TIER = process.env.SENSORIUM_TIER ?? 'off';
29
+ const SPOOL_DIR = process.env.SENSORIUM_SPOOL ?? '';
30
+ const INVOCATION = process.env.SENSORIUM_INVOCATION ?? null;
31
+ /**
32
+ * The focus, read once at module load for the reason the tier is: which
33
+ * functions were instrumented for statements is a property of the run, not
34
+ * something a program may change halfway through. What the specs SAY is the
35
+ * transform's business; this module needs only whether there was one.
36
+ */
37
+ const FOCUS = process.env.SENSORIUM_FOCUS ?? '';
38
+
39
+ const FLUSH_MS = 100;
40
+ const BUFFERED = 256;
41
+ /** @type {NodeJS.Signals[]} */
42
+ const SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'];
43
+
44
+ /** What a reader may ask of a trace this run writes (§2.4). */
45
+ const CAPABILITIES = capabilities(FOCUS);
46
+
47
+ /**
48
+ * Recording at all. A tier that is not `call` records nothing, and neither does
49
+ * a `call` tier with nowhere to write: a spool directory that was not given is
50
+ * not guessed at. Cleared for good if the disk refuses a write.
51
+ */
52
+ let on = TIER === 'call' && SPOOL_DIR !== '';
53
+
54
+ /** @type {AsyncLocalStorage<Task>} */
55
+ const als = new AsyncLocalStorage();
56
+ /** Frames running in no task — a hook, a module body — share the container's. */
57
+ /** @type {Frame[]} */
58
+ const rootStack = [];
59
+ /**
60
+ * Each FILE record's `codes`, by the id its calls carry: the one thing a
61
+ * frame needs about its own site AFTER the CALL is written, which is the
62
+ * qualname rule v1 reads a RETURN's name off (B7). Grows with the files a
63
+ * container loads and is never cleared — a frame may return long after its
64
+ * module did.
65
+ * @type {Map<number, [string, number, string][]>}
66
+ */
67
+ const fileCodes = new Map();
68
+ /** The `describe` chain, per container, as it stands during collection. */
69
+ /** @type {{title: string}[]} */
70
+ const suiteStack = [];
71
+
72
+ /**
73
+ * How many activations this CONTAINER has already given each capped task name.
74
+ * Module-level and not per registration (R39): `#k` exists to tell two runs of
75
+ * one test apart, and a reader who sees `#2` reads "the second time this name
76
+ * ran here" -- which is a fact about the container, not about which `test(...)`
77
+ * call produced it. Held in `wrapTask`'s closure, two registrations that shared
78
+ * a name both printed the bare name and the ledger's promise was false.
79
+ * @type {Map<string, number>}
80
+ */
81
+ const activations = new Map();
82
+
83
+ let nextFile = 1;
84
+ let nextTask = 1;
85
+ let nextFrame = 1;
86
+
87
+ /** @type {string[]} */
88
+ const buf = [];
89
+ let spoolPath = '';
90
+ let booted = false;
91
+
92
+ /** Monotonic nanoseconds, the clock every record is stamped with. */
93
+ const now = () => Number(process.hrtime.bigint());
94
+
95
+ // --- the spool -------------------------------------------------------------
96
+
97
+ /**
98
+ * Append what is buffered. Exported because the harness wiring flushes at the
99
+ * end of a test file, and cheap enough to call when there is nothing to write.
100
+ * @returns {void}
101
+ */
102
+ export function flush() {
103
+ if (!on || spoolPath === '' || buf.length === 0) return;
104
+ const text = `${buf.join('\n')}\n`;
105
+ buf.length = 0;
106
+ try {
107
+ // 0600 at CREATION, which is the only moment the mode is applied.
108
+ fs.appendFileSync(spoolPath, text, { mode: 0o600 });
109
+ } catch (err) {
110
+ // A recorder that cannot write says so once and stops; it does not retry
111
+ // into a full disk, and it does not pretend the records were kept.
112
+ on = false;
113
+ process.emitWarning(`sensorium: recording stopped, cannot write ${spoolPath}: ${err}`);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Boot on the first record, and say whether there is anywhere to write.
119
+ * @returns {boolean}
120
+ */
121
+ function ready() {
122
+ if (!on) return false;
123
+ if (!booted) boot();
124
+ return on;
125
+ }
126
+
127
+ /**
128
+ * @param {Record_} rec
129
+ * @returns {void}
130
+ */
131
+ function emit(rec) {
132
+ if (!ready()) return;
133
+ buf.push(JSON.stringify(rec));
134
+ budget.note(String(rec.e), buf[buf.length - 1].length + 1);
135
+ if (buf.length >= BUFFERED) flush();
136
+ }
137
+
138
+ /**
139
+ * The same, for the record kinds that carry a timestamp (`ts` last, always).
140
+ * The clock is read AFTER the boot it may trigger, so BOOT's `ts` is the
141
+ * smallest on the wire and no record appears to predate the run.
142
+ * @param {Record_} rec
143
+ * @returns {void}
144
+ */
145
+ function emitTs(rec) {
146
+ if (!ready()) return;
147
+ rec.ts = now();
148
+ emit(rec);
149
+ }
150
+
151
+ /** The first record of the spool, written on the first record of the run. */
152
+ function boot() {
153
+ booted = true;
154
+ try {
155
+ fs.mkdirSync(SPOOL_DIR, { recursive: true, mode: 0o700 });
156
+ } catch (err) {
157
+ on = false;
158
+ process.emitWarning(`sensorium: recording stopped, cannot use ${SPOOL_DIR}: ${err}`);
159
+ return;
160
+ }
161
+ spoolPath = path.join(SPOOL_DIR, `${process.pid}-${threadId}.jsonl`);
162
+ // Rule v1 applies HERE, before a byte reaches the disk: `env` is what the
163
+ // trace will hold, `envHash` is over THAT, and the other two say what was
164
+ // taken out and under which rule (`redact.mjs`).
165
+ buf.push(JSON.stringify({
166
+ e: 'BOOT',
167
+ wire: 1,
168
+ pid: process.pid,
169
+ ppid: process.ppid,
170
+ threadId,
171
+ isMainThread,
172
+ argv: process.argv,
173
+ cwd: process.cwd(),
174
+ ...bootEnv(process.env),
175
+ node: process.version,
176
+ version: VERSION,
177
+ tier: TIER,
178
+ capabilities: { ...CAPABILITIES },
179
+ invocation: INVOCATION,
180
+ startTs: Date.now() / 1000,
181
+ ts: now(),
182
+ }));
183
+ budget.note('BOOT', buf[buf.length - 1].length + 1);
184
+ install();
185
+ }
186
+
187
+ let closed = false;
188
+ /** @param {Record_} rec One ELISION, if calls were dropped, then this record. */
189
+ function closeOut(rec) {
190
+ if (!closed) { closed = true; const extra = budget.report(); if (extra) emit(extra); }
191
+ emitTs(rec);
192
+ flush();
193
+ }
194
+
195
+ /**
196
+ * Every path by which records reach the disk. A container killed by `SIGKILL`
197
+ * — vitest's teardown timeout — still loses its unflushed tail and its EXIT,
198
+ * and no count of the loss is written, because the process cannot know one.
199
+ */
200
+ function install() {
201
+ setInterval(flush, FLUSH_MS).unref();
202
+ process.on('exit', (code) => {
203
+ closeOut({ e: 'EXIT', code: process.exitCode ?? code, endTs: Date.now() / 1000 });
204
+ });
205
+ process.on('beforeExit', () => flush());
206
+ for (const sig of SIGNALS) {
207
+ /** @type {NodeJS.SignalsListener} */
208
+ const handler = () => {
209
+ flush();
210
+ // A signalled container still says how it ended (R13): EXIT is the last
211
+ // line, `code` null because none was chosen and `signal` naming what
212
+ // ended it. Only an uncatchable SIGKILL leaves a spool without one.
213
+ closeOut({ e: 'EXIT', code: null, signal: sig, endTs: Date.now() / 1000 });
214
+ // Then put the default disposition back and die of the signal we were
215
+ // sent: the recorder does not decide whether the process survives one.
216
+ process.removeListener(sig, handler);
217
+ process.kill(process.pid, sig);
218
+ };
219
+ process.on(sig, handler);
220
+ }
221
+ process.on('unhandledRejection', (reason) => {
222
+ emitTs({ e: 'UNHANDLED', x: exc(reason, 'rejection') });
223
+ flush();
224
+ });
225
+ }
226
+
227
+ // --- files, tests and suites -----------------------------------------------
228
+
229
+ /**
230
+ * The per-module header: one FILE record, one id the file's calls carry.
231
+ * @param {string} rel root-relative path
232
+ * @param {string} abs absolute path
233
+ * @param {[string, number, string][]} codes `[qualname, line, kind]` per site
234
+ * @param {string} sha sha256 of the ORIGINAL source
235
+ * @returns {number} the file id
236
+ */
237
+ export function file(rel, abs, codes, sha) {
238
+ if (!on) return 0;
239
+ const id = nextFile++;
240
+ fileCodes.set(id, codes);
241
+ emit({ e: 'FILE', id, rel, abs, codes, sha });
242
+ return id;
243
+ }
244
+
245
+ /**
246
+ * A test's argument list, read from the end: `rest` is `[...between, fn, flags]`
247
+ * — the flags always last, the callback the one before it, and `between` the
248
+ * options object vitest's `test(name, options, fn)` form allows (R8c). The
249
+ * flags are the transform's own knowledge of the title and are consumed here;
250
+ * everything else comes back in the order the source wrote it.
251
+ * @param {unknown} title
252
+ * @param {...unknown} rest
253
+ * @returns {unknown[]} `[title, ...between, wrapped]`
254
+ */
255
+ export function task(title, ...rest) {
256
+ const fn = rest[rest.length - 2];
257
+ const head = rest.slice(0, -1);
258
+ if (!on || typeof fn !== 'function') return [title, ...head];
259
+ const flags = Number(rest[rest.length - 1]) || 0;
260
+ return [title, ...head.slice(0, -1), wrapTask(titleOf(title), fn, flags)];
261
+ }
262
+
263
+ /**
264
+ * A suite's argument list: `[...between, fn]`, no flags — a suite is not named
265
+ * by the harness, it only lends its title to the tasks registered inside it.
266
+ * @param {unknown} title
267
+ * @param {...unknown} rest
268
+ * @returns {unknown[]} `[title, ...between, wrapped]`
269
+ */
270
+ export function suite(title, ...rest) {
271
+ const fn = rest[rest.length - 1];
272
+ if (!on || typeof fn !== 'function') return [title, ...rest];
273
+ return [title, ...rest.slice(0, -1), wrapSuite(titleOf(title), fn)];
274
+ }
275
+
276
+ /**
277
+ * Register the harness's own name for the test now running. The vitest setup
278
+ * file supplies `() => expect.getState().currentTestName ?? null`; under
279
+ * `node --test` there is no provider and the lexical name is the name. The
280
+ * rule is `naming.mjs`'s; the tier gate is this module's, because `on` is.
281
+ * @param {unknown} fn
282
+ * @returns {void}
283
+ */
284
+ export function nameProvider(fn) {
285
+ if (!on) return;
286
+ setProvider(fn);
287
+ }
288
+
289
+ /**
290
+ * @param {string} title
291
+ * @param {Function} fn
292
+ * @param {number} flags bit 1: a plain string literal; bit 2: a `.each` chain
293
+ * @returns {Function}
294
+ */
295
+ function wrapTask(title, fn, flags) {
296
+ const lexical = [...suiteStack.map((s) => s.title), title].join(' > ');
297
+ // Activations are counted PER NAME, per CONTAINER — see `activations` above.
298
+ // A harness that gave this activation a name of its own — `test.each`
299
+ // expanding a template into a row's values — has already told them apart, and
300
+ // numbering those would rename tests that never repeated.
301
+ return /** @this {unknown} */ function sensoriumTask(/** @type {unknown[]} */ ...args) {
302
+ const named = nameFor(title, lexical, flags);
303
+ // The name came from the consumer — a title, or whatever the harness calls
304
+ // this test — so it is capped like every other consumer string (R14). The
305
+ // `#k` suffix is the recorder's own and is added after the cut, because two
306
+ // names that were cut to the same text are the same name to a reader.
307
+ const capped = cap(named.name);
308
+ const k = (activations.get(capped.v) ?? 0) + 1;
309
+ activations.set(capped.v, k);
310
+ const name = k >= 2 ? `${capped.v}#${k}` : capped.v;
311
+ /** @type {Task} */
312
+ const t = { id: nextTask++, name, stack: [] };
313
+ /** @type {Record_} */
314
+ const rec = { e: 'TASK', id: t.id, name, basis: named.basis, conflict: named.conflict };
315
+ if (capped.trunc) rec.name_trunc = true;
316
+ emit(rec);
317
+ // A task's records reach the disk when the task settles — however it
318
+ // settles — whatever the harness does to this worker afterwards.
319
+ try {
320
+ // Every continuation of this callback — microtask, timer, jsdom timer,
321
+ // emitter callback — resolves to this task, because the task is a
322
+ // property of the async context and not of the call stack.
323
+ const out = als.run(t, () => fn.apply(this, args));
324
+ if (thenable(out)) return out.then(taskSettled, taskFailed);
325
+ flush();
326
+ return out;
327
+ } catch (err) {
328
+ return taskFailed(err);
329
+ }
330
+ };
331
+ }
332
+
333
+ /** @param {unknown} v @returns {unknown} */
334
+ function taskSettled(v) {
335
+ flush();
336
+ return v;
337
+ }
338
+
339
+ /** @param {unknown} err @returns {never} */
340
+ function taskFailed(err) {
341
+ flush();
342
+ throw err;
343
+ }
344
+
345
+ /**
346
+ * The `describe` title stands while its callback runs, so a task registered
347
+ * inside it knows its lexical chain at REGISTRATION time.
348
+ *
349
+ * A callback that returns a promise keeps its title until the promise settles.
350
+ * The stack is then a temporal approximation of the lexical chain, not the
351
+ * chain itself: a test registered after an `await` inside an async `describe`
352
+ * can see titles pushed by other suites that ran while this one was parked.
353
+ * Where vitest's own name provider runs, that name is the authority; the
354
+ * lexical name is the fallback, and this is one of the places it can be wrong.
355
+ * @param {string} title
356
+ * @param {Function} fn
357
+ * @returns {Function}
358
+ */
359
+ function wrapSuite(title, fn) {
360
+ return /** @this {unknown} */ function sensoriumSuite(/** @type {unknown[]} */ ...args) {
361
+ const entry = { title };
362
+ const done = (/** @type {unknown} */ v) => {
363
+ leave(entry);
364
+ return v;
365
+ };
366
+ const failed = (/** @type {unknown} */ err) => {
367
+ leave(entry);
368
+ throw err;
369
+ };
370
+ suiteStack.push(entry);
371
+ try {
372
+ const out = fn.apply(this, args);
373
+ return thenable(out) ? out.then(done, failed) : done(out);
374
+ } catch (err) {
375
+ return failed(err);
376
+ }
377
+ };
378
+ }
379
+
380
+ /** @param {{title: string}} entry @returns {void} */
381
+ function leave(entry) {
382
+ const i = suiteStack.lastIndexOf(entry);
383
+ if (i >= 0) suiteStack.splice(i, 1);
384
+ }
385
+
386
+ /** @param {any} v @returns {v is PromiseLike<unknown>} */
387
+ const thenable = (v) => v !== null && typeof v === 'object' && typeof v.then === 'function';
388
+
389
+ // --- frames ----------------------------------------------------------------
390
+
391
+ /** @param {Frame|null} f @returns {number|null} */
392
+ const taskId = (f) => (f && f.task ? f.task.id : null);
393
+
394
+ /** @param {Frame} f @returns {Frame[]} */
395
+ const stackOf = (f) => (f.task ? f.task.stack : rootStack);
396
+
397
+ /** @param {Frame} f @returns {void} */
398
+ function drop(f) {
399
+ const stack = stackOf(f);
400
+ const i = stack.lastIndexOf(f);
401
+ if (i >= 0) stack.splice(i, 1);
402
+ }
403
+
404
+ /** @param {Frame|null} frame Skeleton CALL, outermost ancestor first. Arguments are not read. */
405
+ function materialize(frame) {
406
+ if (!frame) return;
407
+ budget.materialize(frame, stackOf(frame), (cur, parent) => {
408
+ emitTs({
409
+ e: 'CALL', f: cur.id, p: parent ? parent.id : null,
410
+ file: cur.file, c: cur.c, t: taskId(/** @type {Frame} */ (cur)),
411
+ });
412
+ });
413
+ }
414
+
415
+ /**
416
+ * Enter an instrumented function: the parent is whatever frame is beneath this
417
+ * one on the stack this one pushes onto. A continuation that runs when its
418
+ * task's stack is empty — a timer callback — opens a parentless frame, and the
419
+ * converter writes `caller: "untraced"` for it.
420
+ *
421
+ * `args`, when passed, is the `[name, value, …]` list the transform writes
422
+ * at every site. An empty list is a read that found no parameters. Omitting
423
+ * the argument leaves `a` off the record: a spool written before arguments
424
+ * were read, or a caller that did not pass them. The absent key is "not
425
+ * read", and an empty map is not that fact.
426
+ * @param {number} fileId
427
+ * @param {number} c index into the file's `codes`
428
+ * @param {unknown[]} [args] `[name, value, …]`; omit it to record nothing
429
+ * @returns {Frame|null}
430
+ */
431
+ export function call(fileId, c, args) {
432
+ if (!on) return null;
433
+ const t = als.getStore() ?? null;
434
+ const stack = t ? t.stack : rootStack;
435
+ const parent = stack.length > 0 ? stack[stack.length - 1] : null;
436
+ const reason = budget.hiding(parent, fileId, c);
437
+ /** @type {Frame} */
438
+ const f = {
439
+ id: nextFrame++,
440
+ task: t,
441
+ // The callee's own name, for the RETURN rule (B7). Empty for a site no
442
+ // FILE record declared, which fires on nothing — a name this runtime does
443
+ // not have is not one it guesses at.
444
+ q: fileCodes.get(fileId)?.[c]?.[0] ?? '',
445
+ open: true,
446
+ mark: null,
447
+ elided: reason !== null,
448
+ reason,
449
+ file: fileId,
450
+ c,
451
+ };
452
+ stack.push(f);
453
+ // An elided activation is counted, not stored, and its arguments are not read.
454
+ if (reason !== null) return f;
455
+ /** @type {Record_} */
456
+ const rec = { e: 'CALL', f: f.id, p: parent ? parent.id : null, file: fileId, c, t: t ? t.id : null };
457
+ if (args !== undefined) rec.a = captures(args);
458
+ emitTs(rec);
459
+ budget.kept(fileId, c);
460
+ return f;
461
+ }
462
+
463
+ /**
464
+ * One completed statement of a focused function.
465
+ *
466
+ * `d` holds what the statement wrote, captured after it completed, and `u` the
467
+ * names the transform knows are NOT in scope at it — a `const` declared in a
468
+ * block that has ended, a binding whose declaration is further down. `u` is
469
+ * written only when there is such a name: an empty list is not a claim about
470
+ * anything, and a reader would have to decide whether it meant "nothing is out
471
+ * of scope" or "nobody looked".
472
+ *
473
+ * A frame that has closed reports no statement: by the time `ret` or `thr` has
474
+ * run this frame is done, and anything still arriving for it is not one of its
475
+ * statements.
476
+ * @param {Frame|null} f
477
+ * @param {number} l the line the statement ended on
478
+ * @param {unknown[]} pairs `[name, value, …]` — the statement's deltas
479
+ * @param {string[]} [unbound] names out of scope at this statement
480
+ * @returns {void}
481
+ */
482
+ export function line(f, l, pairs, unbound) {
483
+ if (!on || !f || !f.open || f.elided) return;
484
+ /** @type {Record_} */
485
+ const rec = { e: 'LINE', f: f.id, t: taskId(f), l, d: captures(pairs) };
486
+ if (unbound !== undefined && unbound.length > 0) rec.u = unbound;
487
+ emitTs(rec);
488
+ }
489
+
490
+ /**
491
+ * Leave by returning. A frame that is already closed is left alone: a
492
+ * generator's wrapper can see this after an UNWIND.
493
+ * @template T
494
+ * @param {Frame|null} f
495
+ * @param {T} v
496
+ * @returns {T} the value the source returns
497
+ */
498
+ export function ret(f, v) {
499
+ if (!on || !f || !f.open) return v;
500
+ f.open = false;
501
+ drop(f);
502
+ if (!f.elided) emitTs({ e: 'RETURN', f: f.id, t: taskId(f), v: redactReturn(f.q, dbg(v)) });
503
+ return v;
504
+ }
505
+
506
+ /**
507
+ * Hold the value a `return` chose, WITHOUT closing the frame (design §4.2).
508
+ *
509
+ * A function whose body returns from inside a `try` with a `finally` is
510
+ * spliced with this in place of `ret`: the program's `finally` then runs on a
511
+ * frame that is still open, so its statements mint their rows and a call it
512
+ * makes opens beneath the frame that made it. The last `pend` wins, which is
513
+ * what a `finally` that returns does to the value the `try` chose.
514
+ * @template T
515
+ * @param {Frame|null} f
516
+ * @param {T} v
517
+ * @returns {T} the value the source returns, untouched
518
+ */
519
+ export function pend(f, v) {
520
+ if (!on || !f || !f.open || f.elided) return v;
521
+ // The rule runs HERE and not at the seal: the seal has no value of its own
522
+ // to judge, and the last `pend` is the one it writes.
523
+ f.pending = redactReturn(f.q, dbg(v));
524
+ return v;
525
+ }
526
+
527
+ /**
528
+ * Close a frame `pend` left open, from the wrapper's own `finally` (§4.2).
529
+ *
530
+ * It emits the RETURN the deferred `return` did not, AFTER the rows of every
531
+ * `finally` the value passed through — the order Python's `sys.monitoring`
532
+ * already gives. A frame `thr` closed on the way out is left exactly as `thr`
533
+ * left it, so a `finally` that throws still reports one UNWIND and no return.
534
+ *
535
+ * `f.pending` is unset only where no `pend` ran at all — a `pend` of
536
+ * `undefined` stores the CAPTURE of it, which is an object. For a deferred
537
+ * function that is exactly one shape: a generator resumed with a RETURN
538
+ * completion (a consumer's `break` or `.return()`), whose body reached
539
+ * neither a `return` nor its own fallthrough close. That value is
540
+ * `unread`, not `undefined`, for `gclose`'s reason (A12, §4.4): `.return(v)`'s
541
+ * value belongs to the consumer and never reaches the body, so the body
542
+ * produced none — and `undefined` would be a value this recorder invented.
543
+ * @param {Frame|null} f
544
+ * @returns {void}
545
+ */
546
+ export function seal(f) {
547
+ if (!on || !f || !f.open) return;
548
+ f.open = false;
549
+ drop(f);
550
+ if (!f.elided) emitTs({ e: 'RETURN', f: f.id, t: taskId(f), v: f.pending ?? { k: 'unread' } });
551
+ }
552
+
553
+ /**
554
+ * Close a generator frame its consumer abandoned (R40).
555
+ *
556
+ * `break` out of a `for…of`, a `return` from inside one, an explicit
557
+ * `.return()`: every one of them resumes the generator body at its `yield`
558
+ * with a RETURN completion, so the body's own `ret` never runs and its `catch`
559
+ * never sees a throw. Without this the frame stayed open to the end of the
560
+ * recording and read `suspended at end of recording` — a loss claim about a
561
+ * generator somebody deliberately closed.
562
+ *
563
+ * The value is `unread`, not `undefined`: `.return(v)`'s value belongs to the
564
+ * consumer and never reaches the body, so the body produced none, and
565
+ * `undefined` would be a value this recorder invented. A frame `ret` or `thr`
566
+ * has already closed is left exactly as they left it.
567
+ * @param {Frame|null} f
568
+ * @returns {void}
569
+ */
570
+ export function gclose(f) {
571
+ if (!on || !f || !f.open) return;
572
+ f.open = false;
573
+ drop(f);
574
+ if (!f.elided) emitTs({ e: 'RETURN', f: f.id, t: taskId(f), v: { k: 'unread' } });
575
+ }
576
+
577
+ /**
578
+ * Leave by throwing.
579
+ * @param {Frame|null} f
580
+ * @param {unknown} e
581
+ * @returns {void}
582
+ */
583
+ export function thr(f, e) {
584
+ if (!on || !f || !f.open) return;
585
+ materialize(f);
586
+ f.open = false;
587
+ drop(f);
588
+ if (!f.elided) emitTs({ e: 'UNWIND', f: f.id, t: taskId(f), x: exc(e, 'throw') });
589
+ }
590
+
591
+ /**
592
+ * Park: the frame comes OFF its stack while it waits, which is what keeps a
593
+ * fan-out's siblings from nesting under one another. A frame that has already
594
+ * closed neither parks nor is recorded — it is not on a stack to leave.
595
+ * @template T
596
+ * @param {Frame|null} f
597
+ * @param {T} x the awaited or yielded value
598
+ * @param {number} kind 0 for `await`, 1 for `yield`
599
+ * @returns {T}
600
+ */
601
+ export function y(f, x, kind) {
602
+ if (!on || !f || !f.open) return x;
603
+ if (!f.elided) emitTs({ e: 'YIELD', f: f.id, t: taskId(f), k: kind === 1 ? 'yield' : 'await' });
604
+ drop(f);
605
+ return x;
606
+ }
607
+
608
+ /**
609
+ * Resume: the frame goes back on its stack — unless it has closed, which would
610
+ * put a finished frame back on a live stack and make it the parent of whatever
611
+ * ran next.
612
+ * @template T
613
+ * @param {Frame|null} f
614
+ * @param {T} v the value the suspension produced
615
+ * @returns {T}
616
+ */
617
+ export function r(f, v) {
618
+ if (!on || !f || !f.open) return v;
619
+ stackOf(f).push(f);
620
+ if (!f.elided) emitTs({ e: 'RESUME', f: f.id, t: taskId(f) });
621
+ return v;
622
+ }
623
+
624
+ // --- throw flow ------------------------------------------------------------
625
+
626
+ /**
627
+ * A `throw` statement, and nothing else.
628
+ * @template T
629
+ * @param {Frame|null} f the enclosing frame, or null outside every one
630
+ * @param {T} e
631
+ * @param {number} line
632
+ * @returns {T} the value the source throws
633
+ */
634
+ export function raise(f, e, line) {
635
+ if (!on) return e;
636
+ materialize(f);
637
+ if (f && f.elided) return e;
638
+ const x = exc(e, 'throw');
639
+ emitTs({ e: 'RAISE', f: f ? f.id : null, t: taskOf(f), x, l: line, how: 'throw' });
640
+ // The throw is now in flight through this frame: a `finally` beneath it that
641
+ // completes discards THIS value, and the mark is how it learns which.
642
+ if (f && f.open) f.mark = x;
643
+ return e;
644
+ }
645
+
646
+ /**
647
+ * A `catch` clause, or the empty-block sink that has none. Whatever the clause
648
+ * then does with the value, the flight this frame was carrying is over: the
649
+ * mark is cleared, so a `finally` beneath a `catch` claims nothing.
650
+ * @param {Frame|null} f
651
+ * @param {unknown} e
652
+ * @param {number} line
653
+ * @param {string} how `catch`, `catch_escaped` or `sink_empty_catch`
654
+ * @returns {void}
655
+ */
656
+ export function handled(f, e, line, how) {
657
+ if (!on) return;
658
+ record(f, e, line, how, 'throw');
659
+ if (f) f.mark = null;
660
+ }
661
+
662
+ /**
663
+ * A throw is in flight through `f` and this runtime is holding the value.
664
+ *
665
+ * The transform's synthetic clause calls it — `catch(__sfe){mark(__sf,__sfe);
666
+ * throw __sfe}` before a completing `finally` — which is what lets a library's
667
+ * throw and an awaited rejection be marked as well as a `throw` statement (P1).
668
+ * The whole `exc` is kept and not just its serial: the contract requires
669
+ * `type` on every one, and here the value is in hand, so nothing goes unread.
670
+ * @param {Frame|null} f
671
+ * @param {unknown} e
672
+ * @returns {void}
673
+ */
674
+ export function mark(f, e) {
675
+ if (on && f && f.open) f.mark = exc(e, 'throw');
676
+ }
677
+
678
+ /**
679
+ * A `finally` block that completes — `return`, `break` or `continue` at closure
680
+ * depth 0 — discards whatever was travelling through the frame. It records a
681
+ * HANDLED only when something WAS: a `finally` reached on the normal path, or
682
+ * one discarding a throw this recorder never saw raised, holds no mark and
683
+ * writes nothing (a declared blind spot, §2.3). The mark is one slot, so the
684
+ * first sink to read it is the one that reports the discard.
685
+ * @param {Frame|null} f
686
+ * @param {number} line
687
+ * @returns {void}
688
+ */
689
+ export function handledFinally(f, line) {
690
+ if (!on || !f || !f.open || f.mark === null) return;
691
+ materialize(f);
692
+ if (f.elided) return;
693
+ emitTs({
694
+ e: 'HANDLED',
695
+ f: f.id,
696
+ t: taskOf(f),
697
+ x: f.mark,
698
+ l: line,
699
+ how: 'sink_finally_return',
700
+ });
701
+ f.mark = null;
702
+ }
703
+
704
+ /**
705
+ * A rejection handler — `p.catch(<arg>)`, `p.then(x, <arg>)` — wrapped so the
706
+ * reason it is given is recorded before it runs. `how` is the transform's
707
+ * verdict about the handler's SHAPE, decided at splice time and written down
708
+ * here unexamined (§2.2).
709
+ *
710
+ * What the wrapper must not change is what the chain continues with: the
711
+ * original is called with the same `this` and the same reason, and its result
712
+ * is returned untouched. A handler that is not callable is a shape the
713
+ * transform does not emit; it is handed straight back rather than wrapped,
714
+ * because breaking the program to record it would be the larger harm.
715
+ *
716
+ * It does NOT clear the frame's mark, and `handled` does. The wrapper runs in a
717
+ * later microtask, by which time the frame it names has usually returned and
718
+ * whatever it was carrying is long over; clearing a mark then would clear one
719
+ * set by some throw now in flight through a frame that happens to be the same.
720
+ * The flight a rejection handler ends was never travelling through `f` in the
721
+ * first place — it arrived as a rejected promise, not up a stack.
722
+ * @param {Frame|null} f
723
+ * @param {number} line
724
+ * @param {string} how one of §2.5's callback words
725
+ * @param {Function} fn
726
+ * @returns {Function}
727
+ */
728
+ export function catchCb(f, line, how, fn) {
729
+ if (!on || typeof fn !== 'function') return fn;
730
+ return /** @this {unknown} */ function sensoriumCatchCb(/** @type {unknown} */ reason) {
731
+ record(f, reason, line, how, 'rejection');
732
+ return fn.call(this, reason);
733
+ };
734
+ }
735
+
736
+ /**
737
+ * @param {Frame|null} f
738
+ * @param {unknown} e
739
+ * @param {number} line
740
+ * @param {string} how
741
+ * @param {'throw'|'rejection'} kind
742
+ */
743
+ function record(f, e, line, how, kind) {
744
+ if (f && f.elided) materialize(f);
745
+ if (f && f.elided) return;
746
+ emitTs({ e: 'HANDLED', f: f ? f.id : null, t: taskOf(f), x: exc(e, kind), l: line, how });
747
+ }
748
+
749
+ /**
750
+ * The task a throw-flow record belongs to. A record that names a FRAME belongs
751
+ * to that frame's task, whichever async context the throw was reported from —
752
+ * the same source `ret`, `thr`, `y` and `r` read, so one frame's rows cannot
753
+ * disagree about their task. Only a frameless record falls back to the async
754
+ * context, which is all there is to ask.
755
+ * @param {Frame|null} f
756
+ * @returns {number|null}
757
+ */
758
+ function taskOf(f) {
759
+ if (f) return taskId(f);
760
+ const t = als.getStore();
761
+ return t ? t.id : null;
762
+ }
763
+
764
+ // --- what the harness wiring records ---------------------------------------
765
+
766
+ /**
767
+ * The start of one test file, from the setup file that runs before it.
768
+ * @param {string} file_ root-relative path
769
+ * @param {string|null} environment vitest's environment name
770
+ * @returns {void}
771
+ */
772
+ export function fileStart(file_, environment) {
773
+ if (!on) return;
774
+ emit({ e: 'FILE_START', path: file_, environment });
775
+ }
776
+
777
+ /**
778
+ * One test the harness itself saw, whatever the transform made of it: the
779
+ * count that catches tests registered through a shape we did not wrap.
780
+ *
781
+ * A non-string is not a test. The setup file passes
782
+ * `expect.getState().currentTestName ?? null`, so a `beforeEach` that runs
783
+ * where the harness has no current test hands this a null; `String(null)` made
784
+ * that a test called `null` and inflated `tests_seen`, which is the one number
785
+ * whose whole job is to name the shortfall against tasks.
786
+ * @param {unknown} name
787
+ * @returns {void}
788
+ */
789
+ export function seen(name) {
790
+ if (!on || typeof name !== 'string') return;
791
+ // Cut exactly as a TASK name is (R14a): the converter compares the two, and
792
+ // two names cut by different rules would not compare.
793
+ const capped = cap(name);
794
+ /** @type {Record_} */
795
+ const rec = { e: 'SEEN', name: capped.v };
796
+ if (capped.trunc) rec.name_trunc = true;
797
+ emit(rec);
798
+ }