ostia 0.4.0 → 0.6.0

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 (64) hide show
  1. package/README.md +31 -30
  2. package/docs/agent-protocol.md +13 -9
  3. package/docs/cli.md +174 -126
  4. package/docs/config.md +2 -2
  5. package/docs/document-schema.md +15 -12
  6. package/docs/library.md +32 -21
  7. package/docs/preload-recipes.md +4 -4
  8. package/docs/statistics.md +14 -13
  9. package/index.d.ts +202 -60
  10. package/package.json +1 -1
  11. package/src/ab/ab-runner.ts +6 -6
  12. package/src/ab/index.ts +56 -6
  13. package/src/ab/unpaired.ts +54 -0
  14. package/src/bench/index.ts +40 -3
  15. package/src/bench/registry.ts +6 -4
  16. package/src/bench/run-tasks.ts +16 -2
  17. package/src/bench/runner.ts +10 -3
  18. package/src/bench/support.ts +8 -4
  19. package/src/bench/sweep.ts +2 -2
  20. package/src/cache/fingerprint.ts +2 -2
  21. package/src/capture/bunflags.ts +2 -2
  22. package/src/capture/cpu.ts +2 -2
  23. package/src/capture/heap-parse.ts +2 -2
  24. package/src/ci/index.ts +39 -48
  25. package/src/cli/agent.ts +54 -0
  26. package/src/cli/flags.ts +58 -9
  27. package/src/cli/help.ts +670 -245
  28. package/src/cli/main.ts +2 -3
  29. package/src/cli/output.ts +17 -14
  30. package/src/cli/run.ts +317 -92
  31. package/src/compare/index.ts +4 -4
  32. package/src/config/index.ts +14 -10
  33. package/src/config/validate.ts +4 -4
  34. package/src/glob.ts +2 -2
  35. package/src/index.ts +3 -2
  36. package/src/ir/document.ts +2 -2
  37. package/src/ir/types.ts +49 -24
  38. package/src/measure/alloc.ts +2 -2
  39. package/src/measure/cpu.ts +2 -2
  40. package/src/measure/environment.ts +11 -6
  41. package/src/measure/inprocess.ts +14 -10
  42. package/src/measure/instructions.ts +2 -2
  43. package/src/measure/noise.ts +51 -13
  44. package/src/measure/paired.ts +2 -2
  45. package/src/measure/peak.ts +4 -4
  46. package/src/measure/timing.ts +27 -6
  47. package/src/profile.ts +6 -4
  48. package/src/renderers/collapsed.ts +2 -2
  49. package/src/renderers/concise.ts +148 -0
  50. package/src/renderers/format.ts +13 -4
  51. package/src/renderers/human.ts +402 -0
  52. package/src/renderers/index.ts +9 -2
  53. package/src/renderers/markdown.ts +2 -2
  54. package/src/renderers/mermaid.ts +2 -2
  55. package/src/renderers/minimal.ts +8 -7
  56. package/src/renderers/relative.ts +2 -2
  57. package/src/renderers/select.ts +2 -2
  58. package/src/renderers/terminal.ts +1178 -383
  59. package/src/renderers/types.ts +3 -0
  60. package/src/spawn/index.ts +47 -14
  61. package/src/stats/bootstrap.ts +2 -2
  62. package/src/stats/index.ts +2 -2
  63. package/src/terminal.ts +321 -0
  64. package/src/time.ts +124 -20
package/src/cli/help.ts CHANGED
@@ -1,245 +1,670 @@
1
- export const TIME_HELP = `ostia time [flags] <command...>
2
- ostia time [flags] -- <argv...>
3
-
4
- Time commands as subprocesses. Each <command> is whitespace-split into argv (no shell);
5
- everything after -- is one more command's argv, verbatim.
6
-
7
- Flags:
8
- --samples N exact trials per command (default: ~3s budget, at least 10)
9
- --budget MS sampling time budget per command
10
- --min-samples N floor on trials when --samples isn't given
11
- --warmup N discarded warmup trials (default: 3)
12
- --no-interleave run commands one after another instead of round-robin
13
- --prepare CMD run before every trial, unmeasured; once, or once per command
14
- --time-source REGEX take each trial's time from capture group 1 in the command's output
15
- --time-unit UNIT unit of --time-source: ns | us | ms | s (default: ms); needs --time-source
16
- --cpu capture one extra CPU-profile trial
17
- --heap capture one extra heap-snapshot trial
18
- --cpu-interval US CPU sampling interval (default: 1000); needs --cpu
19
- --timeout MS kill a trial or --prepare hook after MS
20
- --ignore-failure[=CODE,...] treat these exit codes (bare: all) as success
21
- --out-dir PATH artifact directory (default: node_modules/.cache/ostia)
22
- --no-noise-check skip the ~200ms noise-floor measurement
23
- --export-json PATH write the ProfileDocument to PATH
24
- --format FORMAT table | json | jsonl | markdown | minimal (default: table)
25
- --quiet don't print the report
26
- --help show this message
27
-
28
- A command stops at its first non-ignored non-zero exit.
29
- Exit codes: 0 ok, 2 a command failed or produced no samples (or a bad flag), 130 Ctrl-C.
30
-
31
- Examples:
32
- ostia time "bun a.ts" "bun b.ts"
33
- ostia time --samples 25 --cpu --heap "bun src/server.ts"
34
- ostia time --prepare "rm -rf dist" "bun build.ts"
35
- ostia time --time-source "built in (\\d+)ms" "bun build.ts"
36
- ostia time -- bun -e "console.log('a b')"
37
- `;
38
-
39
- export const BENCH_HELP = `ostia bench [flags] <suite.ts...>
40
-
41
- Run in-process group()/task() suites, each file in its own child process. With no files,
42
- uses ostia.config's "bench" section; each flag overrides its config field.
43
-
44
- Flags:
45
- --budget MS sampling budget per task (default: 500)
46
- --samples N exact trials per task (ignores --budget)
47
- --min-samples N floor on trials (default: cost-aware, 3-20)
48
- --jobs N|auto suite files at once (default: 1; >1 adds noise)
49
- --isolate one process per task, not per file (--no-isolate to undo config)
50
- --gc Bun.gc(true) between trials (--no-gc)
51
- --cpu extra per-task CPU profile with JIT tiers, ~2,000 samples (--no-cpu)
52
- --cpu-interval US CPU sampling interval (default: 100)
53
- --alloc extra per-task retained-heap-per-call measurement: what calls keep
54
- alive after a full GC, not what they allocate (--no-alloc)
55
- --peak-mem extra per-task RSS rise during the task's first call, garbage
56
- included; median of 3 fresh processes (--no-peak-mem)
57
- --filter REGEX only tasks whose "group/name" matches
58
- --preload PATH import before each suite file (repeatable, in order)
59
- --bun-flags FLAGS extra flags for the bun process running each suite (repeatable)
60
- --timeout MS kill a suite (or isolated task) process after MS
61
- --out-dir PATH scratch directory (default: node_modules/.cache/ostia)
62
- --config PATH read this config file instead of ostia.config.ts/.json
63
- --no-noise-check skip the ~200ms noise-floor measurement
64
- --export-json PATH write the ProfileDocument to PATH
65
- --format FORMAT table | json | jsonl | markdown | minimal (default: table)
66
- --quiet don't print the report
67
- --help show this message
68
-
69
- Per-task/per-group options ({ budgetMs, minSamples, gc, isolate, cpu, alloc, peakMem }) override
70
- the suite-wide defaults. Exit codes: 0 ok, 2 a suite failed (or a bad flag), 130 Ctrl-C.
71
-
72
- Examples:
73
- ostia bench bench/*.ts
74
- ostia bench bench/*.ts --filter parse --cpu --alloc
75
- ostia bench --preload ./bench/dom-setup.ts --bun-flags="--conditions=browser" bench/*.ts
76
- `;
77
-
78
- export const AB_HELP = `ostia ab [flags] <suite.ts...>
79
-
80
- Pair every task on a git ref's committed tree (base) against the working tree (candidate), in
81
- one process, alternating ~10ms batches, and gate on the per-round time ratio. Drift between
82
- the two sides cancels within a round. Each suite runs twice, once with each side first, and
83
- the rounds are pooled. With no files, uses ostia.config's "bench" suites.
84
-
85
- Flags:
86
- --base REF git ref for the base side (default: HEAD)
87
- --base-setup CMD shell command run once in a freshly extracted base tree, e.g. to build
88
- gitignored files the suites import (repeatable, in order)
89
- --rounds N base/candidate rounds per task (default: 15)
90
- --metric METRIC judge each round's time or instructions ratio (default: time);
91
- instructions retired per call barely move on a loaded machine
92
- --threshold PCT flag a task whose median ratio moves past PCT (default: 10)
93
- --geomean-threshold PCT fail when the geometric mean of all ratios is slower than PCT
94
- (default: 1.5)
95
- --confirm N re-measure each flagged task in N fresh processes (default: 2; 0 skips)
96
- --alloc also compare retained heap per call on each side (--no-alloc)
97
- --peak-mem also compare each side's first-call RSS rise (--no-peak-mem); both
98
- run in 3 fresh processes per side, and the median counts
99
- --mem-threshold PCT flag a memory reading that moves past PCT of the base's and past
100
- its noise floor (default: 10)
101
- --filter REGEX only tasks whose "group/name" matches
102
- --preload PATH import before each suite file (repeatable, in order)
103
- --bun-flags FLAGS extra flags for the bun process running each suite (repeatable)
104
- --timeout MS kill a suite (or repeat) process after MS
105
- --out-dir PATH scratch directory (default: node_modules/.cache/ostia)
106
- --keep-trees N base trees to keep cached, least recently used go first (default: 5)
107
- --clean remove every cached base tree, then exit
108
- --config PATH read this config file instead of ostia.config.ts/.json
109
- --no-noise-check skip the ~200ms noise-floor measurement
110
- --export-json PATH write the ProfileDocument to PATH
111
- --format FORMAT table | json | jsonl | markdown | minimal (default: table)
112
- --progress print progress to stderr (default: when stderr is a terminal and not
113
- --quiet); --no-progress turns it off
114
- --quiet don't print the report
115
- --help show this message
116
-
117
- The base tree is cached per commit (and --base-setup commands) under .ostia/ab. Setup runs
118
- with the project's node_modules linked in, and OSTIA_AB_SHA and OSTIA_AB_CANDIDATE_DIR (the
119
- working tree) set. Instructions per call are counted where the machine allows (macOS;
120
- Linux with perf_event_paranoid <= 2 and a hardware counter) and shown next to time. A
121
- flagged task counts only when every fresh-process repeat flags it the same way. A task that throws isn't timed; one that throws on the candidate side only fails
122
- the run. A task whose suite file and output both changed reads "not comparable" and stays
123
- out of the verdict. Exit codes: 0 pass, 1 a confirmed regression, a candidate-only throw,
124
- the geomean over its threshold or a memory regression, 2 nothing paired or a harness error (not a git repo,
125
- unknown ref, a failed setup or suite), 130 Ctrl-C.
126
-
127
- Examples:
128
- ostia ab bench/parse.bench.ts
129
- ostia ab bench/*.ts --base origin/main --rounds 21
130
- ostia ab bench/*.ts --filter parse --format minimal
131
- ostia ab bench/*.ts --metric instructions --threshold 3
132
- ostia ab bench/*.ts --base-setup "bun scripts/generate.ts"
133
- ostia ab bench/paint.bench.ts --alloc --peak-mem
134
- `;
135
-
136
- export const COMPARE_HELP = `ostia compare <base.json> <candidate.json>
137
- ostia compare <candidate.json> --baseline <base.json>
138
-
139
- Compare two ProfileDocuments by workload id (or a task's former names, from its
140
- "aliases"). Gates on ostia.config's "thresholds" when present (the same ones "ostia ci"
141
- uses), else the defaults, widened by machine noise and drift. Tasks on only one side are
142
- listed under "Not compared"; with --format json, "compared" holds one row per task.
143
-
144
- Flags:
145
- --baseline PATH the base document, when only the candidate is positional
146
- --config PATH read thresholds from this config file instead of ostia.config.ts/.json
147
- --export-json PATH write the candidate document with comparisons to PATH
148
- --format FORMAT table | json | jsonl | markdown | minimal (default: table)
149
- --quiet don't print the report
150
- --help show this message
151
-
152
- Exactly two document paths (one with --baseline); anything more is an error.
153
- Exit codes: 0 pass, 1 a workload regressed, 2 nothing matched or a harness error.
154
- `;
155
-
156
- export const REPORT_HELP = `ostia report <document.json> [flags]
157
-
158
- Render a saved ProfileDocument. Files, not a GUI for the visualization formats -
159
- hand the output to speedscope.app, flamegraph.pl, or a Mermaid renderer.
160
-
161
- Formats:
162
- table terminal timing/CPU/heap/comparison text (default)
163
- json pretty JSON document
164
- jsonl one metadata line, then one line per measurement
165
- markdown agent- and human-readable report
166
- minimal one compact JSON object per timing measurement, for LLM/CI consumption
167
- collapsed folded stacks: "root;a;b 42" - flamegraph.pl and most flame tooling
168
- mermaid call tree, top-15 frames by total time (never the whole profile)
169
- speedscope sampled profile JSON for speedscope.app
170
- cpuprofile verbatim .cpuprofile pass-through (cpu-prof/inspector origins only)
171
-
172
- Flags:
173
- --format FORMAT one of the formats above (default: table)
174
- --measurement <id> visualization formats only: render only this measurement
175
- (default: every CPU measurement in the document)
176
- --out-dir PATH visualization formats only: write files here instead of stdout
177
- --help show this message
178
-
179
- Examples:
180
- ostia report doc.json
181
- ostia report doc.json --format markdown
182
- ostia report doc.json --format speedscope --out-dir node_modules/.cache/ostia/viz
183
- ostia report doc.json --format collapsed | flamegraph.pl > flame.svg
184
- `;
185
-
186
- export const CI_HELP = `ostia ci [flags]
187
-
188
- Run ostia.config's workloads (reusing cached runs whose declared inputs are unchanged),
189
- compare against a saved baseline, and gate on regressions.
190
-
191
- Flags:
192
- --full ignore the cache
193
- --baseline NAME baseline to compare against (default: config "baseline", or "main")
194
- --save-baseline after a pass, save this run as the new baseline (always measures
195
- fresh: the cache is not used)
196
- --config PATH read this config file instead of ostia.config.ts/.json
197
- --no-noise-check skip the ~200ms noise-floor measurement
198
- --export-json PATH write the candidate document with comparisons to PATH
199
- --format FORMAT table | json | jsonl | markdown | minimal (default: table)
200
- --quiet don't print the report
201
- --help show this message
202
-
203
- Exit codes: 0 pass, 1 regression, 2 harness error (missing config/baseline, a workload
204
- failed or produced no samples, or an onMissingBaseline "fail" mismatch), 130 Ctrl-C (the
205
- partial document is exported; nothing is compared or saved).
206
- `;
207
-
208
- export const BASELINE_HELP = `ostia baseline <save|list|show> [args]
209
-
210
- Manage the baseline ProfileDocuments "ostia ci" gates against and "ostia compare --baseline"
211
- reads.
212
-
213
- Flags (every subcommand): --config PATH reads that config file instead of
214
- ostia.config.ts/.json.
215
-
216
- Subcommands:
217
- save [name] measure every configured workload (same code path as "ostia ci",
218
- no comparison) and write it to <baselineDir>/<name>.json
219
- (default name: config's "baseline" field, or "main")
220
- list list saved baselines: name, created date, workload count
221
- (takes no arguments)
222
- show <name> [flags] render a saved baseline, like "ostia report" (same
223
- --format/--measurement/--out-dir flags)
224
-
225
- Examples:
226
- ostia baseline save
227
- ostia baseline save my-feature
228
- ostia baseline list
229
- ostia baseline show main
230
- ostia baseline show main --format markdown
231
- `;
232
-
233
- export const MAIN_HELP = `ostia - profiling and benchmarking for Bun
234
-
235
- Commands:
236
- time Time commands N times and report timing/CPU/heap
237
- bench Run in-process benchmark suites (group()/task())
238
- ab Pair suites against a git ref in one process, gate on regressions
239
- compare Compare two ProfileDocuments
240
- report Render a saved ProfileDocument (table/json/markdown/collapsed/mermaid/speedscope/...)
241
- ci Run configured workloads against a baseline, gate on regressions
242
- baseline Manage baseline ProfileDocuments (save/list/show)
243
-
244
- Run "ostia <command> --help" for details, "ostia --version" for the version.
245
- `;
1
+ import { processEnv } from "../config/env.ts";
2
+ import {
3
+ createPaint,
4
+ MEASURE,
5
+ type Paint,
6
+ PLAIN,
7
+ SEPARATOR,
8
+ wantsColor,
9
+ } from "../terminal.ts";
10
+ import { TOOL_VERSION } from "../version.ts";
11
+ import { agentVariable } from "./agent.ts";
12
+
13
+ // A status line, Usage, Commands, Options, Examples, then the agent
14
+ // section, within 80 columns. Section heads are bold and defaults gray,
15
+ // so a reader scans for the flag, not the fine print.
16
+
17
+ export type HelpTopic =
18
+ "main" | "time" | "bench" | "ab" | "compare" | "report" | "ci" | "baseline";
19
+
20
+ const NAME_WIDTH = 22;
21
+ const DESCRIPTION_AT = 2 + NAME_WIDTH;
22
+
23
+ // Words packed into lines of `width`, so a long description wraps
24
+ // under itself instead of running ragged.
25
+ function wrapped(text: string, width: number): string[] {
26
+ const lines: string[] = [];
27
+ let line = "";
28
+ for (const word of text.split(" ")) {
29
+ if (line !== "" && line.length + 1 + word.length > width) {
30
+ lines.push(line);
31
+ line = word;
32
+ } else line = line === "" ? word : `${line} ${word}`;
33
+ }
34
+ if (line !== "") lines.push(line);
35
+ return lines;
36
+ }
37
+
38
+ // The default goes gray after the separator, so the eye finds the flag
39
+ // first; a long description wraps under itself, so the columns
40
+ // stay straight.
41
+ function flag(p: Paint, name: string, does: string, preset?: string): string {
42
+ const room = MEASURE - DESCRIPTION_AT;
43
+ const lines = wrapped(does, room);
44
+ if (preset !== undefined) {
45
+ const last = lines.at(-1) ?? "";
46
+ const tail = `${SEPARATOR}${preset}`;
47
+ if (last.length + tail.length <= room) {
48
+ lines[lines.length - 1] = `${last}${p.dim(tail)}`;
49
+ } else lines.push(p.dim(`default ${preset}`));
50
+ }
51
+ const pad = " ".repeat(DESCRIPTION_AT);
52
+ const first =
53
+ // Two spaces at least between a name and its description, or the
54
+ // description starts on the next line.
55
+ name.length <= NAME_WIDTH - 2
56
+ ? ` ${name.padEnd(NAME_WIDTH)}${lines[0] ?? ""}`
57
+ : ` ${name}\n${pad}${lines[0] ?? ""}`;
58
+ return [first, ...lines.slice(1).map((line) => `${pad}${line}`)].join("\n");
59
+ }
60
+
61
+ // Examples carry their intent as a comment, so a reader picks one by
62
+ // what it's for.
63
+ const example = (p: Paint, intent: string, command: string) =>
64
+ ` ${p.dim(`# ${intent}`)}\n ${command}`;
65
+
66
+ const paragraph = (text: string) =>
67
+ wrapped(text, MEASURE - 2)
68
+ .map((line) => ` ${line}`)
69
+ .join("\n");
70
+
71
+ const status = (p: Paint, name: string, tagline: string) =>
72
+ `${p.bold(name)}${p.dim(`${SEPARATOR}${tagline}`)}`;
73
+
74
+ const OUTPUT_FORMATS = "table, concise, events, json, jsonl or markdown";
75
+
76
+ function outputFlags(p: Paint, exported = "the document"): string[] {
77
+ return [
78
+ flag(
79
+ p,
80
+ "--format <name>",
81
+ OUTPUT_FORMATS,
82
+ "table; concise for a coding agent",
83
+ ),
84
+ flag(p, "--json", "same as --format json"),
85
+ flag(p, "--export-json <path>", `write ${exported} to a file`),
86
+ flag(p, "--quiet", "don't print the report"),
87
+ flag(p, "--color, --no-color", "force color on or off", "on in a terminal"),
88
+ flag(p, "-h, --help", "this help"),
89
+ ];
90
+ }
91
+
92
+ const noiseFlags = (p: Paint, budget = true) => [
93
+ flag(p, "--no-noise-check", "skip the noise-floor checks, 50 to 75 ms"),
94
+ ...(budget
95
+ ? [flag(p, "--noise-budget <ms>", "sample the noise floor for exactly ms")]
96
+ : []),
97
+ ];
98
+
99
+ const suiteFlags = (p: Paint, kill: string) => [
100
+ flag(p, "--filter <regex>", 'only tasks whose "group/name" matches'),
101
+ flag(p, "--preload <path>", "import before each suite file; repeatable"),
102
+ flag(p, "--bun-flags <flags>", "more flags for the bun running each suite"),
103
+ flag(p, "--timeout <ms>", `kill a ${kill} process after ms`),
104
+ flag(p, "--out-dir <path>", "scratch directory", "node_modules/.cache/ostia"),
105
+ flag(p, "--config <path>", "this config file", "ostia.config.ts or .json"),
106
+ ];
107
+
108
+ const section = (p: Paint, head: string, lines: readonly string[]) =>
109
+ `${p.bold(head)}\n${lines.join("\n")}`;
110
+
111
+ function main(p: Paint): string {
112
+ return [
113
+ `${p.bold("ostia")} ${TOOL_VERSION}${p.dim(`${SEPARATOR}profiling and benchmarking for Bun`)}`,
114
+ section(p, "Usage", [" ostia <command> [options]"]),
115
+ section(p, "Commands", [
116
+ flag(p, "time <command...>", "time commands as subprocesses"),
117
+ flag(
118
+ p,
119
+ "bench <suite.ts...>",
120
+ "run in-process group() and task() suites",
121
+ ),
122
+ flag(p, "ab <suite.ts...>", "pair suites against a git ref, gate on it"),
123
+ flag(p, "compare <a> <b>", "compare two saved documents, gate on it"),
124
+ flag(p, "report <doc.json>", "render a saved document, or its profile"),
125
+ flag(p, "ci", "run the config's workloads against a baseline"),
126
+ flag(p, "baseline <sub>", "save, list or show baselines"),
127
+ ]),
128
+ section(p, "Options", [
129
+ flag(p, "-h, --help", "help; <command> --help for a command's"),
130
+ flag(p, "-v, --version", "the version"),
131
+ ]),
132
+ section(p, "Examples", [
133
+ example(
134
+ p,
135
+ "which of two commands is faster",
136
+ 'ostia time "bun a.ts" "bun b.ts"',
137
+ ),
138
+ example(
139
+ p,
140
+ "a suite's tasks, with CPU profiles",
141
+ "ostia bench bench/*.ts --cpu",
142
+ ),
143
+ example(
144
+ p,
145
+ "the working tree against HEAD",
146
+ "ostia ab bench/parse.bench.ts",
147
+ ),
148
+ ]),
149
+ section(p, "For agents", [
150
+ paragraph(
151
+ "A coding agent gets --format concise: one line per task, then its warnings. --json prints the whole document; --format events, one JSON line per task. Exit 0 done, 1 regressed, 2 called wrong or failed to measure. The fields are in docs/agent-protocol.md.",
152
+ ),
153
+ ]),
154
+ ].join("\n\n");
155
+ }
156
+
157
+ function time(p: Paint): string {
158
+ return [
159
+ status(p, "ostia time", "time commands as subprocesses"),
160
+ section(p, "Usage", [
161
+ " ostia time [options] <command...>",
162
+ " ostia time [options] -- <argv...>",
163
+ "",
164
+ paragraph(
165
+ "Each <command> is split on whitespace into argv, with no shell; everything after -- is one more command's argv, verbatim. A command stops at its first non-zero exit not ignored. Exit 0 done, 2 a command failed or produced no samples, or a bad flag, 130 Ctrl-C.",
166
+ ),
167
+ ]),
168
+ section(p, "Options", [
169
+ flag(
170
+ p,
171
+ "--samples <n>",
172
+ "exact runs per command",
173
+ "about 3 s, at least 10",
174
+ ),
175
+ flag(p, "--budget <ms>", "sampling time per command"),
176
+ flag(
177
+ p,
178
+ "--min-samples <n>",
179
+ "the fewest runs, when --samples isn't given",
180
+ ),
181
+ flag(p, "--warmup <n>", "runs to discard first", "3"),
182
+ flag(p, "--no-interleave", "run commands one after another, not in turn"),
183
+ flag(
184
+ p,
185
+ "--prepare <cmd>",
186
+ "run before every run, unmeasured; once, or once per command",
187
+ ),
188
+ flag(p, "--shell <sh>", "run each command and --prepare as sh -c CMD"),
189
+ flag(
190
+ p,
191
+ "--save-output <dir>",
192
+ "save each run's output as dir/<command>/trial-N.log",
193
+ ),
194
+ flag(p, "--show-output", "pass each run's output to stderr"),
195
+ flag(
196
+ p,
197
+ "--time-source <regex>",
198
+ "take each run's time from capture group 1 of its output",
199
+ ),
200
+ flag(
201
+ p,
202
+ "--time-unit <unit>",
203
+ "unit of --time-source: ns, us, ms or s",
204
+ "ms",
205
+ ),
206
+ flag(p, "--cpu", "capture one more run's CPU profile"),
207
+ flag(p, "--heap", "capture one more run's heap snapshot"),
208
+ flag(
209
+ p,
210
+ "--cpu-interval <us>",
211
+ "CPU sampling interval; needs --cpu",
212
+ "1000",
213
+ ),
214
+ flag(p, "--timeout <ms>", "kill a run or a --prepare hook after ms"),
215
+ flag(
216
+ p,
217
+ "--ignore-failure[=<codes>]",
218
+ "treat these exit codes, comma-separated, as success; bare, every one",
219
+ ),
220
+ flag(
221
+ p,
222
+ "--out-dir <path>",
223
+ "artifact directory",
224
+ "node_modules/.cache/ostia",
225
+ ),
226
+ ...noiseFlags(p),
227
+ ...outputFlags(p),
228
+ ]),
229
+ section(p, "Examples", [
230
+ example(p, "which of two is faster", 'ostia time "bun a.ts" "bun b.ts"'),
231
+ example(
232
+ p,
233
+ "25 runs, with a CPU profile and a heap snapshot",
234
+ 'ostia time --samples 25 --cpu --heap "bun src/server.ts"',
235
+ ),
236
+ example(
237
+ p,
238
+ "a cold build each run",
239
+ 'ostia time --prepare "rm -rf dist" "bun build.ts"',
240
+ ),
241
+ example(
242
+ p,
243
+ "the time the build prints, not its wall time",
244
+ 'ostia time --time-source "built in (\\d+)ms" "bun build.ts"',
245
+ ),
246
+ example(
247
+ p,
248
+ "an argv with spaces in it",
249
+ "ostia time -- bun -e \"console.log('a b')\"",
250
+ ),
251
+ ]),
252
+ ].join("\n\n");
253
+ }
254
+
255
+ function bench(p: Paint): string {
256
+ return [
257
+ status(p, "ostia bench", "run in-process group() and task() suites"),
258
+ section(p, "Usage", [
259
+ " ostia bench [options] <suite.ts...>",
260
+ "",
261
+ paragraph(
262
+ "Each suite file runs in its own process. With no files, the config's \"bench\" section names them; each option overrides its config field, and a task's or group's own options override both. Exit 0 done, 2 a suite failed or a bad flag, 130 Ctrl-C.",
263
+ ),
264
+ ]),
265
+ section(p, "Options", [
266
+ flag(p, "--budget <ms>", "sampling time per task", "500"),
267
+ flag(p, "--samples <n>", "exact samples per task; ignores --budget"),
268
+ flag(p, "--min-samples <n>", "the fewest samples", "by cost, 3 to 20"),
269
+ flag(
270
+ p,
271
+ "--jobs <n|auto>",
272
+ "suite files at once; more than 1 adds noise",
273
+ "1",
274
+ ),
275
+ flag(
276
+ p,
277
+ "--isolate",
278
+ "one process per task, not per file; --no-isolate undoes the config's",
279
+ ),
280
+ flag(p, "--gc", "Bun.gc(true) between samples; --no-gc"),
281
+ flag(
282
+ p,
283
+ "--cpu",
284
+ "one more pass per task for a CPU profile with JIT tiers, about 2,000 samples; --no-cpu",
285
+ ),
286
+ flag(p, "--cpu-interval <us>", "CPU sampling interval", "100"),
287
+ flag(
288
+ p,
289
+ "--alloc",
290
+ "heap each call keeps alive after a full GC, not what it allocates; --no-alloc",
291
+ ),
292
+ flag(
293
+ p,
294
+ "--peak-mem",
295
+ "RSS rise of the first call, garbage included, median of 3 processes; --no-peak-mem",
296
+ ),
297
+ ...suiteFlags(p, "suite (or isolated task)"),
298
+ ...noiseFlags(p),
299
+ ...outputFlags(p),
300
+ ]),
301
+ section(p, "Examples", [
302
+ example(p, "every suite", "ostia bench bench/*.ts"),
303
+ example(
304
+ p,
305
+ "the parse tasks, with CPU profiles and retained heap",
306
+ "ostia bench bench/*.ts --filter parse --cpu --alloc",
307
+ ),
308
+ example(
309
+ p,
310
+ "suites that need a DOM",
311
+ 'ostia bench --preload ./dom.ts --bun-flags="--conditions=browser" bench/*.ts',
312
+ ),
313
+ ]),
314
+ ].join("\n\n");
315
+ }
316
+
317
+ function ab(p: Paint): string {
318
+ return [
319
+ status(p, "ostia ab", "pair suites against a git ref, gate on regressions"),
320
+ section(p, "Usage", [
321
+ " ostia ab [options] <suite.ts...>",
322
+ "",
323
+ paragraph(
324
+ 'Each task runs on a git ref\'s committed tree (base) and the working tree (candidate) in one process, in alternating batches of about 10 ms, so drift cancels within a round. Each suite runs twice, each side first once. With no files, the config\'s "bench" suites. A flagged task counts only when every fresh-process repeat flags it the same way. A task whose suite file and output both changed reads "not comparable" and stays out of the verdict.',
325
+ ),
326
+ "",
327
+ paragraph(
328
+ "The base tree is cached per commit and --base-setup under .ostia/ab, with the project's node_modules linked in; setup runs with OSTIA_AB_SHA and OSTIA_AB_CANDIDATE_DIR set. Instructions per call are counted where the machine allows (macOS; Linux with perf_event_paranoid at most 2).",
329
+ ),
330
+ "",
331
+ paragraph(
332
+ "Exit 0 pass; 1 a confirmed regression, a throw on the candidate only, the geomean over its threshold, or a memory regression; 2 nothing paired or a harness error (not a git repo, an unknown ref, a failed setup or suite); 130 Ctrl-C.",
333
+ ),
334
+ ]),
335
+ section(p, "Options", [
336
+ flag(p, "--base <ref>", "the git ref for the base side", "HEAD"),
337
+ flag(
338
+ p,
339
+ "--base-setup <cmd>",
340
+ "a shell command run once in a new base tree, to build what its suites import; repeatable",
341
+ ),
342
+ flag(p, "--rounds <n>", "base and candidate rounds per task", "15"),
343
+ flag(
344
+ p,
345
+ "--metric <name>",
346
+ "judge each round's time or instructions; instructions barely move on a busy machine",
347
+ "time",
348
+ ),
349
+ flag(
350
+ p,
351
+ "--threshold <pct>",
352
+ "flag a task whose median ratio moves past pct",
353
+ "10",
354
+ ),
355
+ flag(
356
+ p,
357
+ "--geomean-threshold <pct>",
358
+ "fail when the geometric mean of all ratios is slower by pct",
359
+ "1.5",
360
+ ),
361
+ flag(
362
+ p,
363
+ "--confirm <n>",
364
+ "recheck a flagged task in n fresh processes; 0 skips",
365
+ "2",
366
+ ),
367
+ flag(p, "--alloc", "compare retained heap per call too; --no-alloc"),
368
+ flag(
369
+ p,
370
+ "--peak-mem",
371
+ "compare the first call's RSS rise too, median of 3 processes a side; --no-peak-mem",
372
+ ),
373
+ flag(
374
+ p,
375
+ "--mem-threshold <pct>",
376
+ "flag a memory reading that moves past pct and its noise floor",
377
+ "10",
378
+ ),
379
+ ...suiteFlags(p, "suite (or repeat)"),
380
+ flag(
381
+ p,
382
+ "--keep-trees <n>",
383
+ "base trees to keep cached, oldest out first",
384
+ "5",
385
+ ),
386
+ flag(p, "--clean", "remove every cached base tree, then exit"),
387
+ flag(
388
+ p,
389
+ "--progress",
390
+ "progress on stderr (--no-progress)",
391
+ "on in a terminal",
392
+ ),
393
+ ...noiseFlags(p),
394
+ ...outputFlags(p),
395
+ ]),
396
+ section(p, "Examples", [
397
+ example(
398
+ p,
399
+ "the working tree against HEAD",
400
+ "ostia ab bench/parse.bench.ts",
401
+ ),
402
+ example(
403
+ p,
404
+ "against main, with more rounds",
405
+ "ostia ab bench/*.ts --base origin/main --rounds 21",
406
+ ),
407
+ example(
408
+ p,
409
+ "a tight gate on a busy CI machine",
410
+ "ostia ab bench/*.ts --metric instructions --threshold 3",
411
+ ),
412
+ example(
413
+ p,
414
+ "a base that needs a build step",
415
+ 'ostia ab bench/*.ts --base-setup "bun scripts/generate.ts"',
416
+ ),
417
+ example(
418
+ p,
419
+ "memory too",
420
+ "ostia ab bench/paint.bench.ts --alloc --peak-mem",
421
+ ),
422
+ ]),
423
+ ].join("\n\n");
424
+ }
425
+
426
+ function compare(p: Paint): string {
427
+ return [
428
+ status(
429
+ p,
430
+ "ostia compare",
431
+ "compare two saved documents, gate on regressions",
432
+ ),
433
+ section(p, "Usage", [
434
+ " ostia compare [options] <base.json> <candidate.json>",
435
+ " ostia compare [options] <candidate.json> --baseline <base.json>",
436
+ "",
437
+ paragraph(
438
+ 'Tasks match by workload id, or by a task\'s former names from its "aliases". The gate uses the config\'s "thresholds", as ostia ci does, else the defaults, widened by machine noise and drift. Exit 0 pass, 1 a workload regressed, 2 nothing matched or a harness error.',
439
+ ),
440
+ ]),
441
+ section(p, "Options", [
442
+ flag(
443
+ p,
444
+ "--baseline <path>",
445
+ "the base document, when only the candidate is positional",
446
+ ),
447
+ flag(
448
+ p,
449
+ "--config <path>",
450
+ "read thresholds from this config file",
451
+ "ostia.config.ts or .json",
452
+ ),
453
+ ...outputFlags(p, "the candidate with its comparisons"),
454
+ ]),
455
+ section(p, "Examples", [
456
+ example(
457
+ p,
458
+ "a branch's run against main's",
459
+ "ostia compare main.json branch.json",
460
+ ),
461
+ example(
462
+ p,
463
+ "every row, for a script",
464
+ "ostia compare main.json branch.json --json",
465
+ ),
466
+ ]),
467
+ ].join("\n\n");
468
+ }
469
+
470
+ function report(p: Paint): string {
471
+ return [
472
+ status(p, "ostia report", "render a saved document, or its profile"),
473
+ section(p, "Usage", [
474
+ " ostia report <document.json> [options]",
475
+ "",
476
+ paragraph(
477
+ "Files, not a GUI: hand a visualization format to speedscope.app, flamegraph.pl or a Mermaid renderer.",
478
+ ),
479
+ ]),
480
+ section(p, "Formats", [
481
+ flag(p, "table", "the terminal report", "default"),
482
+ flag(p, "json", "the document, pretty"),
483
+ flag(p, "jsonl", "a metadata line, then one line per measurement"),
484
+ flag(p, "markdown", "a report for a pull request or an agent"),
485
+ flag(p, "concise", "one line per task, then its warnings; alias agent"),
486
+ flag(p, "events", "one JSON line per timing measurement; alias minimal"),
487
+ flag(p, "collapsed", 'folded stacks, "root;a;b 42", for flamegraph.pl'),
488
+ flag(p, "mermaid", "the call tree, the top 15 frames by total time"),
489
+ flag(p, "speedscope", "a sampled profile for speedscope.app"),
490
+ flag(
491
+ p,
492
+ "cpuprofile",
493
+ "the .cpuprofile as captured, inspector origins only",
494
+ ),
495
+ ]),
496
+ section(p, "Options", [
497
+ flag(p, "--format <name>", "one of the formats above", "table"),
498
+ flag(
499
+ p,
500
+ "--measurement <id>",
501
+ "visualizations: this measurement only",
502
+ "every CPU one",
503
+ ),
504
+ flag(
505
+ p,
506
+ "--out-dir <path>",
507
+ "visualizations: write files here, not to stdout",
508
+ ),
509
+ flag(
510
+ p,
511
+ "--color, --no-color",
512
+ "force color on or off",
513
+ "on in a terminal",
514
+ ),
515
+ flag(p, "-h, --help", "this help"),
516
+ ]),
517
+ section(p, "Examples", [
518
+ example(p, "the table again", "ostia report doc.json"),
519
+ example(
520
+ p,
521
+ "for a pull request",
522
+ "ostia report doc.json --format markdown",
523
+ ),
524
+ example(
525
+ p,
526
+ "a flame graph",
527
+ "ostia report doc.json --format collapsed | flamegraph.pl > flame.svg",
528
+ ),
529
+ example(
530
+ p,
531
+ "files for speedscope.app",
532
+ "ostia report doc.json --format speedscope --out-dir viz",
533
+ ),
534
+ ]),
535
+ ].join("\n\n");
536
+ }
537
+
538
+ function ci(p: Paint): string {
539
+ return [
540
+ status(p, "ostia ci", "run the config's workloads against a baseline"),
541
+ section(p, "Usage", [
542
+ " ostia ci [options]",
543
+ "",
544
+ paragraph(
545
+ "Runs the config's workloads, reusing a cached run whose declared inputs haven't changed, compares them with a saved baseline and gates on regressions. Exit 0 pass, 1 a regression, 2 a harness error (no config or baseline, a workload failed or produced no samples, or an onMissingBaseline \"fail\" mismatch), 130 Ctrl-C (the partial document is exported; nothing is compared or saved).",
546
+ ),
547
+ ]),
548
+ section(p, "Options", [
549
+ flag(p, "--full", "ignore the cache"),
550
+ flag(
551
+ p,
552
+ "--baseline <name>",
553
+ "gate on this baseline",
554
+ 'the config\'s "baseline", or main',
555
+ ),
556
+ flag(
557
+ p,
558
+ "--save-baseline",
559
+ "after a pass, save this run as the baseline; always measures fresh",
560
+ ),
561
+ flag(
562
+ p,
563
+ "--config <path>",
564
+ "this config file",
565
+ "ostia.config.ts or .json",
566
+ ),
567
+ ...noiseFlags(p, false),
568
+ ...outputFlags(p, "the candidate with its comparisons"),
569
+ ]),
570
+ section(p, "Examples", [
571
+ example(p, "gate a pull request", "ostia ci"),
572
+ example(
573
+ p,
574
+ "after a merge to main, move the baseline",
575
+ "ostia ci --save-baseline",
576
+ ),
577
+ ]),
578
+ ].join("\n\n");
579
+ }
580
+
581
+ function baseline(p: Paint): string {
582
+ return [
583
+ status(p, "ostia baseline", "save, list or show baselines"),
584
+ section(p, "Usage", [
585
+ " ostia baseline <save|list|show> [args]",
586
+ "",
587
+ paragraph(
588
+ "The documents ostia ci gates against and ostia compare --baseline reads.",
589
+ ),
590
+ ]),
591
+ section(p, "Commands", [
592
+ flag(
593
+ p,
594
+ "save [name]",
595
+ 'measure every configured workload, as ostia ci does, without comparing; write <baselineDir>/<name>.json, name the config\'s "baseline", or main',
596
+ ),
597
+ flag(p, "list", "saved baselines: name, created date, workload count"),
598
+ flag(
599
+ p,
600
+ "show <name>",
601
+ "render a saved baseline, as ostia report does, with its --format, --measurement and --out-dir",
602
+ ),
603
+ ]),
604
+ section(p, "Options", [
605
+ flag(
606
+ p,
607
+ "--config <path>",
608
+ "this config file",
609
+ "ostia.config.ts or .json",
610
+ ),
611
+ flag(p, "-h, --help", "this help"),
612
+ ]),
613
+ section(p, "Examples", [
614
+ example(p, "save the main baseline", "ostia baseline save"),
615
+ example(p, "a named one, for a branch", "ostia baseline save my-feature"),
616
+ example(p, "what's saved", "ostia baseline list"),
617
+ example(
618
+ p,
619
+ "a baseline, for a pull request",
620
+ "ostia baseline show main --format markdown",
621
+ ),
622
+ ]),
623
+ ].join("\n\n");
624
+ }
625
+
626
+ const TOPICS: Record<HelpTopic, (p: Paint) => string> = {
627
+ main,
628
+ time,
629
+ bench,
630
+ ab,
631
+ compare,
632
+ report,
633
+ ci,
634
+ baseline,
635
+ };
636
+
637
+ export function helpText(topic: HelpTopic, paint: Paint): string {
638
+ return `${TOPICS[topic](paint)}\n`;
639
+ }
640
+
641
+ // The forced color from argv, read before (or without) the rest parsing,
642
+ // so help and a usage error honor --no-color.
643
+ function forcedColor(argv: readonly string[]): boolean | undefined {
644
+ const end = argv.indexOf("--");
645
+ const own = end === -1 ? argv : argv.slice(0, end);
646
+ if (own.includes("--no-color")) return false;
647
+ return own.includes("--color") ? true : undefined;
648
+ }
649
+
650
+ // The flag, then the terminal, so help, output and errors agree.
651
+ export async function paintFor(
652
+ fd: 1 | 2,
653
+ forced: boolean | undefined = forcedColor(process.argv),
654
+ ): Promise<Paint> {
655
+ // perf: imported lazily, since loading node:tty up front costs every
656
+ // invocation about 4 ms (median of 150 runs, before and after).
657
+ const { isatty } = await import("node:tty");
658
+ const env = processEnv();
659
+ return wantsColor(forced, isatty(fd), env, agentVariable(env) !== undefined)
660
+ ? createPaint()
661
+ : PLAIN;
662
+ }
663
+
664
+ export async function showHelp(
665
+ topic: HelpTopic,
666
+ requested: boolean,
667
+ ): Promise<0 | 2> {
668
+ await Bun.write(Bun.stdout, helpText(topic, await paintFor(1)));
669
+ return requested ? 0 : 2;
670
+ }