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
sensorium/ts/focus.py ADDED
@@ -0,0 +1,146 @@
1
+ """What `--focus` selected, settled before the run.
2
+
3
+ The driver cannot answer a focus itself: which functions a spec selects is a
4
+ property of the consumer's own AST, read with the consumer's own TypeScript,
5
+ by the same pass one the transform splices from. So it asks the recorder's
6
+ Node package -- `src/resolve.mjs`, one process, one JSON line -- and turns
7
+ what comes back into either a list of matches or a list of refusals.
8
+
9
+ The refusal is the reason this happens BEFORE anything is minted. A spec
10
+ that matches nothing splices no probes at all, and the run that follows
11
+ records a program the caller did not ask about while declaring it looked; a
12
+ spec that matches only a function this recorder never instruments (an
13
+ overload signature, a `declare`, a vitest-hoisted factory) does the same and
14
+ is not the caller's spelling mistake at all. Both are cheap to say up front
15
+ and expensive to discover in a trace.
16
+ """
17
+ import json
18
+ import os
19
+ import subprocess
20
+ import time
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+
24
+ from sensorium.ts import pkg as pkg_mod
25
+
26
+ #: The unit separator the specs are joined with on their way to the harness
27
+ #: and to the resolver. A spec may hold a path, a dot and a colon; this is the
28
+ #: one byte it cannot. `typescript/src/focus.mjs` splits on the same one.
29
+ SEP = "\x1f"
30
+
31
+ #: The resolver, inside the package. Named here rather than built at the call
32
+ #: site so the refusal for its absence can name it too.
33
+ SCRIPT = Path("src") / "resolve.mjs"
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class Resolution:
38
+ """What the resolver saw: what each spec selected, and what it walked.
39
+
40
+ `matched` is one entry per FUNCTION (`rel`, `qualname`, `line`, `kind`),
41
+ deduplicated across specs -- two specs naming one function focus it once.
42
+ `unmatched` and `excluded_only` are one entry per bad SPEC, each carrying
43
+ the spec as typed so the refusal can quote it back.
44
+ """
45
+
46
+ matched: list[dict]
47
+ unmatched: list[dict]
48
+ excluded_only: list[dict]
49
+ files_scanned: int
50
+ files_unparsable: int
51
+ wall: float
52
+
53
+ @property
54
+ def matched_specs(self) -> list[str]:
55
+ """`rel:qualname` for every match, sorted -- what `invocation.json`
56
+ carries as `focus_matched` and what a reader is shown when they ask
57
+ what a recording was focused on. Sorted and not in match order: it is
58
+ a set of functions, and the order the walk happened to reach them in
59
+ is not a fact about the recording.
60
+
61
+ A set in the other sense too (R30). `matched` is one entry per
62
+ FUNCTION, and two functions can share a `rel:qualname`: anonymous
63
+ twins on one line are indistinguishable by name, and listing
64
+ `src/a.ts:<anonymous>` twice answers nothing twice."""
65
+ return sorted({f"{m['rel']}:{m['qualname']}" for m in self.matched})
66
+
67
+
68
+ def resolve(root: Path, package: Path, specs: list[str],
69
+ node: str = "node") -> Resolution:
70
+ """Run the resolver over `root` and read its one line back.
71
+
72
+ Raises `pkg.PackageError` -- the driver's existing refusal for "the Node
73
+ side cannot be used" -- when the script is absent, cannot be started, or
74
+ answers with anything but one JSON object at exit 0. The resolver itself
75
+ treats an unmatched spec as an ANSWER and exits 0 with it; a non-zero
76
+ exit means the call it was given made no sense, and its sentence is the
77
+ one worth showing.
78
+ """
79
+ script = Path(package) / SCRIPT
80
+ if not script.is_file():
81
+ raise pkg_mod.PackageError(
82
+ f"the recorder's Node package at {package} has no {SCRIPT}: a "
83
+ f"`--focus` is resolved against the project before the run, and "
84
+ f"this package cannot answer one")
85
+ env = dict(os.environ, SENSORIUM_TS_ROOT=str(root),
86
+ SENSORIUM_TS_PKG=str(package), SENSORIUM_FOCUS=SEP.join(specs))
87
+ start = time.perf_counter()
88
+ try:
89
+ out = subprocess.run([node, str(script)], env=env, cwd=root,
90
+ capture_output=True, text=True)
91
+ except OSError as e:
92
+ raise pkg_mod.PackageError(
93
+ f"cannot run `{node} {script}`: {e.strerror}") from None
94
+ wall = time.perf_counter() - start
95
+ if out.returncode != 0:
96
+ raise pkg_mod.PackageError(
97
+ f"{script} refused: {_one_line(out.stderr) or f'exit {out.returncode}, nothing said'}")
98
+ try:
99
+ data = json.loads(out.stdout)
100
+ except json.JSONDecodeError:
101
+ raise pkg_mod.PackageError(
102
+ f"{script} answered something this driver cannot read: "
103
+ f"{_one_line(out.stdout) or 'nothing at all'}") from None
104
+ return Resolution(matched=data["matched"], unmatched=data["unmatched"],
105
+ excluded_only=data["excluded_only"],
106
+ files_scanned=data["files_scanned"],
107
+ files_unparsable=data["files_unparsable"], wall=wall)
108
+
109
+
110
+ def _one_line(text: str) -> str:
111
+ """The first thing said, on one line. Every refusal the driver prints is
112
+ one line, and a Node stack trace pasted into it would bury the sentence
113
+ the caller has to act on."""
114
+ for line in text.splitlines():
115
+ if line.strip():
116
+ return line.strip()
117
+ return ""
118
+
119
+
120
+ def refusals(res: Resolution, root: Path) -> list[str]:
121
+ """One line per bad spec, or an empty list when every spec selected
122
+ something.
123
+
124
+ Two sentences, because they are two different problems. "Matches no
125
+ function" is a spelling to fix, and the closest eligible names are what
126
+ fixes it -- dropped, rather than printed empty, when there is nothing to
127
+ suggest. "Matches only functions this recorder does not instrument" is
128
+ not a spelling problem at all: the name IS in the tree, and the reason
129
+ it cannot be recorded belongs to the recorder, so the reason is named.
130
+
131
+ The unmatched come first and the excluded-only after; within each, the
132
+ order is the order the specs were given.
133
+ """
134
+ lines = []
135
+ for item in res.unmatched:
136
+ tail = (f" Closest: {', '.join(item['closest'])}"
137
+ if item["closest"] else "")
138
+ lines.append(f"--focus {item['spec']} matches no function under "
139
+ f"{root}; nothing was run.{tail}")
140
+ for item in res.excluded_only:
141
+ reasons = ", ".join(f"{k} x{n}"
142
+ for k, n in sorted(item["reasons"].items()))
143
+ lines.append(f"--focus {item['spec']} matches only functions this "
144
+ f"recorder does not instrument ({reasons}); nothing was "
145
+ f"run.")
146
+ return lines
@@ -0,0 +1,314 @@
1
+ """Which harness a typed command names, and what it takes to wire it.
2
+
3
+ `sensorium ts run` takes the harness command AFTER `--`, as the user types
4
+ it, and does not re-implement a harness's command line (design section 2.3).
5
+ So this module's whole job is to read that command and answer one of three
6
+ things: it is vitest, it is `node --test`, or it is refused with a sentence
7
+ that names the fix.
8
+
9
+ The refusals are the interesting part, and each one exists because guessing
10
+ would be worse than refusing:
11
+
12
+ * `npm test`, `npm run test`, `npm t` and the pnpm and yarn equivalents are
13
+ read from the nearest `package.json` only when `scripts.test` is a simple
14
+ `vitest` or `node --test` command. A shell metacharacter, a missing
15
+ script, or a manifest that is not in the working directory is a refusal
16
+ that names the script text: this module does not spawn a shell and does
17
+ not change directory;
18
+ * any other package script is refused, because a script cannot take the
19
+ flags the driver appends and guessing a shell string would be a guess;
20
+ * `jest` was not measured and the consumer does not run it, so a wiring for
21
+ it would be a claim nobody has checked;
22
+ * anything else names neither harness, and a driver that spawned it anyway
23
+ would record nothing and exit 0 -- the one failure this recorder must
24
+ never have.
25
+
26
+ Nothing here spawns or writes. It reads `package.json` only to expand the
27
+ test-script forms above.
28
+ """
29
+ import json
30
+ import os
31
+ import shlex
32
+ from dataclasses import dataclass
33
+ from pathlib import Path
34
+
35
+ #: Command prefixes that mean "resolve the next token from the project's
36
+ #: bin directory". They are kept in the spawned command: which `vitest` runs
37
+ #: is the user's choice, and dropping `npx` would run a different one.
38
+ RUNNERS = ("npx", "pnpm", "yarn")
39
+
40
+ #: The package managers whose script verbs are refused. `npx` is not one of
41
+ #: them: `npx test` names a binary, not a script.
42
+ MANAGERS = ("npm", "pnpm", "yarn")
43
+ SCRIPT_VERBS = ("test", "run", "t")
44
+
45
+ #: vitest's own config search, in vitest's own order, looked for in the
46
+ #: ROOT. Written out rather than globbed so the order is the contract.
47
+ CONFIG_NAMES = tuple(f"{stem}.config.{ext}"
48
+ for stem in ("vitest", "vite")
49
+ for ext in ("ts", "mts", "cts", "js", "mjs", "cjs"))
50
+
51
+ _BOTH = ("sensorium ts run -- vitest run …, or "
52
+ "sensorium ts run -- node --test …")
53
+
54
+ JEST = ("jest is not supported: not measured, and the consumer does not "
55
+ "run it")
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Refusal:
60
+ """Why this command was not wired. One sentence, and the whole answer."""
61
+
62
+ message: str
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Plan:
67
+ """A recognised command, and everything the driver needs to wire it.
68
+
69
+ `argv` is what the user typed, kept whole for the record; `stripped` is
70
+ the same command with the flags the driver re-issues taken out, and is
71
+ what the spawned command is built from. They differ exactly when the
72
+ user passed `--root` or `--config`.
73
+ """
74
+
75
+ kind: str
76
+ argv: list[str]
77
+ stripped: list[str]
78
+ harness_args: list[str]
79
+ root: Path
80
+ user_config: Path | None
81
+ harness_index: int
82
+
83
+ def vitest_command(self, config: Path) -> list[str]:
84
+ """The command to spawn, with the wrapper re-issued ONCE at the end.
85
+
86
+ Last wins in vitest's own parser, and appending is what makes the
87
+ re-issue independent of where the user's own flags were: a config
88
+ inserted in the middle could be overridden by a later one of theirs.
89
+ """
90
+ return [*self.stripped, "--config", str(config),
91
+ "--root", str(self.root)]
92
+
93
+ def node_command(self, register: Path) -> list[str]:
94
+ """The command to spawn, with the loader hook on NODE's side.
95
+
96
+ `--import` is node's own flag. After `--test` it would be an
97
+ argument to the test runner, which would either refuse it or pass it
98
+ to the file.
99
+ """
100
+ cut = self.harness_index + 1
101
+ return [*self.stripped[:cut], "--import", str(register),
102
+ *self.stripped[cut:]]
103
+
104
+
105
+ #: Characters that make `scripts.test` a shell program rather than an argv.
106
+ #: `&&` and `||` are covered by `&` and `|`. A newline is one of them.
107
+ _SHELL_META = frozenset("&|;<>`$\n\r")
108
+
109
+
110
+ def recognise(cmd: list[str], cwd: Path, *, expand: bool = True) -> Plan | Refusal:
111
+ """Read a typed command. See the module docstring for the rules."""
112
+ cwd = Path(cwd)
113
+ if not cmd:
114
+ return Refusal(f"no harness command given: {_BOTH}")
115
+ if expand and _is_test_script(cmd):
116
+ return _expand_test_script(cmd, cwd)
117
+ start = _skip_runners(cmd)
118
+ if isinstance(start, Refusal):
119
+ # `npm run jest` is both a script and jest, and the script sentence's
120
+ # advice -- run the harness directly -- would send them at a harness
121
+ # this recorder does not wire. The jest sentence is the one they get.
122
+ return Refusal(JEST) if _script_names_jest(cmd) else start
123
+ head = cmd[start]
124
+ # The HARNESS token, and no other (R44, finding 11). Scanning every token
125
+ # refused `vitest run src/jest` -- an ordinary vitest run over a directory
126
+ # somebody called `jest` -- with a sentence naming a harness that appears
127
+ # nowhere in what they typed.
128
+ if _names(head, "jest"):
129
+ return Refusal(JEST)
130
+ if _names(head, "vitest"):
131
+ return _vitest(cmd, start, cwd)
132
+ if _names(head, "node") and "--test" in cmd[start + 1:]:
133
+ return _node_test(cmd, start, cwd)
134
+ return Refusal(f"{' '.join(cmd)} names no harness this recorder wires: "
135
+ f"{_BOTH}")
136
+
137
+
138
+ def _is_test_script(cmd: list[str]) -> bool:
139
+ """The exact forms whose `scripts.test` this recorder will read.
140
+
141
+ `npm run unit` is not one of them, and neither is `npm test -- src`:
142
+ extra tokens are arguments a script would receive, and appending them
143
+ is a second guess. `npm run jest` is jest's sentence, decided later.
144
+ """
145
+ if not cmd or cmd[0] not in MANAGERS:
146
+ return False
147
+ if len(cmd) == 2 and cmd[1] in ("test", "t"):
148
+ return True
149
+ return len(cmd) == 3 and cmd[1] == "run" and cmd[2] == "test"
150
+
151
+
152
+ def _expand_test_script(cmd: list[str], cwd: Path) -> Plan | Refusal:
153
+ """Replace `npm test` with the argv `scripts.test` names, or refuse.
154
+
155
+ The plan's `argv` stays what was typed. `stripped` is the script's
156
+ argv, which is what the driver spawns. No shell.
157
+ """
158
+ manifest = _package_json(cwd)
159
+ if manifest is None:
160
+ return Refusal(
161
+ "no package.json found, so scripts.test was not read. "
162
+ f"Run the harness directly, {_BOTH}")
163
+ if manifest.parent.resolve() != Path(cwd).resolve():
164
+ return Refusal(
165
+ f"{' '.join(cmd)} would run scripts.test from {manifest.parent}, "
166
+ "and this recorder does not change directory. "
167
+ f"Run the harness directly, {_BOTH}")
168
+ try:
169
+ data = json.loads(manifest.read_text(encoding="utf-8"))
170
+ except (OSError, json.JSONDecodeError):
171
+ return Refusal(
172
+ f"{manifest} does not parse as JSON, so scripts.test was not "
173
+ f"read. Run the harness directly, {_BOTH}")
174
+ scripts = data.get("scripts") if isinstance(data, dict) else None
175
+ script = scripts.get("test") if isinstance(scripts, dict) else None
176
+ if not isinstance(script, str):
177
+ return Refusal(
178
+ "package.json has no scripts.test string. "
179
+ f"Run the harness directly, {_BOTH}")
180
+ if any(ch in _SHELL_META for ch in script):
181
+ return Refusal(
182
+ f"package.json scripts.test is {script!r}, which is a shell "
183
+ "command, and this recorder does not spawn a shell. "
184
+ f"Run the harness directly, {_BOTH}")
185
+ try:
186
+ argv = shlex.split(script)
187
+ except ValueError:
188
+ return Refusal(
189
+ f"package.json scripts.test is {script!r}, which is not a "
190
+ "simple command. Run the harness directly, {_BOTH}")
191
+ inner = recognise(argv, cwd, expand=False)
192
+ if isinstance(inner, Plan):
193
+ return Plan(kind=inner.kind, argv=list(cmd), stripped=inner.stripped,
194
+ harness_args=inner.harness_args, root=inner.root,
195
+ user_config=inner.user_config,
196
+ harness_index=inner.harness_index)
197
+ if inner.message == JEST:
198
+ return Refusal(
199
+ f"package.json scripts.test is {script!r}, and {JEST}. "
200
+ f"Run the harness directly, {_BOTH}")
201
+ return Refusal(
202
+ f"package.json scripts.test is {script!r}, which is not a vitest "
203
+ "or node --test command this recorder can run without a shell. "
204
+ f"Run the harness directly, {_BOTH}")
205
+
206
+
207
+ def _package_json(cwd: Path) -> Path | None:
208
+ """The nearest `package.json`, walking parents the way npm does."""
209
+ here = Path(cwd).resolve()
210
+ for directory in [here, *here.parents]:
211
+ candidate = directory / "package.json"
212
+ if candidate.is_file():
213
+ return candidate
214
+ return None
215
+
216
+
217
+ def _script_names_jest(cmd: list[str]) -> bool:
218
+ """Whether a refused package-script command runs a script called jest.
219
+
220
+ The token straight after the manager's verb is the SCRIPT's name, which
221
+ is the closest thing such a command has to a harness token -- unlike
222
+ the file arguments further along, which name nothing.
223
+ """
224
+ for i, token in enumerate(cmd[:-2]):
225
+ if token in MANAGERS and cmd[i + 1] in SCRIPT_VERBS:
226
+ return _names(cmd[i + 2], "jest")
227
+ return False
228
+
229
+
230
+ def _names(token: str, program: str) -> bool:
231
+ """A bare name, or any path ending in it. `./node_modules/.bin/vitest`
232
+ is vitest; `vitest-helper` is not."""
233
+ return token == program or token.endswith("/" + program)
234
+
235
+
236
+ def _skip_runners(cmd: list[str]) -> int | Refusal:
237
+ """The index of the harness token, past any runner prefix."""
238
+ i = 0
239
+ while i < len(cmd):
240
+ token, following = cmd[i], (cmd[i + 1] if i + 1 < len(cmd) else None)
241
+ if token in MANAGERS and following in SCRIPT_VERBS:
242
+ return Refusal(
243
+ f"{token} {following} runs a package script, and a script "
244
+ "cannot take the flags this recorder appends: run the "
245
+ "harness directly, sensorium ts run -- vitest run …")
246
+ if token in RUNNERS:
247
+ i += 2 if token != "npx" and following == "exec" else 1
248
+ continue
249
+ return i
250
+ return Refusal(f"{' '.join(cmd)} names no harness this recorder wires: "
251
+ f"{_BOTH}")
252
+
253
+
254
+ def _vitest(cmd: list[str], start: int, cwd: Path) -> Plan:
255
+ kept, root_arg, config_arg = _consume(cmd[start + 1:])
256
+ root = _under(cwd, root_arg) or cwd
257
+ config = _under(cwd, config_arg) or _search(root)
258
+ return Plan(kind="vitest", argv=list(cmd),
259
+ stripped=[*cmd[:start + 1], *kept], harness_args=kept,
260
+ root=root, user_config=config, harness_index=start)
261
+
262
+
263
+ def _node_test(cmd: list[str], start: int, cwd: Path) -> Plan:
264
+ """node's command line is node's. Nothing is consumed from it: a
265
+ `--config` there is an argument to the program under test."""
266
+ return Plan(kind="node-test", argv=list(cmd), stripped=list(cmd),
267
+ harness_args=cmd[start + 1:], root=cwd, user_config=None,
268
+ harness_index=start)
269
+
270
+
271
+ def _consume(args: list[str]) -> tuple[list[str], str | None, str | None]:
272
+ """`--root` and `--config` out, in all six spellings, everything else
273
+ kept in order."""
274
+ kept: list[str] = []
275
+ values: dict[str, str | None] = {"--root": None, "--config": None}
276
+ aliases = {"-r": "--root", "-c": "--config"}
277
+ i = 0
278
+ while i < len(args):
279
+ arg = args[i]
280
+ name = aliases.get(arg, arg)
281
+ if name in values:
282
+ values[name] = args[i + 1] if i + 1 < len(args) else None
283
+ i += 2
284
+ continue
285
+ prefix = next((k for k in values if arg.startswith(k + "=")), None)
286
+ if prefix is not None:
287
+ values[prefix] = arg[len(prefix) + 1:]
288
+ i += 1
289
+ continue
290
+ kept.append(arg)
291
+ i += 1
292
+ return kept, values["--root"], values["--config"]
293
+
294
+
295
+ def _under(cwd: Path, value: str | None) -> Path | None:
296
+ """A command-line path, resolved the way vitest resolves it: against the
297
+ directory the command was typed in.
298
+
299
+ `normpath` and not `resolve`: a symlinked checkout is a real place a
300
+ consumer works in, and rewriting their root to its target would make
301
+ every path in every trace name a directory they never mentioned.
302
+ """
303
+ if value is None:
304
+ return None
305
+ return Path(os.path.normpath(cwd / value))
306
+
307
+
308
+ def _search(root: Path) -> Path | None:
309
+ """vitest's own config search, in the root. No config is a FACT: a
310
+ project can have none, and the wrapper then merges onto `{}`."""
311
+ for name in CONFIG_NAMES:
312
+ if (root / name).is_file():
313
+ return root / name
314
+ return None