@kurvball/rehearse 1.4.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 (43) hide show
  1. package/README.md +2 -0
  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/compare.d.ts +4 -2
  6. package/dist/commands/compare.js +22 -20
  7. package/dist/commands/index.d.ts +4 -0
  8. package/dist/commands/index.js +8 -0
  9. package/dist/commands/mcp.d.ts +4 -0
  10. package/dist/commands/mcp.js +44 -0
  11. package/dist/commands/synopsis.d.ts +19 -0
  12. package/dist/commands/synopsis.js +26 -0
  13. package/dist/commands/tools.d.ts +11 -0
  14. package/dist/commands/tools.js +118 -0
  15. package/dist/compare/announce.d.ts +13 -0
  16. package/dist/compare/announce.js +19 -1
  17. package/dist/compare/changesets.d.ts +3 -2
  18. package/dist/compare/changesets.js +22 -8
  19. package/dist/compare/compare.js +6 -18
  20. package/dist/compare/index.d.ts +1 -1
  21. package/dist/compare/index.js +1 -1
  22. package/dist/drive/grammar.d.ts +2 -0
  23. package/dist/drive/grammar.js +14 -4
  24. package/dist/drive/index.d.ts +1 -1
  25. package/dist/drive/index.js +1 -1
  26. package/dist/git/checkout.d.ts +7 -0
  27. package/dist/git/checkout.js +9 -2
  28. package/dist/git/index.d.ts +1 -1
  29. package/dist/git/index.js +1 -1
  30. package/dist/mcp/call.d.ts +13 -0
  31. package/dist/mcp/call.js +53 -0
  32. package/dist/mcp/index.d.ts +4 -0
  33. package/dist/mcp/index.js +3 -0
  34. package/dist/mcp/output.d.ts +3 -0
  35. package/dist/mcp/output.js +43 -0
  36. package/dist/mcp/server.d.ts +16 -0
  37. package/dist/mcp/server.js +152 -0
  38. package/dist/mcp/tool.d.ts +19 -0
  39. package/dist/mcp/tool.js +1 -0
  40. package/dist/services/service.js +11 -2
  41. package/llms.txt +3 -1
  42. package/package.json +4 -2
  43. package/skill/rehearse/SKILL.md +52 -2
@@ -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';
@@ -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>;
@@ -0,0 +1,152 @@
1
+ import { Ajv2020 } from 'ajv/dist/2020.js';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
+ import { errorJson, RehearseError, usage } from '../errors.js';
6
+ import { explain, validate } from '../schema.js';
7
+ import { VERSION } from '../version.js';
8
+ import { runCommandLine } from './call.js';
9
+ import { outputSchemaOf } from './output.js';
10
+ export 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.";
11
+ export const HEARTBEAT_MS = 5_000;
12
+ const asText = (json) => [{ type: 'text', text: JSON.stringify(json) }];
13
+ const refused = (error) => ({
14
+ content: asText(errorJson(error)),
15
+ isError: true,
16
+ });
17
+ function answerOf(tool, ran) {
18
+ if (ran.json === null || typeof ran.json !== 'object')
19
+ return refused(new RehearseError('crashed', `Rehearse stopped${ran.stopped ? ' when the call was cancelled' : ''}${ran.lastWords ? `: ${ran.lastWords}` : '.'}`));
20
+ if (validate('error', ran.json).length === 0)
21
+ return { content: asText(ran.json), isError: true };
22
+ const failed = tool.failsWhenNotOk && ran.json.ok === false;
23
+ return {
24
+ content: asText(ran.json),
25
+ structuredContent: ran.json,
26
+ isError: failed,
27
+ };
28
+ }
29
+ const ajv = new Ajv2020({ allErrors: true, strict: false });
30
+ const validators = new WeakMap();
31
+ function argumentsRefused(tool, args) {
32
+ const check = validators.get(tool) ?? ajv.compile(tool.inputSchema);
33
+ validators.set(tool, check);
34
+ if (check(args))
35
+ return null;
36
+ const first = explain(check.errors ?? [])[0];
37
+ if (!first)
38
+ return usage(`The ${tool.name} tool can't take these arguments.`);
39
+ if (first.at.length === 0 && first.key !== undefined)
40
+ return usage(`The ${tool.name} tool takes no “${first.key}”. It takes ${Object.keys(tool.inputSchema.properties).join(', ')}.`);
41
+ if (first.at.length === 0)
42
+ return usage(`The ${tool.name} tool ${first.says.replace(/^the top /, '')}`);
43
+ return usage(`The ${tool.name} tool's ${first.says}`);
44
+ }
45
+ function progressOf(extra, o) {
46
+ const { _meta: meta } = extra;
47
+ const token = meta?.progressToken;
48
+ const begun = Date.now();
49
+ let sent = 0;
50
+ let last = begun;
51
+ const send = (message) => {
52
+ if (token === undefined)
53
+ return;
54
+ sent += 1;
55
+ last = Date.now();
56
+ void extra
57
+ .sendNotification({
58
+ method: 'notifications/progress',
59
+ params: { progressToken: token, progress: sent, message },
60
+ })
61
+ .catch(() => undefined);
62
+ };
63
+ const every = o.heartbeatMs ?? HEARTBEAT_MS;
64
+ const heartbeat = token === undefined
65
+ ? null
66
+ : setInterval(() => {
67
+ if (Date.now() - last >= every)
68
+ send(`Still working, ${Math.round((Date.now() - begun) / 1000)} s in.`);
69
+ }, Math.min(every, 1_000));
70
+ return {
71
+ line(text) {
72
+ o.log(text);
73
+ send(text);
74
+ },
75
+ stop() {
76
+ if (heartbeat)
77
+ clearInterval(heartbeat);
78
+ },
79
+ };
80
+ }
81
+ async function called(tools, o, name, given, extra) {
82
+ const tool = tools.find((t) => t.name === name);
83
+ if (!tool)
84
+ return refused(usage(`Rehearse has no tool “${name}”. It has ${tools.map((t) => t.name).join(', ')}.`));
85
+ const args = given ?? {};
86
+ const wrong = argumentsRefused(tool, args);
87
+ if (wrong)
88
+ return refused(wrong);
89
+ const progress = progressOf(extra, o);
90
+ try {
91
+ const ran = await runCommandLine(tool.argvOf(args), {
92
+ cwd: o.cwd,
93
+ env: o.env,
94
+ signal: extra.signal,
95
+ line: progress.line,
96
+ });
97
+ return answerOf(tool, ran);
98
+ }
99
+ finally {
100
+ progress.stop();
101
+ }
102
+ }
103
+ export function rehearseServer(tools, o) {
104
+ const server = new Server({ name: 'rehearse', version: VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
105
+ const listed = tools.map((t) => ({
106
+ name: t.name,
107
+ description: t.description,
108
+ inputSchema: t.inputSchema,
109
+ outputSchema: outputSchemaOf(t.output),
110
+ annotations: t.annotations,
111
+ }));
112
+ const calls = new Set();
113
+ server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: listed }));
114
+ server.setRequestHandler(CallToolRequestSchema, (request, extra) => {
115
+ const call = called(tools, o, request.params.name, request.params.arguments, extra);
116
+ calls.add(call);
117
+ void call.finally(() => calls.delete(call));
118
+ return call;
119
+ });
120
+ return {
121
+ server,
122
+ async idle() {
123
+ while (calls.size)
124
+ await Promise.allSettled(calls);
125
+ },
126
+ };
127
+ }
128
+ class StdioThatSaysWhenItCloses extends StdioServerTransport {
129
+ closed;
130
+ hasClosed = () => undefined;
131
+ constructor() {
132
+ super();
133
+ this.closed = new Promise((resolve) => {
134
+ this.hasClosed = resolve;
135
+ });
136
+ }
137
+ async close() {
138
+ await super.close();
139
+ this.hasClosed();
140
+ }
141
+ }
142
+ export async function serveOnStdio(tools, o) {
143
+ const { server, idle } = rehearseServer(tools, o);
144
+ const transport = new StdioThatSaysWhenItCloses();
145
+ const close = () => void server.close();
146
+ process.stdin.once('end', close);
147
+ process.once('SIGINT', close);
148
+ process.once('SIGTERM', close);
149
+ await server.connect(transport);
150
+ await transport.closed;
151
+ await idle();
152
+ }
@@ -0,0 +1,19 @@
1
+ import type { SchemaName } from '../schema.ts';
2
+ export type JsonSchema = Record<string, unknown>;
3
+ export interface Annotations {
4
+ readOnlyHint?: boolean;
5
+ destructiveHint?: boolean;
6
+ idempotentHint?: boolean;
7
+ }
8
+ export interface Tool {
9
+ name: string;
10
+ description: string;
11
+ inputSchema: JsonSchema & {
12
+ type: 'object';
13
+ properties: Record<string, JsonSchema>;
14
+ };
15
+ output: SchemaName;
16
+ annotations: Annotations;
17
+ failsWhenNotOk: boolean;
18
+ argvOf(args: Readonly<Record<string, unknown>>): string[];
19
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -169,9 +169,14 @@ export async function restart(m, r, whileDown = async () => undefined) {
169
169
  const startedHereNotHandedOver = new Map();
170
170
  const keyOf = (r) => `${r.name}@${path.resolve(r.checkout)}`;
171
171
  export const release = (r) => startedHereNotHandedOver.delete(keyOf(r));
172
+ let stoppingWhatStartedHere = false;
172
173
  export async function downStartedHere() {
173
- for (const { m, r } of [...startedHereNotHandedOver.values()].toReversed())
174
- await bringDown(m, r).catch(() => undefined);
174
+ stoppingWhatStartedHere = true;
175
+ while (startedHereNotHandedOver.size > 0)
176
+ for (const [key, { m, r }] of [...startedHereNotHandedOver].toReversed()) {
177
+ startedHereNotHandedOver.delete(key);
178
+ await bringDown(m, r).catch(() => undefined);
179
+ }
175
180
  }
176
181
  export async function bringUp(m, s, checkout, options) {
177
182
  const already = runningServices(m.dir).find((r) => r.name === s.name && path.resolve(r.checkout) === path.resolve(checkout));
@@ -217,6 +222,10 @@ export async function bringUp(m, s, checkout, options) {
217
222
  ...(port !== null && { PORT: String(port) }),
218
223
  REHEARSE_SCRATCH: scratch,
219
224
  };
225
+ if (stoppingWhatStartedHere) {
226
+ rmSync(scratch, { recursive: true, force: true });
227
+ throw new RehearseError('service', `Rehearse is stopping, so it doesn't bring ${s.name} up.`);
228
+ }
220
229
  mkdirSync(logDir(m), { recursive: true });
221
230
  const log = logOf(m, s.name, checkout);
222
231
  const out = openSync(log, 'w');
package/llms.txt CHANGED
@@ -11,11 +11,13 @@
11
11
  - `rehearse up [<service>…] [--world] [--real <stand-in>]` and `rehearse down [--all]`: services left running with a world built on them (schema up).
12
12
  - `rehearse run <scenario> [--on <checkout|ref>] [--world] [--as <person>] [--real <stand-in>] [--keep] [--parallel <n>] --json`: one observation (schema observation).
13
13
  - `rehearse compare [<id or glob>…] [--affected] [--base <ref|./folder>] [--head <ref|./folder>] [--announce <file>] [--announce-from changesets] [--said <id>]… [--world] [--as] [--real] [--fresh] [--parallel <n>] --json`: a verdict per scenario (schema comparison). --announce-from changesets also reads the `announce` blocks of the changesets the change adds. Exit 0 when both sides came up and nothing fails on the head or changed without saying so. --parallel runs groups that share no service at once, and the base beside the head when budget.services allows two; the result is the same as one at a time.
14
+ - `rehearse announce [<id or glob>…] [--draft] [--base] [--head] [--announce <file>] [--announce-from changesets] [--said <id>]… [--format yaml|changeset] --json`: what a comparison would read as announced (schema announce); with --draft (and compare's own options) it compares and proposes {scenario, why} for each scenario whose verdict is unsaid, its why the first difference, for you to rewrite as the reason. --format changeset prints an `announce` block for a changeset. It writes no file; refuses with code not_compared when the base or head doesn't come up.
14
15
  - `rehearse drive start [--service <name> | --piece <id>] [--world] [--as <person>] [--scheme light|dark]` (or DRIVE_SCHEME), then `rehearse drive click --name <name> [--role <role>] | fill --name <name> --with <text> | type <text> | key <key> | snapshot [--name <name> [--role <role>]] | screenshot <file.png> | stop`, each with --json: the drive result shape {ok, command, ms, file, tree} plus v and driver (schema drive). Exit 0 done, 1 failed, 2 usage.
15
16
  - `rehearse stage [--base] [--head] [--port] [--announce <file>] [--announce-from changesets] [--said <id>]…`: the stage on 127.0.0.1 (default port 4400): every scenario in Base, Head and Diff, with Works, Doesn't and a note (kept in .rehearse/tries.jsonl, schema try).
16
17
  - `rehearse open <scenario> [--json]`: the stage's address for a scenario (schema open), starting the stage if none runs.
17
18
  - `rehearse clean [--all]`: removes old base checkouts, runs and comparisons (schema clean).
18
19
  - `rehearse validate <schema> [file]`: checks a JSON or YAML file, or stdin, against a v1 schema (schema validate).
20
+ - `rehearse mcp`: an MCP server on stdio whose tools are list, compare, drive and announce. Each takes its command's words and flags in camelCase (drive takes step), and answers with its command's --json object, as structuredContent and as JSON text, with the command's schema as outputSchema. isError is true for a refusal (the error object, as text only) and for a failed drive step, false for a comparison that isn't ok. people and stage are not tools.
19
21
 
20
22
  ## Kinds
21
23
 
@@ -33,7 +35,7 @@
33
35
 
34
36
  ## Schemas (schema/v1/)
35
37
 
36
- - manifest.schema.json: rehearse.yaml. flow.schema.json: *.flow.yaml. file-scenario.schema.json: *.rehearse.yaml. announce.schema.json: announcements.
38
+ - manifest.schema.json: rehearse.yaml. flow.schema.json: *.flow.yaml. file-scenario.schema.json: *.rehearse.yaml. announce.schema.json: announcements, and what `rehearse announce --json` prints.
37
39
  - check, init, services, people, worlds, list, up, observation, comparison, drive, open, try, clean, validate, error: one per command's --json output, each with a sample in schema/v1/samples/.
38
40
  - dependents.schema.json: what Rehearse reads from an import graph (`ashlar dependents <files> --json`, or the manifest's affected.graph).
39
41
  - Within v1 an output only gains optional fields, and open string fields may gain values: readers ignore what they don't know.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kurvball/rehearse",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Rehearse a change before it ships: bring the product up, sign in as named people, start from named worlds, and compare any scenario on the base and on the head.",
5
5
  "homepage": "https://rehearse.kurvball.ca/",
6
6
  "repository": {
@@ -50,10 +50,12 @@
50
50
  "node": ">=22.18"
51
51
  },
52
52
  "dependencies": {
53
+ "@modelcontextprotocol/sdk": "1.32.2",
53
54
  "ajv": "8.20.0",
54
55
  "axe-core": "4.14.1",
55
56
  "es-module-lexer": "1.7.0",
56
- "yaml": "2.9.1"
57
+ "yaml": "2.9.1",
58
+ "zod": "4.6.7"
57
59
  },
58
60
  "optionalDependencies": {
59
61
  "playwright-core": "1.64.1"
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: rehearse
3
- description: Use in a repository with a rehearse.yaml, or when asked to try, compare, prove or check a change before it ships, write piece/flow/call/file scenarios, or drive a running product step by step. Teaches Rehearse's commands, its scenario formats and how to read a comparison's verdicts.
3
+ description: Use in a repository with a rehearse.yaml, or when asked to try, compare, prove or check a change before it ships, write piece/flow/call/file scenarios, or drive a running product step by step. Teaches Rehearse's commands and MCP tools, its scenario formats, how to read a comparison's verdicts, and how to announce what a change meant before pushing it.
4
4
  ---
5
5
 
6
6
  # Rehearse
@@ -9,6 +9,25 @@ Rehearse sits beside a repository. It brings the product up, signs in as named p
9
9
  scenarios on a base and on the head, and compares them. Every command takes `--json` and prints one object whose
10
10
  schema is in Rehearse's `schema/v1/`. Read JSON, not the words: the words are for people.
11
11
 
12
+ ## Two paths, one answer
13
+
14
+ When Rehearse's MCP server is there (`rehearse mcp`, often named `rehearse` in `.mcp.json`), call its tools: `list`,
15
+ `compare`, `drive` and `announce`. When it isn't, run the command with `--json`. A tool answers with the very object
16
+ the command prints, so every field below reads the same either way.
17
+
18
+ A tool's arguments are the command's words and flags in camelCase. A flag that repeats, or a word that does, is a list.
19
+
20
+ | Command | Tool call |
21
+ | ---------------------------------------------------------------- | ------------------------------------------------------------- |
22
+ | `rehearse list --affected src/a.ts --json` | `list` `{"affected": true, "file": ["src/a.ts"]}` |
23
+ | `rehearse compare --base main --announce-from changesets --json` | `compare` `{"base": "main", "announceFrom": "changesets"}` |
24
+ | `rehearse announce --draft --said 'apps/web/**' --json` | `announce` `{"draft": true, "said": ["apps/web/**"]}` |
25
+ | `rehearse drive click --name Save --role button --json` | `drive` `{"step": "click", "name": "Save", "role": "button"}` |
26
+
27
+ A tool's answer is an error (`isError`) when the command refused, with the `error` object as its text, and when a drive
28
+ step failed. A comparison that isn't `ok` is not an error: read its verdicts. `people` and `stage` have no tool: run
29
+ them as commands.
30
+
12
31
  ## 1. Look before you change anything
13
32
 
14
33
  ```bash
@@ -106,7 +125,23 @@ Read `line`, then each entry of `scenarios`:
106
125
  `byChange` groups unannounced changes by what changed. `notRun` lists scenarios that couldn't run, and `base.ok: false`
107
126
  means the base didn't come up. The command exits 0 only when nothing fails on the head and nothing changed unsaid.
108
127
 
109
- ## 5. Announce what you meant to change
128
+ ## 5. Announce what you meant, before you push
129
+
130
+ Announce every change you made on purpose, so a reviewer sees what you meant apart from what slipped. Before you push:
131
+
132
+ 1. **Compare:** `rehearse compare --base main --json` (tool `compare`).
133
+ 2. **Draft:** `rehearse announce --draft --base main --json` (tool `announce` with `"draft": true`). It proposes one
134
+ entry per scenario whose verdict is `unsaid`, its `why` the first thing that changed, such as
135
+ `$.items[*].price: 3.5 → "3.50"`. It writes nothing.
136
+ 3. **Rewrite each why as the reason**, for the reviewer: "Prices are sent with two decimals.", not what the diff says.
137
+ Drop every entry you didn't mean: that change is a bug to fix, not to announce.
138
+ 4. **Write it down:** in the changeset you add, as an `announce` block
139
+ (`rehearse announce --draft --format changeset` prints one), or in `.rehearse/announce.yaml`.
140
+ 5. **Compare again** (with `--announce-from changesets` when you wrote a changeset) until nothing is `unsaid` that you
141
+ didn't mean to leave, and nothing `fails` that `failsOnBase` doesn't excuse. Then push.
142
+
143
+ `rehearse announce --json` without `--draft` prints what a comparison would read as announced right now, from the
144
+ file, `--said` and, with `--announce-from changesets`, the changesets you added: check it before you compare.
110
145
 
111
146
  Write `.rehearse/announce.yaml` beside `rehearse.yaml` (or pass `--announce <file>`, or `--said <id>`):
112
147
 
@@ -124,8 +159,23 @@ In a repository with changesets (`.changeset/`), announce in the changeset you a
124
159
  `announce` block with one `rehearse: <id or glob>` per line, then `rehearse compare --announce-from changesets --json`.
125
160
  The summary is each line's why, unless the line ends with ` — <why>`. Leave other tools' lines (`cast:` …) as they are.
126
161
 
162
+ ````md
163
+ ---
164
+ '@acme/shop': minor
165
+ ---
166
+
167
+ Prices are sent with two decimals.
168
+
169
+ ```announce
170
+ rehearse: packages/api/items.hurl#The owner sees every item
171
+ rehearse: packages/report/weekly.rehearse.yaml — The weekly report prints prices with two decimals.
172
+ ```
173
+ ````
174
+
127
175
  ## 6. Drive the product step by step
128
176
 
177
+ Each step is one call: `rehearse drive <step> … --json`, or the `drive` tool with `step` and the step's arguments.
178
+
129
179
  ```bash
130
180
  rehearse drive start --json # --service, --piece, --world, --as, --scheme dark
131
181
  rehearse drive snapshot --json # the accessibility tree