@kurvball/rehearse 1.14.0 → 1.15.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 (59) hide show
  1. package/dist/commands/announce.js +2 -2
  2. package/dist/commands/clean.js +6 -3
  3. package/dist/commands/compare.js +6 -1
  4. package/dist/commands/drive.js +8 -2
  5. package/dist/commands/init.js +1 -1
  6. package/dist/commands/run.js +8 -4
  7. package/dist/commands/services.d.ts +2 -0
  8. package/dist/commands/services.js +9 -1
  9. package/dist/commands/stage.js +18 -2
  10. package/dist/commands/up.js +11 -3
  11. package/dist/compare/compare.d.ts +2 -0
  12. package/dist/compare/compare.js +19 -10
  13. package/dist/detect/detect.js +4 -0
  14. package/dist/detect/index.d.ts +1 -0
  15. package/dist/detect/index.js +1 -0
  16. package/dist/detect/keys.d.ts +16 -0
  17. package/dist/detect/keys.js +141 -0
  18. package/dist/detect/write.d.ts +2 -0
  19. package/dist/detect/write.js +20 -1
  20. package/dist/drive/open.js +2 -0
  21. package/dist/git/checkout.d.ts +6 -0
  22. package/dist/git/checkout.js +28 -19
  23. package/dist/git/index.d.ts +3 -2
  24. package/dist/git/index.js +3 -2
  25. package/dist/kinds/flow/kind.js +2 -2
  26. package/dist/manifest/index.d.ts +1 -1
  27. package/dist/manifest/load.js +12 -0
  28. package/dist/manifest/types.d.ts +15 -0
  29. package/dist/repositories/copies.d.ts +16 -0
  30. package/dist/repositories/copies.js +132 -0
  31. package/dist/repositories/index.d.ts +1 -0
  32. package/dist/repositories/index.js +1 -0
  33. package/dist/run/cache.d.ts +2 -1
  34. package/dist/run/cache.js +3 -1
  35. package/dist/run/index.d.ts +1 -1
  36. package/dist/run/index.js +1 -0
  37. package/dist/run/observation.d.ts +4 -0
  38. package/dist/run/observation.js +5 -1
  39. package/dist/run/session.d.ts +3 -1
  40. package/dist/run/session.js +22 -12
  41. package/dist/services/index.d.ts +2 -2
  42. package/dist/services/index.js +2 -2
  43. package/dist/services/registry.d.ts +1 -0
  44. package/dist/services/service.d.ts +4 -0
  45. package/dist/services/service.js +24 -8
  46. package/dist/stage/api.d.ts +2 -0
  47. package/dist/stage/api.js +4 -0
  48. package/dist/stage/sending.d.ts +2 -1
  49. package/dist/stage/sending.js +8 -2
  50. package/dist/stage/server.d.ts +2 -0
  51. package/dist/stage/server.js +14 -1
  52. package/llms.txt +5 -5
  53. package/package.json +2 -2
  54. package/schema/v1/common.schema.json +22 -0
  55. package/schema/v1/init.schema.json +2 -1
  56. package/schema/v1/manifest.schema.json +30 -0
  57. package/schema/v1/samples/manifest.yaml +8 -0
  58. package/schema/v1/services.schema.json +8 -0
  59. package/skill/rehearse/SKILL.md +4 -0
@@ -10,7 +10,7 @@ export const NOT_COMPARED = 'not_compared';
10
10
  const ONLY_FOR_A_GATE = ['gate', 'preview'];
11
11
  const ONLY_WITH_A_DRAFT = {
12
12
  bare: ['affected', 'fresh'],
13
- valued: ['world', 'as', 'real', 'parallel'],
13
+ valued: ['base-repository', 'head-repository', 'world', 'as', 'real', 'parallel'],
14
14
  };
15
15
  function formatOf(args) {
16
16
  const given = one(args, 'format') ?? 'yaml';
@@ -55,7 +55,7 @@ export function announcementText(a, format) {
55
55
  export const announce = {
56
56
  name: 'announce',
57
57
  summary: 'Prints what the change announces, or, with --draft, proposes an announcement for each scenario that changed without saying so.',
58
- usage: `rehearse announce [<scenario>…] [--draft] [--affected] [--base <ref|checkout>] [--head <ref|checkout>] [--announce <file>] [--announce-from changesets] [--said <scenario>]… [--world <name>] [--as <person>] [--real <stand-in>]… [--fresh] [--parallel <n>] [--format yaml|changeset] [--json]
58
+ usage: `rehearse announce [<scenario>…] [--draft] [--affected] [--base <ref|checkout>] [--head <ref|checkout>] [--base-repository <name=ref|folder>]… [--head-repository <name=ref|folder>]… [--announce <file>] [--announce-from changesets] [--said <scenario>]… [--world <name>] [--as <person>] [--real <stand-in>]… [--fresh] [--parallel <n>] [--format yaml|changeset] [--json]
59
59
 
60
60
  Without --draft it reads what rehearse compare would read: the announcement file, each --said, and with
61
61
  --announce-from changesets the changesets the change adds. With --draft it compares as rehearse compare does, and
@@ -2,6 +2,7 @@ import { existsSync, readdirSync, rmSync, statSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { checkoutOf, manifestOf, said } from './command.js';
4
4
  import { evict } from '../git/index.js';
5
+ import { evictCopies } from '../repositories/index.js';
5
6
  import { stateDir } from '../services/index.js';
6
7
  const DAY = 24 * 60 * 60 * 1000;
7
8
  export const clean = {
@@ -13,9 +14,11 @@ export const clean = {
13
14
  const m = manifestOf(ctx);
14
15
  const repo = checkoutOf(m, null, ctx.cwd);
15
16
  const all = args.flags.has('all');
16
- const removed = all
17
- ? evict({ ...m, budget: { ...m.budget, checkouts: 0 } }, repo)
18
- : evict(m, repo);
17
+ const budgeted = all ? { ...m, budget: { ...m.budget, checkouts: 0 } } : m;
18
+ const removed = [
19
+ ...evict(budgeted, repo),
20
+ ...Object.keys(m.repositories).flatMap((name) => evictCopies(budgeted, name)),
21
+ ];
19
22
  for (const folder of ['runs', 'compare', 'pieces', ...(all ? ['cache'] : [])]) {
20
23
  const dir = path.join(stateDir(m.dir), folder);
21
24
  if (!existsSync(dir))
@@ -5,6 +5,7 @@ import { many, one } from '../args.js';
5
5
  import { compare as compareSides, gateAnswer, } from '../compare/index.js';
6
6
  import { errorText, RehearseError, usage } from '../errors.js';
7
7
  import { topOf } from '../git/index.js';
8
+ import { refsOf } from '../repositories/index.js';
8
9
  import { VERSION } from '../version.js';
9
10
  const VERDICT_WORDS = {
10
11
  fails: 'fails on the head',
@@ -67,6 +68,8 @@ export function compareOptionsOf(args, ctx, repo) {
67
68
  cwd: ctx.cwd,
68
69
  head: one(args, 'head'),
69
70
  base: one(args, 'base'),
71
+ headRepositories: refsOf(many(args, 'head-repository'), 'head-repository'),
72
+ baseRepositories: refsOf(many(args, 'base-repository'), 'base-repository'),
70
73
  ids: args.positional,
71
74
  affected: args.flags.has('affected'),
72
75
  announce: announce ? path.resolve(ctx.cwd, announce) : null,
@@ -135,11 +138,13 @@ async function gated(args, ctx) {
135
138
  export const compare = {
136
139
  name: 'compare',
137
140
  summary: 'Runs scenarios on the base and on the head, compares them, and sorts each into a verdict.',
138
- 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>] [--gate [--preview <url>]] [--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.\n--gate prints the gate answer instead, one JSON object a pull request report reads, with --preview as its stage preview link;\nit exits 0 when ok, 1 when not, and 2 when it can't compare, the base not coming up included.",
141
+ usage: "rehearse compare [<scenario>…] [--affected] [--base <ref|checkout>] [--head <ref|checkout>] [--base-repository <name=ref|folder>]… [--head-repository <name=ref|folder>]… [--announce <file>] [--announce-from changesets] [--said <scenario>]… [--world <name>] [--as <person>] [--real <stand-in>]… [--fresh] [--parallel <n>] [--gate [--preview <url>]] [--json]\n\nThe base defaults to the manifest's base branch; the head to this checkout as it is now.\nAnother repository runs at its own base on both sides, unless --base-repository or --head-repository names it: --head-repository api=feature-x.\nScenario ids may be globs: 'apps/api/**'. It exits 0 when nothing fails on the head or changed without saying so.\n--gate prints the gate answer instead, one JSON object a pull request report reads, with --preview as its stage preview link;\nit exits 0 when ok, 1 when not, and 2 when it can't compare, the base not coming up included.",
139
142
  spec: {
140
143
  valued: [
141
144
  'base',
142
145
  'head',
146
+ 'base-repository',
147
+ 'head-repository',
143
148
  'announce',
144
149
  'announce-from',
145
150
  'said',
@@ -8,7 +8,8 @@ import { sh, tail } from '../exec.js';
8
8
  import { knowKeys } from '../keys/index.js';
9
9
  import { fillEnv } from '../manifest/index.js';
10
10
  import { applyWorld, baseVars } from '../run/index.js';
11
- import { alive, runningServices, stateDir, bringDown, bringUp, envOf, handoverSettled, release, } from '../services/index.js';
11
+ import { alive, runningServices, stateDir, bringDown, bringUp, cwdOf, envOf, handoverSettled, release, } from '../services/index.js';
12
+ import { copiesFor, rootsOf } from '../repositories/index.js';
12
13
  const quote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
13
14
  const here = fileURLToPath(import.meta.url);
14
15
  const daemonFile = path.join(path.dirname(here), '..', 'drive', `daemon${path.extname(here)}`);
@@ -78,6 +79,7 @@ Each answers in the drive result shape (schema/v1/drive.schema.json): 0 done, 1
78
79
  world,
79
80
  real: new Set(),
80
81
  vars: baseVars(m, checkout, running),
82
+ roots: rootsOf(await copiesFor(m, {}, checkout, ctx.progress, ctx.cwd)),
81
83
  progress: ctx.progress,
82
84
  });
83
85
  await handoverSettled(r);
@@ -199,7 +201,11 @@ Each answers in the drive result shape (schema/v1/drive.schema.json): 0 done, 1
199
201
  }
200
202
  if (command.command === 'fill')
201
203
  return answer(failed('fill', at, 'usage', `${svc.name}'s driver takes no fill step: click the field, then type.`, 'service'));
202
- const cwd = svc.cwd ? path.resolve(driving.checkout, svc.cwd) : driving.checkout;
204
+ const cwd = running
205
+ ? cwdOf(svc, running)
206
+ : svc.cwd
207
+ ? path.resolve(driving.checkout, svc.cwd)
208
+ : driving.checkout;
203
209
  const env = running ? envOf(m, running) : fillEnv(svc.env, {});
204
210
  const ran = await sh(`${svc.drive} ${driveArgv(command).map(quote).join(' ')} --json`, {
205
211
  cwd,
@@ -45,7 +45,7 @@ function detectedText(file, d) {
45
45
  export const init = {
46
46
  name: 'init',
47
47
  summary: 'Writes a starter rehearse.yaml in this folder, every block commented, or with --detect, filled in from what it finds.',
48
- usage: "rehearse init [--detect] [--force] [--json]\n\n--detect looks at the repository and fills in what it finds: the base branch, prepare, services and scenarios.\nEach block says what it was detected from; what it found but couldn't write is named, with the next step.",
48
+ usage: "rehearse init [--detect] [--force] [--json]\n\n--detect looks at the repository and fills in what it finds: the base branch, prepare, services, the keys they read by name, and scenarios.\nEach block says what it was detected from; what it found but couldn't write is named, with the next step.",
49
49
  spec: { valued: [], bare: ['detect', 'force'] },
50
50
  async run(args, ctx) {
51
51
  const file = path.join(ctx.cwd, MANIFEST_FILE);
@@ -3,7 +3,8 @@ 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';
6
- import { runSide, keep } from '../run/index.js';
6
+ import { copiesFor, refsOf } from '../repositories/index.js';
7
+ import { runSide, keep, withCopies } from '../run/index.js';
7
8
  import { infoOf, checkoutFor } from '../git/index.js';
8
9
  import { VERSION } from '../version.js';
9
10
  export function observationText(o) {
@@ -25,8 +26,8 @@ export function observationText(o) {
25
26
  export const run = {
26
27
  name: 'run',
27
28
  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] [--parallel <n>] [--json]',
29
- spec: { valued: ['on', 'world', 'as', 'real', 'parallel'], bare: ['keep'] },
29
+ usage: 'rehearse run <scenario> [--on <checkout|ref>] [--repository <name=ref|folder>]… [--world <name>] [--as <person>] [--real <stand-in>]… [--keep] [--parallel <n>] [--json]',
30
+ spec: { valued: ['on', 'repository', 'world', 'as', 'real', 'parallel'], bare: ['keep'] },
30
31
  async run(args, ctx) {
31
32
  const id = args.positional[0];
32
33
  if (!id)
@@ -36,6 +37,7 @@ export const run = {
36
37
  const repo = checkoutOf(m, null, ctx.cwd);
37
38
  const on = one(args, 'on');
38
39
  const target = on ? await checkoutFor(m, repo, on, ctx.progress, [], ctx.cwd) : { path: repo, ref: null };
40
+ const repositories = refsOf(many(args, 'repository'), 'repository');
39
41
  const read = await readScenarios(m, target.path);
40
42
  const s = read.scenarios.find((x) => x.id === id) ??
41
43
  read.scenarios.find((x) => x.id.endsWith(id) || x.name === id);
@@ -45,6 +47,7 @@ export const run = {
45
47
  ? `${refused.file}${refused.line ? `:${refused.line}` : ''}: ${refused.says}`
46
48
  : `There is no scenario “${id}” in ${target.path}. rehearse list shows them.`);
47
49
  }
50
+ const copies = await copiesFor(m, repositories, target.path, ctx.progress, ctx.cwd);
48
51
  const side = await runSide(m, target.path, [s], {
49
52
  world: one(args, 'world'),
50
53
  as: one(args, 'as'),
@@ -53,6 +56,7 @@ export const run = {
53
56
  progress: ctx.progress,
54
57
  ref: target.ref,
55
58
  parallel,
59
+ copies,
56
60
  });
57
61
  let o = side.observations.get(s.id);
58
62
  if (!o) {
@@ -61,7 +65,7 @@ export const run = {
61
65
  v: 1,
62
66
  ok: false,
63
67
  scenario: refOf(s),
64
- checkout: infoOf(m, target.path, target.ref),
68
+ checkout: withCopies(infoOf(m, target.path, target.ref), copies),
65
69
  world: one(args, 'world') ?? s.world,
66
70
  person: one(args, 'as') ?? s.person,
67
71
  standins: [],
@@ -16,9 +16,11 @@ export declare function servicesOut(m: Manifest): Promise<{
16
16
  } | null;
17
17
  drive: string | null;
18
18
  keys: Record<string, string>;
19
+ repository: string | null;
19
20
  standins: string[];
20
21
  running: {
21
22
  checkout: string;
23
+ root?: string | undefined;
22
24
  url: string | null;
23
25
  port: number | null;
24
26
  pid: number;
@@ -16,12 +16,20 @@ export async function servicesOut(m) {
16
16
  isolate: s.isolate,
17
17
  drive: s.drive,
18
18
  keys: s.keys,
19
+ repository: s.repository,
19
20
  standins: Object.values(m.standins)
20
21
  .filter((x) => x.services === null || x.services.includes(s.name))
21
22
  .map((x) => x.name),
22
23
  running: running
23
24
  .filter((r) => r.name === s.name)
24
- .map((r) => ({ checkout: r.checkout, url: r.url, port: r.port, pid: r.pid, since: r.since })),
25
+ .map((r) => ({
26
+ checkout: r.checkout,
27
+ ...(r.root !== undefined && { root: r.root }),
28
+ url: r.url,
29
+ port: r.port,
30
+ pid: r.pid,
31
+ since: r.since,
32
+ })),
25
33
  })),
26
34
  };
27
35
  }
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { announceFromOf, checkoutOf, manifestOf, said } from './command.js';
3
3
  import { many, one } from '../args.js';
4
+ import { refsOf } from '../repositories/index.js';
4
5
  import { errorText, usage } from '../errors.js';
5
6
  import { baseWords, headWords, startStage, writeStaticCopy } from '../stage/index.js';
6
7
  export const DEFAULT_STAGE_PORT = 4400;
@@ -28,8 +29,21 @@ export function portOf(given) {
28
29
  export const stage = {
29
30
  name: 'stage',
30
31
  summary: "Serves the stage: every scenario on one page, in Base, Head and Diff, with Works, Doesn't and a note.",
31
- usage: 'rehearse stage [--base <ref|checkout>] [--head <ref|checkout>] [--port <port>] [--announce <file>] [--announce-from changesets] [--said <scenario>]… [--static <dir>]\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.\nWith --static <dir>, it writes the stage of the latest comparison into <dir> as plain files, for any static host, and exits.',
32
- spec: { valued: ['base', 'head', 'port', 'announce', 'announce-from', 'said', 'static'], bare: [] },
32
+ usage: 'rehearse stage [--base <ref|checkout>] [--head <ref|checkout>] [--base-repository <name=ref|folder>]… [--head-repository <name=ref|folder>]… [--port <port>] [--announce <file>] [--announce-from changesets] [--said <scenario>]… [--static <dir>]\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.\nWith --static <dir>, it writes the stage of the latest comparison into <dir> as plain files, for any static host, and exits.',
33
+ spec: {
34
+ valued: [
35
+ 'base',
36
+ 'head',
37
+ 'base-repository',
38
+ 'head-repository',
39
+ 'port',
40
+ 'announce',
41
+ 'announce-from',
42
+ 'said',
43
+ 'static',
44
+ ],
45
+ bare: [],
46
+ },
33
47
  async run(args, ctx) {
34
48
  const dir = one(args, 'static');
35
49
  if (dir !== null)
@@ -43,6 +57,8 @@ export const stage = {
43
57
  cwd: ctx.cwd,
44
58
  head: one(args, 'head'),
45
59
  base: one(args, 'base'),
60
+ headRepositories: refsOf(many(args, 'head-repository'), 'head-repository'),
61
+ baseRepositories: refsOf(many(args, 'base-repository'), 'base-repository'),
46
62
  port,
47
63
  anyPort,
48
64
  announce: announce ? path.resolve(ctx.cwd, announce) : null,
@@ -2,7 +2,8 @@ import path from 'node:path';
2
2
  import { checkoutOf, manifestOf, said } from './command.js';
3
3
  import { many, one } from '../args.js';
4
4
  import { RehearseError } from '../errors.js';
5
- import { bringDown, bringUp, handoverSettled, liveServices, makeRoom, release, runningServices, } from '../services/index.js';
5
+ import { bringDown, bringUp, handoverSettled, liveServices, makeRoom, release, runningServices, upFromAnotherCopy, } from '../services/index.js';
6
+ import { copiesFor, refsOf, rootsOf } from '../repositories/index.js';
6
7
  import { baseVars } from '../run/index.js';
7
8
  import { applyWorld } from '../worlds/index.js';
8
9
  import { overlay } from '../git/index.js';
@@ -18,8 +19,8 @@ const rowOf = (r) => ({
18
19
  export const up = {
19
20
  name: 'up',
20
21
  summary: 'Brings services up and leaves them running, with a world built on them.',
21
- usage: 'rehearse up [<service>…] [--on <checkout>] [--world <name>] [--real <stand-in>]… [--json]',
22
- spec: { valued: ['on', 'world', 'real'], bare: [] },
22
+ usage: 'rehearse up [<service>…] [--on <checkout>] [--repository <name=ref|folder>]… [--world <name>] [--real <stand-in>]… [--json]',
23
+ spec: { valued: ['on', 'repository', 'world', 'real'], bare: [] },
23
24
  async run(args, ctx) {
24
25
  const m = manifestOf(ctx);
25
26
  const checkout = checkoutOf(m, one(args, 'on'), ctx.cwd);
@@ -30,7 +31,13 @@ export const up = {
30
31
  const world = one(args, 'world') ?? m.defaults.world;
31
32
  overlay(m, checkout);
32
33
  await makeRoom(m, checkout, ctx.progress);
34
+ const roots = rootsOf(await copiesFor(m, refsOf(many(args, 'repository'), 'repository'), checkout, ctx.progress, ctx.cwd));
33
35
  let running = await liveServices(m, checkout);
36
+ for (const r of running.filter((x) => names.includes(x.name))) {
37
+ const another = upFromAnotherCopy(m, r, roots);
38
+ if (another)
39
+ throw new RehearseError('service', another);
40
+ }
34
41
  const fresh = names.filter((n) => !running.some((r) => r.name === n));
35
42
  if (world && fresh.length)
36
43
  await applyWorld(m, world, 'before', checkout, baseVars(m, checkout, running));
@@ -39,6 +46,7 @@ export const up = {
39
46
  world,
40
47
  real: new Set(many(args, 'real')),
41
48
  vars: baseVars(m, checkout, running),
49
+ roots,
42
50
  progress: ctx.progress,
43
51
  });
44
52
  running = [...running, r];
@@ -21,6 +21,8 @@ export interface CompareOptions {
21
21
  real: ReadonlySet<string>;
22
22
  progress: (line: string) => void;
23
23
  parallel?: number;
24
+ baseRepositories?: Readonly<Record<string, string>>;
25
+ headRepositories?: Readonly<Record<string, string>>;
24
26
  }
25
27
  export interface Side {
26
28
  checkout: CheckoutInfo;
@@ -6,8 +6,9 @@ import { RehearseError, errorText } from '../errors.js';
6
6
  import { checkoutFor, infoOf, commitOf, gitOr, topOf } from '../git/index.js';
7
7
  import { runnerOf } from '../kinds/index.js';
8
8
  import { loadManifest } from '../manifest/index.js';
9
- import { cached, cacheKeyOf, groupsOf, keep, runSideSharing, slotsFor, } from '../run/index.js';
9
+ import { cached, cacheKeyOf, commitsOf, dirtyAnywhere, groupsOf, keep, runSideSharing, slotsFor, withCopies, } from '../run/index.js';
10
10
  import { readScenarios, refOf, globToRegExp, } from '../scenarios/index.js';
11
+ import { copiesFor, refuseUnknownRepositories } from '../repositories/index.js';
11
12
  import { runningServices, stateDir } from '../services/index.js';
12
13
  import { announcedBy, announcementFor } from './announce.js';
13
14
  import { nonZeroCounts, noCounts, rulesOf } from './setaside.js';
@@ -57,13 +58,14 @@ function cachedWholeGroupsOnly(found, scenarios, groups) {
57
58
  }
58
59
  async function fromCache(m, info, scenarios, o, groups) {
59
60
  const found = new Map();
60
- if (o.fresh || !info.commit || info.dirty)
61
+ if (o.fresh || !info.commit || dirtyAnywhere(info))
61
62
  return found;
62
63
  for (const s of scenarios) {
63
64
  const runner = await runnerOf(s.kind);
64
65
  const key = cacheKeyOf({
65
66
  group: groups.get(s.id) ?? null,
66
67
  commit: info.commit,
68
+ copies: commitsOf(info),
67
69
  scenario: s,
68
70
  world: o.world ?? s.world,
69
71
  person: o.as ?? s.person,
@@ -79,7 +81,9 @@ async function fromCache(m, info, scenarios, o, groups) {
79
81
  }
80
82
  function bothSidesMayRunAtOnce(m, base, head) {
81
83
  const onlyTheseTwo = new Set([path.resolve(base.path), path.resolve(head.path)]);
82
- const headCouldReadWhatTheBaseKeeps = !head.dirty && head.commit === base.commit;
84
+ const headCouldReadWhatTheBaseKeeps = !dirtyAnywhere(head) &&
85
+ head.commit === base.commit &&
86
+ JSON.stringify(commitsOf(head)) === JSON.stringify(commitsOf(base));
83
87
  return (m.budget.services >= 2 &&
84
88
  !headCouldReadWhatTheBaseKeeps &&
85
89
  runningServices(m.dir).every((r) => onlyTheseTwo.has(path.resolve(r.checkout))));
@@ -112,15 +116,20 @@ export async function compare(m, o) {
112
116
  const head = o.head
113
117
  ? await checkoutFor(m, o.repo, o.head, o.progress, [], o.cwd)
114
118
  : { path: o.repo, ref: null };
119
+ refuseUnknownRepositories(m, o.baseRepositories ?? {});
120
+ const headCopies = await copiesFor(m, o.headRepositories ?? {}, head.path, o.progress, o.cwd);
121
+ const headInfoOf = () => withCopies(infoOf(m, head.path, head.ref), headCopies);
115
122
  const baseRef = o.base ?? m.base;
116
123
  const everyScenario = o.ids.length === 0 && !o.affected;
117
124
  let base;
125
+ let baseCopies = {};
118
126
  try {
119
127
  base = await checkoutFor(m, head.path, baseRef, o.progress, [head.path], o.cwd);
128
+ baseCopies = await copiesFor(m, o.baseRepositories ?? {}, base.path, o.progress, o.cwd);
120
129
  }
121
130
  catch (error) {
122
131
  const info = { path: '', ref: baseRef, commit: commitOf(head.path, baseRef), dirty: false };
123
- return failedBase(m, info, infoOf(m, head.path, head.ref), error instanceof RehearseError && ['git', 'no_checkout'].includes(error.code) ? 'checkout' : 'prepare', errorText(error), begun, everyScenario);
132
+ return failedBase(m, info, headInfoOf(), error instanceof RehearseError && ['git', 'no_checkout'].includes(error.code) ? 'checkout' : 'prepare', errorText(error), begun, everyScenario);
124
133
  }
125
134
  if (path.resolve(base.path) === path.resolve(head.path))
126
135
  throw new RehearseError('usage', `The base and the head are the same checkout (${head.path}): name a base ref, or another folder.`, { exit: 2 });
@@ -145,7 +154,7 @@ export async function compare(m, o) {
145
154
  const baseIds = new Set([...ids, ...baseReach.reached.map((r) => r.scenario.id)]);
146
155
  baseScenarios = baseScenarios.filter((s) => baseIds.has(s.id));
147
156
  }
148
- const baseInfo = infoOf(m, base.path, base.ref);
157
+ const baseInfo = withCopies(infoOf(m, base.path, base.ref), baseCopies);
149
158
  const baseRunsOnlyWhatTheHeadStillHas = baseScenarios.filter((s) => headIds.has(s.id) && headScenarios.some((h) => h.id === s.id));
150
159
  const baseGroups = await groupsOf(m, baseRunsOnlyWhatTheHeadStillHas, o.world);
151
160
  const hits = await fromCache(m, baseInfo, baseRunsOnlyWhatTheHeadStillHas, o, baseGroups);
@@ -154,23 +163,23 @@ export async function compare(m, o) {
154
163
  const runHead = async (info) => {
155
164
  const groups = await groupsOf(m, headScenarios, o.world);
156
165
  const headHits = await fromCache(m, info, headScenarios, o, groups);
157
- const run = await runSideSharing(m, head.path, headScenarios.filter((s) => !headHits.has(s.id)), { ...session(head.ref), groups }, slots);
166
+ const run = await runSideSharing(m, head.path, headScenarios.filter((s) => !headHits.has(s.id)), { ...session(head.ref), groups, copies: headCopies }, slots);
158
167
  return { info, hits: headHits, run };
159
168
  };
160
169
  let headAlongside = null;
161
170
  if (parallel >= 2) {
162
- const headAsItIs = infoOf(m, head.path, head.ref);
171
+ const headAsItIs = headInfoOf();
163
172
  if (bothSidesMayRunAtOnce(m, baseInfo, headAsItIs))
164
173
  headAlongside = runHead(headAsItIs);
165
174
  }
166
175
  const headDone = headAlongside?.then(() => undefined, () => undefined);
167
- const baseRun = await runSideSharing(m, base.path, baseRunsOnlyWhatTheHeadStillHas.filter((s) => !hits.has(s.id)), { ...session(base.ref), groups: baseGroups }, slots).catch(async (error) => {
176
+ const baseRun = await runSideSharing(m, base.path, baseRunsOnlyWhatTheHeadStillHas.filter((s) => !hits.has(s.id)), { ...session(base.ref), groups: baseGroups, copies: baseCopies }, slots).catch(async (error) => {
168
177
  await headDone;
169
178
  throw error;
170
179
  });
171
180
  if (baseRun.broke) {
172
181
  await headDone;
173
- return failedBase(m, baseRun.checkout, infoOf(m, head.path, head.ref), baseRun.broke.step, baseRun.broke.says, begun, everyScenario, [
182
+ return failedBase(m, baseRun.checkout, headInfoOf(), baseRun.broke.step, baseRun.broke.says, begun, everyScenario, [
174
183
  ...baseRead.refused.map((r) => ({ side: 'base', ...r })),
175
184
  ...headRead.refused.map((r) => ({ side: 'head', ...r })),
176
185
  ]);
@@ -178,7 +187,7 @@ export async function compare(m, o) {
178
187
  const baseObs = new Map([...hits, ...baseRun.observations]);
179
188
  for (const ob of baseRun.observations.values())
180
189
  keep(m, ob);
181
- const { info: headInfo, hits: headHits, run: headRun, } = await (headAlongside ?? runHead(infoOf(m, head.path, head.ref)));
190
+ const { info: headInfo, hits: headHits, run: headRun } = await (headAlongside ?? runHead(headInfoOf()));
182
191
  const headObs = new Map([...headHits, ...headRun.observations]);
183
192
  for (const ob of headRun.observations.values())
184
193
  keep(m, ob);
@@ -1,3 +1,4 @@
1
+ import { keysOf } from './keys.js';
1
2
  import { buildsOf, prepareOf } from './prepare.js';
2
3
  import { defaultBranch, readRepository } from './repository.js';
3
4
  import { scenariosOf } from './scenarios.js';
@@ -8,6 +9,7 @@ export function detect(root) {
8
9
  const repo = readRepository(root);
9
10
  const branch = defaultBranch(root);
10
11
  const found = servicesOf(repo);
12
+ const keys = keysOf(repo, found.services);
11
13
  const scenarios = scenariosOf(repo, found.services);
12
14
  const prepare = prepareOf(repo, buildsOf(repo, found.services, scenarios.pieceDirs));
13
15
  const findings = [
@@ -16,6 +18,7 @@ export function detect(root) {
16
18
  : []),
17
19
  ...prepare.findings,
18
20
  ...found.findings,
21
+ ...keys.findings,
19
22
  ...scenarios.findings,
20
23
  ...(repo.git && !repo.ignored('.rehearse/runs')
21
24
  ? [
@@ -36,6 +39,7 @@ export function detect(root) {
36
39
  base: branch,
37
40
  prepare: prepare.command === null ? null : { command: prepare.command, from: prepare.from },
38
41
  services: found.services,
42
+ keys: keys.keys,
39
43
  blocks: scenarios.blocks,
40
44
  prefix: repo.prefix,
41
45
  }),
@@ -1,2 +1,3 @@
1
1
  export { detect, type Detection } from './detect.ts';
2
2
  export { printable, type Detected, type Finding } from './finding.ts';
3
+ export { keyNameOf, looksSecret, type DetectedKey } from './keys.ts';
@@ -1,2 +1,3 @@
1
1
  export { detect } from './detect.js';
2
2
  export { printable } from './finding.js';
3
+ export { keyNameOf, looksSecret } from './keys.js';
@@ -0,0 +1,16 @@
1
+ import type { Finding } from './finding.ts';
2
+ import { type Repository } from './repository.ts';
3
+ import type { Service } from './services.ts';
4
+ export interface DetectedKey {
5
+ name: string;
6
+ env: string;
7
+ from: string;
8
+ onlyNamed: boolean;
9
+ services: string[];
10
+ }
11
+ export declare function looksSecret(env: string): boolean;
12
+ export declare const keyNameOf: (env: string) => string;
13
+ export declare function keysOf(repo: Repository, services: readonly Service[]): {
14
+ keys: DetectedKey[];
15
+ findings: Finding[];
16
+ };
@@ -0,0 +1,141 @@
1
+ import path from 'node:path';
2
+ import { readText, within } from './repository.js';
3
+ const ENV_NAME = '[A-Z][A-Z0-9_]*';
4
+ const WITHOUT_A_FALLBACK = '(?!\\s*(?:\\?\\?|\\|\\||\\?(?!\\.)|=(?!=)))';
5
+ const READS = [
6
+ new RegExp(`process\\.env\\.(${ENV_NAME})\\b${WITHOUT_A_FALLBACK}`, 'g'),
7
+ new RegExp(`process\\.env\\[\\s*['"\`](${ENV_NAME})['"\`]\\s*\\]${WITHOUT_A_FALLBACK}`, 'g'),
8
+ new RegExp(`(?:import\\.meta|Bun)\\.env\\.(${ENV_NAME})\\b${WITHOUT_A_FALLBACK}`, 'g'),
9
+ new RegExp(`Deno\\.env\\.get\\(\\s*['"\`](${ENV_NAME})['"\`]\\s*\\)${WITHOUT_A_FALLBACK}`, 'g'),
10
+ ];
11
+ const TAKEN_APART = /\{([^{}]*)\}\s*=\s*process\.env\b/g;
12
+ const TAKEN_WITHOUT_A_DEFAULT = new RegExp(`^\\s*(${ENV_NAME})\\s*(?::\\s*[A-Za-z_$][\\w$]*\\s*)?$`);
13
+ const SET_IN_AN_EXAMPLE = new RegExp(`^\\s*(?:export\\s+)?(${ENV_NAME})\\s*=`, 'gm');
14
+ const AN_EXAMPLE_ENV_FILE = /^\.env(?:\.[\w-]+)?\.(?:example|sample|template)$/;
15
+ const NOT_THE_APP = /^(?:scripts|tools|docs|bench|benchmarks|playwright|cypress|\.[^/]+)\/|^[^/]+\.config\.[^/]+$|(?:^|\/)(?:test|tests|__tests__|__mocks__|fixtures|e2e|examples)\/|\.(?:test|spec|stories)\.[^/]+$/;
16
+ const READ_AS_CODE = /\.(?:[cm]?[jt]s|tsx|jsx|astro|vue|svelte)$/;
17
+ const BLOCK_COMMENT = /(^|[\s;{}(),])\/\*[\s\S]*?\*\//gm;
18
+ const LINE_COMMENT = /(^|[\s;{}(),])\/\/.*$/gm;
19
+ const SOURCES_READ = 400;
20
+ const LAST_WORD_OF_A_SECRET = new Set([
21
+ 'KEY',
22
+ 'SECRET',
23
+ 'TOKEN',
24
+ 'PASSWORD',
25
+ 'PASSWD',
26
+ 'PASS',
27
+ 'CREDENTIAL',
28
+ 'CREDENTIALS',
29
+ ]);
30
+ const MEANT_TO_BE_SEEN = new Set(['PUBLIC', 'PUBLISHABLE']);
31
+ const A_KEY_THAT_NAMES_DATA = new Set([
32
+ 'SORT',
33
+ 'PARTITION',
34
+ 'PRIMARY',
35
+ 'FOREIGN',
36
+ 'IDEMPOTENCY',
37
+ 'DEDUP',
38
+ 'DEDUPE',
39
+ 'CACHE',
40
+ 'HASH',
41
+ 'ROUTING',
42
+ 'LOCK',
43
+ 'QUEUE',
44
+ 'OBJECT',
45
+ 'BUCKET',
46
+ 'STORAGE',
47
+ 'FILE',
48
+ 'INDEX',
49
+ 'LOOKUP',
50
+ 'SHARD',
51
+ 'TABLE',
52
+ 'ROW',
53
+ 'COLUMN',
54
+ 'NAMESPACE',
55
+ ]);
56
+ const and = (items) => items.length <= 1 ? (items[0] ?? '') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`;
57
+ export function looksSecret(env) {
58
+ const words = env.split('_').filter(Boolean);
59
+ const last = words.at(-1) ?? '';
60
+ if (!LAST_WORD_OF_A_SECRET.has(last) || words.some((w) => MEANT_TO_BE_SEEN.has(w)))
61
+ return false;
62
+ return !(last === 'KEY' && A_KEY_THAT_NAMES_DATA.has(words.at(-2) ?? ''));
63
+ }
64
+ export const keyNameOf = (env) => env
65
+ .toLowerCase()
66
+ .replace(/_+/g, '-')
67
+ .replace(/^-+|-+$/g, '');
68
+ function namesRead(code) {
69
+ const text = code.replace(BLOCK_COMMENT, '$1').replace(LINE_COMMENT, '$1');
70
+ const names = READS.flatMap((re) => [...text.matchAll(re)].map((m) => m[1]));
71
+ for (const m of text.matchAll(TAKEN_APART))
72
+ for (const part of m[1].split(',')) {
73
+ const name = TAKEN_WITHOUT_A_DEFAULT.exec(part)?.[1];
74
+ if (name)
75
+ names.push(name);
76
+ }
77
+ return names;
78
+ }
79
+ const namesSetIn = (text) => [...text.matchAll(SET_IN_AN_EXAMPLE)].map((m) => m[1]);
80
+ function filesOf(repo, s) {
81
+ const dir = s.pkg.dir;
82
+ const others = repo.packages.map((p) => p.dir).filter((d) => d !== dir && within(dir, d));
83
+ return repo.files
84
+ .filter((f) => within(dir, f) && !others.some((d) => within(d, f)))
85
+ .map((f) => (dir ? f.slice(dir.length + 1) : f))
86
+ .filter((f) => !NOT_THE_APP.test(f));
87
+ }
88
+ function seenBy(repo, s) {
89
+ const inRepo = (f) => (s.pkg.dir ? `${s.pkg.dir}/${f}` : f);
90
+ const files = filesOf(repo, s);
91
+ const out = [];
92
+ for (const file of files.filter((f) => READ_AS_CODE.test(f)).slice(0, SOURCES_READ)) {
93
+ const text = readText(path.join(repo.root, inRepo(file)));
94
+ if (text !== null)
95
+ for (const env of namesRead(text))
96
+ out.push({ env, from: inRepo(file), onlyNamed: false, service: s.name });
97
+ }
98
+ for (const file of files.filter((f) => AN_EXAMPLE_ENV_FILE.test(f))) {
99
+ const text = readText(path.join(repo.root, inRepo(file)));
100
+ if (text !== null)
101
+ for (const env of namesSetIn(text))
102
+ out.push({ env, from: inRepo(file), onlyNamed: true, service: s.name });
103
+ }
104
+ return out.filter((x) => looksSecret(x.env) && !(x.env in s.env));
105
+ }
106
+ export function keysOf(repo, services) {
107
+ const byEnv = new Map();
108
+ for (const seen of services.flatMap((s) => seenBy(repo, s))) {
109
+ const known = byEnv.get(seen.env);
110
+ if (!known)
111
+ byEnv.set(seen.env, {
112
+ name: keyNameOf(seen.env),
113
+ env: seen.env,
114
+ from: seen.from,
115
+ onlyNamed: seen.onlyNamed,
116
+ services: [seen.service],
117
+ });
118
+ else if (!known.services.includes(seen.service))
119
+ known.services.push(seen.service);
120
+ }
121
+ const keys = [...byEnv.values()].sort((a, b) => (a.env < b.env ? -1 : a.env > b.env ? 1 : 0));
122
+ const taken = new Set();
123
+ for (const k of keys) {
124
+ let name = k.name;
125
+ for (let n = 2; taken.has(name); n += 1)
126
+ name = `${k.name}-${n}`;
127
+ k.name = name;
128
+ taken.add(name);
129
+ }
130
+ const findings = keys.map((k) => ({
131
+ kind: 'key',
132
+ name: k.name,
133
+ from: k.from,
134
+ written: true,
135
+ why: k.onlyNamed
136
+ ? `${k.env}, which ${k.from} names for ${and(k.services)}`
137
+ : `${k.env}, which ${and(k.services)} ${k.services.length === 1 ? 'reads' : 'read'}`,
138
+ next: `Keep it on this computer with rehearse keys add ${k.name}, or say where it is with from: op://…`,
139
+ }));
140
+ return { keys, findings };
141
+ }
@@ -1,3 +1,4 @@
1
+ import type { DetectedKey } from './keys.ts';
1
2
  import type { Blocks } from './scenarios.ts';
2
3
  import type { Service } from './services.ts';
3
4
  export interface Plan {
@@ -10,6 +11,7 @@ export interface Plan {
10
11
  from: string[];
11
12
  } | null;
12
13
  services: readonly Service[];
14
+ keys: readonly DetectedKey[];
13
15
  blocks: Blocks;
14
16
  prefix: string;
15
17
  }