@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
@@ -55,10 +55,28 @@ function services(plan) {
55
55
  for (const s of plan.services) {
56
56
  const cwd = joined(plan.prefix, s.pkg.dir);
57
57
  const env = Object.entries(s.env);
58
- lines.push(` # Detected from ${printable(s.pkg.file)}: ${WHAT[s.server]}${s.built ? ', built first' : ''}.`, ` ${s.name}:`, ` up: ${scalar(s.up)}`, ...(cwd ? [` cwd: ${scalar(cwd)}`] : []), ' port: auto', ` ready: ${scalar(s.ready)}`, ...(env.length ? [' env:', ...env.map(([k, v]) => ` ${k}: ${scalar(v)}`)] : []));
58
+ lines.push(` # Detected from ${printable(s.pkg.file)}: ${WHAT[s.server]}${s.built ? ', built first' : ''}.`, ` ${s.name}:`, ` up: ${scalar(s.up)}`, ...(cwd ? [` cwd: ${scalar(cwd)}`] : []), ' port: auto', ` ready: ${scalar(s.ready)}`, ...(env.length ? [' env:', ...env.map(([k, v]) => ` ${k}: ${scalar(v)}`)] : []), ...keysGivenTo(plan, s));
59
59
  }
60
60
  return `${lines.join('\n')}\n`;
61
61
  }
62
+ function keysGivenTo(plan, s) {
63
+ const given = plan.keys.filter((k) => k.services.includes(s.name));
64
+ return given.length ? [' keys:', ...given.map((k) => ` ${k.env}: ${scalar(k.name)}`)] : [];
65
+ }
66
+ function keys(plan) {
67
+ if (plan.keys.length === 0)
68
+ return null;
69
+ return [
70
+ '# The keys services get as they start, by name: where each comes from, never its value.',
71
+ '# None says where it is yet: keep each with rehearse keys add <key>, or give it from: op://vault/item/field.',
72
+ 'keys:',
73
+ ...plan.keys.flatMap((k) => [
74
+ ` # ${k.onlyNamed ? 'Named' : 'Read'} in ${printable(k.from)}.`,
75
+ ` ${scalar(k.name)}:`,
76
+ ]),
77
+ '',
78
+ ].join('\n');
79
+ }
62
80
  function scenarios(plan) {
63
81
  const b = plan.blocks;
64
82
  if (!b.pieces && !b.flows && !b.calls && !b.files)
@@ -107,6 +125,7 @@ export function manifestText(plan) {
107
125
  base(plan),
108
126
  prepare(plan),
109
127
  services(plan),
128
+ ...[keys(plan)].filter((block) => block !== null),
110
129
  commented(STARTER_BLOCKS.people),
111
130
  commented(STARTER_BLOCKS.worlds),
112
131
  commented(STARTER_BLOCKS.standins),
@@ -5,6 +5,7 @@ import { scrub, signIn } from '../people/index.js';
5
5
  import { startPieceServer } from '../kinds/index.js';
6
6
  import { applyWorld, baseVars } from '../run/index.js';
7
7
  import { bringDown, bringUp, runningServices, stateDir } from '../services/index.js';
8
+ import { copiesFor, rootsOf } from '../repositories/index.js';
8
9
  import { readScenarios } from '../scenarios/index.js';
9
10
  import { calm, contextFor, errorsOf, FIXED_TIME, launch, signInBySteps, signInOf, } from './browser.js';
10
11
  import { noteSecretsOn, SECRET_AUTOCOMPLETE } from './secrets.js';
@@ -57,6 +58,7 @@ export async function openPage(m, checkout, o, showing = {}) {
57
58
  world: o.world,
58
59
  real: new Set(),
59
60
  vars: baseVars(m, checkout, running),
61
+ roots: rootsOf(await copiesFor(m, {}, checkout, showing.progress ?? (() => undefined))),
60
62
  ...(showing.progress && { progress: showing.progress }),
61
63
  });
62
64
  started.push(mine);
@@ -10,7 +10,13 @@ export type Tree = {
10
10
  repo: string;
11
11
  commit: string;
12
12
  };
13
+ export declare function folderNamed(given: string, cwd?: string): string | null;
13
14
  export declare function locate(repo: string, given: string, cwd?: string): Tree;
15
+ export declare function preparedOnce(dir: string, how: {
16
+ prepare: string | null;
17
+ seed: boolean;
18
+ given: string;
19
+ }, progress: (line: string) => void): Promise<void>;
14
20
  export declare function checkoutFor(m: Manifest, repo: string, given: string, progress: (line: string) => void, keep?: readonly string[], cwd?: string): Promise<{
15
21
  path: string;
16
22
  ref: string | null;
@@ -33,18 +33,39 @@ export function overlay(m, checkout) {
33
33
  }
34
34
  }
35
35
  const NAMED_AS_A_FOLDER = /^(?:\.{1,2}(?:\/|$)|\/|~\/)/;
36
+ export function folderNamed(given, cwd = process.cwd()) {
37
+ if (!NAMED_AS_A_FOLDER.test(given))
38
+ return null;
39
+ const asPath = path.resolve(cwd, given.replace(/^~(?=\/)/, process.env.HOME ?? '~'));
40
+ if (!existsSync(asPath) || !statSync(asPath).isDirectory())
41
+ throw new RehearseError('no_checkout', `There is no checkout at ${asPath}.`);
42
+ return topOf(asPath) ?? asPath;
43
+ }
36
44
  export function locate(repo, given, cwd = process.cwd()) {
37
- if (NAMED_AS_A_FOLDER.test(given)) {
38
- const asPath = path.resolve(cwd, given.replace(/^~(?=\/)/, process.env.HOME ?? '~'));
39
- if (!existsSync(asPath) || !statSync(asPath).isDirectory())
40
- throw new RehearseError('no_checkout', `There is no checkout at ${asPath}.`);
41
- return { folder: topOf(asPath) ?? asPath };
42
- }
45
+ const folder = folderNamed(given, cwd);
46
+ if (folder !== null)
47
+ return { folder };
43
48
  const commit = commitOf(repo, given);
44
49
  if (!commit)
45
50
  throw new RehearseError('git', `${given} isn't a commit Rehearse can find in ${repo}.${existsSync(path.resolve(cwd, given)) ? ` To mean the folder, write ./${given}.` : ''}`);
46
51
  return { repo: topOf(repo) ?? repo, commit };
47
52
  }
53
+ export async function preparedOnce(dir, how, progress) {
54
+ const { prepare, given } = how;
55
+ if (!prepare || existsSync(preparedMark(dir)))
56
+ return;
57
+ const seeded = how.seed ? seedDependencies(dir, progress) : [];
58
+ progress(`Preparing ${dir}: ${prepare}`);
59
+ let ran = await sh(prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
60
+ if (ran.code !== 0 && seeded.length > 0) {
61
+ progress(`Preparing ${dir} again, without the seeded dependencies: ${prepare}`);
62
+ unseed(seeded);
63
+ ran = await sh(prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
64
+ }
65
+ if (ran.code !== 0)
66
+ throw new RehearseError('prepare', `Preparing ${given} failed (${prepare}): ${tail(ran.stderr || ran.stdout) || `exit ${ran.code}`}`);
67
+ writeFileSync(preparedMark(dir), `${new Date().toISOString()}\n`);
68
+ }
48
69
  export async function checkoutFor(m, repo, given, progress, keep = [], cwd = process.cwd()) {
49
70
  const found = locate(repo, given, cwd);
50
71
  if ('folder' in found)
@@ -57,19 +78,7 @@ export async function checkoutFor(m, repo, given, progress, keep = [], cwd = pro
57
78
  gitOr(repo, ['worktree', 'prune']);
58
79
  git(repo, ['worktree', 'add', '--detach', dir, commit]);
59
80
  }
60
- if (m.prepare && !existsSync(preparedMark(dir))) {
61
- const seeded = m.seed ? seedDependencies(dir, progress) : [];
62
- progress(`Preparing ${dir}: ${m.prepare}`);
63
- let ran = await sh(m.prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
64
- if (ran.code !== 0 && seeded.length > 0) {
65
- progress(`Preparing ${dir} again, without the seeded dependencies: ${m.prepare}`);
66
- unseed(seeded);
67
- ran = await sh(m.prepare, { cwd: dir, timeoutMs: 30 * 60_000 });
68
- }
69
- if (ran.code !== 0)
70
- throw new RehearseError('prepare', `Preparing ${given} failed (${m.prepare}): ${tail(ran.stderr || ran.stdout) || `exit ${ran.code}`}`);
71
- writeFileSync(preparedMark(dir), `${new Date().toISOString()}\n`);
72
- }
81
+ await preparedOnce(dir, { prepare: m.prepare, seed: m.seed, given }, progress);
73
82
  const now = new Date();
74
83
  utimesSync(dir, now, now);
75
84
  evict(m, repo, [dir, ...keep]);
@@ -1,2 +1,3 @@
1
- export { checkoutFor, evict, infoOf, locate, overlay, type Tree } from './checkout.ts';
2
- export { commitOf, gitOr, topOf } from './git.ts';
1
+ export { checkoutFor, evict, folderNamed, infoOf, locate, overlay, preparedOnce, type Tree, } from './checkout.ts';
2
+ export { commitOf, git, gitOr, isDirty, topOf } from './git.ts';
3
+ export { preparedMark } from './seed.ts';
package/dist/git/index.js CHANGED
@@ -1,2 +1,3 @@
1
- export { checkoutFor, evict, infoOf, locate, overlay } from './checkout.js';
2
- export { commitOf, gitOr, topOf } from './git.js';
1
+ export { checkoutFor, evict, folderNamed, infoOf, locate, overlay, preparedOnce, } from './checkout.js';
2
+ export { commitOf, git, gitOr, isDirty, topOf } from './git.js';
3
+ export { preparedMark } from './seed.js';
@@ -10,7 +10,7 @@ import { readScenarios, registerReader } from '../../scenarios/index.js';
10
10
  import { validate } from '../../schema.js';
11
11
  import { broken, registerRunner } from '../kind.js';
12
12
  import { startPieceServer } from '../piece/server.js';
13
- import { envOf, handoverSettled, restart, restartable, stateDir, } from '../../services/index.js';
13
+ import { cwdOf, envOf, handoverSettled, restart, restartable, stateDir, } from '../../services/index.js';
14
14
  import { applyWorld } from '../../worlds/index.js';
15
15
  import { defaultExportOf, LiteralError } from './literal.js';
16
16
  const refuse = (says, line) => {
@@ -95,7 +95,7 @@ async function throughDriver(s, ctx) {
95
95
  const m = ctx.manifest;
96
96
  const svc = m.services[s.service];
97
97
  const running = ctx.running.find((r) => r.name === svc.name);
98
- const cwd = svc.cwd ? path.resolve(ctx.checkout, svc.cwd) : ctx.checkout;
98
+ const cwd = cwdOf(svc, running);
99
99
  const env = envOf(m, running);
100
100
  const drive = async (argv) => {
101
101
  const ran = await sh(`${svc.drive} ${argv.map(quote).join(' ')} --json`, { cwd, env, timeoutMs: 60_000 });
@@ -1,5 +1,5 @@
1
1
  export { fill, fillEnv, placeholdersIn } from './fill.ts';
2
2
  export { STARTER, STARTER_BLOCKS, STARTER_HEAD } from './init.ts';
3
3
  export { findManifest, hashOf, INERT_BY_DEFAULT, loadManifest, MANIFEST_FILE, manifestFrom } from './load.ts';
4
- export { KIND_BLOCK, KINDS, type Key, type Kind, type Manifest, type PathEntry, type Person, type Real, type Service, type Standin, type World, } from './types.ts';
4
+ export { KIND_BLOCK, KINDS, type Key, type Kind, type Manifest, type PathEntry, type Person, type Real, type Repository, type Service, type Standin, type World, } from './types.ts';
5
5
  export { readYaml } from './yaml.ts';
@@ -75,8 +75,16 @@ function serviceOf(name, s) {
75
75
  isolate: s.isolate ?? null,
76
76
  drive: s.drive ?? null,
77
77
  keys: s.keys ?? {},
78
+ repository: s.repository ?? null,
78
79
  };
79
80
  }
81
+ const AN_ADDRESS = /^(?:[a-z][a-z0-9+.-]*:\/\/|[\w.-]+@[\w.-]+:|[\w-]+(?:\.[\w-]+)+:)/i;
82
+ function repositoryOf(dir, name, r) {
83
+ const from = AN_ADDRESS.test(r.from)
84
+ ? r.from
85
+ : path.resolve(dir, r.from.replace(/^~(?=\/)/, process.env.HOME ?? '~'));
86
+ return { name, from, base: r.base ?? null, prepare: r.prepare ?? null };
87
+ }
80
88
  function keyOf(name, k) {
81
89
  if (k === null)
82
90
  return { name, from: null, find: null };
@@ -150,6 +158,9 @@ function checkWhatTheSchemaCant(m) {
150
158
  };
151
159
  defaults('person', Object.values(m.people), 'people');
152
160
  defaults('world', Object.values(m.worlds), 'worlds');
161
+ for (const s of Object.values(m.services))
162
+ if (s.repository !== null)
163
+ named('The repository', s.repository, Object.keys(m.repositories), ['services', s.name, 'repository']);
153
164
  for (const s of Object.values(m.services))
154
165
  for (const [env, key] of Object.entries(s.keys)) {
155
166
  named('The key', key, Object.keys(m.keys), ['services', s.name, 'keys', env]);
@@ -249,6 +260,7 @@ export function manifestFrom(text, file) {
249
260
  affected: { graph: raw.affected?.graph ?? null, inert: raw.affected?.inert ?? [...INERT_BY_DEFAULT] },
250
261
  budget: { services: raw.budget?.services ?? 1, checkouts: raw.budget?.checkouts ?? 3 },
251
262
  keys: Object.fromEntries(Object.entries(raw.keys ?? {}).map(([n, k]) => [n, keyOf(n, k)])),
263
+ repositories: Object.fromEntries(Object.entries(raw.repositories ?? {}).map(([n, r]) => [n, repositoryOf(dir, n, r)])),
252
264
  lineOf: (at, key) => read.lineOf(at, key),
253
265
  };
254
266
  checkWhatTheSchemaCant(m);
@@ -47,6 +47,18 @@ export interface RawManifest {
47
47
  checkouts?: number;
48
48
  };
49
49
  keys?: Record<string, RawKey>;
50
+ repositories?: Record<string, RawRepository>;
51
+ }
52
+ export interface RawRepository {
53
+ from: string;
54
+ base?: string;
55
+ prepare?: string;
56
+ }
57
+ export interface Repository {
58
+ name: string;
59
+ from: string;
60
+ base: string | null;
61
+ prepare: string | null;
50
62
  }
51
63
  export type RawKey = string | null | {
52
64
  from?: string;
@@ -78,6 +90,7 @@ export interface RawService {
78
90
  };
79
91
  drive?: string;
80
92
  keys?: Record<string, string>;
93
+ repository?: string;
81
94
  }
82
95
  export type Ready = {
83
96
  http: string;
@@ -102,6 +115,7 @@ export interface Service {
102
115
  } | null;
103
116
  drive: string | null;
104
117
  keys: Record<string, string>;
118
+ repository: string | null;
105
119
  }
106
120
  export type Real = 'local' | 'stand-in' | 'real';
107
121
  export interface Step {
@@ -267,5 +281,6 @@ export interface Manifest {
267
281
  checkouts: number;
268
282
  };
269
283
  keys: Record<string, Key>;
284
+ repositories: Record<string, Repository>;
270
285
  lineOf(at: readonly string[], key?: string): number | undefined;
271
286
  }
@@ -0,0 +1,16 @@
1
+ import type { Manifest } from '../manifest/index.ts';
2
+ export interface Copy {
3
+ path: string;
4
+ ref: string | null;
5
+ commit: string | null;
6
+ dirty: boolean;
7
+ }
8
+ export type Copies = Record<string, Copy>;
9
+ export declare const repositoriesDir: (m: Manifest) => string;
10
+ export declare function copyOf(m: Manifest, name: string, given: string | null, forSet: string, progress: (line: string) => void, cwd?: string): Promise<Copy>;
11
+ export declare function evictCopies(m: Manifest, name: string): string[];
12
+ export declare function refsOf(given: readonly string[], flag: string): Record<string, string>;
13
+ export declare function refuseUnknownRepositories(m: Manifest, given: Readonly<Record<string, string>>): void;
14
+ export declare function copiesFor(m: Manifest, given: Readonly<Record<string, string>>, forSet: string, progress: (line: string) => void, cwd?: string): Promise<Copies>;
15
+ export declare const pinnedOf: (copies: Readonly<Copies>) => Record<string, string>;
16
+ export declare const rootsOf: (copies: Readonly<Copies> | undefined) => Record<string, string>;
@@ -0,0 +1,132 @@
1
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, utimesSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { RehearseError, errorText, usage } from '../errors.js';
4
+ import { commitOf, folderNamed, git, gitOr, isDirty, preparedMark, preparedOnce, topOf, } from '../git/index.js';
5
+ import { checkoutKey, runningServices, stateDir } from '../services/index.js';
6
+ export const repositoriesDir = (m) => path.join(stateDir(m.dir), 'repositories');
7
+ const cloneOf = (m, name) => path.join(repositoriesDir(m), `${name}.git`);
8
+ const copiesOf = (m, name) => path.join(repositoriesDir(m), name);
9
+ const WITH_CREDENTIALS = /(?<=:\/\/)[^/@\s]+@/g;
10
+ const withoutCredentials = (text) => text.replace(WITH_CREDENTIALS, '');
11
+ const usedHere = new Set();
12
+ function cloned(m, r, progress) {
13
+ const clone = cloneOf(m, r.name);
14
+ const from = withoutCredentials(r.from);
15
+ if (existsSync(clone)) {
16
+ if (gitOr(clone, ['config', '--get', 'remote.origin.url']) !== r.from) {
17
+ progress(`${r.name} now comes from ${from}.`);
18
+ git(clone, ['remote', 'set-url', 'origin', r.from]);
19
+ }
20
+ const fetched = gitOr(clone, [
21
+ 'fetch',
22
+ '--quiet',
23
+ '--prune',
24
+ 'origin',
25
+ '+refs/heads/*:refs/heads/*',
26
+ '+refs/tags/*:refs/tags/*',
27
+ ]);
28
+ if (fetched === null)
29
+ progress(`Rehearse couldn't fetch ${r.name} from ${from}, so it uses what it fetched before.`);
30
+ return clone;
31
+ }
32
+ mkdirSync(repositoriesDir(m), { recursive: true });
33
+ progress(`Cloning ${r.name} from ${from}`);
34
+ const into = `${clone}.${process.pid}.cloning`;
35
+ rmSync(into, { recursive: true, force: true });
36
+ try {
37
+ git(repositoriesDir(m), ['clone', '--bare', '--quiet', r.from, into]);
38
+ renameSync(into, clone);
39
+ }
40
+ catch (error) {
41
+ rmSync(into, { recursive: true, force: true });
42
+ if (!existsSync(clone))
43
+ throw new RehearseError('git', withoutCredentials(`Rehearse can't clone ${r.name} from ${r.from}: ${errorText(error)}`));
44
+ }
45
+ return clone;
46
+ }
47
+ const baseOf = (clone, r) => r.base ?? gitOr(clone, ['symbolic-ref', '--short', 'HEAD']) ?? 'main';
48
+ const dirtyIn = (folder) => {
49
+ const status = gitOr(folder, ['status', '--porcelain', '--untracked-files=all']);
50
+ return status === null || status !== '';
51
+ };
52
+ export async function copyOf(m, name, given, forSet, progress, cwd = process.cwd()) {
53
+ const r = m.repositories[name];
54
+ if (!r)
55
+ throw new RehearseError('usage', `There is no repository “${name}” in the manifest.`, { exit: 2 });
56
+ const folder = given === null ? null : folderNamed(given, cwd);
57
+ if (folder !== null)
58
+ return { path: folder, ref: null, commit: commitOf(folder), dirty: dirtyIn(folder) };
59
+ const clone = cloned(m, r, progress);
60
+ const ref = given ?? baseOf(clone, r);
61
+ const commit = commitOf(clone, ref);
62
+ if (commit === null)
63
+ throw new RehearseError('git', `${ref} isn't a branch, tag or commit of ${name} (${withoutCredentials(r.from)}).${r.base === null && given === null ? ' Say its base in rehearse.yaml.' : ''}`);
64
+ const dir = path.join(copiesOf(m, name), `${commit.slice(0, 12)}@${checkoutKey(forSet)}`);
65
+ if (!existsSync(dir)) {
66
+ mkdirSync(copiesOf(m, name), { recursive: true });
67
+ progress(`Checking out ${name} at ${ref} (${commit.slice(0, 12)}) into ${dir}`);
68
+ gitOr(clone, ['worktree', 'prune']);
69
+ git(clone, ['worktree', 'add', '--detach', dir, commit]);
70
+ }
71
+ await preparedOnce(dir, { prepare: r.prepare, seed: m.seed, given: `${name} at ${ref}` }, progress);
72
+ const now = new Date();
73
+ utimesSync(dir, now, now);
74
+ usedHere.add(path.resolve(dir));
75
+ evictCopies(m, name);
76
+ return { path: dir, ref, commit, dirty: isDirty(dir) };
77
+ }
78
+ export function evictCopies(m, name) {
79
+ const root = copiesOf(m, name);
80
+ if (!existsSync(root))
81
+ return [];
82
+ const dirs = readdirSync(root, { withFileTypes: true })
83
+ .filter((d) => d.isDirectory())
84
+ .map((d) => path.join(root, d.name))
85
+ .sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs);
86
+ const gone = [];
87
+ const clone = cloneOf(m, name);
88
+ const inUse = [
89
+ ...usedHere,
90
+ ...runningServices(m.dir).flatMap((r) => (r.root === undefined ? [] : [r.root])),
91
+ ];
92
+ for (const dir of dirs.slice(m.budget.checkouts * 2)) {
93
+ if (inUse.some((k) => path.resolve(k) === path.resolve(dir)))
94
+ continue;
95
+ if (existsSync(clone))
96
+ gitOr(clone, ['worktree', 'remove', '--force', dir]);
97
+ rmSync(dir, { recursive: true, force: true });
98
+ rmSync(preparedMark(dir), { force: true });
99
+ gone.push(dir);
100
+ }
101
+ if (existsSync(clone))
102
+ gitOr(clone, ['worktree', 'prune']);
103
+ return gone;
104
+ }
105
+ const A_REPOSITORY_NAMED = /^([A-Za-z_][A-Za-z0-9_-]*)=(.+)$/;
106
+ export function refsOf(given, flag) {
107
+ const refs = {};
108
+ for (const value of given) {
109
+ const named = A_REPOSITORY_NAMED.exec(value);
110
+ if (!named)
111
+ throw usage(`--${flag} takes a repository's name, = and a ref or folder, as in api=feature-x: not “${value}”.`);
112
+ const [, name = '', ref = ''] = named;
113
+ if (name in refs)
114
+ throw usage(`--${flag} names ${name} twice.`);
115
+ refs[name] = ref;
116
+ }
117
+ return refs;
118
+ }
119
+ export function refuseUnknownRepositories(m, given) {
120
+ for (const name of Object.keys(given))
121
+ if (!(name in m.repositories))
122
+ throw usage(`There is no repository “${name}”${Object.keys(m.repositories).length ? `: the manifest names ${Object.keys(m.repositories).join(', ')}` : ' in the manifest'}.`);
123
+ }
124
+ export async function copiesFor(m, given, forSet, progress, cwd = process.cwd()) {
125
+ refuseUnknownRepositories(m, given);
126
+ const out = {};
127
+ for (const name of Object.keys(m.repositories))
128
+ out[name] = await copyOf(m, name, given[name] ?? null, topOf(forSet) ?? forSet, progress, cwd);
129
+ return out;
130
+ }
131
+ export const pinnedOf = (copies) => Object.fromEntries(Object.entries(copies).map(([name, c]) => [name, c.ref === null ? c.path : (c.commit ?? c.path)]));
132
+ export const rootsOf = (copies) => Object.fromEntries(Object.entries(copies ?? {}).map(([name, c]) => [name, c.path]));
@@ -0,0 +1 @@
1
+ export { copiesFor, copyOf, evictCopies, pinnedOf, refsOf, refuseUnknownRepositories, repositoriesDir, rootsOf, type Copies, type Copy, } from './copies.ts';
@@ -0,0 +1 @@
1
+ export { copiesFor, copyOf, evictCopies, pinnedOf, refsOf, refuseUnknownRepositories, repositoriesDir, rootsOf, } from './copies.js';
@@ -1,13 +1,14 @@
1
1
  import type { KindRunner } from '../kinds/index.ts';
2
2
  import { type Manifest } from '../manifest/index.ts';
3
3
  import type { Scenario } from '../scenarios/index.ts';
4
- import type { Observation } from './observation.ts';
4
+ import { type Observation } from './observation.ts';
5
5
  export declare function hashOfContents(at: string): string;
6
6
  export declare function manifestPartsUsedBy(m: Manifest, services: readonly string[], world: string | null, kind: string): unknown;
7
7
  export declare function groupsOf(m: Manifest, scenarios: readonly Scenario[], world: string | null): Promise<Map<string, string>>;
8
8
  export interface KeyParts {
9
9
  group?: string | null;
10
10
  commit: string;
11
+ copies?: Readonly<Record<string, string>> | undefined;
11
12
  scenario: Scenario;
12
13
  world: string | null;
13
14
  person: string | null;
package/dist/run/cache.js CHANGED
@@ -4,6 +4,7 @@ import path from 'node:path';
4
4
  import { hashOf } from '../manifest/index.js';
5
5
  import { stateDir } from '../services/index.js';
6
6
  import { chainOf } from '../worlds/index.js';
7
+ import { dirtyAnywhere } from './observation.js';
7
8
  export function hashOfContents(at) {
8
9
  const hash = createHash('sha256');
9
10
  const walk = (p, rel) => {
@@ -62,6 +63,7 @@ export function cacheKeyOf(p) {
62
63
  const services = p.runner.services(p.scenario, p.manifest);
63
64
  return hashOf({
64
65
  commit: p.commit,
66
+ ...(p.copies && { copies: p.copies }),
65
67
  id: p.scenario.id,
66
68
  definition: p.scenario.definition,
67
69
  context: p.scenario.context ?? null,
@@ -87,7 +89,7 @@ export function cached(m, commit, key) {
87
89
  }
88
90
  const didntAnswer = (o) => o.failures.some((f) => typeof f.got === 'string' && /^It didn’t answer|timed out/.test(f.got));
89
91
  export function keep(m, o) {
90
- if (!o.cacheKey || !o.checkout.commit || o.checkout.dirty || o.broke)
92
+ if (!o.cacheKey || !o.checkout.commit || dirtyAnywhere(o.checkout) || o.broke)
91
93
  return false;
92
94
  if (didntAnswer(o))
93
95
  return false;
@@ -1,5 +1,5 @@
1
1
  export { cached, cacheKeyOf, groupsOf, keep, type KeyParts } from './cache.ts';
2
- export type { CheckoutInfo, Observation } from './observation.ts';
2
+ export { commitsOf, dirtyAnywhere, withCopies, type CheckoutInfo, type Observation } from './observation.ts';
3
3
  export { slotsFor, type Slots } from './parallel.ts';
4
4
  export { applyWorld, placedIn, runSide, runSideSharing, type NotRun, type SessionOptions, type SideRun, } from './session.ts';
5
5
  export { baseVars } from './vars.ts';
package/dist/run/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { cached, cacheKeyOf, groupsOf, keep } from './cache.js';
2
+ export { commitsOf, dirtyAnywhere, withCopies } from './observation.js';
2
3
  export { slotsFor } from './parallel.js';
3
4
  export { applyWorld, placedIn, runSide, runSideSharing, } from './session.js';
4
5
  export { baseVars } from './vars.js';
@@ -5,7 +5,11 @@ export interface CheckoutInfo {
5
5
  ref: string | null;
6
6
  commit: string | null;
7
7
  dirty: boolean;
8
+ repositories?: Record<string, CheckoutInfo>;
8
9
  }
10
+ export declare const withCopies: (info: CheckoutInfo, copies: Readonly<Record<string, CheckoutInfo>> | undefined) => CheckoutInfo;
11
+ export declare const dirtyAnywhere: (info: CheckoutInfo) => boolean;
12
+ export declare const commitsOf: (info: CheckoutInfo) => Record<string, string> | undefined;
9
13
  export interface Observation {
10
14
  v: 1;
11
15
  ok: boolean;
@@ -1 +1,5 @@
1
- export {};
1
+ export const withCopies = (info, copies) => (copies && Object.keys(copies).length ? { ...info, repositories: { ...copies } } : info);
2
+ export const dirtyAnywhere = (info) => info.dirty || Object.values(info.repositories ?? {}).some((c) => c.dirty || c.commit === null);
3
+ export const commitsOf = (info) => info.repositories
4
+ ? Object.fromEntries(Object.entries(info.repositories).map(([name, c]) => [name, c.commit ?? '']))
5
+ : undefined;
@@ -1,9 +1,10 @@
1
1
  import { type Scenario } from '../scenarios/index.ts';
2
2
  import { type StandinUse } from '../kinds/index.ts';
3
3
  import { type Manifest } from '../manifest/index.ts';
4
+ import { type Copies } from '../repositories/index.ts';
4
5
  import { applyWorld } from '../worlds/index.ts';
5
6
  export { applyWorld };
6
- import type { CheckoutInfo, Observation } from './observation.ts';
7
+ import { type CheckoutInfo, type Observation } from './observation.ts';
7
8
  import { type Slots } from './parallel.ts';
8
9
  export interface SessionOptions {
9
10
  world: string | null;
@@ -14,6 +15,7 @@ export interface SessionOptions {
14
15
  ref: string | null;
15
16
  groups?: ReadonlyMap<string, string>;
16
17
  parallel?: number;
18
+ copies?: Copies;
17
19
  }
18
20
  export interface NotRun {
19
21
  scenario: Scenario;
@@ -7,11 +7,13 @@ import { broken, runnerOf, } from '../kinds/index.js';
7
7
  import { knowKeys, withoutKeysDeep } from '../keys/index.js';
8
8
  import { fill } from '../manifest/index.js';
9
9
  import { signIn } from '../people/index.js';
10
- import { stateDir, bringDown, bringUp, handoverSettled, inUse, liveServices, makeRoom, release, standinsFor, } from '../services/index.js';
10
+ import { rootsOf } from '../repositories/index.js';
11
+ import { stateDir, bringDown, bringUp, handoverSettled, inUse, liveServices, makeRoom, release, standinsFor, upFromAnotherCopy, } from '../services/index.js';
11
12
  import { VERSION } from '../version.js';
12
13
  import { applyWorld, chainOf } from '../worlds/index.js';
13
14
  export { applyWorld };
14
15
  import { cacheKeyOf, groupsOf } from './cache.js';
16
+ import { commitsOf, dirtyAnywhere, withCopies } from './observation.js';
15
17
  import { inTurn, slotsFor, unitsOf } from './parallel.js';
16
18
  import { baseVars } from './vars.js';
17
19
  const worldOf = (s, o) => o.world ?? s.world;
@@ -100,14 +102,16 @@ function undeclaredIn(m, needed) {
100
102
  }
101
103
  : null;
102
104
  }
103
- function upInAnotherWorld(checkout, world, leftUp) {
105
+ function leftUpOtherwise(scope, world, leftUp) {
104
106
  const other = leftUp.find((r) => (r.world ?? null) !== world);
105
- return other
106
- ? {
107
+ if (other)
108
+ return {
107
109
  step: 'world',
108
- says: `${other.name} is already up in ${checkout} with ${other.world ? `the world ${other.world}` : 'no world Rehearse built'}, not ${world ?? 'no world'}: run with --world ${other.world ?? '…'}, or stop it with \`rehearse down\`.`,
109
- }
110
- : null;
110
+ says: `${other.name} is already up in ${scope.checkout} with ${other.world ? `the world ${other.world}` : 'no world Rehearse built'}, not ${world ?? 'no world'}: run with --world ${other.world ?? '…'}, or stop it with \`rehearse down\`.`,
111
+ };
112
+ const roots = rootsOf(scope.o.copies);
113
+ const fromAnotherCopy = leftUp.map((r) => upFromAnotherCopy(scope.m, r, roots)).find(Boolean);
114
+ return fromAnotherCopy ? { step: 'up', says: fromAnotherCopy } : null;
111
115
  }
112
116
  const everyOneOf = (group, why) => group.map((s) => ({ scenario: s, ...why, byItsRunner: false }));
113
117
  async function runGroup(side, world, group, runners, needed, upAlready, rehearseCanVouchForTheirState) {
@@ -132,6 +136,7 @@ async function runGroup(side, world, group, runners, needed, upAlready, rehearse
132
136
  world,
133
137
  real: o.real,
134
138
  vars: vars(),
139
+ roots: rootsOf(o.copies),
135
140
  progress: o.progress,
136
141
  });
137
142
  started.push(r);
@@ -224,10 +229,11 @@ async function runGroup(side, world, group, runners, needed, upAlready, rehearse
224
229
  at: new Date().toISOString(),
225
230
  rehearse: VERSION,
226
231
  runner: runner.version,
227
- cacheKey: side.info.commit && !side.info.dirty && rehearseCanVouchForTheirState
232
+ cacheKey: side.info.commit && !dirtyAnywhere(side.info) && rehearseCanVouchForTheirState
228
233
  ? cacheKeyOf({
229
234
  group: side.groups.get(s.id) ?? null,
230
235
  commit: side.info.commit,
236
+ copies: commitsOf(side.info),
231
237
  scenario: s,
232
238
  world,
233
239
  person,
@@ -280,7 +286,7 @@ async function oneWorldAfterAnother(scope, worlds, side) {
280
286
  }
281
287
  const running = await liveServices(m, checkout);
282
288
  const leftUp = running.filter((r) => plan.needed.has(r.name));
283
- const elsewhere = upInAnotherWorld(checkout, world, leftUp);
289
+ const elsewhere = leftUpOtherwise(scope, world, leftUp);
284
290
  if (elsewhere) {
285
291
  side.notRun.push(...everyOneOf(group, elsewhere).map(asNotRun));
286
292
  continue;
@@ -327,7 +333,7 @@ async function inTurns(scope, worlds, side, slots) {
327
333
  for (const [world, group] of worlds) {
328
334
  const plan = await planOf(m, world, group);
329
335
  const leftUp = upAtFirst.filter((r) => plan.needed.has(r.name));
330
- const refused = undeclaredIn(m, plan.needed) ?? upInAnotherWorld(checkout, world, leftUp);
336
+ const refused = undeclaredIn(m, plan.needed) ?? leftUpOtherwise(scope, world, leftUp);
331
337
  if (refused) {
332
338
  planned.push({ refused: everyOneOf(group, refused) });
333
339
  continue;
@@ -365,7 +371,7 @@ export function runSide(m, checkout, scenarios, o) {
365
371
  export function runSideSharing(m, checkout, scenarios, o, slots) {
366
372
  return inUse(checkout, async () => {
367
373
  const side = {
368
- checkout: infoOf(m, checkout, o.ref),
374
+ checkout: withCopies(infoOf(m, checkout, o.ref), o.copies),
369
375
  observations: new Map(),
370
376
  broke: null,
371
377
  notRun: [],
@@ -379,7 +385,7 @@ export function runSideSharing(m, checkout, scenarios, o, slots) {
379
385
  side.broke = { step: 'overlay', says: errorText(error) };
380
386
  return side;
381
387
  }
382
- side.checkout = infoOf(m, checkout, o.ref);
388
+ side.checkout = withCopies(infoOf(m, checkout, o.ref), o.copies);
383
389
  const manifestAs = manifestFolderAsOnBothSides(m);
384
390
  const keepDir = path.join(stateDir(m.dir), 'runs', `${Date.now().toString(36)}-${path.basename(checkout)}`);
385
391
  mkdirSync(keepDir, { recursive: true });
@@ -393,6 +399,10 @@ export function runSideSharing(m, checkout, scenarios, o, slots) {
393
399
  placed: (v) => placedIn(v, [
394
400
  [path.resolve(checkout), '{{checkout}}'],
395
401
  [path.resolve(m.dir), manifestAs],
402
+ ...Object.entries(o.copies ?? {}).map(([name, c]) => [
403
+ path.resolve(c.path),
404
+ `{{${name}_checkout}}`,
405
+ ]),
396
406
  ]),
397
407
  };
398
408
  const worlds = new Map();
@@ -1,2 +1,2 @@
1
- export { alive, runningServices, stateDir, type Running } from './registry.ts';
2
- export { bringDown, bringUp, downStartedHere, envOf, freePort, handoverSettled, inUse, liveServices, makeRoom, release, restart, restartable, standinsFor, } from './service.ts';
1
+ export { alive, checkoutKey, runningServices, stateDir, type Running } from './registry.ts';
2
+ export { bringDown, bringUp, cwdOf, downStartedHere, envOf, freePort, handoverSettled, inUse, liveServices, makeRoom, release, restart, restartable, rootOf, standinsFor, upFromAnotherCopy, } from './service.ts';
@@ -1,2 +1,2 @@
1
- export { alive, runningServices, stateDir } from './registry.js';
2
- export { bringDown, bringUp, downStartedHere, envOf, freePort, handoverSettled, inUse, liveServices, makeRoom, release, restart, restartable, standinsFor, } from './service.js';
1
+ export { alive, checkoutKey, runningServices, stateDir } from './registry.js';
2
+ export { bringDown, bringUp, cwdOf, downStartedHere, envOf, freePort, handoverSettled, inUse, liveServices, makeRoom, release, restart, restartable, rootOf, standinsFor, upFromAnotherCopy, } from './service.js';
@@ -1,6 +1,7 @@
1
1
  export interface Running {
2
2
  name: string;
3
3
  checkout: string;
4
+ root?: string;
4
5
  pid: number;
5
6
  port: number | null;
6
7
  url: string | null;