vouchington-tooling 0.65.1 → 0.66.1

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 (26) hide show
  1. package/README.md +9 -0
  2. package/dist/shell-parse/git-invocations.d.mts +25 -0
  3. package/dist/shell-parse/git-invocations.mjs +153 -0
  4. package/dist/shell-parse/git-wrapper-options.d.mts +7 -0
  5. package/dist/shell-parse/git-wrapper-options.mjs +80 -0
  6. package/dist/shell-parse/index.d.mts +2 -0
  7. package/dist/shell-parse/index.mjs +1 -0
  8. package/dist/storybook-browser-runner/attempt-result.mjs +2 -0
  9. package/dist/storybook-browser-runner/bootstrap-telemetry.d.mts +4 -0
  10. package/dist/storybook-browser-runner/bootstrap-telemetry.mjs +14 -2
  11. package/dist/storybook-browser-runner/fixtures.test-helpers.d.mts +2 -0
  12. package/dist/storybook-browser-runner/fixtures.test-helpers.mjs +20 -1
  13. package/dist/storybook-browser-runner/observer-state.d.mts +2 -0
  14. package/dist/storybook-browser-runner/observer-state.mjs +2 -0
  15. package/dist/storybook-browser-runner/output-observer.mjs +7 -1
  16. package/dist/storybook-browser-runner/output-patterns.d.mts +4 -0
  17. package/dist/storybook-browser-runner/output-patterns.mjs +11 -0
  18. package/dist/storybook-browser-runner/process-sample.d.mts +31 -0
  19. package/dist/storybook-browser-runner/process-sample.mjs +106 -0
  20. package/dist/storybook-browser-runner/run-attempt.mjs +3 -0
  21. package/dist/storybook-browser-runner/session-deps.mjs +2 -0
  22. package/dist/storybook-browser-runner/types.d.mts +2 -0
  23. package/dist/storybook-browser-runner/watchdog.d.mts +3 -1
  24. package/dist/storybook-browser-runner/watchdog.mjs +10 -1
  25. package/package.json +1 -1
  26. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
package/README.md CHANGED
@@ -393,6 +393,13 @@ retried and the guidance names `--optimize-deps-config`. Progress markers and `v
393
393
  output are kept out of the log and replayed from a bounded tail when an attempt fails, and a
394
394
  diagnostics file (`_DIAGNOSTICS_FILE`, default `storybook-browser-diagnostics.log`) holds the
395
395
  per-attempt summaries and the output tail.
396
+ Before it terminates a stall or hang, the runner writes
397
+ `[storybook-browser] process group <pgid> at stall:` and one line per process of the test command's
398
+ group and its descendants, including the detached browser (pid, RSS in MB, %CPU, state, role such as `renderer`, `gpu-process` or `browser`; never argv,
399
+ capped near 4KB), sampled with `ps -ax` and best effort. The semantic-stall message names the last
400
+ progress marker and its age, and the attempt summary counts Playwright `Target.targetCrashed` and
401
+ `Inspector.targetCrashed` (`targetCrashCount`) and `Target.detachedFromTarget`
402
+ (`targetDetachCount`) protocol lines.
396
403
 
397
404
  Everything repository-specific is a parameter: the Vitest project name (also the browser-project
398
405
  output marker), the command and argv, the `--result-file` paths removed before each attempt, the
@@ -581,6 +588,8 @@ import { tokenizeShellWords } from 'vouchington-tooling/shell-parse'
581
588
 
582
589
  `vouchington-tooling/shell-parse` splits shell text into words, heredocs, redirections, and command prefixes. Callers pass the text. The parser does not decide which commands are allowed. `stripQuotedShellText` and `commandsToInspect*` do not scan `$(...)` substitutions in the command text: call `extractShellCommandSubstitutions` and inspect each result too.
583
590
 
591
+ `gitInvocations(command)` returns each `git` run in command position (after `;`, `&&`, `||`, `|`, a newline, env assignments, or wrappers such as `env`, `sudo`, `xargs`, `timeout`, `nice`) as `{ globalOptions, configOverrides: [{ key, value }], subcommand, args }`. Global options (`-c`, `-C`, `--git-dir`, `--no-pager`, ...) are skipped to reach the subcommand, and `git` as an argument (`printf '%s' git`) is not an invocation. `overridesConfig(invocation, 'core.hooksPath')` checks the `-c` keys case-insensitively. Substitutions and `bash -c` scripts are not read; run it on each result of `extractShellCommandSubstitutions` and `extractShellCommandArguments`. Known best-effort limits: value options inside clustered short wrapper flags are not read, backtick bodies are not read, and a quoted redirection-looking word mid-argv can truncate `args`.
592
+
584
593
  `vouchington-tooling/command-policy` judges a tool call's shell command against a rule table the
585
594
  caller supplies. `evaluateCommandPolicy(payload, policy, { automationContext })` returns a
586
595
  `BlockDecision` or `null`. The `CommandPolicy` table holds typo paths, protected paths (blocked only
@@ -0,0 +1,25 @@
1
+ /** One `-c key=value` (or `--config-env=key=ENVVAR`, whose value is the variable name). */
2
+ export type GitConfigOverride = {
3
+ key: string;
4
+ value: string;
5
+ };
6
+ export type GitInvocation = {
7
+ /** Subcommand arguments, unquoted, up to the end of the command segment. */
8
+ args: string[];
9
+ /** `-c key=value` pairs in order, with each key as written. */
10
+ configOverrides: GitConfigOverride[];
11
+ /** Every global option word skipped to reach the subcommand, as written (`['-C', '/x']`). */
12
+ globalOptions: string[];
13
+ /** The subcommand word, or undefined for a bare `git` or `git --version`. */
14
+ subcommand: string | undefined;
15
+ };
16
+ /**
17
+ * Each `git` the shell would run in command position: after a separator, env assignments, or a
18
+ * wrapper (`env`, `sudo`, `xargs`, `timeout`, `nice`, ...). A `git` word in argument position
19
+ * (`printf %s git`) is not an invocation. Global options are skipped to reach the subcommand and
20
+ * `-c` pairs are collected. `$(...)` text and `bash -c` scripts are not read: feed those to
21
+ * `extractShellCommandSubstitutions` / `extractShellCommandArguments` and call this on each.
22
+ */
23
+ export declare function gitInvocations(command: string): GitInvocation[];
24
+ /** True when the invocation sets `key` with `-c`. Keys compare case-insensitively. */
25
+ export declare function overridesConfig(invocation: GitInvocation, key: string): boolean;
@@ -0,0 +1,153 @@
1
+ import { EXTRA_WRAPPERS, skipWrapper } from "./git-wrapper-options.mjs";
2
+ import { stripNonShellHeredocBodies } from "./shell-heredoc.mjs";
3
+ import { readCommandPrefix, withoutRedirections } from "./shell-command-wrappers.mjs";
4
+ import { tokenizeShellWordsDetailed } from "./shell-tokenizer.mjs";
5
+ const VALUE_OPTIONS = new Set([
6
+ '-C',
7
+ '-c',
8
+ '--git-dir',
9
+ '--work-tree',
10
+ '--namespace',
11
+ '--config-env',
12
+ '--super-prefix',
13
+ '--attr-source',
14
+ ]);
15
+ // These print and exit: any later word is not a subcommand.
16
+ const TERMINAL_OPTIONS = new Set([
17
+ '-h',
18
+ '-v',
19
+ '--exec-path',
20
+ '--help',
21
+ '--html-path',
22
+ '--info-path',
23
+ '--man-path',
24
+ '--version',
25
+ ]);
26
+ const FLAG_OPTIONS = new Set([
27
+ '-p',
28
+ '-P',
29
+ '--bare',
30
+ '--glob-pathspecs',
31
+ '--icase-pathspecs',
32
+ '--literal-pathspecs',
33
+ '--no-advice',
34
+ '--no-lazy-fetch',
35
+ '--no-literal-pathspecs',
36
+ '--no-optional-locks',
37
+ '--no-pager',
38
+ '--no-replace-objects',
39
+ '--noglob-pathspecs',
40
+ '--paginate',
41
+ ]);
42
+ const ATTACHED_OPTION = /^--(?:git-dir|work-tree|namespace|exec-path|config-env|super-prefix|attr-source|list-cmds)=/;
43
+ const CONFIG_ENV_PREFIX = '--config-env=';
44
+ /**
45
+ * Each `git` the shell would run in command position: after a separator, env assignments, or a
46
+ * wrapper (`env`, `sudo`, `xargs`, `timeout`, `nice`, ...). A `git` word in argument position
47
+ * (`printf %s git`) is not an invocation. Global options are skipped to reach the subcommand and
48
+ * `-c` pairs are collected. `$(...)` text and `bash -c` scripts are not read: feed those to
49
+ * `extractShellCommandSubstitutions` / `extractShellCommandArguments` and call this on each.
50
+ */
51
+ export function gitInvocations(command) {
52
+ const invocations = [];
53
+ for (const segment of segmentsOf(command)) {
54
+ const words = commandWords(segment);
55
+ if (words !== null && basename(words[0]) === 'git')
56
+ invocations.push(readInvocation(words));
57
+ }
58
+ return invocations;
59
+ }
60
+ /** True when the invocation sets `key` with `-c`. Keys compare case-insensitively. */
61
+ export function overridesConfig(invocation, key) {
62
+ const wanted = key.toLowerCase();
63
+ return invocation.configOverrides.some((override) => override.key.toLowerCase() === wanted);
64
+ }
65
+ // Heredoc bodies that are data are dropped. A `$(` opens a substitution, `name=(` an array literal, and `<(` / `>(` a process substitution;: its body is skipped (it
66
+ // belongs to `extractShellCommandSubstitutions`) so the outer command keeps its later arguments.
67
+ function segmentsOf(command) {
68
+ const segments = [[]];
69
+ let depth = 0;
70
+ const words = tokenizeShellWordsDetailed(stripNonShellHeredocBodies(command).textWithoutBodies, {
71
+ markOperators: true,
72
+ splitRedirections: true,
73
+ });
74
+ for (const word of words) {
75
+ const current = segments.at(-1);
76
+ if (depth > 0 ||
77
+ (word.operator === true && word.value === '(' && /[$=<>]$/.test(current.at(-1) ?? ''))) {
78
+ // A bare `<` / `>` before `(` is a process substitution, not a redirection of the next word.
79
+ if (/^[<>]$/.test(current.at(-1)))
80
+ current.pop();
81
+ if (word.operator === true)
82
+ depth += word.value === '(' ? 1 : word.value === ')' ? -1 : 0;
83
+ }
84
+ else if (word.operator === true) {
85
+ segments.push([]);
86
+ }
87
+ else {
88
+ current.push(word.value);
89
+ }
90
+ }
91
+ return segments;
92
+ }
93
+ function basename(word) {
94
+ return word.slice(word.lastIndexOf('/') + 1);
95
+ }
96
+ /** The words from the command word on, or null when the segment runs nothing readable. */
97
+ function commandWords(segment) {
98
+ // A quoted `'>'` argument is indistinguishable from a redirection here; keep the words then.
99
+ let words = withoutRedirections(segment) ?? segment;
100
+ for (;;) {
101
+ const read = readCommandPrefix(words);
102
+ if (read === null || read.commandIndex >= words.length)
103
+ return null;
104
+ words = words.slice(read.commandIndex);
105
+ const wrapper = EXTRA_WRAPPERS.get(basename(words[0]));
106
+ if (wrapper === undefined)
107
+ return words;
108
+ words = skipWrapper(words, wrapper);
109
+ }
110
+ }
111
+ function readInvocation(words) {
112
+ const globalOptions = [];
113
+ const configOverrides = [];
114
+ let cursor = 1;
115
+ while (cursor < words.length) {
116
+ const word = words[cursor];
117
+ if (VALUE_OPTIONS.has(word)) {
118
+ const value = words[cursor + 1];
119
+ if (value === undefined)
120
+ break;
121
+ globalOptions.push(word, value);
122
+ if (word === '-c' || word === '--config-env')
123
+ configOverrides.push(splitOverride(value));
124
+ cursor += 2;
125
+ }
126
+ else if (TERMINAL_OPTIONS.has(word)) {
127
+ globalOptions.push(word);
128
+ return { args: [], configOverrides, globalOptions, subcommand: undefined };
129
+ }
130
+ else if (FLAG_OPTIONS.has(word) || ATTACHED_OPTION.test(word)) {
131
+ globalOptions.push(word);
132
+ if (word.startsWith(CONFIG_ENV_PREFIX)) {
133
+ configOverrides.push(splitOverride(word.slice(CONFIG_ENV_PREFIX.length)));
134
+ }
135
+ cursor += 1;
136
+ }
137
+ else {
138
+ break;
139
+ }
140
+ }
141
+ return {
142
+ args: words.slice(cursor + 1),
143
+ configOverrides,
144
+ globalOptions,
145
+ subcommand: words[cursor],
146
+ };
147
+ }
148
+ function splitOverride(pair) {
149
+ const equals = pair.indexOf('=');
150
+ return equals < 0
151
+ ? { key: pair, value: '' }
152
+ : { key: pair.slice(0, equals), value: pair.slice(equals + 1) };
153
+ }
@@ -0,0 +1,7 @@
1
+ export type ExtraWrapper = {
2
+ duration?: true;
3
+ values: readonly string[];
4
+ };
5
+ export declare const EXTRA_WRAPPERS: ReadonlyMap<string, ExtraWrapper>;
6
+ /** The words after a wrapper's own options (and `timeout`'s duration). */
7
+ export declare function skipWrapper(words: string[], wrapper: ExtraWrapper): string[];
@@ -0,0 +1,80 @@
1
+ // Wrappers `readCommandPrefix` does not read through, with the options that take a separate value.
2
+ export const EXTRA_WRAPPERS = new Map([
3
+ ['doas', { values: ['-u', '-C'] }],
4
+ [
5
+ 'ionice',
6
+ {
7
+ values: ['-c', '-n', '-p', '-P', '-u', '--class', '--classdata', '--pid', '--pgid', '--uid'],
8
+ },
9
+ ],
10
+ ['nice', { values: ['-n', '--adjustment'] }],
11
+ ['setsid', { values: [] }],
12
+ ['stdbuf', { values: ['-i', '-o', '-e', '--input', '--output', '--error'] }],
13
+ [
14
+ 'sudo',
15
+ {
16
+ values: [
17
+ '-u',
18
+ '-g',
19
+ '-h',
20
+ '-p',
21
+ '-C',
22
+ '-D',
23
+ '-R',
24
+ '-T',
25
+ '-U',
26
+ '-r',
27
+ '-t',
28
+ '--user',
29
+ '--group',
30
+ '--host',
31
+ '--prompt',
32
+ '--close-from',
33
+ '--chdir',
34
+ '--chroot',
35
+ '--command-timeout',
36
+ '--other-user',
37
+ '--role',
38
+ '--type',
39
+ ],
40
+ },
41
+ ],
42
+ ['timeout', { duration: true, values: ['-s', '-k', '--signal', '--kill-after'] }],
43
+ [
44
+ 'xargs',
45
+ {
46
+ // `--replace`, `--eof` and `--max-lines` take their value only attached (`--eof=END`).
47
+ values: [
48
+ '-I',
49
+ '-n',
50
+ '-P',
51
+ '-L',
52
+ '-s',
53
+ '-E',
54
+ '-d',
55
+ '-a',
56
+ '--max-args',
57
+ '--max-procs',
58
+ '--max-chars',
59
+ '--delimiter',
60
+ '--arg-file',
61
+ ],
62
+ },
63
+ ],
64
+ ]);
65
+ const DURATION = /^(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?[smhd]?$|^inf(?:inity)?[smhd]?$/i;
66
+ /** The words after a wrapper's own options (and `timeout`'s duration). */
67
+ export function skipWrapper(words, wrapper) {
68
+ let cursor = 1;
69
+ while (words[cursor]?.startsWith('-') === true) {
70
+ const word = words[cursor];
71
+ cursor += 1;
72
+ if (word === '--')
73
+ break;
74
+ if (wrapper.values.includes(word))
75
+ cursor += 1;
76
+ }
77
+ if (wrapper.duration === true && DURATION.test(words[cursor] ?? ''))
78
+ cursor += 1;
79
+ return words.slice(cursor);
80
+ }
@@ -1,6 +1,8 @@
1
1
  export { decodeAnsiCStringEscape, decodeNumericAnsiEscape, readAnsiCString, } from './ansi-c-string.mts';
2
2
  export { readBacktickSubstitution, readParenthesizedSubstitution, } from './shell-command-substitution-reads.mts';
3
3
  export { extractShellCommandSubstitutions } from './shell-command-substitutions.mts';
4
+ export { gitInvocations, overridesConfig } from './git-invocations.mts';
5
+ export type { GitConfigOverride, GitInvocation } from './git-invocations.mts';
4
6
  export { parseCommandPrefix, readCommandPrefix, withoutRedirections, } from './shell-command-wrappers.mts';
5
7
  export type { CommandPrefix } from './shell-command-wrappers.mts';
6
8
  export { commandsToInspectForGitPolicy, commandsToInspectPreservingQuotes, envPrefixSetsEditor, extractShellCommandArguments, isInteractiveRebaseContinue, shellCommandInheritsEditor, stripGitGlobalOptionsForPolicy, stripQuotedShellText, } from './shell-commands.mts';
@@ -1,6 +1,7 @@
1
1
  export { decodeAnsiCStringEscape, decodeNumericAnsiEscape, readAnsiCString, } from "./ansi-c-string.mjs";
2
2
  export { readBacktickSubstitution, readParenthesizedSubstitution, } from "./shell-command-substitution-reads.mjs";
3
3
  export { extractShellCommandSubstitutions } from "./shell-command-substitutions.mjs";
4
+ export { gitInvocations, overridesConfig } from "./git-invocations.mjs";
4
5
  export { parseCommandPrefix, readCommandPrefix, withoutRedirections, } from "./shell-command-wrappers.mjs";
5
6
  export { commandsToInspectForGitPolicy, commandsToInspectPreservingQuotes, envPrefixSetsEditor, extractShellCommandArguments, isInteractiveRebaseContinue, shellCommandInheritsEditor, stripGitGlobalOptionsForPolicy, stripQuotedShellText, } from "./shell-commands.mjs";
6
7
  export { readHeredocDelimiter } from "./shell-heredoc-delimiter.mjs";
@@ -99,6 +99,8 @@ export function formatAttemptResult(attempt, result) {
99
99
  `bootstrapStage=${result.bootstrap.terminalStage}`,
100
100
  `bootstrapTimeline=${JSON.stringify(result.bootstrap.timeline)}`,
101
101
  `orchestratorDisconnectCount=${result.bootstrap.orchestratorDisconnectCount}`,
102
+ `targetCrashCount=${result.bootstrap.targetCrashCount}`,
103
+ `targetDetachCount=${result.bootstrap.targetDetachCount}`,
102
104
  `requestFailureCount=${result.bootstrap.requestFailureCount}`,
103
105
  `requestFailureSamples=${JSON.stringify(result.bootstrap.requestFailureSamples)}`,
104
106
  `viteFetchFailure=${String(result.viteFetchFailure)}`,
@@ -5,6 +5,8 @@ export interface StorybookBrowserBootstrapSnapshot {
5
5
  orchestratorDisconnectCount: number;
6
6
  requestFailureCount: number;
7
7
  requestFailureSamples: string[];
8
+ targetCrashCount: number;
9
+ targetDetachCount: number;
8
10
  terminalStage: StorybookBrowserBootstrapTerminalStage;
9
11
  timeline: Array<{
10
12
  atMs: number;
@@ -23,6 +25,8 @@ export declare class StorybookBrowserBootstrapTelemetry {
23
25
  private playwrightBrowserLineCount;
24
26
  private orchestratorDisconnectCount;
25
27
  private requestFailureCount;
28
+ private targetCrashCount;
29
+ private targetDetachCount;
26
30
  consume(stream: OutputStream, chunk: string | Buffer, atMs: number): ConsumedOutput;
27
31
  flush(stream: OutputStream, atMs: number): ConsumedOutput;
28
32
  recordSemanticProgress(atMs: number): void;
@@ -1,3 +1,4 @@
1
+ import { targetCrashedPattern, targetDetachedPattern } from "./output-patterns.mjs";
1
2
  import { stripAnsi } from "./vite-detectors.mjs";
2
3
  import { boundPendingLine, splitCompleteLines } from "../process-line-buffer/index.mjs";
3
4
  const maxRequestFailureLines = 20;
@@ -35,6 +36,8 @@ export class StorybookBrowserBootstrapTelemetry {
35
36
  playwrightBrowserLineCount = 0;
36
37
  orchestratorDisconnectCount = 0;
37
38
  requestFailureCount = 0;
39
+ targetCrashCount = 0;
40
+ targetDetachCount = 0;
38
41
  consume(stream, chunk, atMs) {
39
42
  const combined = this.lineBuffers[stream] + String(chunk);
40
43
  const { complete, pending } = splitCompleteLines(combined);
@@ -57,6 +60,8 @@ export class StorybookBrowserBootstrapTelemetry {
57
60
  orchestratorDisconnectCount: this.orchestratorDisconnectCount,
58
61
  requestFailureCount: this.requestFailureCount,
59
62
  requestFailureSamples: [...this.requestFailureSamples],
63
+ targetCrashCount: this.targetCrashCount,
64
+ targetDetachCount: this.targetDetachCount,
60
65
  terminalStage: terminalMilestone
61
66
  ? terminalStageByMilestone[terminalMilestone]
62
67
  : 'no-provider-evidence',
@@ -97,6 +102,10 @@ export class StorybookBrowserBootstrapTelemetry {
97
102
  if (orchestratorDisconnectedPattern.test(plainLine)) {
98
103
  this.orchestratorDisconnectCount += 1;
99
104
  }
105
+ if (targetCrashedPattern.test(plainLine))
106
+ this.targetCrashCount += 1;
107
+ if (targetDetachedPattern.test(plainLine))
108
+ this.targetDetachCount += 1;
100
109
  if (plainLine.includes('[PW Error]')) {
101
110
  this.requestFailureCount += 1;
102
111
  if (this.requestFailureSamples.length < maxRequestFailureSamples) {
@@ -117,8 +126,11 @@ export class StorybookBrowserBootstrapTelemetry {
117
126
  ? '[storybook-browser] suppressed additional request-failure diagnostic lines; see attempt summary count\n'
118
127
  : '';
119
128
  }
120
- if (/\bpw:protocol\b/.test(plainLine))
121
- return '';
129
+ if (/\bpw:protocol\b/.test(plainLine)) {
130
+ return targetCrashedPattern.test(plainLine) || targetDetachedPattern.test(plainLine)
131
+ ? originalLine
132
+ : '';
133
+ }
122
134
  if (/\bpw:browser\b/.test(plainLine)) {
123
135
  this.playwrightBrowserLineCount += 1;
124
136
  if (this.playwrightBrowserLineCount <= maxPlaywrightBrowserLines)
@@ -13,6 +13,7 @@ export type FakeOptions = {
13
13
  exists?: (path: string) => boolean;
14
14
  isProcessGroupAlive?: StorybookBrowserRunnerDeps['isProcessGroupAlive'];
15
15
  now?: () => number;
16
+ sampleProcessGroup?: StorybookBrowserRunnerDeps['sampleProcessGroup'];
16
17
  };
17
18
  /** Injected spawn, clock, timers, filesystem and streams: no process or browser is started. */
18
19
  export declare function makeDeps(children: Child[], options?: FakeOptions): {
@@ -22,6 +23,7 @@ export declare function makeDeps(children: Child[], options?: FakeOptions): {
22
23
  }[];
23
24
  deps: StorybookBrowserRunnerDeps;
24
25
  dirs: string[];
26
+ events: string[];
25
27
  intervals: {
26
28
  callback: () => void;
27
29
  }[];
@@ -26,6 +26,7 @@ export function makeDeps(children, options = {}) {
26
26
  const stderr = [];
27
27
  const stdout = [];
28
28
  const written = [];
29
+ const events = [];
29
30
  const live = new Set();
30
31
  let index = 0;
31
32
  const deps = {
@@ -43,12 +44,18 @@ export function makeDeps(children, options = {}) {
43
44
  if (signal === 'SIGTERM')
44
45
  live.add(pid);
45
46
  killed.push({ pid, signal });
47
+ events.push(`kill:${signal}`);
46
48
  },
47
49
  mkdirSync: (path) => (dirs.push(String(path)), undefined),
48
50
  now: options.now ?? (() => 0),
49
51
  offParentSignal: () => undefined,
50
52
  onParentSignal: () => undefined,
51
53
  rmSync: (path) => void removed.push(String(path)),
54
+ sampleProcessGroup: options.sampleProcessGroup ??
55
+ ((pgid) => {
56
+ events.push(`sample:${pgid}`);
57
+ return ` processes=1 (fake ${pgid})\n`;
58
+ }),
52
59
  setInterval: ((callback) => {
53
60
  const interval = { callback };
54
61
  intervals.push(interval);
@@ -74,7 +81,19 @@ export function makeDeps(children, options = {}) {
74
81
  path: String(path),
75
82
  }),
76
83
  };
77
- return { copied, deps, dirs, intervals, killed, removed, spawnCalls, stderr, stdout, written };
84
+ return {
85
+ copied,
86
+ deps,
87
+ dirs,
88
+ events,
89
+ intervals,
90
+ killed,
91
+ removed,
92
+ spawnCalls,
93
+ stderr,
94
+ stdout,
95
+ written,
96
+ };
78
97
  }
79
98
  export function exitChild(child, code, signal = null) {
80
99
  child.emit('exit', code, signal);
@@ -5,6 +5,8 @@ export type OutputObserverSnapshot = {
5
5
  lastHangProgressAt: number;
6
6
  lastOutputAt: number;
7
7
  lastSemanticProgressAt: number;
8
+ lastSemanticProgressLine: string | null;
9
+ lastSemanticProgressMarkerAt: number | null;
8
10
  newOptimizeDeps: string[];
9
11
  optimizerLastProgressAt: number | null;
10
12
  optimizerReadyAt: number | null;
@@ -6,6 +6,8 @@ export function initialObserverState(startedAt) {
6
6
  lastHangProgressAt: startedAt,
7
7
  lastOutputAt: startedAt,
8
8
  lastSemanticProgressAt: startedAt,
9
+ lastSemanticProgressLine: null,
10
+ lastSemanticProgressMarkerAt: null,
9
11
  optimizerLastProgressAt: null,
10
12
  optimizerReadyAt: null,
11
13
  outputBuffer: '',
@@ -1,6 +1,6 @@
1
1
  import { latestStorybookProgressSequence } from "../vitest-diagnostics/index.mjs";
2
2
  import { StringDecoder } from 'node:string_decoder';
3
- import { hasAddonVitestSetupFile, optimizerProgressPattern, viteServerFetchFailurePattern, viteServerScriptNetworkChangePattern, vitestRunnerMissingMarker, } from "./output-patterns.mjs";
3
+ import { hasAddonVitestSetupFile, optimizerProgressPattern, progressMarkerLine, viteServerFetchFailurePattern, viteServerScriptNetworkChangePattern, vitestRunnerMissingMarker, } from "./output-patterns.mjs";
4
4
  import { initialObserverState, } from "./observer-state.mjs";
5
5
  import { hasStorybookBrowserViteDependencyReady, hasStorybookBrowserViteReady, hasStorybookViteNewDependenciesFound, hasStorybookViteOptimizerReload, parseStorybookViteNewDependencies, stripAnsi, } from "./vite-detectors.mjs";
6
6
  const BUFFER_CHARS = 1000;
@@ -86,8 +86,14 @@ export class OutputObserver {
86
86
  const sequence = latestStorybookProgressSequence(progressText, progressPrefix);
87
87
  if (sequence != null && sequence > this.lastSemanticSequence) {
88
88
  this.lastSemanticSequence = sequence;
89
+ state.lastSemanticProgressLine = progressMarkerLine(progressText, progressPrefix, sequence);
90
+ state.lastSemanticProgressMarkerAt = now;
89
91
  this.recordSemanticProgress(now);
90
92
  }
93
+ else if (sequence != null && sequence === this.lastSemanticSequence) {
94
+ // A marker split across chunks completes later: refresh its text, not the timestamp.
95
+ state.lastSemanticProgressLine = progressMarkerLine(progressText, progressPrefix, sequence);
96
+ }
91
97
  if (storybookOutput && !state.storybookBrowserOutputSeen) {
92
98
  state.storybookBrowserOutputSeen = true;
93
99
  this.recordSemanticProgress(now);
@@ -12,3 +12,7 @@ export type ProjectOutputPatterns = {
12
12
  };
13
13
  export declare function createProjectOutputPatterns(projectName: string): ProjectOutputPatterns;
14
14
  export declare function hasAddonVitestSetupFile(plainText: string, plainOutputBuffer: string): boolean;
15
+ export declare const targetCrashedPattern: RegExp;
16
+ export declare const targetDetachedPattern: RegExp;
17
+ /** The marker line for `sequence`, bounded, for the stall message. */
18
+ export declare function progressMarkerLine(text: string, prefix: string, sequence: number): string | null;
@@ -24,3 +24,14 @@ export function hasAddonVitestSetupFile(plainText, plainOutputBuffer) {
24
24
  haystack.includes(addonVitestSetupFileNameMarker);
25
25
  return hasBoth(plainText) || hasBoth(plainOutputBuffer);
26
26
  }
27
+ // Playwright protocol lines are otherwise dropped; these methods are crash evidence.
28
+ export const targetCrashedPattern = /\bpw:protocol\b.*\b(?:Target|Inspector)\.targetCrashed\b/;
29
+ export const targetDetachedPattern = /\bpw:protocol\b.*\bTarget\.detachedFromTarget\b/;
30
+ /** The marker line for `sequence`, bounded, for the stall message. */
31
+ export function progressMarkerLine(text, prefix, sequence) {
32
+ const start = text.lastIndexOf(`${prefix} seq=${sequence} `);
33
+ if (start === -1)
34
+ return null;
35
+ const end = text.indexOf('\n', start);
36
+ return text.slice(start, end === -1 ? undefined : end).slice(0, 512);
37
+ }
@@ -0,0 +1,31 @@
1
+ import type { StorybookBrowserRunnerDeps } from './types.mts';
2
+ /** Upper bound on the rendered sample, so a huge process tree cannot flood the log. */
3
+ export declare const MAX_SAMPLE_BYTES = 4096;
4
+ type ProcessRow = {
5
+ args: string;
6
+ cpu: string;
7
+ pgid: number;
8
+ pid: number;
9
+ ppid: number;
10
+ rssKb: number;
11
+ stat: string;
12
+ };
13
+ type Exec = (file: string, args: string[], options: {
14
+ encoding: 'utf8';
15
+ maxBuffer: number;
16
+ timeout: number;
17
+ }) => string;
18
+ /**
19
+ * Parses `ps -axww -o pid=,ppid=,pgid=,rss=,pcpu=,stat=,args=` output and keeps the processes of one
20
+ * process group plus their descendants: Playwright launches the browser detached, in its own group.
21
+ */
22
+ export declare function parseProcessGroupRows(psOutput: string, processGroupId: number): ProcessRow[];
23
+ /** Chromium's `--type=<x>`, `browser` for a main Chromium binary, else the executable name. */
24
+ export declare function processRole(args: string): string;
25
+ /** One line per process (largest first): never argv, capped at MAX_SAMPLE_BYTES. */
26
+ export declare function renderProcessGroupSample(psOutput: string, processGroupId: number): string;
27
+ /** Default sampler: portable `ps -axww` (full-width args), filtered by pgid and descendants (never `ps -g`). */
28
+ export declare function samplePsProcessGroup(processGroupId: number, exec?: Exec): string;
29
+ /** Best effort: writes the sample, or one line naming why it failed, and never throws. */
30
+ export declare function writeProcessGroupSample(deps: Pick<StorybookBrowserRunnerDeps, 'sampleProcessGroup' | 'stderr'>, processGroupId: number | undefined): void;
31
+ export {};
@@ -0,0 +1,106 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { basename } from 'node:path';
3
+ /** Upper bound on the rendered sample, so a huge process tree cannot flood the log. */
4
+ export const MAX_SAMPLE_BYTES = 4096;
5
+ const PS_TIMEOUT_MS = 2000;
6
+ const PS_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
7
+ const RESERVED_TRAILER_BYTES = 80;
8
+ const psRowPattern = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+(?:\.\d+)?)\s+(\S+)\s*(.*)$/;
9
+ const chromiumTypePattern = /(?:^|\s)--type=([\w.-]+)/;
10
+ // Only known Chromium process types are echoed; any other --type value is not copied to the log.
11
+ const chromiumTypes = new Set([
12
+ 'broker',
13
+ 'crashpad-handler',
14
+ 'extension',
15
+ 'gpu-process',
16
+ 'ppapi',
17
+ 'ppapi-broker',
18
+ 'renderer',
19
+ 'sandbox-ipc',
20
+ 'service-worker',
21
+ 'utility',
22
+ 'zygote',
23
+ ]);
24
+ const chromiumBinaryPattern = /^(?:chrome|chromium|chromium-browser|headless_shell|chrome-headless-shell|google chrome.*|chromium.*)$/i;
25
+ /**
26
+ * Parses `ps -axww -o pid=,ppid=,pgid=,rss=,pcpu=,stat=,args=` output and keeps the processes of one
27
+ * process group plus their descendants: Playwright launches the browser detached, in its own group.
28
+ */
29
+ export function parseProcessGroupRows(psOutput, processGroupId) {
30
+ const all = [];
31
+ for (const line of psOutput.split('\n')) {
32
+ const match = psRowPattern.exec(line);
33
+ if (!match)
34
+ continue;
35
+ all.push({
36
+ args: match[7],
37
+ cpu: match[5],
38
+ pgid: Number(match[3]),
39
+ pid: Number(match[1]),
40
+ ppid: Number(match[2]),
41
+ rssKb: Number(match[4]),
42
+ stat: match[6],
43
+ });
44
+ }
45
+ const included = new Set(all.filter((row) => row.pgid === processGroupId).map((row) => row.pid));
46
+ for (let grew = true; grew;) {
47
+ grew = false;
48
+ for (const row of all) {
49
+ if (!included.has(row.pid) && included.has(row.ppid)) {
50
+ included.add(row.pid);
51
+ grew = true;
52
+ }
53
+ }
54
+ }
55
+ return all.filter((row) => included.has(row.pid));
56
+ }
57
+ /** Chromium's `--type=<x>`, `browser` for a main Chromium binary, else the executable name. */
58
+ export function processRole(args) {
59
+ const type = chromiumTypePattern.exec(args)?.[1];
60
+ if (type)
61
+ return chromiumTypes.has(type) ? type : 'other';
62
+ const executable = basename(args.split(' --')[0].trim());
63
+ if (chromiumBinaryPattern.test(executable))
64
+ return 'browser';
65
+ return basename(args.trim().split(/\s+/)[0]).replace(/[^\w.()-]/g, '') || 'unknown';
66
+ }
67
+ const megabytes = (kb) => (kb / 1024).toFixed(1);
68
+ /** One line per process (largest first): never argv, capped at MAX_SAMPLE_BYTES. */
69
+ export function renderProcessGroupSample(psOutput, processGroupId) {
70
+ const rows = parseProcessGroupRows(psOutput, processGroupId).sort((a, b) => b.rssKb - a.rssKb);
71
+ const totalKb = rows.reduce((sum, row) => sum + row.rssKb, 0);
72
+ let out = ` processes=${rows.length} totalRssMB=${megabytes(totalKb)}\n`;
73
+ let rendered = 0;
74
+ for (const row of rows) {
75
+ const line = ` pid=${row.pid} rssMB=${megabytes(row.rssKb)} cpu=${row.cpu}% stat=${row.stat} role=${processRole(row.args)}\n`;
76
+ if (Buffer.byteLength(out + line) > MAX_SAMPLE_BYTES - RESERVED_TRAILER_BYTES)
77
+ break;
78
+ out += line;
79
+ rendered += 1;
80
+ }
81
+ if (rendered < rows.length)
82
+ out += ` ... ${rows.length - rendered} more processes omitted\n`;
83
+ return out;
84
+ }
85
+ /** Default sampler: portable `ps -axww` (full-width args), filtered by pgid and descendants (never `ps -g`). */
86
+ export function samplePsProcessGroup(processGroupId, exec = execFileSync) {
87
+ const output = exec('ps', ['-axww', '-o', 'pid=,ppid=,pgid=,rss=,pcpu=,stat=,args='], {
88
+ encoding: 'utf8',
89
+ maxBuffer: PS_MAX_BUFFER_BYTES,
90
+ timeout: PS_TIMEOUT_MS,
91
+ });
92
+ return renderProcessGroupSample(output, processGroupId);
93
+ }
94
+ /** Best effort: writes the sample, or one line naming why it failed, and never throws. */
95
+ export function writeProcessGroupSample(deps, processGroupId) {
96
+ if (processGroupId == null)
97
+ return;
98
+ try {
99
+ const sample = deps.sampleProcessGroup(processGroupId);
100
+ deps.stderr.write(`[storybook-browser] process group ${processGroupId} at stall:\n${sample}`);
101
+ }
102
+ catch (error) {
103
+ const reason = error instanceof Error ? error.message : String(error);
104
+ deps.stderr.write(`[storybook-browser] process group ${processGroupId} sample failed: ${reason.slice(0, 200)}\n`);
105
+ }
106
+ }
@@ -31,6 +31,7 @@ export async function runUpstreamAttempt(input) {
31
31
  stalled: false,
32
32
  };
33
33
  let spawnFailed = false;
34
+ let processGroupId;
34
35
  let completed;
35
36
  const replayQuietOutput = () => {
36
37
  const quiet = quietOutput.drain();
@@ -70,6 +71,7 @@ export async function runUpstreamAttempt(input) {
70
71
  const started = spawnTestCommand(project, env, deps, () => {
71
72
  spawnFailed = true;
72
73
  });
74
+ processGroupId = started.processGroupId;
73
75
  return started;
74
76
  },
75
77
  startupStallMs: DISABLED_STALL_TIMER_MS,
@@ -79,6 +81,7 @@ export async function runUpstreamAttempt(input) {
79
81
  hangMs: options.hangMs,
80
82
  observer,
81
83
  outcome,
84
+ processGroupId: () => processGroupId,
82
85
  stallMs: options.stallMs,
83
86
  }),
84
87
  }, createBrowserSessionDeps(deps));
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { isProcessGroupAlive, waitForProcessGroupExit, } from "../browser-session-runner/index.mjs";
4
+ import { samplePsProcessGroup } from "./process-sample.mjs";
4
5
  /** browser-session-runner uses this delay for its disabled startup and semantic stall timers. */
5
6
  export const DISABLED_STALL_TIMER_MS = 2_147_483_647;
6
7
  export const defaultRunnerDeps = () => ({
@@ -24,6 +25,7 @@ export const defaultRunnerDeps = () => ({
24
25
  offParentSignal: (signal, listener) => process.off(signal, listener),
25
26
  onParentSignal: (signal, listener) => process.on(signal, listener),
26
27
  rmSync,
28
+ sampleProcessGroup: samplePsProcessGroup,
27
29
  setInterval,
28
30
  setTimeout,
29
31
  spawn,
@@ -39,6 +39,8 @@ export type StorybookBrowserRunnerDeps = {
39
39
  offParentSignal: BrowserSessionDeps['offParentSignal'];
40
40
  onParentSignal: BrowserSessionDeps['onParentSignal'];
41
41
  rmSync: typeof rmSync;
42
+ /** Renders the processes of one process group; best effort, may throw. */
43
+ sampleProcessGroup: (processGroupId: number) => string;
42
44
  setInterval: typeof setInterval;
43
45
  setTimeout: typeof setTimeout;
44
46
  spawn: typeof defaultSpawn;
@@ -10,10 +10,12 @@ export type WatchdogOutcome = {
10
10
  };
11
11
  export type StorybookWatchdogOptions = {
12
12
  completionFile: string | undefined;
13
- deps: Pick<StorybookBrowserRunnerDeps, 'clearInterval' | 'cwd' | 'existsSync' | 'now' | 'setInterval' | 'stderr'>;
13
+ deps: Pick<StorybookBrowserRunnerDeps, 'clearInterval' | 'cwd' | 'existsSync' | 'now' | 'sampleProcessGroup' | 'setInterval' | 'stderr'>;
14
14
  hangMs: number;
15
15
  observer: OutputObserver;
16
16
  outcome: WatchdogOutcome;
17
+ /** The spawned test command's process group (its pid), once started. */
18
+ processGroupId: () => number | undefined;
17
19
  stallMs: number;
18
20
  };
19
21
  /** Terminates the attempt on an optimizer stall, a mid-suite stall, or a tester-connection hang. */
@@ -1,4 +1,5 @@
1
1
  import { resolve } from 'node:path';
2
+ import { writeProcessGroupSample } from "./process-sample.mjs";
2
3
  const MAX_WATCHDOG_INTERVAL_MS = 5000;
3
4
  /** Terminates the attempt on an optimizer stall, a mid-suite stall, or a tester-connection hang. */
4
5
  export function createStorybookWatchdog(options) {
@@ -18,12 +19,14 @@ export function createStorybookWatchdog(options) {
18
19
  outcome.stalled = true;
19
20
  deps.stderr.write(`[storybook-browser] Vite optimizer made no startup progress for ${stallMs}ms; terminating attempt\n`);
20
21
  decided = true;
22
+ writeProcessGroupSample(deps, options.processGroupId());
21
23
  controller.terminate();
22
24
  }
23
25
  else if (seen.semanticProgressSeen && now - seen.lastSemanticProgressAt >= hangMs) {
24
26
  outcome.semanticStall = true;
25
- deps.stderr.write(`[storybook-browser] no semantic test progress for ${hangMs}ms; terminating terminal mid-suite stall\n`);
27
+ deps.stderr.write(`[storybook-browser] no semantic test progress for ${hangMs}ms; terminating terminal mid-suite stall (${lastMarkerNote(seen, now)})\n`);
26
28
  decided = true;
29
+ writeProcessGroupSample(deps, options.processGroupId());
27
30
  controller.terminate();
28
31
  }
29
32
  else if (seen.anyOutputSeen &&
@@ -32,6 +35,7 @@ export function createStorybookWatchdog(options) {
32
35
  outcome.hung = true;
33
36
  deps.stderr.write(`[storybook-browser] no test output for ${hangMs}ms after Vite startup — suspected Vitest/Chromium tester-connection hang; last output:\n${seen.outputBuffer}\n`);
34
37
  decided = true;
38
+ writeProcessGroupSample(deps, options.processGroupId());
35
39
  controller.terminate();
36
40
  }
37
41
  };
@@ -53,3 +57,8 @@ export function isSpawnedProcessGroupId(processGroupId) {
53
57
  processGroupId > 1 &&
54
58
  processGroupId <= 2_147_483_647);
55
59
  }
60
+ function lastMarkerNote(seen, now) {
61
+ if (seen.lastSemanticProgressMarkerAt == null)
62
+ return 'no progress marker line seen';
63
+ return `last progress marker ${now - seen.lastSemanticProgressMarkerAt}ms ago: ${seen.lastSemanticProgressLine}`;
64
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.65.1",
3
+ "version": "0.66.1",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {