vouchington-tooling 0.63.0 → 0.65.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 (90) hide show
  1. package/README.md +109 -7
  2. package/dist/cli/commands/cloc.d.mts +7 -0
  3. package/dist/cli/commands/cloc.mjs +47 -0
  4. package/dist/cli/commands/storybook-browser-runner.d.mts +7 -0
  5. package/dist/cli/commands/storybook-browser-runner.mjs +29 -0
  6. package/dist/cli/commands/worktree.d.mts +1 -1
  7. package/dist/cli/commands/worktree.mjs +54 -7
  8. package/dist/cli/index.mjs +4 -0
  9. package/dist/cli/parse-forwarded-commands.d.mts +6 -0
  10. package/dist/cli/parse-forwarded-commands.mjs +4 -0
  11. package/dist/cli/parse.d.mts +6 -0
  12. package/dist/cli/usage-text.d.mts +1 -1
  13. package/dist/cli/usage-text.mjs +19 -1
  14. package/dist/cloc/child-process.d.mts +3 -0
  15. package/dist/cloc/child-process.mjs +14 -0
  16. package/dist/cloc/classify.d.mts +8 -0
  17. package/dist/cloc/classify.mjs +20 -0
  18. package/dist/cloc/config-load.d.mts +7 -0
  19. package/dist/cloc/config-load.mjs +26 -0
  20. package/dist/cloc/config.d.mts +55 -0
  21. package/dist/cloc/config.mjs +109 -0
  22. package/dist/cloc/count.d.mts +9 -0
  23. package/dist/cloc/count.mjs +33 -0
  24. package/dist/cloc/index.d.mts +12 -0
  25. package/dist/cloc/index.mjs +7 -0
  26. package/dist/cloc/layout.test-helpers.d.mts +8 -0
  27. package/dist/cloc/layout.test-helpers.mjs +42 -0
  28. package/dist/cloc/paths.d.mts +7 -0
  29. package/dist/cloc/paths.mjs +29 -0
  30. package/dist/cloc/patterns.d.mts +10 -0
  31. package/dist/cloc/patterns.mjs +25 -0
  32. package/dist/cloc/rows.d.mts +13 -0
  33. package/dist/cloc/rows.mjs +42 -0
  34. package/dist/cloc/scc.d.mts +10 -0
  35. package/dist/cloc/scc.mjs +55 -0
  36. package/dist/cloc/tracked.d.mts +4 -0
  37. package/dist/cloc/tracked.mjs +40 -0
  38. package/dist/command-policy/engine.mjs +9 -2
  39. package/dist/command-policy/hook/post-tool-use.mjs +3 -0
  40. package/dist/git-worktrees/assess.d.mts +15 -0
  41. package/dist/git-worktrees/assess.mjs +25 -6
  42. package/dist/git-worktrees/reclaim.d.mts +15 -2
  43. package/dist/git-worktrees/reclaim.mjs +49 -11
  44. package/dist/git-worktrees/reclaim.test-helpers.mjs +11 -5
  45. package/dist/git-worktrees/run.d.mts +2 -0
  46. package/dist/git-worktrees/run.mjs +4 -1
  47. package/dist/shell-parse/shell-heredoc.mjs +9 -1
  48. package/dist/storybook-browser-runner/args.d.mts +8 -0
  49. package/dist/storybook-browser-runner/args.mjs +52 -0
  50. package/dist/storybook-browser-runner/attempt-result.d.mts +41 -0
  51. package/dist/storybook-browser-runner/attempt-result.mjs +108 -0
  52. package/dist/storybook-browser-runner/bootstrap-telemetry.d.mts +35 -0
  53. package/dist/storybook-browser-runner/bootstrap-telemetry.mjs +138 -0
  54. package/dist/storybook-browser-runner/cache-plan.d.mts +22 -0
  55. package/dist/storybook-browser-runner/cache-plan.mjs +53 -0
  56. package/dist/storybook-browser-runner/diagnostics.d.mts +8 -0
  57. package/dist/storybook-browser-runner/diagnostics.mjs +29 -0
  58. package/dist/storybook-browser-runner/env.d.mts +2 -0
  59. package/dist/storybook-browser-runner/env.mjs +59 -0
  60. package/dist/storybook-browser-runner/fixtures.test-helpers.d.mts +49 -0
  61. package/dist/storybook-browser-runner/fixtures.test-helpers.mjs +95 -0
  62. package/dist/storybook-browser-runner/index.d.mts +15 -0
  63. package/dist/storybook-browser-runner/index.mjs +70 -0
  64. package/dist/storybook-browser-runner/observer-state.d.mts +22 -0
  65. package/dist/storybook-browser-runner/observer-state.mjs +21 -0
  66. package/dist/storybook-browser-runner/options.d.mts +18 -0
  67. package/dist/storybook-browser-runner/options.mjs +49 -0
  68. package/dist/storybook-browser-runner/output-observer.d.mts +37 -0
  69. package/dist/storybook-browser-runner/output-observer.mjs +130 -0
  70. package/dist/storybook-browser-runner/output-patterns.d.mts +14 -0
  71. package/dist/storybook-browser-runner/output-patterns.mjs +26 -0
  72. package/dist/storybook-browser-runner/quiet-output.d.mts +16 -0
  73. package/dist/storybook-browser-runner/quiet-output.mjs +79 -0
  74. package/dist/storybook-browser-runner/run-attempt.d.mts +14 -0
  75. package/dist/storybook-browser-runner/run-attempt.mjs +111 -0
  76. package/dist/storybook-browser-runner/runtime-metadata.d.mts +12 -0
  77. package/dist/storybook-browser-runner/runtime-metadata.mjs +50 -0
  78. package/dist/storybook-browser-runner/session-deps.d.mts +11 -0
  79. package/dist/storybook-browser-runner/session-deps.mjs +70 -0
  80. package/dist/storybook-browser-runner/types.d.mts +49 -0
  81. package/dist/storybook-browser-runner/types.mjs +1 -0
  82. package/dist/storybook-browser-runner/vite-detectors.d.mts +6 -0
  83. package/dist/storybook-browser-runner/vite-detectors.mjs +20 -0
  84. package/dist/storybook-browser-runner/watchdog.d.mts +23 -0
  85. package/dist/storybook-browser-runner/watchdog.mjs +55 -0
  86. package/package.json +12 -2
  87. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
  88. package/skills/blackboard/SKILL.md +6 -3
  89. package/skills/manifest.json +20 -20
  90. package/skills/retrospective-distill/SKILL.md +3 -4
@@ -1,6 +1,6 @@
1
1
  import { existsSync, realpathSync } from 'node:fs';
2
2
  import { sep } from 'node:path';
3
- import { assessLocal, assessPullRequest, readRepository } from "./assess.mjs";
3
+ import { assessLocal, assessPullRequest, assessListedPulls, readPullSnapshot, readRepository, } from "./assess.mjs";
4
4
  import { parseWorktreeList } from "./list.mjs";
5
5
  import { git } from "./run.mjs";
6
6
  /** Assesses (and with `yes` removes) one worktree; undefined means it is not a candidate. */
@@ -15,46 +15,73 @@ function reclaimOne(record, context) {
15
15
  if (nests(context.registered)) {
16
16
  return keep('contains another worktree');
17
17
  }
18
- const worktree = { cwd: path, env: context.runtime.env };
18
+ const worktree = { ...context.runtime, cwd: path };
19
19
  const local = assessLocal(worktree);
20
20
  if ('reason' in local)
21
21
  return keep(local.reason);
22
- const reason = assessPullRequest(branch, local.head, context.repository, context.mainRun);
22
+ const reason = assessListedPulls(context.pulls, branch, local.head, context.repository);
23
23
  if (reason !== undefined)
24
24
  return keep(reason);
25
25
  if (!context.yes)
26
26
  return { path, branch, status: 'would reclaim' };
27
- const again = assessLocal(worktree);
28
27
  const pullAgain = assessPullRequest(branch, local.head, context.repository, context.mainRun);
28
+ const again = assessLocal(worktree);
29
29
  const listed = parseWorktreeList(git(['worktree', 'list', '--porcelain', '-z'], context.runtime));
30
30
  const same = listed.some((entry) => entry.path === path && entry.branch === branch && entry.head === local.head);
31
31
  if (nests(listed.map((entry) => entry.path)))
32
32
  return keep('contains another worktree');
33
33
  if ('reason' in again || again.head !== local.head || pullAgain !== undefined || !same)
34
34
  return keep('changed since check');
35
+ if (context.now() >= context.deadline)
36
+ return keep('scan budget exhausted');
35
37
  if (git(['worktree', 'remove', path], { ...context.mainRun, timeout: 0 }) === undefined) {
36
38
  return keep('git worktree remove refused');
37
39
  }
38
40
  return { path, branch, status: 'reclaimed' };
39
41
  }
40
42
  /** Lists finished worktrees and, with `yes`, removes them with a plain (never forced) `git worktree remove`. */
41
- export function reclaimWorktrees(yes, runtime) {
43
+ export function reclaimWorktrees(yes, runtime, options = {}) {
44
+ const prLimit = options.prLimit ?? 1000;
45
+ const maxWorktrees = options.maxWorktrees ?? 100;
46
+ const timeoutMs = options.timeoutMs ?? 30_000;
47
+ if (!Number.isSafeInteger(prLimit) ||
48
+ prLimit < 1 ||
49
+ prLimit > 10_000 ||
50
+ !Number.isSafeInteger(maxWorktrees) ||
51
+ maxWorktrees < 1 ||
52
+ !Number.isSafeInteger(timeoutMs) ||
53
+ timeoutMs < 1)
54
+ throw new Error('scan limits must be positive integers; PR limit must not exceed 10000');
55
+ const now = options.now ?? Date.now;
56
+ const deadline = now() + timeoutMs;
57
+ runtime = { ...runtime, deadline, now };
42
58
  const listing = git(['worktree', 'list', '--porcelain', '-z'], runtime);
43
59
  const self = git(['rev-parse', '--show-toplevel'], runtime)?.replace(/\n$/, '');
44
60
  const [main, ...others] = parseWorktreeList(listing);
45
61
  if (main === undefined || !self)
46
62
  throw new Error('not inside a git worktree');
47
- const mainRun = { cwd: main.path, env: runtime.env };
63
+ const mainRun = { ...runtime, cwd: main.path };
64
+ const repository = readRepository(mainRun);
48
65
  const context = {
49
66
  yes,
67
+ now,
68
+ deadline,
50
69
  runtime,
51
70
  mainRun,
52
71
  selfReal: realpathSync(self),
53
72
  registered: [main, ...others].map((record) => record.path),
54
- repository: readRepository(mainRun),
73
+ repository,
74
+ pulls: repository === undefined ? undefined : readPullSnapshot(mainRun, prLimit),
55
75
  };
56
76
  const worktrees = [];
57
- for (const record of others) {
77
+ const pending = others
78
+ .filter((record) => options.after === undefined || record.path > options.after)
79
+ .sort((a, b) => Number(a.path > b.path) - Number(a.path < b.path));
80
+ let processed = 0;
81
+ let nextAfter = options.after ?? '';
82
+ for (const record of pending) {
83
+ if (processed >= maxWorktrees || now() >= deadline)
84
+ break;
58
85
  try {
59
86
  const entry = reclaimOne(record, context);
60
87
  if (entry !== undefined)
@@ -64,17 +91,28 @@ export function reclaimWorktrees(yes, runtime) {
64
91
  const reason = `error: ${error.message}`;
65
92
  worktrees.push({ path: record.path, branch: record.branch, status: 'kept', reason });
66
93
  }
94
+ if (now() >= deadline)
95
+ break;
96
+ processed += 1;
97
+ nextAfter = record.path;
67
98
  }
68
- return { dryRun: !yes, worktrees };
99
+ const hasMore = processed < pending.length;
100
+ return hasMore
101
+ ? { dryRun: !yes, worktrees, hasMore: true, nextAfter }
102
+ : { dryRun: !yes, worktrees, hasMore: false };
69
103
  }
70
104
  function escape(text) {
71
105
  return text.replace(/\p{Cc}/gu, (char) => `\\x${char.charCodeAt(0).toString(16).padStart(2, '0')}`);
72
106
  }
73
107
  export function formatReport(report) {
74
- return report.worktrees
108
+ return (report.worktrees
75
109
  .map((entry) => {
76
110
  const status = entry.status === 'kept' ? `kept: ${entry.reason}` : entry.status;
77
111
  return `${escape(entry.path)}: ${escape(status)}\n`;
78
112
  })
79
- .join('');
113
+ .join('') +
114
+ (report.hasMore ? `Scan incomplete; resume with --after ${quote(report.nextAfter)}\n` : ''));
115
+ }
116
+ function quote(value) {
117
+ return "'" + value.replaceAll("'", "'\\''") + "'";
80
118
  }
@@ -18,8 +18,9 @@ if (env.FAKE_GH_GARBAGE) {
18
18
  process.exit(0)
19
19
  }
20
20
  const state = args[args.indexOf('--state') + 1]
21
+ if (env.FAKE_GH_LOG) fs.appendFileSync(env.FAKE_GH_LOG, JSON.stringify(args) + '\\n')
21
22
  // Simulates a change that lands between the first assessment and the re-check.
22
- if (state === 'all') {
23
+ if (state === 'all' && args.includes('--head')) {
23
24
  const { execFileSync } = require('node:child_process')
24
25
  const run = (cwd, ...a) => execFileSync('git', a, { cwd, stdio: 'ignore' })
25
26
  if (env.FAKE_GH_NEST && !fs.existsSync(env.FAKE_GH_DIR + '/nested')) {
@@ -33,15 +34,19 @@ if (state === 'all') {
33
34
  run(env.FAKE_GH_ADVANCE, 'push', 'origin', 'HEAD')
34
35
  }
35
36
  }
36
- const branch = args[args.indexOf('--head') + 1]
37
- const file = env.FAKE_GH_DIR + '/' + branch.replaceAll('/', '_') + '.json'
38
- let pulls = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : []
37
+ const branch = args.includes('--head') ? args[args.indexOf('--head') + 1] : undefined
38
+ const file = env.FAKE_GH_DIR + '/' + (branch || '').replaceAll('/', '_') + '.json'
39
+ let pulls = branch === undefined
40
+ ? fs.readdirSync(env.FAKE_GH_DIR).filter(name => name.endsWith('.json')).flatMap(name => JSON.parse(fs.readFileSync(env.FAKE_GH_DIR + '/' + name, 'utf8')))
41
+ : fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : []
39
42
  if (state === 'open') pulls = pulls.filter((pr) => pr.state === 'OPEN')
40
43
  const pad = Number(env['FAKE_GH_PAD_' + state.toUpperCase()] || 0)
41
44
  for (let i = 0; i < pad; i += 1) pulls.push({ state: 'CLOSED' })
42
45
  console.log(JSON.stringify(pulls))
43
46
  // Reopen every PR after the first full answer, as if it changed before the re-check.
44
47
  if (state === 'all' && env.FAKE_GH_REOPEN && !fs.existsSync(file + '.reopened')) {
48
+ const target = branch === undefined ? fs.readdirSync(env.FAKE_GH_DIR).find(name => name.endsWith('.json')) : undefined
49
+ if (target) fs.writeFileSync(env.FAKE_GH_DIR + '/' + target, JSON.stringify(pulls.map(pr => ({ ...pr, state: 'OPEN' }))))
45
50
  fs.writeFileSync(file, JSON.stringify(pulls.map((pr) => ({ ...pr, state: 'OPEN' }))))
46
51
  fs.writeFileSync(file + '.reopened', '')
47
52
  }
@@ -56,7 +61,7 @@ export function createFixture() {
56
61
  writeFileSync(join(bin, 'gh'), FAKE_GH);
57
62
  chmodSync(join(bin, 'gh'), 0o755);
58
63
  // A git wrapper that fails any invocation containing the words in FAKE_GIT_FAIL, to reach error paths.
59
- writeFileSync(join(bin, 'git'), `#!/bin/sh\ncase " $* " in *" $FAKE_GIT_FAIL "*) [ -n "$FAKE_GIT_FAIL" ] && exit 1;; esac\nexec '${realGit}' "$@"\n`);
64
+ writeFileSync(join(bin, 'git'), `#!/bin/sh\n[ -z "$FAKE_GIT_LOG" ] || printf '%s\\n' "$*" >> "$FAKE_GIT_LOG"\ncase " $* " in *" $FAKE_GIT_FAIL "*) [ -n "$FAKE_GIT_FAIL" ] && exit 1;; esac\nexec '${realGit}' "$@"\n`);
60
65
  chmodSync(join(bin, 'git'), 0o755);
61
66
  const env = {
62
67
  ...process.env,
@@ -100,6 +105,7 @@ export function createFixture() {
100
105
  setPrs: (branch, prs) => {
101
106
  const tip = git(main, 'rev-parse', `refs/heads/${branch}`).trim();
102
107
  const filled = prs.map((pr) => ({
108
+ headRefName: branch,
103
109
  headRefOid: tip,
104
110
  isCrossRepository: false,
105
111
  headRepository: { name: 'Widgets' },
@@ -3,6 +3,8 @@ export interface RunOptions {
3
3
  readonly env: NodeJS.ProcessEnv;
4
4
  /** Milliseconds before a read-only call is killed; 0 for none (worktree removal). */
5
5
  readonly timeout?: number;
6
+ readonly deadline?: number;
7
+ readonly now?: () => number;
6
8
  }
7
9
  /** Runs a command without a shell; returns stdout, or undefined when it fails to start or exits non-zero. */
8
10
  export declare function run(file: string, args: readonly string[], options: RunOptions): string | undefined;
@@ -1,6 +1,9 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  /** Runs a command without a shell; returns stdout, or undefined when it fails to start or exits non-zero. */
3
3
  export function run(file, args, options) {
4
+ const remaining = options.deadline === undefined ? Infinity : options.deadline - (options.now ?? Date.now)();
5
+ if (remaining <= 0 && options.timeout !== 0)
6
+ return undefined;
4
7
  try {
5
8
  return execFileSync(file, args, {
6
9
  cwd: options.cwd,
@@ -8,7 +11,7 @@ export function run(file, args, options) {
8
11
  encoding: 'utf8',
9
12
  maxBuffer: 64 * 1024 * 1024,
10
13
  stdio: ['ignore', 'pipe', 'ignore'],
11
- timeout: options.timeout ?? 120_000,
14
+ timeout: options.timeout === 0 ? 0 : Math.max(1, Math.min(options.timeout ?? 120_000, remaining)),
12
15
  });
13
16
  }
14
17
  catch {
@@ -20,7 +20,7 @@ export function stripNonShellHeredocBodies(command) {
20
20
  }
21
21
  // The hook does not pair each operator with its body, so a line with a shell-read heredoc
22
22
  // inspects every body on it.
23
- const isShellScriptHeredoc = lineFeedsShellHeredoc(line);
23
+ const isShellScriptHeredoc = lineFeedsShellHeredoc(line) || lineFeedsShellHeredoc(logicalLine(lines, index));
24
24
  for (const spec of specs) {
25
25
  const bodyLines = [];
26
26
  index += 1;
@@ -79,6 +79,14 @@ function heredocBodySubstitutions(body) {
79
79
  }
80
80
  return substitutions;
81
81
  }
82
+ // A line ending in an odd run of backslashes continues onto the next, so the command that owns a
83
+ // heredoc operator may start on earlier lines (`bash \\\n-s <<'EOF'`).
84
+ function logicalLine(lines, index) {
85
+ let start = index;
86
+ while (start > 0 && /(?:^|[^\\])(?:\\\\)*\\$/.test(lines[start - 1]))
87
+ start -= 1;
88
+ return lines.slice(start, index + 1).join('\n');
89
+ }
82
90
  function heredocLineDelimiter(line, spec) {
83
91
  return spec.stripLeadingTabs ? line.replace(/^\t+/, '') : line;
84
92
  }
@@ -0,0 +1,8 @@
1
+ import type { StorybookBrowserProject } from './types.mts';
2
+ export type ParsedStorybookBrowserRunnerArgs = StorybookBrowserProject;
3
+ /**
4
+ * Parses the `storybook-browser-runner` flags. Arguments after `--` replace the default argv
5
+ * (`exec vitest run --project <name>`), so they may begin with a dash. Flag values that begin
6
+ * with a dash use the `--flag=value` form. Throws an Error naming the first problem.
7
+ */
8
+ export declare function parseStorybookBrowserRunnerArgs(argv: readonly string[]): ParsedStorybookBrowserRunnerArgs;
@@ -0,0 +1,52 @@
1
+ import { parseArgs } from 'node:util';
2
+ function required(raw, flag) {
3
+ if (raw.length === 0 || raw.startsWith('-'))
4
+ throw new Error(`${flag} requires a value`);
5
+ return raw;
6
+ }
7
+ /**
8
+ * Parses the `storybook-browser-runner` flags. Arguments after `--` replace the default argv
9
+ * (`exec vitest run --project <name>`), so they may begin with a dash. Flag values that begin
10
+ * with a dash use the `--flag=value` form. Throws an Error naming the first problem.
11
+ */
12
+ export function parseStorybookBrowserRunnerArgs(argv) {
13
+ const { positionals, values } = parseArgs({
14
+ allowPositionals: true,
15
+ args: [...argv],
16
+ options: {
17
+ command: { type: 'string' },
18
+ 'completion-file': { type: 'string' },
19
+ 'coverage-arg': { type: 'string', multiple: true },
20
+ 'env-prefix': { type: 'string' },
21
+ 'optimize-deps-config': { type: 'string' },
22
+ 'progress-prefix': { type: 'string' },
23
+ project: { type: 'string' },
24
+ 'result-file': { type: 'string', multiple: true },
25
+ },
26
+ strict: true,
27
+ });
28
+ if (values.project === undefined)
29
+ throw new Error('--project <name> is required');
30
+ const optional = (flag) => {
31
+ const raw = values[flag];
32
+ return raw === undefined ? undefined : required(raw, `--${flag}`);
33
+ };
34
+ const project = { projectName: required(values.project, '--project') };
35
+ const assign = (key, value) => {
36
+ if (value !== undefined)
37
+ project[key] = value;
38
+ };
39
+ assign('command', optional('command'));
40
+ assign('completionFile', optional('completion-file'));
41
+ assign('envPrefix', optional('env-prefix'));
42
+ assign('optimizeDepsConfigPath', optional('optimize-deps-config'));
43
+ assign('progressPrefix', optional('progress-prefix'));
44
+ if (values['coverage-arg'])
45
+ project.coverageArgs = values['coverage-arg'];
46
+ if (values['result-file']) {
47
+ project.resultFiles = values['result-file'].map((file) => required(file, '--result-file'));
48
+ }
49
+ if (positionals.length > 0)
50
+ project.args = positionals;
51
+ return project;
52
+ }
@@ -0,0 +1,41 @@
1
+ import type { BrowserSessionResult } from '../browser-session-runner/index.mts';
2
+ import type { StorybookBrowserBootstrapSnapshot } from './bootstrap-telemetry.mts';
3
+ import type { OutputObserverSnapshot } from './observer-state.mts';
4
+ import type { WatchdogOutcome } from './watchdog.mts';
5
+ export type AttemptResult = {
6
+ bootstrap: StorybookBrowserBootstrapSnapshot;
7
+ budgetExpired: boolean;
8
+ code: number;
9
+ durationMs: number;
10
+ exitCode: number | null;
11
+ firstTestOutputAtMs: number | null;
12
+ hung: boolean;
13
+ isStall: boolean;
14
+ lastOutputAgeMs: number;
15
+ newOptimizeDeps: string[];
16
+ optimizerReadyAtMs: number | null;
17
+ optimizerReloadFromNewDeps: boolean;
18
+ resultFileDetectedAtMs: number | null;
19
+ retryable: boolean;
20
+ runnerMissing: boolean;
21
+ semanticProgress: boolean;
22
+ semanticStall: boolean;
23
+ signal: NodeJS.Signals | null;
24
+ viteFetchFailure: boolean;
25
+ viteReady: boolean;
26
+ };
27
+ export type AttemptFacts = {
28
+ bootstrap: StorybookBrowserBootstrapSnapshot;
29
+ finishedAt: number;
30
+ observed: OutputObserverSnapshot;
31
+ outcome: WatchdogOutcome;
32
+ spawnFailed: boolean;
33
+ startedAt: number;
34
+ };
35
+ /** Maps the session exit plus the observed output to the attempt result and its retry rule. */
36
+ export declare function buildAttemptResult(session: Pick<BrowserSessionResult, 'exit' | 'reason'>, facts: AttemptFacts): AttemptResult;
37
+ /** The command could not be started: failed, never retryable. */
38
+ export declare function failedSpawnAttempt(bootstrap: StorybookBrowserBootstrapSnapshot, startedAt: number, lastOutputAt: number, now: number): AttemptResult;
39
+ /** The session budget ran out before the session produced a result. */
40
+ export declare function expiredAttempt(bootstrap: StorybookBrowserBootstrapSnapshot, startedAt: number, now: number): AttemptResult;
41
+ export declare function formatAttemptResult(attempt: number, result: AttemptResult): string;
@@ -0,0 +1,108 @@
1
+ const relativeTo = (startedAt, at) => (at == null ? null : at - startedAt);
2
+ /** Maps the session exit plus the observed output to the attempt result and its retry rule. */
3
+ export function buildAttemptResult(session, facts) {
4
+ const { bootstrap, finishedAt, observed, outcome, spawnFailed, startedAt } = facts;
5
+ const optimizerReloadFromNewDeps = observed.sawNewOptimizeDeps && observed.sawOptimizerReload;
6
+ const runnerMissing = observed.sawAddonVitestSetupFile &&
7
+ observed.sawRunnerMissingMessage &&
8
+ !observed.storybookBrowserOutputSeen;
9
+ const connectionTimeout = observed.browserSessionConnectionTimedOut && !observed.semanticProgressSeen;
10
+ const budgetExpired = session.reason === 'deadline';
11
+ const killedByWatchdog = outcome.stalled ||
12
+ outcome.hung ||
13
+ outcome.semanticStall ||
14
+ budgetExpired ||
15
+ session.reason === 'parent-signal';
16
+ return {
17
+ bootstrap,
18
+ budgetExpired,
19
+ code: spawnFailed || killedByWatchdog ? 1 : (session.exit.code ?? 1),
20
+ durationMs: finishedAt - startedAt,
21
+ exitCode: spawnFailed ? 1 : session.exit.code,
22
+ firstTestOutputAtMs: relativeTo(startedAt, observed.firstTestOutputAt),
23
+ hung: outcome.hung || connectionTimeout,
24
+ isStall: outcome.stalled,
25
+ lastOutputAgeMs: finishedAt - observed.lastOutputAt,
26
+ newOptimizeDeps: observed.newOptimizeDeps,
27
+ optimizerReadyAtMs: relativeTo(startedAt, observed.optimizerReadyAt),
28
+ optimizerReloadFromNewDeps,
29
+ resultFileDetectedAtMs: relativeTo(startedAt, outcome.resultFileDetectedAt),
30
+ retryable: !spawnFailed &&
31
+ !budgetExpired &&
32
+ session.reason !== 'parent-signal' &&
33
+ !outcome.semanticStall &&
34
+ !optimizerReloadFromNewDeps &&
35
+ (observed.retryableViteFailure ||
36
+ runnerMissing ||
37
+ (!observed.semanticProgressSeen && (outcome.stalled || outcome.hung || connectionTimeout))),
38
+ runnerMissing,
39
+ semanticProgress: observed.semanticProgressSeen,
40
+ semanticStall: outcome.semanticStall,
41
+ signal: session.exit.signal,
42
+ viteFetchFailure: observed.retryableViteFailure,
43
+ viteReady: observed.startupComplete,
44
+ };
45
+ }
46
+ const baseResult = (bootstrap) => ({
47
+ bootstrap,
48
+ budgetExpired: false,
49
+ code: 1,
50
+ durationMs: 0,
51
+ exitCode: null,
52
+ firstTestOutputAtMs: null,
53
+ hung: false,
54
+ isStall: false,
55
+ lastOutputAgeMs: 0,
56
+ newOptimizeDeps: [],
57
+ optimizerReadyAtMs: null,
58
+ optimizerReloadFromNewDeps: false,
59
+ resultFileDetectedAtMs: null,
60
+ retryable: false,
61
+ runnerMissing: false,
62
+ semanticProgress: false,
63
+ semanticStall: false,
64
+ signal: null,
65
+ viteFetchFailure: false,
66
+ viteReady: false,
67
+ });
68
+ /** The command could not be started: failed, never retryable. */
69
+ export function failedSpawnAttempt(bootstrap, startedAt, lastOutputAt, now) {
70
+ return {
71
+ ...baseResult(bootstrap),
72
+ durationMs: now - startedAt,
73
+ exitCode: 1,
74
+ lastOutputAgeMs: now - lastOutputAt,
75
+ };
76
+ }
77
+ /** The session budget ran out before the session produced a result. */
78
+ export function expiredAttempt(bootstrap, startedAt, now) {
79
+ return { ...baseResult(bootstrap), budgetExpired: true, durationMs: now - startedAt };
80
+ }
81
+ export function formatAttemptResult(attempt, result) {
82
+ return `${[
83
+ `[storybook-browser] attempt=${attempt} finished in ${result.durationMs}ms`,
84
+ `code=${result.exitCode ?? 'null'}`,
85
+ `signal=${result.signal ?? 'null'}`,
86
+ `resolvedCode=${result.code}`,
87
+ `retryable=${String(result.retryable)}`,
88
+ `stall=${String(result.isStall)}`,
89
+ `hang=${String(result.hung)}`,
90
+ `runnerMissing=${String(result.runnerMissing)}`,
91
+ `budgetExpired=${String(result.budgetExpired)}`,
92
+ `semanticProgress=${String(result.semanticProgress)}`,
93
+ `semanticStall=${String(result.semanticStall)}`,
94
+ `viteReady=${String(result.viteReady)}`,
95
+ `optimizerReadyAtMs=${result.optimizerReadyAtMs ?? 'none'}`,
96
+ `firstTestOutputAtMs=${result.firstTestOutputAtMs ?? 'none'}`,
97
+ `lastOutputAgeMs=${result.lastOutputAgeMs}`,
98
+ `resultFileAtMs=${result.resultFileDetectedAtMs ?? 'none'}`,
99
+ `bootstrapStage=${result.bootstrap.terminalStage}`,
100
+ `bootstrapTimeline=${JSON.stringify(result.bootstrap.timeline)}`,
101
+ `orchestratorDisconnectCount=${result.bootstrap.orchestratorDisconnectCount}`,
102
+ `requestFailureCount=${result.bootstrap.requestFailureCount}`,
103
+ `requestFailureSamples=${JSON.stringify(result.bootstrap.requestFailureSamples)}`,
104
+ `viteFetchFailure=${String(result.viteFetchFailure)}`,
105
+ `optimizerReloadFromNewDeps=${String(result.optimizerReloadFromNewDeps)}`,
106
+ `newOptimizeDeps=${result.newOptimizeDeps.join(',') || 'none'}`,
107
+ ].join('; ')}\n`;
108
+ }
@@ -0,0 +1,35 @@
1
+ type OutputStream = 'stderr' | 'stdout';
2
+ export type StorybookBrowserBootstrapMilestone = 'context-ready' | 'navigation-requested' | 'orchestrator-connected' | 'page-ready' | 'provider-started' | 'semantic-progress';
3
+ type StorybookBrowserBootstrapTerminalStage = 'context-to-page' | 'handshake-after-websocket' | 'launch-or-context' | 'navigation-to-websocket' | 'no-provider-evidence' | 'page-to-navigation' | 'semantic-progress';
4
+ export interface StorybookBrowserBootstrapSnapshot {
5
+ orchestratorDisconnectCount: number;
6
+ requestFailureCount: number;
7
+ requestFailureSamples: string[];
8
+ terminalStage: StorybookBrowserBootstrapTerminalStage;
9
+ timeline: Array<{
10
+ atMs: number;
11
+ milestone: StorybookBrowserBootstrapMilestone;
12
+ }>;
13
+ }
14
+ interface ConsumedOutput {
15
+ hasNonDiagnosticOutput: boolean;
16
+ output: string;
17
+ }
18
+ export declare class StorybookBrowserBootstrapTelemetry {
19
+ private readonly lineBuffers;
20
+ private readonly milestones;
21
+ private readonly requestFailureSamples;
22
+ private readonly timeline;
23
+ private playwrightBrowserLineCount;
24
+ private orchestratorDisconnectCount;
25
+ private requestFailureCount;
26
+ consume(stream: OutputStream, chunk: string | Buffer, atMs: number): ConsumedOutput;
27
+ flush(stream: OutputStream, atMs: number): ConsumedOutput;
28
+ recordSemanticProgress(atMs: number): void;
29
+ snapshot(): StorybookBrowserBootstrapSnapshot;
30
+ private consumeLines;
31
+ private observeLine;
32
+ private filterLine;
33
+ private recordMilestone;
34
+ }
35
+ export {};
@@ -0,0 +1,138 @@
1
+ import { stripAnsi } from "./vite-detectors.mjs";
2
+ import { boundPendingLine, splitCompleteLines } from "../process-line-buffer/index.mjs";
3
+ const maxRequestFailureLines = 20;
4
+ const maxRequestFailureSamples = 5;
5
+ const maxPlaywrightBrowserLines = 200;
6
+ const maxSampleLength = 400;
7
+ const diagnosticLinePattern = /\bvitest:browser:(?:api|playwright)\b|\bpw:(?:browser|protocol)\b|\[PW Error\]/;
8
+ const providerStartedPattern = /\bvitest:browser:playwright\b.*(?:creating the browser page|initializing the browser)/;
9
+ const contextReadyPattern = /\bvitest:browser:playwright\b.*the context is ready/;
10
+ const pageReadyPattern = /\bvitest:browser:playwright\b.*the page is ready/;
11
+ const navigationRequestedPattern = /\bvitest:browser:playwright\b.*browser page is created, opening /;
12
+ const orchestratorConnectedPattern = /\bvitest:browser:api\b.*Browser API connected to orchestrator/;
13
+ const orchestratorDisconnectedPattern = /\bvitest:browser:api\b.*Browser API disconnected from orchestrator/;
14
+ const terminalStageByMilestone = {
15
+ 'provider-started': 'launch-or-context',
16
+ 'context-ready': 'context-to-page',
17
+ 'page-ready': 'page-to-navigation',
18
+ 'navigation-requested': 'navigation-to-websocket',
19
+ 'orchestrator-connected': 'handshake-after-websocket',
20
+ 'semantic-progress': 'semantic-progress',
21
+ };
22
+ const milestoneRank = {
23
+ 'provider-started': 1,
24
+ 'context-ready': 2,
25
+ 'page-ready': 3,
26
+ 'navigation-requested': 4,
27
+ 'orchestrator-connected': 5,
28
+ 'semantic-progress': 6,
29
+ };
30
+ export class StorybookBrowserBootstrapTelemetry {
31
+ lineBuffers = { stderr: '', stdout: '' };
32
+ milestones = new Set();
33
+ requestFailureSamples = [];
34
+ timeline = [];
35
+ playwrightBrowserLineCount = 0;
36
+ orchestratorDisconnectCount = 0;
37
+ requestFailureCount = 0;
38
+ consume(stream, chunk, atMs) {
39
+ const combined = this.lineBuffers[stream] + String(chunk);
40
+ const { complete, pending } = splitCompleteLines(combined);
41
+ this.lineBuffers[stream] = boundPendingLine(pending);
42
+ return this.consumeLines(complete, atMs);
43
+ }
44
+ flush(stream, atMs) {
45
+ const pending = this.lineBuffers[stream];
46
+ this.lineBuffers[stream] = '';
47
+ return pending
48
+ ? this.consumeLines([pending], atMs)
49
+ : { hasNonDiagnosticOutput: false, output: '' };
50
+ }
51
+ recordSemanticProgress(atMs) {
52
+ this.recordMilestone('semantic-progress', atMs);
53
+ }
54
+ snapshot() {
55
+ const terminalMilestone = this.timeline.reduce((furthest, { milestone }) => !furthest || milestoneRank[milestone] > milestoneRank[furthest] ? milestone : furthest, undefined);
56
+ return {
57
+ orchestratorDisconnectCount: this.orchestratorDisconnectCount,
58
+ requestFailureCount: this.requestFailureCount,
59
+ requestFailureSamples: [...this.requestFailureSamples],
60
+ terminalStage: terminalMilestone
61
+ ? terminalStageByMilestone[terminalMilestone]
62
+ : 'no-provider-evidence',
63
+ timeline: [...this.timeline],
64
+ };
65
+ }
66
+ consumeLines(lines, atMs) {
67
+ let hasNonDiagnosticOutput = false;
68
+ let output = '';
69
+ for (const line of lines) {
70
+ const plainLine = stripAnsi(line);
71
+ const trimmed = plainLine.trim();
72
+ if (!trimmed) {
73
+ output += line;
74
+ continue;
75
+ }
76
+ this.observeLine(plainLine, atMs);
77
+ const diagnostic = diagnosticLinePattern.test(plainLine);
78
+ if (!diagnostic)
79
+ hasNonDiagnosticOutput = true;
80
+ output += this.filterLine(line, plainLine);
81
+ }
82
+ return { hasNonDiagnosticOutput, output };
83
+ }
84
+ observeLine(plainLine, atMs) {
85
+ if (providerStartedPattern.test(plainLine))
86
+ this.recordMilestone('provider-started', atMs);
87
+ if (contextReadyPattern.test(plainLine))
88
+ this.recordMilestone('context-ready', atMs);
89
+ if (pageReadyPattern.test(plainLine))
90
+ this.recordMilestone('page-ready', atMs);
91
+ if (navigationRequestedPattern.test(plainLine)) {
92
+ this.recordMilestone('navigation-requested', atMs);
93
+ }
94
+ if (orchestratorConnectedPattern.test(plainLine)) {
95
+ this.recordMilestone('orchestrator-connected', atMs);
96
+ }
97
+ if (orchestratorDisconnectedPattern.test(plainLine)) {
98
+ this.orchestratorDisconnectCount += 1;
99
+ }
100
+ if (plainLine.includes('[PW Error]')) {
101
+ this.requestFailureCount += 1;
102
+ if (this.requestFailureSamples.length < maxRequestFailureSamples) {
103
+ this.requestFailureSamples.push(plainLine.trim().slice(0, maxSampleLength));
104
+ }
105
+ }
106
+ }
107
+ filterLine(originalLine, plainLine) {
108
+ if (plainLine.includes('vitest:browser:api') &&
109
+ !orchestratorConnectedPattern.test(plainLine) &&
110
+ !orchestratorDisconnectedPattern.test(plainLine)) {
111
+ return '';
112
+ }
113
+ if (plainLine.includes('[PW Error]')) {
114
+ if (this.requestFailureCount <= maxRequestFailureLines)
115
+ return originalLine;
116
+ return this.requestFailureCount === maxRequestFailureLines + 1
117
+ ? '[storybook-browser] suppressed additional request-failure diagnostic lines; see attempt summary count\n'
118
+ : '';
119
+ }
120
+ if (/\bpw:protocol\b/.test(plainLine))
121
+ return '';
122
+ if (/\bpw:browser\b/.test(plainLine)) {
123
+ this.playwrightBrowserLineCount += 1;
124
+ if (this.playwrightBrowserLineCount <= maxPlaywrightBrowserLines)
125
+ return originalLine;
126
+ return this.playwrightBrowserLineCount === maxPlaywrightBrowserLines + 1
127
+ ? '[storybook-browser] suppressed additional pw:browser lines after 200 entries\n'
128
+ : '';
129
+ }
130
+ return originalLine;
131
+ }
132
+ recordMilestone(milestone, atMs) {
133
+ if (this.milestones.has(milestone))
134
+ return;
135
+ this.milestones.add(milestone);
136
+ this.timeline.push({ atMs, milestone });
137
+ }
138
+ }
@@ -0,0 +1,22 @@
1
+ import type { AttemptResult } from './attempt-result.mts';
2
+ import type { ResolvedStorybookBrowserProject, StorybookBrowserRunnerDeps } from './types.mts';
3
+ export type CachePlan = {
4
+ dir: string;
5
+ persistentDir: string | undefined;
6
+ role: 'attempt' | 'persistent';
7
+ };
8
+ type CacheDeps = Pick<StorybookBrowserRunnerDeps, 'cpSync' | 'cwd' | 'existsSync' | 'mkdirSync' | 'rmSync' | 'stderr'>;
9
+ export declare function storybookBrowserPersistentCacheDir(project: ResolvedStorybookBrowserProject, env: NodeJS.ProcessEnv, cwd: string): string | undefined;
10
+ export declare function initialCachePlan(attemptEnv: NodeJS.ProcessEnv, persistentCacheDir: string | undefined): CachePlan;
11
+ export declare function nextCachePlan(input: {
12
+ attempt: number;
13
+ attemptEnv: NodeJS.ProcessEnv;
14
+ cachePlan: CachePlan;
15
+ deps: CacheDeps;
16
+ persistentCacheDir: string | undefined;
17
+ result: AttemptResult;
18
+ }): CachePlan;
19
+ export declare function clearPersistentCache(cacheDir: string, deps: CacheDeps): void;
20
+ /** Copies a successful attempt's optimizer cache over the persistent cache. */
21
+ export declare function promoteAttemptCache(cachePlan: CachePlan, deps: CacheDeps, result: AttemptResult): void;
22
+ export {};