@kurvball/rehearse 1.3.0 → 1.5.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/README.md +5 -2
  2. package/dist/cli.js +4 -1
  3. package/dist/commands/announce.d.ts +16 -0
  4. package/dist/commands/announce.js +77 -0
  5. package/dist/commands/clean.js +2 -2
  6. package/dist/commands/command.d.ts +1 -0
  7. package/dist/commands/command.js +8 -0
  8. package/dist/commands/compare.d.ts +4 -2
  9. package/dist/commands/compare.js +25 -22
  10. package/dist/commands/index.d.ts +4 -0
  11. package/dist/commands/index.js +8 -0
  12. package/dist/commands/mcp.d.ts +4 -0
  13. package/dist/commands/mcp.js +44 -0
  14. package/dist/commands/stage.js +4 -3
  15. package/dist/commands/synopsis.d.ts +19 -0
  16. package/dist/commands/synopsis.js +26 -0
  17. package/dist/commands/tools.d.ts +11 -0
  18. package/dist/commands/tools.js +118 -0
  19. package/dist/compare/announce.d.ts +14 -0
  20. package/dist/compare/announce.js +19 -1
  21. package/dist/compare/changesets.d.ts +9 -0
  22. package/dist/compare/changesets.js +105 -0
  23. package/dist/compare/compare.d.ts +1 -0
  24. package/dist/compare/compare.js +8 -13
  25. package/dist/compare/index.d.ts +2 -1
  26. package/dist/compare/index.js +2 -1
  27. package/dist/drive/daemon.js +2 -1
  28. package/dist/drive/grammar.d.ts +2 -0
  29. package/dist/drive/grammar.js +14 -4
  30. package/dist/drive/index.d.ts +1 -1
  31. package/dist/drive/index.js +1 -1
  32. package/dist/git/checkout.d.ts +7 -0
  33. package/dist/git/checkout.js +9 -2
  34. package/dist/git/index.d.ts +1 -1
  35. package/dist/git/index.js +1 -1
  36. package/dist/kinds/flow/kind.js +2 -1
  37. package/dist/kinds/piece/conventions.d.ts +1 -1
  38. package/dist/kinds/piece/conventions.js +1 -2
  39. package/dist/kinds/piece/kind.js +2 -0
  40. package/dist/kinds/piece/server.d.ts +1 -0
  41. package/dist/kinds/piece/server.js +1 -1
  42. package/dist/mcp/call.d.ts +13 -0
  43. package/dist/mcp/call.js +53 -0
  44. package/dist/mcp/index.d.ts +4 -0
  45. package/dist/mcp/index.js +3 -0
  46. package/dist/mcp/output.d.ts +3 -0
  47. package/dist/mcp/output.js +43 -0
  48. package/dist/mcp/server.d.ts +16 -0
  49. package/dist/mcp/server.js +152 -0
  50. package/dist/mcp/tool.d.ts +19 -0
  51. package/dist/mcp/tool.js +1 -0
  52. package/dist/services/service.js +11 -2
  53. package/dist/stage/api.d.ts +1 -0
  54. package/dist/stage/api.js +1 -0
  55. package/dist/stage/server.d.ts +1 -0
  56. package/dist/stage/server.js +2 -1
  57. package/llms.txt +5 -3
  58. package/package.json +4 -2
  59. package/skill/rehearse/SKILL.md +56 -2
@@ -0,0 +1,105 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { RehearseError } from '../errors.js';
4
+ import { gitOr } from '../git/index.js';
5
+ const CHANGESETS = '.changeset';
6
+ const NOT_A_CHANGESET = new Set(['README.md']);
7
+ const FENCE = /^(`{3,}|~{3,})\s*([^\s`~]*)/;
8
+ const TARGET = /^([a-z][a-z0-9-]*):\s*(.*)$/;
9
+ const OWN_WHY = /^(.*?)\s+—(?:\s+(.*))?$/;
10
+ const treeOf = (side) => (typeof side === 'string' ? { folder: side } : side);
11
+ const isAChangeset = (name) => name.endsWith('.md') && !NOT_A_CHANGESET.has(name);
12
+ function namesIn(tree) {
13
+ if ('folder' in tree) {
14
+ const folder = path.join(tree.folder, CHANGESETS);
15
+ return existsSync(folder) ? readdirSync(folder) : [];
16
+ }
17
+ const listed = gitOr(tree.repo, ['ls-tree', '--name-only', tree.commit, `${CHANGESETS}/`]) ?? '';
18
+ return listed
19
+ .split('\n')
20
+ .filter(Boolean)
21
+ .map((file) => path.posix.basename(file));
22
+ }
23
+ const changesetsIn = (tree) => new Set(namesIn(tree).filter(isAChangeset));
24
+ function textIn(tree, file) {
25
+ if ('folder' in tree)
26
+ return readFileSync(path.join(tree.folder, file), 'utf8');
27
+ return gitOr(tree.repo, ['show', `${tree.commit}:${file}`]) ?? '';
28
+ }
29
+ export function addedChangesets(base, head) {
30
+ const onBase = changesetsIn(treeOf(base));
31
+ return [...changesetsIn(treeOf(head))]
32
+ .filter((name) => !onBase.has(name))
33
+ .sort()
34
+ .map((name) => `${CHANGESETS}/${name}`);
35
+ }
36
+ function bodyStart(lines) {
37
+ if (lines[0]?.trim() !== '---')
38
+ return 0;
39
+ const end = lines.findIndex((line, i) => i > 0 && line.trim() === '---');
40
+ return end === -1 ? lines.length : end + 1;
41
+ }
42
+ function closes(line, fence) {
43
+ return line.startsWith(fence) && new RegExp(`^\\${fence[0]}+$`).test(line);
44
+ }
45
+ function proseAndBlocks(lines, from) {
46
+ const prose = [];
47
+ const blocks = [];
48
+ let open = null;
49
+ for (let i = from; i < lines.length; i += 1) {
50
+ const text = lines[i].trim();
51
+ if (open) {
52
+ if (closes(text, open.fence))
53
+ open = null;
54
+ else
55
+ open.block.lines.push({ text, line: i + 1 });
56
+ continue;
57
+ }
58
+ const fence = FENCE.exec(text);
59
+ if (fence) {
60
+ open = { fence: fence[1], block: { announce: fence[2] === 'announce', lines: [] } };
61
+ blocks.push(open.block);
62
+ continue;
63
+ }
64
+ prose.push(text);
65
+ }
66
+ return { prose, blocks };
67
+ }
68
+ function summaryOf(prose) {
69
+ const first = prose.findIndex((line) => line !== '');
70
+ if (first === -1)
71
+ return '';
72
+ const end = prose.findIndex((line, i) => i > first && line === '');
73
+ return prose
74
+ .slice(first, end === -1 ? undefined : end)
75
+ .join(' ')
76
+ .trim();
77
+ }
78
+ export function announcedIn(text, file) {
79
+ const lines = text.split(/\r?\n/);
80
+ const { prose, blocks } = proseAndBlocks(lines, bodyStart(lines));
81
+ const summary = summaryOf(prose);
82
+ const refuse = (line, says) => new RehearseError('announce', `${file}:${line}: ${says}`, { file, line });
83
+ const announced = [];
84
+ for (const { text: entry, line } of blocks.filter((b) => b.announce).flatMap((b) => b.lines)) {
85
+ if (entry === '' || entry.startsWith('#'))
86
+ continue;
87
+ const target = TARGET.exec(entry);
88
+ if (!target)
89
+ throw refuse(line, `Rehearse can't read “${entry}”: write each line as <tool>: <target>, such as rehearse: <scenario>.`);
90
+ if (target[1] !== 'rehearse')
91
+ continue;
92
+ const own = OWN_WHY.exec(target[2]);
93
+ const scenario = (own ? own[1] : target[2]).trim();
94
+ const why = own?.[2]?.trim() || summary;
95
+ if (!scenario)
96
+ throw refuse(line, 'The line names no scenario after rehearse:.');
97
+ if (!why)
98
+ throw refuse(line, `The line announces ${scenario} with no why: give the changeset a summary, or end the line with — and why.`);
99
+ announced.push({ scenario, why, file, line });
100
+ }
101
+ return announced;
102
+ }
103
+ export function announcedByChangesets(base, head) {
104
+ return addedChangesets(base, head).flatMap((file) => announcedIn(textIn(treeOf(head), file), file));
105
+ }
@@ -13,6 +13,7 @@ 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;
@@ -1,14 +1,14 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { 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
8
  import { cached, cacheKeyOf, groupsOf, keep, runSideSharing, slotsFor, } from '../run/index.js';
9
9
  import { readScenarios, refOf, globToRegExp, } from '../scenarios/index.js';
10
10
  import { runningServices, stateDir } from '../services/index.js';
11
- import { announcementFor, readAnnouncement } from './announce.js';
11
+ import { announcedBy, announcementFor } from './announce.js';
12
12
  import { nonZeroCounts, noCounts, rulesOf } from './setaside.js';
13
13
  import { lineOf, verdictOf } from './verdict.js';
14
14
  const emptyCounts = () => ({
@@ -112,15 +112,10 @@ export async function compare(m, o) {
112
112
  }
113
113
  if (path.resolve(base.path) === path.resolve(head.path))
114
114
  throw new RehearseError('usage', `The base and the head are the same checkout (${head.path}): name a base ref, or another folder.`, { exit: 2 });
115
- const announced = [];
116
- const announceFile = o.announce ??
117
- (existsSync(path.join(stateDir(m.dir), 'announce.yaml'))
118
- ? path.join(stateDir(m.dir), 'announce.yaml')
119
- : null);
120
- if (announceFile)
121
- announced.push(...readAnnouncement(path.resolve(o.repo, announceFile)));
122
- for (const id of o.said)
123
- announced.push({ scenario: id, why: 'Said on the command line.' });
115
+ const announced = announcedBy(m, o, () => ({
116
+ base: { folder: topOf(base.path) ?? base.path },
117
+ head: { folder: topOf(head.path) ?? head.path },
118
+ }));
124
119
  const headRead = await readScenarios(m, head.path);
125
120
  const baseRead = await readScenarios(m, base.path);
126
121
  let headScenarios = select(headRead.scenarios, o.ids);
@@ -285,7 +280,7 @@ export async function compare(m, o) {
285
280
  if (mayBeATypo)
286
281
  out.refused.push({
287
282
  side: 'head',
288
- file: announceFile ?? '--said',
283
+ file: a.from ?? '--said',
289
284
  says: `The announcement names ${a.scenario}, which matches no scenario compared.`,
290
285
  });
291
286
  if (named.length > 0 && named.every((c) => !c.changed))
@@ -1,4 +1,5 @@
1
- export { readAnnouncement } from './announce.ts';
1
+ export { announcedBy, readAnnouncement, SAID_ON_THE_COMMAND_LINE, type Announced, type AnnouncedFrom, } from './announce.ts';
2
+ export { addedChangesets, announcedByChangesets, announcedIn, type ChangesetAnnounced, } from './changesets.ts';
2
3
  export { changedFiles, compare, type CompareOptions, type Compared, type Comparison } from './compare.ts';
3
4
  export { clip, jsonDifferences, lineHunks, textDifferences, type Difference } from './diff.ts';
4
5
  export { noCounts, noRules, setAsideJson, setAsideText, type Counts as AsideCounts, type Rules, } from './setaside.ts';
@@ -1,4 +1,5 @@
1
- export { readAnnouncement } from './announce.js';
1
+ export { announcedBy, readAnnouncement, SAID_ON_THE_COMMAND_LINE, } from './announce.js';
2
+ export { addedChangesets, announcedByChangesets, announcedIn, } from './changesets.js';
2
3
  export { changedFiles, compare } from './compare.js';
3
4
  export { clip, jsonDifferences, lineHunks, textDifferences } from './diff.js';
4
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,
@@ -79,6 +79,8 @@ export declare const exitOf: (r: DriveResult) => number;
79
79
  export declare function stepCommand(step: Step): Command;
80
80
  export declare function stepWords(step: Step): string;
81
81
  export declare function stepOf(v: unknown, n: number): Step;
82
+ export declare const STEP_FLAGS: Readonly<Record<Verb, readonly string[]>>;
83
+ export declare const STEP_WORDS: Readonly<Record<Verb, string | null>>;
82
84
  export type Parsed = {
83
85
  ok: true;
84
86
  command: Command;
@@ -163,7 +163,7 @@ export function stepOf(v, n) {
163
163
  throw new Error(`Step ${n} has more than its ${verb}: ${extra.join(', ')}.`);
164
164
  return s;
165
165
  }
166
- const FLAGS = {
166
+ export const STEP_FLAGS = {
167
167
  start: ['service', 'piece', 'world', 'as', 'on', 'start', 'scheme'],
168
168
  click: ['name', 'role'],
169
169
  type: [],
@@ -174,6 +174,17 @@ const FLAGS = {
174
174
  record: [],
175
175
  stop: [],
176
176
  };
177
+ export const STEP_WORDS = {
178
+ start: null,
179
+ click: null,
180
+ type: 'text',
181
+ key: 'key',
182
+ fill: null,
183
+ snapshot: null,
184
+ screenshot: 'file',
185
+ record: 'file',
186
+ stop: null,
187
+ };
177
188
  export function parseDrive(argv) {
178
189
  const [verb, ...rest] = argv;
179
190
  if (verb === undefined || verb.startsWith('--'))
@@ -200,7 +211,7 @@ export function parseDrive(argv) {
200
211
  i += eq === -1 ? 1 : 0;
201
212
  continue;
202
213
  }
203
- if (!FLAGS[v].includes(flag))
214
+ if (!STEP_FLAGS[v].includes(flag))
204
215
  return { ok: false, says: `Drive's ${v} takes no --${flag}.` };
205
216
  const value = eq === -1 ? rest[++i] : arg.slice(eq + 1);
206
217
  if (!value || value.startsWith('--'))
@@ -215,8 +226,7 @@ export function parseDrive(argv) {
215
226
  if (role !== null && !options.name)
216
227
  return { ok: false, says: '`--role` narrows `--name`: give the name too.' };
217
228
  const one = positional.length === 1 ? positional[0] : null;
218
- if (positional.length > 1 ||
219
- (positional.length === 1 && ['start', 'click', 'fill', 'snapshot', 'stop'].includes(v)))
229
+ if (positional.length > 1 || (positional.length === 1 && STEP_WORDS[v] === null))
220
230
  return { ok: false, says: `Drive's ${v} takes nothing more.` };
221
231
  const r = role;
222
232
  switch (v) {
@@ -1,4 +1,4 @@
1
1
  export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, signInBySteps, signInOf, type SignIn, } from './browser.ts';
2
- export { driveArgv, exitOf, parseDrive, resultText, stepCommand, stepOf, stepWords, VERBS, type DriveResult, type Step, type Verb, } from './grammar.ts';
2
+ export { driveArgv, exitOf, parseDrive, resultText, stepCommand, stepOf, stepWords, STEP_FLAGS, STEP_WORDS, VERBS, type DriveResult, type Step, type Verb, } from './grammar.ts';
3
3
  export { findNamed, namedIn } from './names.ts';
4
4
  export { forgetDriving, readDriving, writeDriving } from './state.ts';
@@ -1,4 +1,4 @@
1
1
  export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, signInBySteps, signInOf, } from './browser.js';
2
- export { driveArgv, exitOf, parseDrive, resultText, stepCommand, stepOf, stepWords, VERBS, } from './grammar.js';
2
+ export { driveArgv, exitOf, parseDrive, resultText, stepCommand, stepOf, stepWords, STEP_FLAGS, STEP_WORDS, VERBS, } from './grammar.js';
3
3
  export { findNamed, namedIn } from './names.js';
4
4
  export { forgetDriving, readDriving, writeDriving } from './state.js';
@@ -4,6 +4,13 @@ export declare const checkoutsDir: (m: Manifest) => string;
4
4
  export declare function dirtyOf(m: Manifest, checkout: string): boolean;
5
5
  export declare function infoOf(m: Manifest, checkout: string, ref: string | null): CheckoutInfo;
6
6
  export declare function overlay(m: Manifest, checkout: string): void;
7
+ export type Tree = {
8
+ folder: string;
9
+ } | {
10
+ repo: string;
11
+ commit: string;
12
+ };
13
+ export declare function locate(repo: string, given: string, cwd?: string): Tree;
7
14
  export declare function checkoutFor(m: Manifest, repo: string, given: string, progress: (line: string) => void, keep?: readonly string[], cwd?: string): Promise<{
8
15
  path: string;
9
16
  ref: string | null;
@@ -33,16 +33,23 @@ export function overlay(m, checkout) {
33
33
  }
34
34
  }
35
35
  const NAMED_AS_A_FOLDER = /^(?:\.{1,2}(?:\/|$)|\/|~\/)/;
36
- export async function checkoutFor(m, repo, given, progress, keep = [], cwd = process.cwd()) {
36
+ export function locate(repo, given, cwd = process.cwd()) {
37
37
  if (NAMED_AS_A_FOLDER.test(given)) {
38
38
  const asPath = path.resolve(cwd, given.replace(/^~(?=\/)/, process.env.HOME ?? '~'));
39
39
  if (!existsSync(asPath) || !statSync(asPath).isDirectory())
40
40
  throw new RehearseError('no_checkout', `There is no checkout at ${asPath}.`);
41
- return { path: topOf(asPath) ?? asPath, ref: null };
41
+ return { folder: topOf(asPath) ?? asPath };
42
42
  }
43
43
  const commit = commitOf(repo, given);
44
44
  if (!commit)
45
45
  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
+ return { repo: topOf(repo) ?? repo, commit };
47
+ }
48
+ export async function checkoutFor(m, repo, given, progress, keep = [], cwd = process.cwd()) {
49
+ const found = locate(repo, given, cwd);
50
+ if ('folder' in found)
51
+ return { path: found.folder, ref: null };
52
+ const { commit } = found;
46
53
  const dir = path.join(checkoutsDir(m), commit.slice(0, 12));
47
54
  if (!existsSync(dir)) {
48
55
  mkdirSync(checkoutsDir(m), { recursive: true });
@@ -1,2 +1,2 @@
1
- export { checkoutFor, evict, infoOf, overlay } from './checkout.ts';
1
+ export { checkoutFor, evict, infoOf, locate, overlay, type Tree } from './checkout.ts';
2
2
  export { commitOf, gitOr, topOf } from './git.ts';
package/dist/git/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { checkoutFor, evict, infoOf, overlay } from './checkout.js';
1
+ export { checkoutFor, evict, infoOf, locate, overlay } from './checkout.js';
2
2
  export { commitOf, gitOr, topOf } from './git.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 { restart, restartable } from '../../services/index.js';
13
+ import { 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) => {
@@ -355,6 +355,7 @@ registerRunner({
355
355
  try {
356
356
  server = await startPieceServer({
357
357
  dir: pspec.packageDir,
358
+ state: stateDir(ctx.manifest.dir),
358
359
  config: ctx.manifest.scenarios.pieces.config ?? null,
359
360
  styles: ctx.manifest.scenarios.pieces.styles ?? null,
360
361
  preview: ctx.manifest.scenarios.pieces.preview ?? null,
@@ -5,7 +5,7 @@ export interface Found {
5
5
  }
6
6
  export declare const CONFIG_CONVENTIONS: readonly string[];
7
7
  export declare const STYLES_CONVENTIONS: readonly string[];
8
- export declare const cacheDirOf: (dir: string, under?: string) => string;
8
+ export declare const cacheDirOf: (dir: string, state: string) => string;
9
9
  export declare const SKIPPED_FOLDERS: ReadonlySet<string>;
10
10
  export declare function findConfig(dir: string, given?: string | null): Found | null;
11
11
  export declare function findStyles(dir: string, given?: string | null): Found | null;
@@ -1,12 +1,11 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
3
- import { tmpdir } from 'node:os';
4
3
  import path from 'node:path';
5
4
  import { PIECE_FILE } from './csf.js';
6
5
  const EXTENSIONS = ['ts', 'mts', 'js', 'mjs', 'cts', 'cjs'];
7
6
  export const CONFIG_CONVENTIONS = ['vite', 'vitest'].flatMap((name) => EXTENSIONS.map((ext) => `${name}.config.${ext}`));
8
7
  export const STYLES_CONVENTIONS = ['src/styles.css', 'src/index.css'];
9
- export const cacheDirOf = (dir, under = tmpdir()) => path.join(under, 'rehearse-pieces', createHash('sha256').update(path.resolve(dir)).digest('hex').slice(0, 16));
8
+ export const cacheDirOf = (dir, state) => path.join(state, 'pieces', createHash('sha256').update(path.resolve(dir)).digest('hex').slice(0, 16));
10
9
  export const SKIPPED_FOLDERS = new Set(['node_modules', 'dist', 'out']);
11
10
  const isFile = (file) => {
12
11
  try {
@@ -7,6 +7,7 @@ import { calm, contextFor, errorsOf, FIXED_TIME, launch } from '../../drive/inde
7
7
  import { errorText } from '../../errors.js';
8
8
  import { hashOf } from '../../manifest/index.js';
9
9
  import { registerReader, toPosix } from '../../scenarios/index.js';
10
+ import { stateDir } from '../../services/index.js';
10
11
  import { broken, registerRunner } from '../kind.js';
11
12
  import { ROOT_ID, THREW } from './canvas.js';
12
13
  import { metaTitle, propertyString, statementAt, storyExportsOf, storyNameFromExport, titleFromPath, toId, } from './csf.js';
@@ -177,6 +178,7 @@ export async function runPieces(scenarios, ctx, browser) {
177
178
  try {
178
179
  server = await startPieceServer({
179
180
  dir,
181
+ state: stateDir(m.dir),
180
182
  config: settings.config ?? null,
181
183
  styles: settings.styles ?? null,
182
184
  preview: settings.preview ?? null,
@@ -3,6 +3,7 @@ export declare const HOST = "127.0.0.1";
3
3
  export declare const resolvable: (dir: string, request: string) => boolean;
4
4
  export interface PieceServerOptions {
5
5
  dir: string;
6
+ state: string;
6
7
  config?: string | null;
7
8
  styles?: string | null;
8
9
  preview?: string | null;
@@ -164,7 +164,7 @@ export async function startPieceServer(o) {
164
164
  const inline = {
165
165
  configFile: config?.file ?? false,
166
166
  root: dir,
167
- cacheDir: cacheDirOf(dir),
167
+ cacheDir: cacheDirOf(dir, o.state),
168
168
  base: '/',
169
169
  mode: 'development',
170
170
  clearScreen: false,
@@ -0,0 +1,13 @@
1
+ export declare const CLI_FILE: string;
2
+ export interface Ran {
3
+ json: unknown;
4
+ stopped: boolean;
5
+ lastWords: string;
6
+ }
7
+ export interface RunOptions {
8
+ cwd: string;
9
+ env: NodeJS.ProcessEnv;
10
+ signal: AbortSignal;
11
+ line(text: string): void;
12
+ }
13
+ export declare function runCommandLine(argv: readonly string[], o: RunOptions): Promise<Ran>;
@@ -0,0 +1,53 @@
1
+ import { spawn } from 'node:child_process';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ const here = fileURLToPath(import.meta.url);
5
+ export const CLI_FILE = path.join(path.dirname(here), '..', `cli${path.extname(here)}`);
6
+ const LAST_WORDS = 5;
7
+ function lastJsonLine(out) {
8
+ const line = out.trim().split('\n').at(-1) ?? '';
9
+ try {
10
+ return JSON.parse(line);
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ export function runCommandLine(argv, o) {
17
+ if (o.signal.aborted)
18
+ return Promise.resolve({ json: null, stopped: true, lastWords: '' });
19
+ return new Promise((resolve) => {
20
+ const child = spawn(process.execPath, [CLI_FILE, ...argv], {
21
+ cwd: o.cwd,
22
+ env: o.env,
23
+ stdio: ['ignore', 'pipe', 'pipe'],
24
+ });
25
+ let out = '';
26
+ let partial = '';
27
+ const said = [];
28
+ const tell = (text) => {
29
+ if (!text.trim())
30
+ return;
31
+ said.push(text);
32
+ if (said.length > LAST_WORDS)
33
+ said.shift();
34
+ o.line(text);
35
+ };
36
+ child.stdout.setEncoding('utf8').on('data', (d) => void (out += d));
37
+ child.stderr.setEncoding('utf8').on('data', (d) => {
38
+ const lines = `${partial}${d}`.split('\n');
39
+ partial = lines.pop() ?? '';
40
+ lines.forEach(tell);
41
+ });
42
+ const stopAsCtrlCDoes = () => void child.kill('SIGINT');
43
+ o.signal.addEventListener('abort', stopAsCtrlCDoes, { once: true });
44
+ const done = (lastWords) => {
45
+ o.signal.removeEventListener('abort', stopAsCtrlCDoes);
46
+ tell(partial);
47
+ partial = '';
48
+ resolve({ json: lastJsonLine(out), stopped: o.signal.aborted, lastWords });
49
+ };
50
+ child.on('error', (error) => done(error.message));
51
+ child.on('close', () => done(said.join('\n')));
52
+ });
53
+ }
@@ -0,0 +1,4 @@
1
+ export { CLI_FILE } from './call.ts';
2
+ export { outputSchemaOf } from './output.ts';
3
+ export { HEARTBEAT_MS, INSTRUCTIONS, rehearseServer, serveOnStdio, type Served, type ServeOptions, } from './server.ts';
4
+ export type { Annotations, JsonSchema, Tool } from './tool.ts';
@@ -0,0 +1,3 @@
1
+ export { CLI_FILE } from './call.js';
2
+ export { outputSchemaOf } from './output.js';
3
+ export { HEARTBEAT_MS, INSTRUCTIONS, rehearseServer, serveOnStdio, } from './server.js';
@@ -0,0 +1,3 @@
1
+ import { type SchemaName } from '../schema.ts';
2
+ import type { JsonSchema } from './tool.ts';
3
+ export declare function outputSchemaOf(name: SchemaName): JsonSchema;
@@ -0,0 +1,43 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { SCHEMA_DIR } from '../schema.js';
4
+ const read = new Map();
5
+ function fileOf(name) {
6
+ const known = read.get(name);
7
+ if (known)
8
+ return known;
9
+ const schema = JSON.parse(readFileSync(path.join(SCHEMA_DIR, name), 'utf8'));
10
+ read.set(name, schema);
11
+ return schema;
12
+ }
13
+ const unescaped = (segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~');
14
+ function pointedAt(schema, pointer) {
15
+ return pointer
16
+ .split('/')
17
+ .slice(1)
18
+ .map(unescaped)
19
+ .reduce((node, key) => node[key], schema);
20
+ }
21
+ function inlined(node, file, within) {
22
+ if (Array.isArray(node))
23
+ return node.map((n) => inlined(n, file, within));
24
+ if (node === null || typeof node !== 'object')
25
+ return node;
26
+ const { $ref, ...rest } = node;
27
+ const own = Object.fromEntries(Object.entries(rest).map(([k, v]) => [k, inlined(v, file, within)]));
28
+ if (typeof $ref !== 'string')
29
+ return own;
30
+ const [target, pointer = ''] = $ref.split('#');
31
+ const into = target || file;
32
+ const place = `${into}#${pointer}`;
33
+ if (within.includes(place))
34
+ throw new Error(`${place} refers to itself, so it can't be inlined.`);
35
+ const resolved = inlined(pointedAt(fileOf(into), pointer), into, [...within, place]);
36
+ return Object.keys(own).length ? { allOf: [resolved], ...own } : resolved;
37
+ }
38
+ export function outputSchemaOf(name) {
39
+ const file = `${name}.schema.json`;
40
+ const whole = inlined(fileOf(file), file, []);
41
+ const withoutDefs = Object.fromEntries(Object.entries(whole).filter(([key]) => key !== '$defs'));
42
+ return { ...withoutDefs, type: 'object' };
43
+ }
@@ -0,0 +1,16 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import type { Tool } from './tool.ts';
3
+ export interface ServeOptions {
4
+ cwd: string;
5
+ env: NodeJS.ProcessEnv;
6
+ log(line: string): void;
7
+ heartbeatMs?: number;
8
+ }
9
+ export declare const INSTRUCTIONS = "Rehearse runs a repository's scenarios on the base and on the head and compares them, so you can see what a change changes before it ships. Each tool is a rehearse command and answers with what that command prints with --json. The rehearse skill (skill/rehearse/SKILL.md in the package, or https://rehearse.kurvball.ca/SKILL.md) teaches the loop: list what a change reaches, compare, announce what you meant to change, drive the product step by step.";
10
+ export declare const HEARTBEAT_MS = 5000;
11
+ export interface Served {
12
+ server: Server;
13
+ idle(): Promise<void>;
14
+ }
15
+ export declare function rehearseServer(tools: readonly Tool[], o: ServeOptions): Served;
16
+ export declare function serveOnStdio(tools: readonly Tool[], o: ServeOptions): Promise<void>;