@kurvball/rehearse 1.2.1 → 1.4.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 (46) hide show
  1. package/README.md +9 -3
  2. package/dist/commands/clean.js +2 -2
  3. package/dist/commands/command.d.ts +3 -1
  4. package/dist/commands/command.js +18 -1
  5. package/dist/commands/compare.js +9 -3
  6. package/dist/commands/run.js +5 -3
  7. package/dist/commands/stage.js +9 -4
  8. package/dist/compare/announce.d.ts +1 -0
  9. package/dist/compare/changesets.d.ts +8 -0
  10. package/dist/compare/changesets.js +91 -0
  11. package/dist/compare/compare.d.ts +2 -0
  12. package/dist/compare/compare.js +44 -12
  13. package/dist/compare/index.d.ts +2 -0
  14. package/dist/compare/index.js +2 -0
  15. package/dist/drive/daemon.js +2 -1
  16. package/dist/git/checkout.js +8 -2
  17. package/dist/git/seed.d.ts +3 -0
  18. package/dist/git/seed.js +115 -0
  19. package/dist/kinds/flow/kind.js +27 -15
  20. package/dist/kinds/index.d.ts +1 -1
  21. package/dist/kinds/kind.d.ts +6 -0
  22. package/dist/kinds/piece/conventions.d.ts +1 -1
  23. package/dist/kinds/piece/conventions.js +1 -2
  24. package/dist/kinds/piece/kind.js +2 -0
  25. package/dist/kinds/piece/server.d.ts +1 -0
  26. package/dist/kinds/piece/server.js +1 -1
  27. package/dist/manifest/load.js +1 -0
  28. package/dist/manifest/types.d.ts +2 -0
  29. package/dist/run/index.d.ts +2 -1
  30. package/dist/run/index.js +2 -1
  31. package/dist/run/parallel.d.ts +28 -0
  32. package/dist/run/parallel.js +140 -0
  33. package/dist/run/session.d.ts +3 -0
  34. package/dist/run/session.js +312 -171
  35. package/dist/services/index.d.ts +1 -1
  36. package/dist/services/index.js +1 -1
  37. package/dist/services/service.d.ts +2 -1
  38. package/dist/services/service.js +41 -12
  39. package/dist/stage/api.d.ts +3 -0
  40. package/dist/stage/api.js +3 -2
  41. package/dist/stage/server.d.ts +3 -0
  42. package/dist/stage/server.js +5 -1
  43. package/llms.txt +3 -3
  44. package/package.json +1 -1
  45. package/schema/v1/manifest.schema.json +4 -0
  46. package/skill/rehearse/SKILL.md +4 -0
package/README.md CHANGED
@@ -1,4 +1,9 @@
1
- # Rehearse
1
+ <h1>
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset=".github/brand/readme-dark.png">
4
+ <img alt="Rehearse" src=".github/brand/readme-light.png" width="640">
5
+ </picture>
6
+ </h1>
2
7
 
3
8
  Rehearse a change before it ships.
4
9
 
@@ -80,7 +85,8 @@ Rehearse runs on [Kurvball](https://www.kurvball.ca) from a scratch clone, with
80
85
 
81
86
  Rehearse 1.0 is built on [the decisions in its design](docs/plans/v1.md). [CHANGELOG.md](CHANGELOG.md) says what each version
82
87
  changed, and [RELEASING.md](RELEASING.md) how a change gets its changeset and how a release and a hotfix go. Each
83
- release is a tag and a [GitHub Release](https://github.com/kurvball/rehearse/releases) with the package's tarball.
88
+ release is a tag, a version on [npm](https://www.npmjs.com/package/@kurvball/rehearse) published with provenance, and a
89
+ [GitHub Release](https://github.com/kurvball/rehearse/releases) with the package's tarball.
84
90
 
85
91
  It runs on its own. Other tools read it only through its JSON commands, and [Ashlar](https://github.com/kurvball/ashlar), when present, lends it an import
86
92
  graph. Neither is required.
@@ -88,7 +94,7 @@ graph. Neither is required.
88
94
  ## Name
89
95
 
90
96
  The package is `@kurvball/rehearse`; its command is `rehearse`. The bare name `rehearse` is taken on npm and on PyPI by
91
- unrelated projects. It isn't on npm yet: each release is a tarball on its GitHub Release.
97
+ unrelated projects. Install it with `pnpm add -D @kurvball/rehearse`.
92
98
 
93
99
  ## Licence
94
100
 
@@ -6,7 +6,7 @@ import { stateDir } from '../services/index.js';
6
6
  const DAY = 24 * 60 * 60 * 1000;
7
7
  export const clean = {
8
8
  name: 'clean',
9
- summary: 'Removes base checkouts beyond the budget, and runs and comparisons older than a week. Keeps the cache.',
9
+ summary: "Removes base checkouts beyond the budget, and runs, comparisons and pieces' Vite caches older than a week. Keeps the cache.",
10
10
  usage: 'rehearse clean [--all] [--json]\n\n--all also removes every base checkout and the baseline cache.',
11
11
  spec: { valued: [], bare: ['all'] },
12
12
  async run(args, ctx) {
@@ -16,7 +16,7 @@ export const clean = {
16
16
  const removed = all
17
17
  ? evict({ ...m, budget: { ...m.budget, checkouts: 0 } }, repo)
18
18
  : evict(m, repo);
19
- for (const folder of ['runs', 'compare', ...(all ? ['cache'] : [])]) {
19
+ for (const folder of ['runs', 'compare', 'pieces', ...(all ? ['cache'] : [])]) {
20
20
  const dir = path.join(stateDir(m.dir), folder);
21
21
  if (!existsSync(dir))
22
22
  continue;
@@ -1,4 +1,4 @@
1
- import type { Args, ArgSpec } from '../args.ts';
1
+ import { type Args, type ArgSpec } from '../args.ts';
2
2
  import { type Manifest } from '../manifest/index.ts';
3
3
  export interface Context {
4
4
  cwd: string;
@@ -27,3 +27,5 @@ export declare const said: (json: unknown, text: string, code?: number) => Said;
27
27
  export declare function manifestOf(ctx: Context): Manifest;
28
28
  export declare function checkoutOf(m: Manifest, given: string | null, cwd: string): string;
29
29
  export declare function columns(rows: readonly (readonly [string, string])[], indent?: string): string;
30
+ export declare function parallelOf(args: Args): number;
31
+ export declare function announceFromOf(args: Args): 'changesets' | null;
@@ -1,7 +1,8 @@
1
1
  import path from 'node:path';
2
+ import { one } from '../args.js';
2
3
  import { findManifest, loadManifest } from '../manifest/index.js';
3
4
  import { topOf } from '../git/index.js';
4
- import { RehearseError } from '../errors.js';
5
+ import { RehearseError, usage } from '../errors.js';
5
6
  import { existsSync, statSync } from 'node:fs';
6
7
  export const GLOBAL_VALUED = ['manifest'];
7
8
  export const GLOBAL_BARE = ['json', 'help'];
@@ -27,3 +28,19 @@ export function columns(rows, indent = ' ') {
27
28
  const width = Math.min(32, Math.max(0, ...rows.map(([a]) => a.length)));
28
29
  return rows.map(([a, b]) => `${indent}${a.padEnd(width)} ${b}`.trimEnd()).join('\n');
29
30
  }
31
+ export function parallelOf(args) {
32
+ const given = one(args, 'parallel');
33
+ if (given === null)
34
+ return 1;
35
+ if (!/^[1-9]\d*$/.test(given))
36
+ throw usage(`--parallel takes a whole number, 1 or more, not “${given}”.`);
37
+ return Number(given);
38
+ }
39
+ export function announceFromOf(args) {
40
+ const given = one(args, 'announce-from');
41
+ if (given === null)
42
+ return null;
43
+ if (given !== 'changesets')
44
+ throw usage(`--announce-from takes changesets, not “${given}”.`);
45
+ return given;
46
+ }
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { checkoutOf, manifestOf, said } from './command.js';
2
+ import { announceFromOf, checkoutOf, manifestOf, parallelOf, said } from './command.js';
3
3
  import { many, one } from '../args.js';
4
4
  import { compare as compareSides } from '../compare/index.js';
5
5
  const VERDICT_WORDS = {
@@ -58,12 +58,16 @@ export function comparisonText(c) {
58
58
  export const compare = {
59
59
  name: 'compare',
60
60
  summary: 'Runs scenarios on the base and on the head, compares them, and sorts each into a verdict.',
61
- usage: "rehearse compare [<scenario>…] [--affected] [--base <ref|checkout>] [--head <ref|checkout>] [--announce <file>] [--said <scenario>]… [--world <name>] [--as <person>] [--real <stand-in>]… [--fresh] [--json]\n\nThe base defaults to the manifest's base branch; the head to this checkout as it is now.\nScenario ids may be globs: 'apps/api/**'. It exits 0 when nothing fails on the head or changed without saying so.",
62
- spec: { valued: ['base', 'head', 'announce', 'said', 'world', 'as', 'real'], bare: ['affected', 'fresh'] },
61
+ usage: "rehearse compare [<scenario>…] [--affected] [--base <ref|checkout>] [--head <ref|checkout>] [--announce <file>] [--announce-from changesets] [--said <scenario>]… [--world <name>] [--as <person>] [--real <stand-in>]… [--fresh] [--parallel <n>] [--json]\n\nThe base defaults to the manifest's base branch; the head to this checkout as it is now.\nScenario ids may be globs: 'apps/api/**'. It exits 0 when nothing fails on the head or changed without saying so.",
62
+ spec: {
63
+ valued: ['base', 'head', 'announce', 'announce-from', 'said', 'world', 'as', 'real', 'parallel'],
64
+ bare: ['affected', 'fresh'],
65
+ },
63
66
  async run(args, ctx) {
64
67
  const m = manifestOf(ctx);
65
68
  const repo = checkoutOf(m, null, ctx.cwd);
66
69
  const announce = one(args, 'announce');
70
+ const parallel = parallelOf(args);
67
71
  const c = await compareSides(m, {
68
72
  repo,
69
73
  cwd: ctx.cwd,
@@ -72,12 +76,14 @@ export const compare = {
72
76
  ids: args.positional,
73
77
  affected: args.flags.has('affected'),
74
78
  announce: announce ? path.resolve(ctx.cwd, announce) : null,
79
+ announceFrom: announceFromOf(args),
75
80
  said: many(args, 'said'),
76
81
  fresh: args.flags.has('fresh'),
77
82
  world: one(args, 'world'),
78
83
  as: one(args, 'as'),
79
84
  real: new Set(many(args, 'real')),
80
85
  progress: ctx.progress,
86
+ parallel,
81
87
  });
82
88
  return said(c, comparisonText(c), c.ok ? 0 : 1);
83
89
  },
@@ -1,5 +1,5 @@
1
1
  import { runnerOf } from '../kinds/index.js';
2
- import { checkoutOf, manifestOf, said } from './command.js';
2
+ import { checkoutOf, manifestOf, parallelOf, said } from './command.js';
3
3
  import { many, one } from '../args.js';
4
4
  import { RehearseError, usage } from '../errors.js';
5
5
  import { readScenarios, refOf } from '../scenarios/index.js';
@@ -25,12 +25,13 @@ export function observationText(o) {
25
25
  export const run = {
26
26
  name: 'run',
27
27
  summary: 'Runs one scenario on a checkout and prints what it observed.',
28
- usage: 'rehearse run <scenario> [--on <checkout|ref>] [--world <name>] [--as <person>] [--real <stand-in>]… [--keep] [--json]',
29
- spec: { valued: ['on', 'world', 'as', 'real'], bare: ['keep'] },
28
+ usage: 'rehearse run <scenario> [--on <checkout|ref>] [--world <name>] [--as <person>] [--real <stand-in>]… [--keep] [--parallel <n>] [--json]',
29
+ spec: { valued: ['on', 'world', 'as', 'real', 'parallel'], bare: ['keep'] },
30
30
  async run(args, ctx) {
31
31
  const id = args.positional[0];
32
32
  if (!id)
33
33
  throw usage('Name the scenario to run: rehearse list shows their ids.');
34
+ const parallel = parallelOf(args);
34
35
  const m = manifestOf(ctx);
35
36
  const repo = checkoutOf(m, null, ctx.cwd);
36
37
  const on = one(args, 'on');
@@ -51,6 +52,7 @@ export const run = {
51
52
  keepUp: args.flags.has('keep'),
52
53
  progress: ctx.progress,
53
54
  ref: target.ref,
55
+ parallel,
54
56
  });
55
57
  let o = side.observations.get(s.id);
56
58
  if (!o) {
@@ -1,5 +1,6 @@
1
- import { checkoutOf, manifestOf, said } from './command.js';
2
- import { one } from '../args.js';
1
+ import path from 'node:path';
2
+ import { announceFromOf, checkoutOf, manifestOf, said } from './command.js';
3
+ import { many, one } from '../args.js';
3
4
  import { errorText, usage } from '../errors.js';
4
5
  import { startStage } from '../stage/index.js';
5
6
  export const DEFAULT_STAGE_PORT = 4400;
@@ -14,11 +15,12 @@ export function portOf(given) {
14
15
  export const stage = {
15
16
  name: 'stage',
16
17
  summary: "Serves the stage: every scenario on one page, in Base, Head and Diff, with Works, Doesn't and a note.",
17
- usage: 'rehearse stage [--base <ref|checkout>] [--head <ref|checkout>] [--port <port>]\n\nIt runs until you stop it (Ctrl-C), and stops the services it brought up.',
18
- spec: { valued: ['base', 'head', 'port'], bare: [] },
18
+ usage: 'rehearse stage [--base <ref|checkout>] [--head <ref|checkout>] [--port <port>] [--announce <file>] [--announce-from changesets] [--said <scenario>]…\n\nIt runs until you stop it (Ctrl-C), and stops the services it brought up.\nCompare on the stage reads the announcement as rehearse compare does.',
19
+ spec: { valued: ['base', 'head', 'port', 'announce', 'announce-from', 'said'], bare: [] },
19
20
  async run(args, ctx) {
20
21
  const m = manifestOf(ctx);
21
22
  const { port, anyPort } = portOf(one(args, 'port'));
23
+ const announce = one(args, 'announce');
22
24
  const s = await startStage({
23
25
  manifest: m,
24
26
  repo: checkoutOf(m, null, ctx.cwd),
@@ -27,6 +29,9 @@ export const stage = {
27
29
  base: one(args, 'base'),
28
30
  port,
29
31
  anyPort,
32
+ announce: announce ? path.resolve(ctx.cwd, announce) : null,
33
+ announceFrom: announceFromOf(args),
34
+ said: many(args, 'said'),
30
35
  progress: ctx.progress,
31
36
  });
32
37
  process.stdout.write(ctx.json
@@ -1,6 +1,7 @@
1
1
  export interface Announced {
2
2
  scenario: string;
3
3
  why: string;
4
+ from?: string;
4
5
  }
5
6
  export declare function readAnnouncement(file: string): Announced[];
6
7
  export declare function announcementFor(id: string, announced: readonly Announced[]): Announced | null;
@@ -0,0 +1,8 @@
1
+ import type { Announced } from './announce.ts';
2
+ export interface ChangesetAnnounced extends Announced {
3
+ file: string;
4
+ line: number;
5
+ }
6
+ export declare function addedChangesets(base: string, head: string): string[];
7
+ export declare function announcedIn(text: string, file: string): ChangesetAnnounced[];
8
+ export declare function announcedByChangesets(base: string, head: string): ChangesetAnnounced[];
@@ -0,0 +1,91 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { RehearseError } from '../errors.js';
4
+ const CHANGESETS = '.changeset';
5
+ const NOT_A_CHANGESET = new Set(['README.md']);
6
+ const FENCE = /^(`{3,}|~{3,})\s*([^\s`~]*)/;
7
+ const TARGET = /^([a-z][a-z0-9-]*):\s*(.*)$/;
8
+ const OWN_WHY = /^(.*?)\s+—(?:\s+(.*))?$/;
9
+ function changesetsIn(checkout) {
10
+ const folder = path.join(checkout, CHANGESETS);
11
+ if (!existsSync(folder))
12
+ return new Set();
13
+ return new Set(readdirSync(folder).filter((name) => name.endsWith('.md') && !NOT_A_CHANGESET.has(name)));
14
+ }
15
+ export function addedChangesets(base, head) {
16
+ const onBase = changesetsIn(base);
17
+ return [...changesetsIn(head)]
18
+ .filter((name) => !onBase.has(name))
19
+ .sort()
20
+ .map((name) => `${CHANGESETS}/${name}`);
21
+ }
22
+ function bodyStart(lines) {
23
+ if (lines[0]?.trim() !== '---')
24
+ return 0;
25
+ const end = lines.findIndex((line, i) => i > 0 && line.trim() === '---');
26
+ return end === -1 ? lines.length : end + 1;
27
+ }
28
+ function closes(line, fence) {
29
+ return line.startsWith(fence) && new RegExp(`^\\${fence[0]}+$`).test(line);
30
+ }
31
+ function proseAndBlocks(lines, from) {
32
+ const prose = [];
33
+ const blocks = [];
34
+ let open = null;
35
+ for (let i = from; i < lines.length; i += 1) {
36
+ const text = lines[i].trim();
37
+ if (open) {
38
+ if (closes(text, open.fence))
39
+ open = null;
40
+ else
41
+ open.block.lines.push({ text, line: i + 1 });
42
+ continue;
43
+ }
44
+ const fence = FENCE.exec(text);
45
+ if (fence) {
46
+ open = { fence: fence[1], block: { announce: fence[2] === 'announce', lines: [] } };
47
+ blocks.push(open.block);
48
+ continue;
49
+ }
50
+ prose.push(text);
51
+ }
52
+ return { prose, blocks };
53
+ }
54
+ function summaryOf(prose) {
55
+ const first = prose.findIndex((line) => line !== '');
56
+ if (first === -1)
57
+ return '';
58
+ const end = prose.findIndex((line, i) => i > first && line === '');
59
+ return prose
60
+ .slice(first, end === -1 ? undefined : end)
61
+ .join(' ')
62
+ .trim();
63
+ }
64
+ export function announcedIn(text, file) {
65
+ const lines = text.split(/\r?\n/);
66
+ const { prose, blocks } = proseAndBlocks(lines, bodyStart(lines));
67
+ const summary = summaryOf(prose);
68
+ const refuse = (line, says) => new RehearseError('announce', `${file}:${line}: ${says}`, { file, line });
69
+ const announced = [];
70
+ for (const { text: entry, line } of blocks.filter((b) => b.announce).flatMap((b) => b.lines)) {
71
+ if (entry === '' || entry.startsWith('#'))
72
+ continue;
73
+ const target = TARGET.exec(entry);
74
+ if (!target)
75
+ throw refuse(line, `Rehearse can't read “${entry}”: write each line as <tool>: <target>, such as rehearse: <scenario>.`);
76
+ if (target[1] !== 'rehearse')
77
+ continue;
78
+ const own = OWN_WHY.exec(target[2]);
79
+ const scenario = (own ? own[1] : target[2]).trim();
80
+ const why = own?.[2]?.trim() || summary;
81
+ if (!scenario)
82
+ throw refuse(line, 'The line names no scenario after rehearse:.');
83
+ if (!why)
84
+ throw refuse(line, `The line announces ${scenario} with no why: give the changeset a summary, or end the line with — and why.`);
85
+ announced.push({ scenario, why, file, line });
86
+ }
87
+ return announced;
88
+ }
89
+ export function announcedByChangesets(base, head) {
90
+ return addedChangesets(base, head).flatMap((file) => announcedIn(readFileSync(path.join(head, file), 'utf8'), file));
91
+ }
@@ -13,12 +13,14 @@ export interface CompareOptions {
13
13
  ids: string[];
14
14
  affected: boolean;
15
15
  announce: string | null;
16
+ announceFrom?: 'changesets' | null;
16
17
  said: string[];
17
18
  fresh: boolean;
18
19
  world: string | null;
19
20
  as: string | null;
20
21
  real: ReadonlySet<string>;
21
22
  progress: (line: string) => void;
23
+ parallel?: number;
22
24
  }
23
25
  export interface Side {
24
26
  checkout: CheckoutInfo;
@@ -3,12 +3,13 @@ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { affected } from '../affected/index.js';
5
5
  import { RehearseError, errorText } from '../errors.js';
6
- import { checkoutFor, infoOf, commitOf, gitOr } from '../git/index.js';
6
+ import { checkoutFor, infoOf, commitOf, gitOr, topOf } from '../git/index.js';
7
7
  import { runnerOf } from '../kinds/index.js';
8
- import { cached, cacheKeyOf, groupsOf, keep, runSide, } from '../run/index.js';
8
+ import { cached, cacheKeyOf, groupsOf, keep, runSideSharing, slotsFor, } from '../run/index.js';
9
9
  import { readScenarios, refOf, globToRegExp, } from '../scenarios/index.js';
10
- import { stateDir } from '../services/index.js';
10
+ import { runningServices, stateDir } from '../services/index.js';
11
11
  import { announcementFor, readAnnouncement } from './announce.js';
12
+ import { announcedByChangesets } from './changesets.js';
12
13
  import { nonZeroCounts, noCounts, rulesOf } from './setaside.js';
13
14
  import { lineOf, verdictOf } from './verdict.js';
14
15
  const emptyCounts = () => ({
@@ -76,9 +77,18 @@ async function fromCache(m, info, scenarios, o, groups) {
76
77
  }
77
78
  return cachedWholeGroupsOnly(found, scenarios, groups);
78
79
  }
80
+ function bothSidesMayRunAtOnce(m, base, head) {
81
+ const onlyTheseTwo = new Set([path.resolve(base.path), path.resolve(head.path)]);
82
+ const headCouldReadWhatTheBaseKeeps = !head.dirty && head.commit === base.commit;
83
+ return (m.budget.services >= 2 &&
84
+ !headCouldReadWhatTheBaseKeeps &&
85
+ runningServices(m.dir).every((r) => onlyTheseTwo.has(path.resolve(r.checkout))));
86
+ }
79
87
  const latestComparisonFile = (m, everyScenario) => path.join(stateDir(m.dir), 'compare', everyScenario ? 'latest.json' : 'latest-partial.json');
80
88
  export async function compare(m, o) {
81
89
  const begun = Date.now();
90
+ const parallel = o.parallel ?? 1;
91
+ const slots = slotsFor(parallel);
82
92
  const session = (ref) => ({
83
93
  world: o.world,
84
94
  as: o.as,
@@ -86,6 +96,7 @@ export async function compare(m, o) {
86
96
  keepUp: false,
87
97
  progress: o.progress,
88
98
  ref,
99
+ parallel,
89
100
  });
90
101
  const head = o.head
91
102
  ? await checkoutFor(m, o.repo, o.head, o.progress, [], o.cwd)
@@ -108,9 +119,15 @@ export async function compare(m, o) {
108
119
  ? path.join(stateDir(m.dir), 'announce.yaml')
109
120
  : null);
110
121
  if (announceFile)
111
- announced.push(...readAnnouncement(path.resolve(o.repo, announceFile)));
122
+ announced.push(...readAnnouncement(path.resolve(o.repo, announceFile)).map((a) => ({ ...a, from: announceFile })));
123
+ if (o.announceFrom === 'changesets')
124
+ announced.push(...announcedByChangesets(topOf(base.path) ?? base.path, topOf(head.path) ?? head.path).map((a) => ({
125
+ scenario: a.scenario,
126
+ why: a.why,
127
+ from: a.file,
128
+ })));
112
129
  for (const id of o.said)
113
- announced.push({ scenario: id, why: 'Said on the command line.' });
130
+ announced.push({ scenario: id, why: 'Said on the command line.', from: '--said' });
114
131
  const headRead = await readScenarios(m, head.path);
115
132
  const baseRead = await readScenarios(m, base.path);
116
133
  let headScenarios = select(headRead.scenarios, o.ids);
@@ -132,19 +149,34 @@ export async function compare(m, o) {
132
149
  const hits = await fromCache(m, baseInfo, baseRunsOnlyWhatTheHeadStillHas, o, baseGroups);
133
150
  if (hits.size)
134
151
  o.progress(`${hits.size} base observation${hits.size === 1 ? '' : 's'} read from the cache (${baseInfo.commit?.slice(0, 12)}).`);
135
- const baseRun = await runSide(m, base.path, baseRunsOnlyWhatTheHeadStillHas.filter((s) => !hits.has(s.id)), { ...session(base.ref), groups: baseGroups });
136
- if (baseRun.broke)
152
+ const runHead = async (info) => {
153
+ const groups = await groupsOf(m, headScenarios, o.world);
154
+ const headHits = await fromCache(m, info, headScenarios, o, groups);
155
+ const run = await runSideSharing(m, head.path, headScenarios.filter((s) => !headHits.has(s.id)), { ...session(head.ref), groups }, slots);
156
+ return { info, hits: headHits, run };
157
+ };
158
+ let headAlongside = null;
159
+ if (parallel >= 2) {
160
+ const headAsItIs = infoOf(m, head.path, head.ref);
161
+ if (bothSidesMayRunAtOnce(m, baseInfo, headAsItIs))
162
+ headAlongside = runHead(headAsItIs);
163
+ }
164
+ const headDone = headAlongside?.then(() => undefined, () => undefined);
165
+ const baseRun = await runSideSharing(m, base.path, baseRunsOnlyWhatTheHeadStillHas.filter((s) => !hits.has(s.id)), { ...session(base.ref), groups: baseGroups }, slots).catch(async (error) => {
166
+ await headDone;
167
+ throw error;
168
+ });
169
+ if (baseRun.broke) {
170
+ await headDone;
137
171
  return failedBase(m, baseRun.checkout, infoOf(m, head.path, head.ref), baseRun.broke.step, baseRun.broke.says, begun, everyScenario, [
138
172
  ...baseRead.refused.map((r) => ({ side: 'base', ...r })),
139
173
  ...headRead.refused.map((r) => ({ side: 'head', ...r })),
140
174
  ]);
175
+ }
141
176
  const baseObs = new Map([...hits, ...baseRun.observations]);
142
177
  for (const ob of baseRun.observations.values())
143
178
  keep(m, ob);
144
- const headInfo = infoOf(m, head.path, head.ref);
145
- const headGroups = await groupsOf(m, headScenarios, o.world);
146
- const headHits = await fromCache(m, headInfo, headScenarios, o, headGroups);
147
- const headRun = await runSide(m, head.path, headScenarios.filter((s) => !headHits.has(s.id)), { ...session(head.ref), groups: headGroups });
179
+ const { info: headInfo, hits: headHits, run: headRun, } = await (headAlongside ?? runHead(infoOf(m, head.path, head.ref)));
148
180
  const headObs = new Map([...headHits, ...headRun.observations]);
149
181
  for (const ob of headRun.observations.values())
150
182
  keep(m, ob);
@@ -260,7 +292,7 @@ export async function compare(m, o) {
260
292
  if (mayBeATypo)
261
293
  out.refused.push({
262
294
  side: 'head',
263
- file: announceFile ?? '--said',
295
+ file: a.from ?? '--said',
264
296
  says: `The announcement names ${a.scenario}, which matches no scenario compared.`,
265
297
  });
266
298
  if (named.length > 0 && named.every((c) => !c.changed))
@@ -1,3 +1,5 @@
1
+ export { readAnnouncement } from './announce.ts';
2
+ export { addedChangesets, announcedByChangesets, announcedIn, type ChangesetAnnounced, } from './changesets.ts';
1
3
  export { changedFiles, compare, type CompareOptions, type Compared, type Comparison } from './compare.ts';
2
4
  export { clip, jsonDifferences, lineHunks, textDifferences, type Difference } from './diff.ts';
3
5
  export { noCounts, noRules, setAsideJson, setAsideText, type Counts as AsideCounts, type Rules, } from './setaside.ts';
@@ -1,3 +1,5 @@
1
+ export { readAnnouncement } from './announce.js';
2
+ export { addedChangesets, announcedByChangesets, announcedIn, } from './changesets.js';
1
3
  export { changedFiles, compare } from './compare.js';
2
4
  export { clip, jsonDifferences, lineHunks, textDifferences } from './diff.js';
3
5
  export { noCounts, noRules, setAsideJson, setAsideText, } from './setaside.js';
@@ -7,7 +7,7 @@ import { fill, loadManifest } from '../manifest/index.js';
7
7
  import { scrub, scrubDeep, signIn } from '../people/index.js';
8
8
  import { startPieceServer } from '../kinds/index.js';
9
9
  import { applyWorld, baseVars } from '../run/index.js';
10
- import { runningServices, bringDown, bringUp, freePort } from '../services/index.js';
10
+ import { runningServices, bringDown, bringUp, freePort, stateDir } from '../services/index.js';
11
11
  import { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, signInBySteps, signInOf, } from './browser.js';
12
12
  import { driveArgv, parseDrive } from './grammar.js';
13
13
  import { forgetDriving, writeDriving } from './state.js';
@@ -45,6 +45,7 @@ async function open() {
45
45
  throw new Error(`There is no piece ${values.piece} in ${checkout}.`);
46
46
  pieces = await startPieceServer({
47
47
  dir: spec.packageDir,
48
+ state: stateDir(m.dir),
48
49
  preview: m.scenarios.pieces.preview ?? null,
49
50
  styles: m.scenarios.pieces.styles ?? null,
50
51
  config: m.scenarios.pieces.config ?? null,
@@ -4,6 +4,7 @@ import { RehearseError } from '../errors.js';
4
4
  import { sh, tail } from '../exec.js';
5
5
  import { stateDir } from '../services/index.js';
6
6
  import { commitOf, git, gitOr, topOf } from './git.js';
7
+ import { preparedMark, seedDependencies, unseed } from './seed.js';
7
8
  export const checkoutsDir = (m) => path.join(stateDir(m.dir), 'checkouts');
8
9
  export function dirtyOf(m, checkout) {
9
10
  const status = gitOr(checkout, ['status', '--porcelain', '--untracked-files=all']);
@@ -31,7 +32,6 @@ export function overlay(m, checkout) {
31
32
  cpSync(o.from, to, { recursive: true });
32
33
  }
33
34
  }
34
- const preparedMark = (dir) => `${dir}.prepared`;
35
35
  const NAMED_AS_A_FOLDER = /^(?:\.{1,2}(?:\/|$)|\/|~\/)/;
36
36
  export async function checkoutFor(m, repo, given, progress, keep = [], cwd = process.cwd()) {
37
37
  if (NAMED_AS_A_FOLDER.test(given)) {
@@ -51,8 +51,14 @@ export async function checkoutFor(m, repo, given, progress, keep = [], cwd = pro
51
51
  git(repo, ['worktree', 'add', '--detach', dir, commit]);
52
52
  }
53
53
  if (m.prepare && !existsSync(preparedMark(dir))) {
54
+ const seeded = m.seed ? seedDependencies(dir, progress) : [];
54
55
  progress(`Preparing ${dir}: ${m.prepare}`);
55
- const ran = await sh(m.prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
56
+ let ran = await sh(m.prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
57
+ if (ran.code !== 0 && seeded.length > 0) {
58
+ progress(`Preparing ${dir} again, without the seeded dependencies: ${m.prepare}`);
59
+ unseed(seeded);
60
+ ran = await sh(m.prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
61
+ }
56
62
  if (ran.code !== 0)
57
63
  throw new RehearseError('prepare', `Preparing ${given} failed (${m.prepare}): ${tail(ran.stderr || ran.stdout) || `exit ${ran.code}`}`);
58
64
  writeFileSync(preparedMark(dir), `${new Date().toISOString()}\n`);
@@ -0,0 +1,3 @@
1
+ export declare const preparedMark: (dir: string) => string;
2
+ export declare function seedDependencies(dir: string, progress: (line: string) => void): string[];
3
+ export declare function unseed(seeded: readonly string[]): void;
@@ -0,0 +1,115 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, writeFileSync, } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { gitOr } from './git.js';
5
+ const LOCKFILES = [
6
+ 'pnpm-lock.yaml',
7
+ 'package-lock.json',
8
+ 'npm-shrinkwrap.json',
9
+ 'yarn.lock',
10
+ 'bun.lock',
11
+ 'bun.lockb',
12
+ ];
13
+ const CACHES_REBUILT_ON_DEMAND = new Set(['.cache', '.vite']);
14
+ const SMALL_ENOUGH_TO_REWRITE = 1_000_000;
15
+ export const preparedMark = (dir) => `${dir}.prepared`;
16
+ function lockfilesOf(dir) {
17
+ const hash = createHash('sha256');
18
+ let found = false;
19
+ for (const name of LOCKFILES) {
20
+ const file = path.join(dir, name);
21
+ if (!existsSync(file))
22
+ continue;
23
+ found = true;
24
+ hash.update(`${name}\n`).update(readFileSync(file));
25
+ }
26
+ return found ? hash.digest('hex') : null;
27
+ }
28
+ function newestPreparedWithTheSameLockfile(dir) {
29
+ const wanted = lockfilesOf(dir);
30
+ if (wanted === null)
31
+ return null;
32
+ const root = path.dirname(dir);
33
+ const prepared = readdirSync(root, { withFileTypes: true })
34
+ .filter((d) => d.isDirectory() && path.join(root, d.name) !== dir)
35
+ .map((d) => path.join(root, d.name))
36
+ .filter((other) => existsSync(preparedMark(other)))
37
+ .sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);
38
+ return prepared.find((other) => lockfilesOf(other) === wanted) ?? null;
39
+ }
40
+ function packageFolders(dir) {
41
+ const listed = gitOr(dir, ['ls-files', '-z', '--', 'package.json', '*/package.json']) ?? '';
42
+ return [
43
+ ...new Set(listed
44
+ .split('\0')
45
+ .filter((f) => f && !f.split('/').includes('node_modules'))
46
+ .map((f) => path.posix.dirname(f))),
47
+ ];
48
+ }
49
+ const placedAgain = (text, from, to) => text.split(from).join(to);
50
+ function copyLink(from, to, roots) {
51
+ const target = readlinkSync(from);
52
+ const inside = path.isAbsolute(target) && target.startsWith(`${roots.from}${path.sep}`);
53
+ symlinkSync(inside ? path.join(roots.to, path.relative(roots.from, target)) : target, to);
54
+ }
55
+ function copyFileOver(from, to, roots, mayNameTheCheckout) {
56
+ const seen = lstatSync(from);
57
+ if (mayNameTheCheckout && seen.size <= SMALL_ENOUGH_TO_REWRITE) {
58
+ const text = readFileSync(from, 'utf8');
59
+ if (text.includes(roots.from)) {
60
+ writeFileSync(to, placedAgain(text, roots.from, roots.to), { mode: seen.mode & 0o7777 });
61
+ return;
62
+ }
63
+ }
64
+ if (seen.nlink > 1)
65
+ try {
66
+ linkSync(from, to);
67
+ return;
68
+ }
69
+ catch {
70
+ rmSync(to, { force: true });
71
+ }
72
+ copyFileSync(from, to, constants.COPYFILE_FICLONE);
73
+ }
74
+ function copyTree(from, to, roots) {
75
+ mkdirSync(to);
76
+ const isBin = path.basename(from) === '.bin';
77
+ const isModules = path.basename(from) === 'node_modules';
78
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
79
+ if (isModules && CACHES_REBUILT_ON_DEMAND.has(entry.name))
80
+ continue;
81
+ const [a, b] = [path.join(from, entry.name), path.join(to, entry.name)];
82
+ if (entry.isSymbolicLink())
83
+ copyLink(a, b, roots);
84
+ else if (entry.isDirectory())
85
+ copyTree(a, b, roots);
86
+ else if (entry.isFile())
87
+ copyFileOver(a, b, roots, isBin || (isModules && entry.name.startsWith('.')));
88
+ }
89
+ }
90
+ export function seedDependencies(dir, progress) {
91
+ const from = newestPreparedWithTheSameLockfile(dir);
92
+ if (from === null)
93
+ return [];
94
+ const seeded = [];
95
+ for (const folder of packageFolders(dir)) {
96
+ const source = path.join(from, folder, 'node_modules');
97
+ const target = path.join(dir, folder, 'node_modules');
98
+ if (!existsSync(source) || existsSync(target) || !existsSync(path.dirname(target)))
99
+ continue;
100
+ try {
101
+ copyTree(source, target, { from, to: dir });
102
+ seeded.push(target);
103
+ }
104
+ catch {
105
+ rmSync(target, { recursive: true, force: true });
106
+ }
107
+ }
108
+ if (seeded.length > 0)
109
+ progress(`Seeded ${seeded.length} node_modules folder${seeded.length === 1 ? '' : 's'} from ${from}, prepared with the same lockfile.`);
110
+ return seeded;
111
+ }
112
+ export function unseed(seeded) {
113
+ for (const dir of seeded)
114
+ rmSync(dir, { recursive: true, force: true });
115
+ }