@llman-sdd/cli 0.11.0 → 0.12.1
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.
- package/package.json +13 -5
- package/src/cli-shared.ts +85 -43
- package/src/commands/archive.ts +0 -9
- package/src/commands/change.ts +71 -33
- package/src/commands/init.ts +9 -11
- package/src/commands/list.ts +0 -2
- package/src/commands/project.ts +0 -6
- package/src/commands/review.ts +5 -3
- package/src/commands/self.ts +3 -1
- package/src/commands/show.ts +8 -46
- package/src/commands/spec.ts +4 -6
- package/src/commands/studio.ts +1315 -0
- package/src/commands/studioMcp.ts +862 -0
- package/src/commands/studioShared.ts +87 -0
- package/src/commands/theorem-write.ts +608 -0
- package/src/commands/theorem.ts +479 -0
- package/src/commands/validate.ts +108 -47
- package/src/io.ts +0 -1
- package/src/main.ts +20 -31
- package/src/program.ts +16 -12
- package/src/progress.ts +1 -3
- package/src/studio-server/changeScope.ts +295 -0
- package/src/studio-server/hub.ts +98 -0
- package/src/studio-server/negotiate.ts +60 -0
- package/src/studio-server/security.ts +71 -0
- package/src/studio-server/server.ts +1694 -0
- package/src/studio-server/static.ts +184 -0
- package/src/studio-server/syncDisk.ts +116 -0
- package/src/theorems/base.ts +53 -0
- package/src/theorems/diagnose.ts +90 -0
- package/src/theorems/draft.ts +252 -0
- package/src/theorems/os-lock.ts +364 -0
- package/src/theorems/paths.ts +11 -0
- package/src/theorems/prompts.ts +79 -0
- package/src/theorems/quiet.ts +21 -0
- package/src/theorems/runner.ts +48 -0
- package/src/theorems/transaction.ts +272 -0
- package/src/theorems/workspace.ts +103 -0
- package/studio-dist/index.html +14 -0
- package/studio-dist/static/css/index.00cf48cf.css +1 -0
- package/studio-dist/static/js/610.51883f69.js +218 -0
- package/studio-dist/static/js/610.51883f69.js.LICENSE.txt +26 -0
- package/studio-dist/static/js/index.c5f7c530.js +13 -0
- package/studio-dist/static/js/lib-react.a4b07007.js +2 -0
- package/studio-dist/static/js/lib-react.a4b07007.js.LICENSE.txt +49 -0
|
@@ -0,0 +1,862 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thin Studio MCP bridge (`llman-sdd studio mcp`, studio-mcp r139-r142).
|
|
3
|
+
* Zero domain logic duplication: delegates all graph validation, semantic diff,
|
|
4
|
+
* revision preview/proposal, comment reply, and atomic state I/O directly to
|
|
5
|
+
* `@llman-sdd/core` and C2 `makeNodeStudioStateIo`.
|
|
6
|
+
*
|
|
7
|
+
* Transport discipline: when serving over stdio, stdout carries ONLY JSON-RPC
|
|
8
|
+
* frames; all warnings, diagnostics, and out-of-band errors write strictly to stderr.
|
|
9
|
+
*/
|
|
10
|
+
import { resolve } from 'node:path';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
applyRevisionOpsToMachine,
|
|
15
|
+
cloneMachineDraft,
|
|
16
|
+
computeMachineDiff,
|
|
17
|
+
currentBranch,
|
|
18
|
+
formatSemanticDiff,
|
|
19
|
+
hasBlockingDiagnostics,
|
|
20
|
+
listStudioStates,
|
|
21
|
+
planStudioApply,
|
|
22
|
+
previewFeatureUnifiedDiff,
|
|
23
|
+
previewRevisionProposal,
|
|
24
|
+
proposeRevision,
|
|
25
|
+
readStudioState,
|
|
26
|
+
renderUpdatedFeatureSource,
|
|
27
|
+
replyStudioComment,
|
|
28
|
+
resolveInstanceRoot,
|
|
29
|
+
SPECS_DIR,
|
|
30
|
+
StudioSyncError,
|
|
31
|
+
validateMachineGraph,
|
|
32
|
+
validateStateId,
|
|
33
|
+
usedReqIds,
|
|
34
|
+
worktreeList,
|
|
35
|
+
writeStudioState,
|
|
36
|
+
type MachineDiagnostic,
|
|
37
|
+
type MachineDraft,
|
|
38
|
+
type RevisionOp,
|
|
39
|
+
type StudioStateIo,
|
|
40
|
+
type WorktreeEntry,
|
|
41
|
+
} from '@llman-sdd/core';
|
|
42
|
+
import type { InMemoryTransport, McpServer } from '@modelcontextprotocol/server';
|
|
43
|
+
import type { Command } from 'commander';
|
|
44
|
+
|
|
45
|
+
import {
|
|
46
|
+
addSpecDirOption,
|
|
47
|
+
CliError,
|
|
48
|
+
loadCliConfig,
|
|
49
|
+
version,
|
|
50
|
+
type CliContext,
|
|
51
|
+
} from '../cli-shared.ts';
|
|
52
|
+
import { makeCliGit, makeIo } from '../io.ts';
|
|
53
|
+
import { makeNodeStudioStateIo, resolveStateIdOrThrow } from './studioShared.ts';
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Lazy helper for in-memory transport tests under `tests/` without eagerly loading
|
|
57
|
+
* `@modelcontextprotocol/server` on every CLI startup.
|
|
58
|
+
*/
|
|
59
|
+
export async function createLinkedMcpTransports(): Promise<[InMemoryTransport, InMemoryTransport]> {
|
|
60
|
+
const { InMemoryTransport: TransportCtor } = await import('@modelcontextprotocol/server');
|
|
61
|
+
return TransportCtor.createLinkedPair();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const MCP_PRINT_CONFIG_CLIENTS = ['claude-code', 'cursor', 'codex', 'generic'] as const;
|
|
65
|
+
export type McpPrintConfigClient = (typeof MCP_PRINT_CONFIG_CLIENTS)[number];
|
|
66
|
+
|
|
67
|
+
export const STUDIO_MCP_TOOL_NAMES = [
|
|
68
|
+
'studio_list_states',
|
|
69
|
+
'studio_get_diff',
|
|
70
|
+
'studio_validate_draft',
|
|
71
|
+
'studio_reply_comment',
|
|
72
|
+
'studio_propose_revision',
|
|
73
|
+
] as const;
|
|
74
|
+
|
|
75
|
+
export function isMcpPrintConfigClient(value: string): value is McpPrintConfigClient {
|
|
76
|
+
return (MCP_PRINT_CONFIG_CLIENTS as readonly string[]).includes(value);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Render a ready-to-paste MCP client configuration snippet for `llman-sdd studio mcp`.
|
|
81
|
+
*/
|
|
82
|
+
export function renderMcpClientConfig(client: McpPrintConfigClient, directory?: string): string {
|
|
83
|
+
const args =
|
|
84
|
+
directory !== undefined && directory.trim() !== ''
|
|
85
|
+
? ['studio', 'mcp', '--directory', directory.trim()]
|
|
86
|
+
: ['studio', 'mcp'];
|
|
87
|
+
|
|
88
|
+
if (client === 'codex') {
|
|
89
|
+
const serializedArgs = args.map((arg) => JSON.stringify(arg)).join(', ');
|
|
90
|
+
return [
|
|
91
|
+
'[mcp_servers.llman-sdd-studio]',
|
|
92
|
+
'command = "llman-sdd"',
|
|
93
|
+
`args = [${serializedArgs}]`,
|
|
94
|
+
].join('\n');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return JSON.stringify(
|
|
98
|
+
{
|
|
99
|
+
mcpServers: {
|
|
100
|
+
'llman-sdd-studio': {
|
|
101
|
+
command: 'llman-sdd',
|
|
102
|
+
args,
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
null,
|
|
107
|
+
2,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export class McpToolError extends Error {
|
|
112
|
+
readonly code: string;
|
|
113
|
+
readonly details?: Record<string, unknown>;
|
|
114
|
+
|
|
115
|
+
constructor(code: string, message: string, details?: Record<string, unknown>) {
|
|
116
|
+
super(message);
|
|
117
|
+
this.name = 'McpToolError';
|
|
118
|
+
this.code = code;
|
|
119
|
+
this.details = details;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface McpRootDefaults {
|
|
124
|
+
/** Explicitly pinned via CLI `--directory <path>` at launch (exempts multi-worktree prompt). */
|
|
125
|
+
pinnedDirectory?: string;
|
|
126
|
+
/** Unique client-declared root path resolved from MCP `roots/list` (when advertised). */
|
|
127
|
+
clientRoot?: string;
|
|
128
|
+
/** Process launch working directory. */
|
|
129
|
+
cwd: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface ResolvedMcpContext {
|
|
133
|
+
instanceRoot: string;
|
|
134
|
+
branch: string | null;
|
|
135
|
+
io: ReturnType<typeof makeIo>;
|
|
136
|
+
studioIo: StudioStateIo;
|
|
137
|
+
git: ReturnType<typeof makeCliGit>;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function surfaceLegacyConfigWarningsToStderr(instanceRoot: string): void {
|
|
141
|
+
try {
|
|
142
|
+
loadCliConfig(instanceRoot);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
console.error(
|
|
145
|
+
`[WARNING] failed to load llmanspec/config.yaml under ${instanceRoot}: ${error instanceof Error ? error.message : String(error)}`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Adaptive multi-worktree instance root resolver (design D3, studio-mcp r140):
|
|
152
|
+
* 1. Explicit `inputDirectory` -> direct `resolveInstanceRoot`.
|
|
153
|
+
* 2. Omitted `inputDirectory` -> `pinnedDirectory` > unique `clientRoot` > `cwd`.
|
|
154
|
+
* When NOT pinned via `--directory` and `worktreeList()` reports >1 valid worktree,
|
|
155
|
+
* rejects with a structured error listing all available worktree paths.
|
|
156
|
+
*/
|
|
157
|
+
export function resolveMcpInstanceRoot(
|
|
158
|
+
inputDirectory: string | undefined,
|
|
159
|
+
defaults: McpRootDefaults,
|
|
160
|
+
): ResolvedMcpContext {
|
|
161
|
+
const trimmedInput = inputDirectory?.trim();
|
|
162
|
+
const hasExplicitInput = trimmedInput !== undefined && trimmedInput !== '';
|
|
163
|
+
|
|
164
|
+
let startPath: string;
|
|
165
|
+
let displayStart: string;
|
|
166
|
+
let isPinned = false;
|
|
167
|
+
|
|
168
|
+
if (hasExplicitInput) {
|
|
169
|
+
displayStart = trimmedInput;
|
|
170
|
+
startPath = resolve(defaults.cwd, trimmedInput);
|
|
171
|
+
} else if (defaults.pinnedDirectory !== undefined && defaults.pinnedDirectory.trim() !== '') {
|
|
172
|
+
displayStart = defaults.pinnedDirectory.trim();
|
|
173
|
+
startPath = resolve(defaults.cwd, displayStart);
|
|
174
|
+
isPinned = true;
|
|
175
|
+
} else if (defaults.clientRoot !== undefined && defaults.clientRoot.trim() !== '') {
|
|
176
|
+
displayStart = defaults.clientRoot.trim();
|
|
177
|
+
startPath = resolve(defaults.cwd, displayStart);
|
|
178
|
+
} else {
|
|
179
|
+
displayStart = defaults.cwd;
|
|
180
|
+
startPath = resolve(defaults.cwd);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const root = resolveInstanceRoot(startPath, makeIo(startPath));
|
|
184
|
+
if (root === null) {
|
|
185
|
+
throw new McpToolError('no_llmanspec_root', `no llmanspec root at or above: ${displayStart}`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const instanceRoot = resolve(root);
|
|
189
|
+
const git = makeCliGit(instanceRoot);
|
|
190
|
+
|
|
191
|
+
if (!hasExplicitInput && !isPinned) {
|
|
192
|
+
let validWorktrees: WorktreeEntry[] = [];
|
|
193
|
+
try {
|
|
194
|
+
validWorktrees = worktreeList(git).filter((entry) => !entry.prunable);
|
|
195
|
+
} catch {
|
|
196
|
+
validWorktrees = [];
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (validWorktrees.length > 1) {
|
|
200
|
+
const worktreeSummaries = validWorktrees.map((w) => ({
|
|
201
|
+
path: w.path,
|
|
202
|
+
branch: w.branch,
|
|
203
|
+
}));
|
|
204
|
+
const pathList = validWorktrees
|
|
205
|
+
.map((w) => (w.branch ? `${w.path} (${w.branch})` : w.path))
|
|
206
|
+
.join(', ');
|
|
207
|
+
throw new McpToolError(
|
|
208
|
+
'multiple_worktrees_detected',
|
|
209
|
+
`multiple git worktrees detected (${String(validWorktrees.length)}): ${pathList}. Pass the target worktree path explicitly in the 'directory' parameter or pin '--directory' at server launch.`,
|
|
210
|
+
{
|
|
211
|
+
worktrees: worktreeSummaries,
|
|
212
|
+
hint: 'Specify `directory` in tool arguments or start `llman-sdd studio mcp --directory <path>`.',
|
|
213
|
+
},
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
surfaceLegacyConfigWarningsToStderr(instanceRoot);
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
instanceRoot,
|
|
222
|
+
branch: currentBranch(git),
|
|
223
|
+
io: makeIo(instanceRoot),
|
|
224
|
+
studioIo: makeNodeStudioStateIo(instanceRoot),
|
|
225
|
+
git,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function okToolResult(payload: unknown): {
|
|
230
|
+
content: Array<{ type: 'text'; text: string }>;
|
|
231
|
+
} {
|
|
232
|
+
return {
|
|
233
|
+
content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function errorToolResult(error: unknown): {
|
|
238
|
+
isError: true;
|
|
239
|
+
content: Array<{ type: 'text'; text: string }>;
|
|
240
|
+
} {
|
|
241
|
+
if (error instanceof McpToolError) {
|
|
242
|
+
return {
|
|
243
|
+
isError: true,
|
|
244
|
+
content: [
|
|
245
|
+
{
|
|
246
|
+
type: 'text',
|
|
247
|
+
text: JSON.stringify(
|
|
248
|
+
{
|
|
249
|
+
error: error.code,
|
|
250
|
+
message: error.message,
|
|
251
|
+
...error.details,
|
|
252
|
+
},
|
|
253
|
+
null,
|
|
254
|
+
2,
|
|
255
|
+
),
|
|
256
|
+
},
|
|
257
|
+
],
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
261
|
+
return {
|
|
262
|
+
isError: true,
|
|
263
|
+
content: [
|
|
264
|
+
{
|
|
265
|
+
type: 'text',
|
|
266
|
+
text: JSON.stringify({ error: 'tool_error', message }, null, 2),
|
|
267
|
+
},
|
|
268
|
+
],
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async function resolveUniqueClientRoot(server: McpServer): Promise<string | undefined> {
|
|
273
|
+
try {
|
|
274
|
+
const caps = server.server.getClientCapabilities();
|
|
275
|
+
if (caps?.roots === undefined) return undefined;
|
|
276
|
+
const listed = await server.server.listRoots(undefined, { timeout: 2000 });
|
|
277
|
+
const filePaths: string[] = [];
|
|
278
|
+
for (const root of listed.roots) {
|
|
279
|
+
if (root.uri.startsWith('file://')) {
|
|
280
|
+
try {
|
|
281
|
+
filePaths.push(fileURLToPath(root.uri));
|
|
282
|
+
} catch {}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return filePaths.length === 1 ? filePaths[0] : undefined;
|
|
286
|
+
} catch {
|
|
287
|
+
return undefined;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export interface StudioMcpServerOptions {
|
|
292
|
+
/** Launch working directory (`ctx.cwd`). */
|
|
293
|
+
cwd: string;
|
|
294
|
+
/** Optional launch-pinned `--directory <path>`. */
|
|
295
|
+
pinnedDirectory?: string;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Construct a fresh `McpServer` registering ONLY the 5 negotiation tools
|
|
300
|
+
* (`studio_list_states`, `studio_get_diff`, `studio_validate_draft`,
|
|
301
|
+
* `studio_reply_comment`, `studio_propose_revision`) — zero direct spec-write tools.
|
|
302
|
+
*/
|
|
303
|
+
export async function createStudioMcpServer(options: StudioMcpServerOptions): Promise<McpServer> {
|
|
304
|
+
const [{ McpServer: McpServerCtor }, { z }] = await Promise.all([
|
|
305
|
+
import('@modelcontextprotocol/server'),
|
|
306
|
+
import('zod'),
|
|
307
|
+
]);
|
|
308
|
+
|
|
309
|
+
const revisionOpSchema = z.discriminatedUnion('op', [
|
|
310
|
+
z.object({ op: z.literal('add_state'), name: z.string().min(1) }).strict(),
|
|
311
|
+
z.object({ op: z.literal('remove_state'), stateName: z.string().min(1) }).strict(),
|
|
312
|
+
z
|
|
313
|
+
.object({ op: z.literal('rename_state'), from: z.string().min(1), to: z.string().min(1) })
|
|
314
|
+
.strict(),
|
|
315
|
+
z
|
|
316
|
+
.object({
|
|
317
|
+
op: z.literal('add_transition'),
|
|
318
|
+
from: z.string().min(1),
|
|
319
|
+
event: z.string().min(1),
|
|
320
|
+
condition: z.string().optional(),
|
|
321
|
+
to: z.string().min(1),
|
|
322
|
+
})
|
|
323
|
+
.strict(),
|
|
324
|
+
z
|
|
325
|
+
.object({
|
|
326
|
+
op: z.literal('remove_transition'),
|
|
327
|
+
from: z.string().min(1),
|
|
328
|
+
event: z.string().min(1),
|
|
329
|
+
condition: z.string().optional(),
|
|
330
|
+
to: z.string().min(1),
|
|
331
|
+
})
|
|
332
|
+
.strict(),
|
|
333
|
+
z
|
|
334
|
+
.object({
|
|
335
|
+
op: z.literal('update_transition'),
|
|
336
|
+
match: z
|
|
337
|
+
.object({
|
|
338
|
+
from: z.string().min(1),
|
|
339
|
+
event: z.string().min(1),
|
|
340
|
+
condition: z.string().optional(),
|
|
341
|
+
to: z.string().min(1),
|
|
342
|
+
})
|
|
343
|
+
.strict(),
|
|
344
|
+
next: z
|
|
345
|
+
.object({
|
|
346
|
+
from: z.string().min(1).optional(),
|
|
347
|
+
event: z.string().min(1).optional(),
|
|
348
|
+
condition: z.string().optional(),
|
|
349
|
+
to: z.string().min(1).optional(),
|
|
350
|
+
})
|
|
351
|
+
.strict(),
|
|
352
|
+
})
|
|
353
|
+
.strict(),
|
|
354
|
+
]);
|
|
355
|
+
|
|
356
|
+
const mcpServer = new McpServerCtor(
|
|
357
|
+
{
|
|
358
|
+
name: 'llman-sdd-studio',
|
|
359
|
+
version,
|
|
360
|
+
},
|
|
361
|
+
{
|
|
362
|
+
capabilities: {
|
|
363
|
+
tools: {},
|
|
364
|
+
},
|
|
365
|
+
},
|
|
366
|
+
);
|
|
367
|
+
|
|
368
|
+
const resolveContext = async (inputDirectory?: string): Promise<ResolvedMcpContext> => {
|
|
369
|
+
const needsClientRoot =
|
|
370
|
+
(inputDirectory === undefined || inputDirectory.trim() === '') &&
|
|
371
|
+
(options.pinnedDirectory === undefined || options.pinnedDirectory.trim() === '');
|
|
372
|
+
const clientRoot = needsClientRoot ? await resolveUniqueClientRoot(mcpServer) : undefined;
|
|
373
|
+
return resolveMcpInstanceRoot(inputDirectory, {
|
|
374
|
+
cwd: options.cwd,
|
|
375
|
+
pinnedDirectory: options.pinnedDirectory,
|
|
376
|
+
clientRoot,
|
|
377
|
+
});
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
mcpServer.registerTool(
|
|
381
|
+
'studio_list_states',
|
|
382
|
+
{
|
|
383
|
+
title: 'List Studio Draft States',
|
|
384
|
+
description:
|
|
385
|
+
'List local Studio draft state files under .llman-sdd/studio/states/ for the target workspace.',
|
|
386
|
+
inputSchema: z.object({
|
|
387
|
+
directory: z
|
|
388
|
+
.string()
|
|
389
|
+
.optional()
|
|
390
|
+
.describe(
|
|
391
|
+
'Target workspace or git worktree path (required when multiple worktrees exist and --directory was not pinned).',
|
|
392
|
+
),
|
|
393
|
+
}),
|
|
394
|
+
annotations: {
|
|
395
|
+
readOnlyHint: true,
|
|
396
|
+
destructiveHint: false,
|
|
397
|
+
idempotentHint: true,
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
async ({ directory }) => {
|
|
401
|
+
try {
|
|
402
|
+
const resolved = await resolveContext(directory);
|
|
403
|
+
const states = listStudioStates(resolved.studioIo);
|
|
404
|
+
return okToolResult({
|
|
405
|
+
instanceRoot: resolved.instanceRoot,
|
|
406
|
+
branch: resolved.branch,
|
|
407
|
+
states,
|
|
408
|
+
});
|
|
409
|
+
} catch (error) {
|
|
410
|
+
return errorToolResult(error);
|
|
411
|
+
}
|
|
412
|
+
},
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
mcpServer.registerTool(
|
|
416
|
+
'studio_get_diff',
|
|
417
|
+
{
|
|
418
|
+
title: 'Get Studio Draft Diff',
|
|
419
|
+
description:
|
|
420
|
+
'Inspect semantic diffs, comments, pending revisions, and optional in-memory Unified Diff preview for a Studio draft.',
|
|
421
|
+
inputSchema: z.object({
|
|
422
|
+
stateId: z
|
|
423
|
+
.string()
|
|
424
|
+
.optional()
|
|
425
|
+
.describe('Studio draft state ID (auto-selected when exactly one draft exists).'),
|
|
426
|
+
includeUnified: z
|
|
427
|
+
.boolean()
|
|
428
|
+
.optional()
|
|
429
|
+
.describe('Include in-memory Unified Diff preview for changed machines (default: true).'),
|
|
430
|
+
directory: z.string().optional().describe('Target workspace or git worktree path.'),
|
|
431
|
+
}),
|
|
432
|
+
annotations: {
|
|
433
|
+
readOnlyHint: true,
|
|
434
|
+
destructiveHint: false,
|
|
435
|
+
idempotentHint: true,
|
|
436
|
+
},
|
|
437
|
+
},
|
|
438
|
+
async ({ stateId, includeUnified, directory }) => {
|
|
439
|
+
try {
|
|
440
|
+
const resolved = await resolveContext(directory);
|
|
441
|
+
const targetId = resolveStateIdOrThrow(resolved.studioIo, stateId);
|
|
442
|
+
const doc = readStudioState(resolved.studioIo, targetId);
|
|
443
|
+
const wantUnified = includeUnified !== false;
|
|
444
|
+
const plan = planStudioApply(doc, usedReqIds(resolved.io, SPECS_DIR));
|
|
445
|
+
|
|
446
|
+
const semanticDiff: Record<
|
|
447
|
+
string,
|
|
448
|
+
{
|
|
449
|
+
mode: MachineDraft['mode'];
|
|
450
|
+
sourceFile: string;
|
|
451
|
+
hasChanges: boolean;
|
|
452
|
+
diff: ReturnType<typeof computeMachineDiff>;
|
|
453
|
+
summary: string;
|
|
454
|
+
}
|
|
455
|
+
> = {};
|
|
456
|
+
const unifiedDiff: Record<string, string | null> = {};
|
|
457
|
+
const unifiedDiffErrors: Record<string, string> = {};
|
|
458
|
+
|
|
459
|
+
for (const [machineKey, originalDraft] of Object.entries(doc.machines)) {
|
|
460
|
+
const draft = plan.doc.machines[plan.keyMap[machineKey] ?? machineKey] ?? originalDraft;
|
|
461
|
+
const diff = computeMachineDiff(draft);
|
|
462
|
+
const summary = formatSemanticDiff(diff, draft);
|
|
463
|
+
semanticDiff[machineKey] = {
|
|
464
|
+
mode: draft.mode,
|
|
465
|
+
sourceFile: draft.sourceFile,
|
|
466
|
+
hasChanges: diff.hasChanges,
|
|
467
|
+
diff,
|
|
468
|
+
summary,
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
if (wantUnified) {
|
|
472
|
+
if (diff.hasChanges) {
|
|
473
|
+
try {
|
|
474
|
+
const beforeText = resolved.io.exists(draft.sourceFile)
|
|
475
|
+
? resolved.io.readText(draft.sourceFile)
|
|
476
|
+
: null;
|
|
477
|
+
const afterText = renderUpdatedFeatureSource(beforeText, draft, {
|
|
478
|
+
existingReqIds: plan.usedReqIds,
|
|
479
|
+
});
|
|
480
|
+
unifiedDiff[machineKey] = previewFeatureUnifiedDiff(
|
|
481
|
+
draft.sourceFile,
|
|
482
|
+
beforeText,
|
|
483
|
+
afterText,
|
|
484
|
+
);
|
|
485
|
+
} catch (error) {
|
|
486
|
+
if (error instanceof StudioSyncError) {
|
|
487
|
+
unifiedDiff[machineKey] = null;
|
|
488
|
+
unifiedDiffErrors[machineKey] = error.message;
|
|
489
|
+
} else {
|
|
490
|
+
throw error;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
} else {
|
|
494
|
+
unifiedDiff[machineKey] = null;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return okToolResult({
|
|
500
|
+
instanceRoot: resolved.instanceRoot,
|
|
501
|
+
branch: resolved.branch,
|
|
502
|
+
stateId: doc.id,
|
|
503
|
+
title: doc.title,
|
|
504
|
+
updatedAt: doc.updatedAt,
|
|
505
|
+
semanticDiff,
|
|
506
|
+
comments: doc.comments,
|
|
507
|
+
openComments: doc.comments.filter((c) => c.status === 'open'),
|
|
508
|
+
pendingRevisions: doc.revisions.filter((r) => r.status === 'pending'),
|
|
509
|
+
...(wantUnified ? { unifiedDiff } : {}),
|
|
510
|
+
...(Object.keys(unifiedDiffErrors).length > 0 ? { unifiedDiffErrors } : {}),
|
|
511
|
+
});
|
|
512
|
+
} catch (error) {
|
|
513
|
+
return errorToolResult(error);
|
|
514
|
+
}
|
|
515
|
+
},
|
|
516
|
+
);
|
|
517
|
+
|
|
518
|
+
mcpServer.registerTool(
|
|
519
|
+
'studio_validate_draft',
|
|
520
|
+
{
|
|
521
|
+
title: 'Validate Studio Draft',
|
|
522
|
+
description:
|
|
523
|
+
'Run E1-E4/W1-W2 state-machine graph validation on a Studio draft, optionally pre-validating hypothetical patchOps in memory without writing to disk.',
|
|
524
|
+
inputSchema: z.object({
|
|
525
|
+
stateId: z
|
|
526
|
+
.string()
|
|
527
|
+
.optional()
|
|
528
|
+
.describe('Studio draft state ID (auto-selected when exactly one draft exists).'),
|
|
529
|
+
machineKey: z
|
|
530
|
+
.string()
|
|
531
|
+
.optional()
|
|
532
|
+
.describe('Target machine key when applying patchOps to a multi-machine draft.'),
|
|
533
|
+
patchOps: z
|
|
534
|
+
.array(revisionOpSchema)
|
|
535
|
+
.optional()
|
|
536
|
+
.describe(
|
|
537
|
+
'Optional RevisionOp[] applied only in memory before validation (never mutates disk).',
|
|
538
|
+
),
|
|
539
|
+
directory: z.string().optional().describe('Target workspace or git worktree path.'),
|
|
540
|
+
}),
|
|
541
|
+
annotations: {
|
|
542
|
+
readOnlyHint: true,
|
|
543
|
+
destructiveHint: false,
|
|
544
|
+
idempotentHint: true,
|
|
545
|
+
},
|
|
546
|
+
},
|
|
547
|
+
async ({ stateId, machineKey, patchOps, directory }) => {
|
|
548
|
+
try {
|
|
549
|
+
const resolved = await resolveContext(directory);
|
|
550
|
+
const targetId = resolveStateIdOrThrow(resolved.studioIo, stateId);
|
|
551
|
+
const doc = readStudioState(resolved.studioIo, targetId);
|
|
552
|
+
|
|
553
|
+
const workingMachines: Record<string, MachineDraft> = {};
|
|
554
|
+
for (const [k, d] of Object.entries(doc.machines)) {
|
|
555
|
+
workingMachines[k] = cloneMachineDraft(d);
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const hasPatch = patchOps !== undefined && patchOps.length > 0;
|
|
559
|
+
if (hasPatch) {
|
|
560
|
+
const keys = Object.keys(workingMachines);
|
|
561
|
+
let targetKey = machineKey?.trim();
|
|
562
|
+
if (!targetKey) {
|
|
563
|
+
if (keys.length === 1) {
|
|
564
|
+
targetKey = keys[0]!;
|
|
565
|
+
} else if (keys.length === 0) {
|
|
566
|
+
throw new McpToolError(
|
|
567
|
+
'no_machines',
|
|
568
|
+
`studio state '${doc.id}' contains no machines`,
|
|
569
|
+
);
|
|
570
|
+
} else {
|
|
571
|
+
throw new McpToolError(
|
|
572
|
+
'ambiguous_machine',
|
|
573
|
+
`multiple machines in state '${doc.id}' (${keys.join(', ')}); specify machineKey alongside patchOps`,
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
const targetDraft = workingMachines[targetKey];
|
|
578
|
+
if (!targetDraft || !targetDraft.current) {
|
|
579
|
+
throw new McpToolError(
|
|
580
|
+
'machine_not_found',
|
|
581
|
+
`cannot patch machine without current graph: ${targetKey}`,
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
targetDraft.current = applyRevisionOpsToMachine(
|
|
585
|
+
targetDraft.current,
|
|
586
|
+
patchOps as RevisionOp[],
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const diagnostics: Array<MachineDiagnostic & { machineKey: string }> = [];
|
|
591
|
+
const machines: Array<{
|
|
592
|
+
machineKey: string;
|
|
593
|
+
mode: MachineDraft['mode'];
|
|
594
|
+
sourceFile: string;
|
|
595
|
+
valid: boolean;
|
|
596
|
+
diagnostics: MachineDiagnostic[];
|
|
597
|
+
}> = [];
|
|
598
|
+
let errorCount = 0;
|
|
599
|
+
let warningCount = 0;
|
|
600
|
+
|
|
601
|
+
for (const [mKey, draft] of Object.entries(workingMachines)) {
|
|
602
|
+
if (draft.mode === 'remove') {
|
|
603
|
+
machines.push({
|
|
604
|
+
machineKey: mKey,
|
|
605
|
+
mode: draft.mode,
|
|
606
|
+
sourceFile: draft.sourceFile,
|
|
607
|
+
valid: true,
|
|
608
|
+
diagnostics: [],
|
|
609
|
+
});
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
const diags: MachineDiagnostic[] = draft.current
|
|
613
|
+
? validateMachineGraph(draft.current)
|
|
614
|
+
: [
|
|
615
|
+
{
|
|
616
|
+
code: 'E1',
|
|
617
|
+
severity: 'error',
|
|
618
|
+
targetKind: 'machine',
|
|
619
|
+
targetId: null,
|
|
620
|
+
message: 'E1 structure: machine draft has no current graph',
|
|
621
|
+
},
|
|
622
|
+
];
|
|
623
|
+
for (const d of diags) {
|
|
624
|
+
if (d.severity === 'error') errorCount += 1;
|
|
625
|
+
else warningCount += 1;
|
|
626
|
+
diagnostics.push({ ...d, machineKey: mKey });
|
|
627
|
+
}
|
|
628
|
+
machines.push({
|
|
629
|
+
machineKey: mKey,
|
|
630
|
+
mode: draft.mode,
|
|
631
|
+
sourceFile: draft.sourceFile,
|
|
632
|
+
valid: !hasBlockingDiagnostics(diags),
|
|
633
|
+
diagnostics: diags,
|
|
634
|
+
});
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
return okToolResult({
|
|
638
|
+
instanceRoot: resolved.instanceRoot,
|
|
639
|
+
branch: resolved.branch,
|
|
640
|
+
stateId: doc.id,
|
|
641
|
+
ok: errorCount === 0,
|
|
642
|
+
patched: hasPatch,
|
|
643
|
+
errorCount,
|
|
644
|
+
warningCount,
|
|
645
|
+
diagnostics,
|
|
646
|
+
machines,
|
|
647
|
+
});
|
|
648
|
+
} catch (error) {
|
|
649
|
+
return errorToolResult(error);
|
|
650
|
+
}
|
|
651
|
+
},
|
|
652
|
+
);
|
|
653
|
+
|
|
654
|
+
mcpServer.registerTool(
|
|
655
|
+
'studio_reply_comment',
|
|
656
|
+
{
|
|
657
|
+
title: 'Reply to Studio Comment',
|
|
658
|
+
description:
|
|
659
|
+
'Atomically append an Agent reply to an anchored comment in a local Studio draft state file (optionally resolving the target comment).',
|
|
660
|
+
inputSchema: z.object({
|
|
661
|
+
stateId: z.string().min(1).describe('Studio draft state ID.'),
|
|
662
|
+
commentId: z.string().min(1).describe('Target comment ID to reply to.'),
|
|
663
|
+
body: z.string().min(1).describe('Reply message text.'),
|
|
664
|
+
resolve: z
|
|
665
|
+
.boolean()
|
|
666
|
+
.optional()
|
|
667
|
+
.describe('Mark the target comment as resolved (default: false).'),
|
|
668
|
+
directory: z.string().optional().describe('Target workspace or git worktree path.'),
|
|
669
|
+
}),
|
|
670
|
+
annotations: {
|
|
671
|
+
readOnlyHint: false,
|
|
672
|
+
destructiveHint: false,
|
|
673
|
+
idempotentHint: false,
|
|
674
|
+
},
|
|
675
|
+
},
|
|
676
|
+
async ({ stateId, commentId, body, resolve: shouldResolve, directory }) => {
|
|
677
|
+
try {
|
|
678
|
+
if (body.trim() === '') {
|
|
679
|
+
throw new McpToolError('invalid_argument', 'body must not be empty');
|
|
680
|
+
}
|
|
681
|
+
const resolved = await resolveContext(directory);
|
|
682
|
+
const targetId = validateStateId(stateId);
|
|
683
|
+
const doc = readStudioState(resolved.studioIo, targetId);
|
|
684
|
+
const nextDoc = replyStudioComment(doc, commentId, {
|
|
685
|
+
author: 'agent',
|
|
686
|
+
body,
|
|
687
|
+
createdAt: resolved.studioIo.now().toISOString(),
|
|
688
|
+
resolve: shouldResolve === true,
|
|
689
|
+
});
|
|
690
|
+
writeStudioState(resolved.studioIo, nextDoc);
|
|
691
|
+
const comment = nextDoc.comments.at(-1)!;
|
|
692
|
+
return okToolResult({
|
|
693
|
+
instanceRoot: resolved.instanceRoot,
|
|
694
|
+
branch: resolved.branch,
|
|
695
|
+
stateId: doc.id,
|
|
696
|
+
resolvedTarget: shouldResolve === true,
|
|
697
|
+
comment,
|
|
698
|
+
});
|
|
699
|
+
} catch (error) {
|
|
700
|
+
return errorToolResult(error);
|
|
701
|
+
}
|
|
702
|
+
},
|
|
703
|
+
);
|
|
704
|
+
|
|
705
|
+
mcpServer.registerTool(
|
|
706
|
+
'studio_propose_revision',
|
|
707
|
+
{
|
|
708
|
+
title: 'Propose Studio Revision',
|
|
709
|
+
description:
|
|
710
|
+
'Atomically append a non-destructive pending Agent revision proposal to a Studio draft without mutating human draft graphs or llmanspec/specs/.',
|
|
711
|
+
inputSchema: z.object({
|
|
712
|
+
stateId: z.string().min(1).describe('Studio draft state ID.'),
|
|
713
|
+
machineKey: z.string().min(1).describe('Target machine key in the draft.'),
|
|
714
|
+
rationale: z.string().min(1).describe('Explanation of why the revision is proposed.'),
|
|
715
|
+
ops: z
|
|
716
|
+
.array(revisionOpSchema)
|
|
717
|
+
.min(1)
|
|
718
|
+
.describe('Non-empty list of structured RevisionOp operations.'),
|
|
719
|
+
directory: z.string().optional().describe('Target workspace or git worktree path.'),
|
|
720
|
+
}),
|
|
721
|
+
annotations: {
|
|
722
|
+
readOnlyHint: false,
|
|
723
|
+
destructiveHint: false,
|
|
724
|
+
idempotentHint: false,
|
|
725
|
+
},
|
|
726
|
+
},
|
|
727
|
+
async ({ stateId, machineKey, rationale, ops, directory }) => {
|
|
728
|
+
try {
|
|
729
|
+
if (rationale.trim() === '') {
|
|
730
|
+
throw new McpToolError('invalid_argument', 'rationale must not be empty');
|
|
731
|
+
}
|
|
732
|
+
const resolved = await resolveContext(directory);
|
|
733
|
+
const targetId = validateStateId(stateId);
|
|
734
|
+
const doc = readStudioState(resolved.studioIo, targetId);
|
|
735
|
+
const draft = doc.machines[machineKey];
|
|
736
|
+
if (!draft) {
|
|
737
|
+
throw new McpToolError(
|
|
738
|
+
'machine_not_found',
|
|
739
|
+
`machine not found in state '${doc.id}': ${machineKey}`,
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const nextDoc = proposeRevision(doc, {
|
|
744
|
+
machineKey,
|
|
745
|
+
rationale,
|
|
746
|
+
ops: ops as RevisionOp[],
|
|
747
|
+
createdAt: resolved.studioIo.now().toISOString(),
|
|
748
|
+
source: 'agent',
|
|
749
|
+
});
|
|
750
|
+
const revision = nextDoc.revisions.at(-1)!;
|
|
751
|
+
const preview = previewRevisionProposal(draft, revision);
|
|
752
|
+
writeStudioState(resolved.studioIo, nextDoc);
|
|
753
|
+
|
|
754
|
+
return okToolResult({
|
|
755
|
+
instanceRoot: resolved.instanceRoot,
|
|
756
|
+
branch: resolved.branch,
|
|
757
|
+
stateId: doc.id,
|
|
758
|
+
revision,
|
|
759
|
+
previewDiff: {
|
|
760
|
+
diffFromCurrent: preview.diffFromCurrent,
|
|
761
|
+
diffFromBaseline: preview.diffFromBaseline,
|
|
762
|
+
diagnostics: preview.diagnostics,
|
|
763
|
+
},
|
|
764
|
+
});
|
|
765
|
+
} catch (error) {
|
|
766
|
+
return errorToolResult(error);
|
|
767
|
+
}
|
|
768
|
+
},
|
|
769
|
+
);
|
|
770
|
+
|
|
771
|
+
return mcpServer;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Register `llman-sdd studio mcp` under the `studio` parent command.
|
|
776
|
+
*/
|
|
777
|
+
export function registerStudioMcp(studioCmd: Command, ctx: CliContext): void {
|
|
778
|
+
const mcpCmd = studioCmd
|
|
779
|
+
.command('mcp')
|
|
780
|
+
.description('Run the Studio MCP server (stdio) or print MCP client configuration')
|
|
781
|
+
.option('--transport <mode>', 'MCP transport mode: stdio (default) | http', 'stdio')
|
|
782
|
+
.option(
|
|
783
|
+
'--print-config [client]',
|
|
784
|
+
'print MCP client configuration snippet (claude-code | cursor | codex | generic) and exit',
|
|
785
|
+
);
|
|
786
|
+
addSpecDirOption(mcpCmd);
|
|
787
|
+
|
|
788
|
+
mcpCmd.action(
|
|
789
|
+
async (options: { transport?: string; printConfig?: string | boolean; directory?: string }) => {
|
|
790
|
+
if (options.printConfig !== undefined && options.printConfig !== false) {
|
|
791
|
+
const requested =
|
|
792
|
+
typeof options.printConfig === 'string' ? options.printConfig.trim() : 'generic';
|
|
793
|
+
if (!isMcpPrintConfigClient(requested)) {
|
|
794
|
+
throw new CliError(
|
|
795
|
+
`invalid --print-config client '${requested}' (expected: ${MCP_PRINT_CONFIG_CLIENTS.join(' | ')})`,
|
|
796
|
+
2,
|
|
797
|
+
);
|
|
798
|
+
}
|
|
799
|
+
console.log(renderMcpClientConfig(requested, options.directory));
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
const transportMode = (options.transport ?? 'stdio').trim();
|
|
804
|
+
if (transportMode === 'http') {
|
|
805
|
+
throw new CliError(
|
|
806
|
+
'MCP Streamable HTTP transport (--transport http) is not yet implemented; use --transport stdio',
|
|
807
|
+
1,
|
|
808
|
+
);
|
|
809
|
+
}
|
|
810
|
+
if (transportMode !== 'stdio') {
|
|
811
|
+
throw new CliError(`invalid --transport '${transportMode}' (expected: stdio | http)`, 2);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
const startupDir =
|
|
815
|
+
options.directory !== undefined ? resolve(ctx.cwd, options.directory) : ctx.cwd;
|
|
816
|
+
const startupRoot = resolveInstanceRoot(startupDir, makeIo(startupDir));
|
|
817
|
+
if (startupRoot !== null) {
|
|
818
|
+
surfaceLegacyConfigWarningsToStderr(resolve(startupRoot));
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
const { serveStdio, StdioServerTransport } =
|
|
822
|
+
await import('@modelcontextprotocol/server/stdio');
|
|
823
|
+
const transport = new StdioServerTransport();
|
|
824
|
+
const handle = serveStdio(
|
|
825
|
+
() =>
|
|
826
|
+
createStudioMcpServer({
|
|
827
|
+
cwd: ctx.cwd,
|
|
828
|
+
pinnedDirectory: options.directory,
|
|
829
|
+
}),
|
|
830
|
+
{
|
|
831
|
+
transport,
|
|
832
|
+
onerror: (error) => {
|
|
833
|
+
console.error(`[llman-sdd studio mcp] ${error.message}`);
|
|
834
|
+
},
|
|
835
|
+
},
|
|
836
|
+
);
|
|
837
|
+
|
|
838
|
+
await new Promise<void>((resolveDone) => {
|
|
839
|
+
let finished = false;
|
|
840
|
+
const finish = (): void => {
|
|
841
|
+
if (finished) return;
|
|
842
|
+
finished = true;
|
|
843
|
+
process.off('SIGINT', onSignal);
|
|
844
|
+
process.off('SIGTERM', onSignal);
|
|
845
|
+
resolveDone();
|
|
846
|
+
};
|
|
847
|
+
const onSignal = (): void => {
|
|
848
|
+
void handle.close().finally(finish);
|
|
849
|
+
};
|
|
850
|
+
const prevOnClose = transport.onclose;
|
|
851
|
+
Object.assign(transport, {
|
|
852
|
+
onclose: () => {
|
|
853
|
+
prevOnClose?.();
|
|
854
|
+
finish();
|
|
855
|
+
},
|
|
856
|
+
});
|
|
857
|
+
process.on('SIGINT', onSignal);
|
|
858
|
+
process.on('SIGTERM', onSignal);
|
|
859
|
+
});
|
|
860
|
+
},
|
|
861
|
+
);
|
|
862
|
+
}
|