@llman-sdd/cli 0.11.0 → 0.12.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.
- 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 +0 -1
- 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 +3 -18
- 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,1315 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `llman-sdd studio` CLI-first bidirectional negotiation command group (studio-cli r134-r137).
|
|
3
|
+
* All pure graph validation, semantic diff, revision, storage, and lossless .feature rendering
|
|
4
|
+
* delegate directly to `@llman-sdd/core` — zero domain logic duplication here.
|
|
5
|
+
*/
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { resolve } from 'node:path';
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
applyDriftProposalsToStateDoc,
|
|
12
|
+
applyRevisionOpsToMachine,
|
|
13
|
+
buildDriftSlicePacket,
|
|
14
|
+
cloneMachineDraft,
|
|
15
|
+
computeMachineDiff,
|
|
16
|
+
createStudioStateDoc,
|
|
17
|
+
currentBranch,
|
|
18
|
+
defaultBranch,
|
|
19
|
+
deleteStudioState,
|
|
20
|
+
discoverSpecs,
|
|
21
|
+
extractStudioMachines,
|
|
22
|
+
formatSemanticDiff,
|
|
23
|
+
hasBlockingDiagnostics,
|
|
24
|
+
hintForStudioDiagnostic,
|
|
25
|
+
listStudioStates,
|
|
26
|
+
parseRuntimeTraceJsonl,
|
|
27
|
+
parseUnifiedDiffHunks,
|
|
28
|
+
planStudioApply,
|
|
29
|
+
previewFeatureUnifiedDiff,
|
|
30
|
+
proposeRevision,
|
|
31
|
+
readStudioState,
|
|
32
|
+
reconcileRuntimeTrace,
|
|
33
|
+
renderUpdatedFeatureSource,
|
|
34
|
+
replyStudioComment,
|
|
35
|
+
StudioSyncError,
|
|
36
|
+
validateMachineGraph,
|
|
37
|
+
validateStateId,
|
|
38
|
+
usedReqIds,
|
|
39
|
+
writeStudioState,
|
|
40
|
+
type DriftSlicePacket,
|
|
41
|
+
type MachineDiagnostic,
|
|
42
|
+
type MachineDraft,
|
|
43
|
+
type RevisionOp,
|
|
44
|
+
type RuntimeTraceParseError,
|
|
45
|
+
type RuntimeTraceReconcileResult,
|
|
46
|
+
type SemanticAnchor,
|
|
47
|
+
type StudioStateDoc,
|
|
48
|
+
} from '@llman-sdd/core';
|
|
49
|
+
import type { Command } from 'commander';
|
|
50
|
+
|
|
51
|
+
import {
|
|
52
|
+
addSpecDirOption,
|
|
53
|
+
emitCliHint,
|
|
54
|
+
CliError,
|
|
55
|
+
exitWith,
|
|
56
|
+
formatNotFound,
|
|
57
|
+
loadRootSpecEntries,
|
|
58
|
+
reRootContext,
|
|
59
|
+
resolveRootSpecsDir,
|
|
60
|
+
version as cliVersion,
|
|
61
|
+
type CliContext,
|
|
62
|
+
} from '../cli-shared.ts';
|
|
63
|
+
import {
|
|
64
|
+
defaultHubFilePath,
|
|
65
|
+
formatLoopbackUrl,
|
|
66
|
+
isLoopbackHost,
|
|
67
|
+
removeHubInfoFile,
|
|
68
|
+
resolveLiveHub,
|
|
69
|
+
} from '../studio-server/hub.ts';
|
|
70
|
+
import { startStudioHub } from '../studio-server/server.ts';
|
|
71
|
+
import { collectDiskSyncPreview } from '../studio-server/syncDisk.ts';
|
|
72
|
+
import { registerStudioMcp } from './studioMcp.ts';
|
|
73
|
+
import {
|
|
74
|
+
EMPTY_DRAFT_NEXT,
|
|
75
|
+
makeNodeStudioStateIo,
|
|
76
|
+
readStudioStateOrThrow,
|
|
77
|
+
resolveStateIdOrThrow,
|
|
78
|
+
} from './studioShared.ts';
|
|
79
|
+
|
|
80
|
+
export { makeNodeStudioStateIo, resolveStateIdOrThrow };
|
|
81
|
+
|
|
82
|
+
function addJsonFlags(cmd: Command): void {
|
|
83
|
+
cmd
|
|
84
|
+
.option('--json', 'emit structured JSON')
|
|
85
|
+
.option('--compact-json', 'emit single-line compact JSON');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function emitStudioOutput(
|
|
89
|
+
payload: unknown,
|
|
90
|
+
options: { json?: boolean; compactJson?: boolean },
|
|
91
|
+
humanFn: () => string,
|
|
92
|
+
): void {
|
|
93
|
+
if (options.compactJson === true) {
|
|
94
|
+
console.log(JSON.stringify(payload));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (options.json === true) {
|
|
98
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
console.log(humanFn());
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
105
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function assertNonEmptyString(val: unknown, field: string): string {
|
|
109
|
+
if (typeof val !== 'string' || val.trim() === '') {
|
|
110
|
+
throw new CliError(`invalid revision op: '${field}' must be a non-empty string`, 2);
|
|
111
|
+
}
|
|
112
|
+
return val;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function assertOptionalString(val: unknown, field: string): string | undefined {
|
|
116
|
+
if (val === undefined) return undefined;
|
|
117
|
+
if (typeof val !== 'string') {
|
|
118
|
+
throw new CliError(`invalid revision op: '${field}' must be a string`, 2);
|
|
119
|
+
}
|
|
120
|
+
return val;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function rejectLegacyGuardKey(value: unknown, path: string): void {
|
|
124
|
+
if (Array.isArray(value)) {
|
|
125
|
+
value.forEach((item, i) => rejectLegacyGuardKey(item, `${path}[${String(i)}]`));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (!isPlainObject(value)) return;
|
|
129
|
+
if (Object.hasOwn(value, 'guard')) {
|
|
130
|
+
throw new CliError(`${path} uses removed key 'guard'; write 'condition'`, 2);
|
|
131
|
+
}
|
|
132
|
+
for (const [k, v] of Object.entries(value)) {
|
|
133
|
+
if (k === 'match' || k === 'next') rejectLegacyGuardKey(v, `${path}.${k}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function parseRevisionOp(raw: unknown, idx: number): RevisionOp {
|
|
138
|
+
if (!isPlainObject(raw) || typeof raw.op !== 'string') {
|
|
139
|
+
throw new CliError(`invalid revision op at index ${String(idx)}: expected object with 'op'`, 2);
|
|
140
|
+
}
|
|
141
|
+
rejectLegacyGuardKey(raw, `ops[${String(idx)}]`);
|
|
142
|
+
switch (raw.op) {
|
|
143
|
+
case 'add_state':
|
|
144
|
+
return { op: 'add_state', name: assertNonEmptyString(raw.name, `ops[${String(idx)}].name`) };
|
|
145
|
+
case 'remove_state':
|
|
146
|
+
return {
|
|
147
|
+
op: 'remove_state',
|
|
148
|
+
stateName: assertNonEmptyString(raw.stateName, `ops[${String(idx)}].stateName`),
|
|
149
|
+
};
|
|
150
|
+
case 'rename_state':
|
|
151
|
+
return {
|
|
152
|
+
op: 'rename_state',
|
|
153
|
+
from: assertNonEmptyString(raw.from, `ops[${String(idx)}].from`),
|
|
154
|
+
to: assertNonEmptyString(raw.to, `ops[${String(idx)}].to`),
|
|
155
|
+
};
|
|
156
|
+
case 'add_transition': {
|
|
157
|
+
const condition = assertOptionalString(raw.condition, `ops[${String(idx)}].condition`);
|
|
158
|
+
return {
|
|
159
|
+
op: 'add_transition',
|
|
160
|
+
from: assertNonEmptyString(raw.from, `ops[${String(idx)}].from`),
|
|
161
|
+
event: assertNonEmptyString(raw.event, `ops[${String(idx)}].event`),
|
|
162
|
+
...(condition !== undefined ? { condition } : {}),
|
|
163
|
+
to: assertNonEmptyString(raw.to, `ops[${String(idx)}].to`),
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
case 'remove_transition': {
|
|
167
|
+
const condition = assertOptionalString(raw.condition, `ops[${String(idx)}].condition`);
|
|
168
|
+
return {
|
|
169
|
+
op: 'remove_transition',
|
|
170
|
+
from: assertNonEmptyString(raw.from, `ops[${String(idx)}].from`),
|
|
171
|
+
event: assertNonEmptyString(raw.event, `ops[${String(idx)}].event`),
|
|
172
|
+
...(condition !== undefined ? { condition } : {}),
|
|
173
|
+
to: assertNonEmptyString(raw.to, `ops[${String(idx)}].to`),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
case 'update_transition': {
|
|
177
|
+
if (!isPlainObject(raw.match) || !isPlainObject(raw.next)) {
|
|
178
|
+
throw new CliError(
|
|
179
|
+
`invalid revision op at index ${String(idx)}: update_transition requires 'match' and 'next' objects`,
|
|
180
|
+
2,
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
const matchCondition = assertOptionalString(
|
|
184
|
+
raw.match.condition,
|
|
185
|
+
`ops[${String(idx)}].match.condition`,
|
|
186
|
+
);
|
|
187
|
+
const nextFrom = assertOptionalString(raw.next.from, `ops[${String(idx)}].next.from`);
|
|
188
|
+
const nextEvent = assertOptionalString(raw.next.event, `ops[${String(idx)}].next.event`);
|
|
189
|
+
const nextCondition = assertOptionalString(
|
|
190
|
+
raw.next.condition,
|
|
191
|
+
`ops[${String(idx)}].next.condition`,
|
|
192
|
+
);
|
|
193
|
+
const nextTo = assertOptionalString(raw.next.to, `ops[${String(idx)}].next.to`);
|
|
194
|
+
return {
|
|
195
|
+
op: 'update_transition',
|
|
196
|
+
match: {
|
|
197
|
+
from: assertNonEmptyString(raw.match.from, `ops[${String(idx)}].match.from`),
|
|
198
|
+
event: assertNonEmptyString(raw.match.event, `ops[${String(idx)}].match.event`),
|
|
199
|
+
...(matchCondition !== undefined ? { condition: matchCondition } : {}),
|
|
200
|
+
to: assertNonEmptyString(raw.match.to, `ops[${String(idx)}].match.to`),
|
|
201
|
+
},
|
|
202
|
+
next: {
|
|
203
|
+
...(nextFrom !== undefined ? { from: nextFrom } : {}),
|
|
204
|
+
...(nextEvent !== undefined ? { event: nextEvent } : {}),
|
|
205
|
+
...(nextCondition !== undefined ? { condition: nextCondition } : {}),
|
|
206
|
+
...(nextTo !== undefined ? { to: nextTo } : {}),
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
default:
|
|
211
|
+
throw new CliError(
|
|
212
|
+
`invalid revision op at index ${String(idx)}: unsupported op '${raw.op}'`,
|
|
213
|
+
2,
|
|
214
|
+
);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
interface ParsedRevisionPayload {
|
|
219
|
+
machineKey: string;
|
|
220
|
+
ops: RevisionOp[];
|
|
221
|
+
rationale: string;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function parseRevisionPayload(
|
|
225
|
+
rawText: string,
|
|
226
|
+
doc: StudioStateDoc,
|
|
227
|
+
explicitMachineKey?: string,
|
|
228
|
+
explicitRationale?: string,
|
|
229
|
+
): ParsedRevisionPayload {
|
|
230
|
+
let parsed: unknown;
|
|
231
|
+
try {
|
|
232
|
+
parsed = JSON.parse(rawText);
|
|
233
|
+
} catch (error) {
|
|
234
|
+
throw new CliError(
|
|
235
|
+
`invalid revision JSON: ${error instanceof Error ? error.message : String(error)}`,
|
|
236
|
+
2,
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
let rawOps: unknown;
|
|
241
|
+
let payloadMachineKey: string | undefined;
|
|
242
|
+
let payloadRationale: string | undefined;
|
|
243
|
+
|
|
244
|
+
if (Array.isArray(parsed)) {
|
|
245
|
+
rawOps = parsed;
|
|
246
|
+
} else if (isPlainObject(parsed)) {
|
|
247
|
+
rawOps = parsed.ops;
|
|
248
|
+
if (parsed.machineKey !== undefined) {
|
|
249
|
+
if (typeof parsed.machineKey !== 'string' || parsed.machineKey.trim() === '') {
|
|
250
|
+
throw new CliError("invalid revision payload: 'machineKey' must be a non-empty string", 2);
|
|
251
|
+
}
|
|
252
|
+
payloadMachineKey = parsed.machineKey.trim();
|
|
253
|
+
}
|
|
254
|
+
if (parsed.rationale !== undefined) {
|
|
255
|
+
if (typeof parsed.rationale !== 'string') {
|
|
256
|
+
throw new CliError("invalid revision payload: 'rationale' must be a string", 2);
|
|
257
|
+
}
|
|
258
|
+
payloadRationale = parsed.rationale;
|
|
259
|
+
}
|
|
260
|
+
} else {
|
|
261
|
+
throw new CliError(
|
|
262
|
+
'invalid revision payload: expected JSON array of RevisionOp or object { machineKey?, rationale?, ops }',
|
|
263
|
+
2,
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (!Array.isArray(rawOps) || rawOps.length === 0) {
|
|
268
|
+
throw new CliError('invalid revision payload: ops must be a non-empty array', 2);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const ops = rawOps.map((item, idx) => parseRevisionOp(item, idx));
|
|
272
|
+
const machineKeys = Object.keys(doc.machines);
|
|
273
|
+
let machineKey = explicitMachineKey?.trim() || payloadMachineKey;
|
|
274
|
+
|
|
275
|
+
if (!machineKey) {
|
|
276
|
+
if (machineKeys.length === 1) {
|
|
277
|
+
machineKey = machineKeys[0]!;
|
|
278
|
+
} else if (machineKeys.length === 0) {
|
|
279
|
+
throw new CliError(`studio state '${doc.id}' contains no machines`, 1);
|
|
280
|
+
} else {
|
|
281
|
+
throw new CliError(
|
|
282
|
+
`multiple machines in state '${doc.id}' (${machineKeys.join(', ')}); specify --machine <key> or include machineKey in JSON`,
|
|
283
|
+
2,
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (!doc.machines[machineKey]) {
|
|
289
|
+
throw new CliError(`machine not found in state '${doc.id}': ${machineKey}`, 1);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const rationale = (explicitRationale ?? payloadRationale ?? 'Agent revision proposal').trim();
|
|
293
|
+
return { machineKey, ops, rationale };
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function readInputText(cwd: string, filePath?: string): string {
|
|
297
|
+
if (filePath !== undefined && filePath !== '-') {
|
|
298
|
+
const abs = resolve(cwd, filePath);
|
|
299
|
+
if (!existsSync(abs)) {
|
|
300
|
+
throw new CliError(`input file not found: ${filePath}`, 2);
|
|
301
|
+
}
|
|
302
|
+
return readFileSync(abs, 'utf8');
|
|
303
|
+
}
|
|
304
|
+
const text = readFileSync(0, 'utf8');
|
|
305
|
+
if (text.trim() === '') {
|
|
306
|
+
throw new CliError('empty JSON input on stdin (pass --file <path> or pipe JSON to stdin)', 2);
|
|
307
|
+
}
|
|
308
|
+
return text;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function formatAnchor(anchor: SemanticAnchor): string {
|
|
312
|
+
if (anchor.kind === 'machine') return `machine:${anchor.machineKey}`;
|
|
313
|
+
if (anchor.kind === 'state') return `state:${anchor.machineKey}#${anchor.stateUid}`;
|
|
314
|
+
if (anchor.kind === 'edge') return `edge:${anchor.machineKey}#${anchor.edgeUid}`;
|
|
315
|
+
if (anchor.kind === 'forest') return `forest:${anchor.capability}`;
|
|
316
|
+
if (anchor.kind === 'macro-edge') return `macro-edge:${anchor.edgeId}`;
|
|
317
|
+
return `doc:${anchor.capability}${anchor.reqId ? `#${anchor.reqId}` : ''}`;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function tryCopyToClipboard(text: string): boolean {
|
|
321
|
+
const candidates: Array<[string, string[]]> =
|
|
322
|
+
process.platform === 'darwin'
|
|
323
|
+
? [['pbcopy', []]]
|
|
324
|
+
: process.platform === 'win32'
|
|
325
|
+
? [['clip', []]]
|
|
326
|
+
: [
|
|
327
|
+
['wl-copy', []],
|
|
328
|
+
['xclip', ['-selection', 'clipboard']],
|
|
329
|
+
['xsel', ['--clipboard', '--input']],
|
|
330
|
+
];
|
|
331
|
+
|
|
332
|
+
for (const [cmd, args] of candidates) {
|
|
333
|
+
const res = spawnSync(cmd, args, { input: text, encoding: 'utf8' });
|
|
334
|
+
if (res.error === undefined && res.status === 0) {
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function assertNonDefaultBranch(git: CliContext['git']): void {
|
|
342
|
+
const branch = currentBranch(git);
|
|
343
|
+
if (branch === null || branch === '') {
|
|
344
|
+
throw new CliError(
|
|
345
|
+
"refusing to write llmanspec/specs/ without a checked-out feature branch; run 'llman-sdd change start <id>' first (or pass --dry-run to preview)",
|
|
346
|
+
1,
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
let def: string | null = null;
|
|
350
|
+
try {
|
|
351
|
+
def = defaultBranch(git);
|
|
352
|
+
} catch {
|
|
353
|
+
def = null;
|
|
354
|
+
}
|
|
355
|
+
if (branch === def || branch === 'main' || branch === 'master') {
|
|
356
|
+
throw new CliError(
|
|
357
|
+
`refusing to write llmanspec/specs/ on default branch '${branch}'; run 'llman-sdd change start <id>' first (or pass --dry-run to preview)`,
|
|
358
|
+
1,
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
interface MachineValidationSummary {
|
|
364
|
+
machineKey: string;
|
|
365
|
+
mode: MachineDraft['mode'];
|
|
366
|
+
sourceFile: string;
|
|
367
|
+
valid: boolean;
|
|
368
|
+
diagnostics: MachineDiagnostic[];
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export function registerStudio(program: Command, ctx: CliContext): void {
|
|
372
|
+
const studio = program
|
|
373
|
+
.command('studio')
|
|
374
|
+
.description('Studio draft negotiation and spec sync for machine, flow, and decision specs');
|
|
375
|
+
|
|
376
|
+
const stateGroup = studio.command('state').description('Manage local Studio draft state files');
|
|
377
|
+
|
|
378
|
+
const stateList = stateGroup
|
|
379
|
+
.command('list')
|
|
380
|
+
.description('List local Studio drafts under .llman-sdd/studio/states/');
|
|
381
|
+
addJsonFlags(stateList);
|
|
382
|
+
addSpecDirOption(stateList);
|
|
383
|
+
stateList.action((options: { json?: boolean; compactJson?: boolean; directory?: string }) => {
|
|
384
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
385
|
+
const io = makeNodeStudioStateIo(rctx.root);
|
|
386
|
+
const states = listStudioStates(io);
|
|
387
|
+
emitStudioOutput({ states }, options, () => {
|
|
388
|
+
if (states.length === 0) return 'No studio drafts found.';
|
|
389
|
+
return states
|
|
390
|
+
.map(
|
|
391
|
+
(s) =>
|
|
392
|
+
`${s.id}\t${s.title}\t(${String(s.machineCount)} machine${s.machineCount === 1 ? '' : 's'}, updated ${s.updatedAt})`,
|
|
393
|
+
)
|
|
394
|
+
.join('\n');
|
|
395
|
+
});
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
const statePrune = stateGroup
|
|
399
|
+
.command('prune')
|
|
400
|
+
.description('Delete one or all local Studio drafts')
|
|
401
|
+
.option('--id <state-id>', 'delete a single studio draft by id')
|
|
402
|
+
.option('--all', 'delete all local studio drafts');
|
|
403
|
+
addSpecDirOption(statePrune);
|
|
404
|
+
statePrune.action((options: { id?: string; all?: boolean; directory?: string }) => {
|
|
405
|
+
const hasId = options.id !== undefined;
|
|
406
|
+
const hasAll = options.all === true;
|
|
407
|
+
if (hasId === hasAll) {
|
|
408
|
+
throw new CliError('specify exactly one of --id <state-id> or --all', 2);
|
|
409
|
+
}
|
|
410
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
411
|
+
const io = makeNodeStudioStateIo(rctx.root);
|
|
412
|
+
if (hasId) {
|
|
413
|
+
const targetId = validateStateId(options.id!);
|
|
414
|
+
const removed = deleteStudioState(io, targetId);
|
|
415
|
+
if (!removed) {
|
|
416
|
+
throw new CliError(
|
|
417
|
+
formatNotFound(
|
|
418
|
+
'studio state',
|
|
419
|
+
targetId,
|
|
420
|
+
listStudioStates(io).map((s) => s.id),
|
|
421
|
+
),
|
|
422
|
+
1,
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
console.log(`Pruned studio state: ${targetId}`);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const states = listStudioStates(io);
|
|
429
|
+
let count = 0;
|
|
430
|
+
for (const s of states) {
|
|
431
|
+
if (deleteStudioState(io, s.id)) count += 1;
|
|
432
|
+
}
|
|
433
|
+
console.log(`Pruned ${String(count)} studio state(s).`);
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
const diffCmd = studio
|
|
437
|
+
.command('diff')
|
|
438
|
+
.description('Inspect semantic diffs, open comments, and Unified Diff preview for a draft')
|
|
439
|
+
.argument('[state-id]', 'studio draft state id (auto-selected when exactly one exists)')
|
|
440
|
+
.option('--no-unified', 'omit in-memory Unified Diff preview');
|
|
441
|
+
addJsonFlags(diffCmd);
|
|
442
|
+
addSpecDirOption(diffCmd);
|
|
443
|
+
diffCmd.action(
|
|
444
|
+
(
|
|
445
|
+
stateIdArg: string | undefined,
|
|
446
|
+
options: { unified?: boolean; json?: boolean; compactJson?: boolean; directory?: string },
|
|
447
|
+
) => {
|
|
448
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
449
|
+
const io = makeNodeStudioStateIo(rctx.root);
|
|
450
|
+
const stateId = resolveStateIdOrThrow(io, stateIdArg, EMPTY_DRAFT_NEXT.diff);
|
|
451
|
+
const doc = readStudioStateOrThrow(io, stateId);
|
|
452
|
+
const includeUnified = options.unified !== false;
|
|
453
|
+
const plan = planStudioApply(
|
|
454
|
+
doc,
|
|
455
|
+
usedReqIds(rctx.io, resolveRootSpecsDir(undefined, rctx.io)),
|
|
456
|
+
);
|
|
457
|
+
|
|
458
|
+
const machineDiffs = Object.entries(doc.machines).map(([machineKey, originalDraft]) => {
|
|
459
|
+
const draft = plan.doc.machines[plan.keyMap[machineKey] ?? machineKey] ?? originalDraft;
|
|
460
|
+
const semanticDiff = computeMachineDiff(draft);
|
|
461
|
+
const semanticSummary = formatSemanticDiff(semanticDiff, draft);
|
|
462
|
+
let unifiedDiff: string | null = null;
|
|
463
|
+
let unifiedDiffError: string | undefined;
|
|
464
|
+
|
|
465
|
+
if (includeUnified && semanticDiff.hasChanges) {
|
|
466
|
+
try {
|
|
467
|
+
const beforeText = rctx.io.exists(draft.sourceFile)
|
|
468
|
+
? rctx.io.readText(draft.sourceFile)
|
|
469
|
+
: null;
|
|
470
|
+
const afterText = renderUpdatedFeatureSource(beforeText, draft, {
|
|
471
|
+
existingReqIds: plan.usedReqIds,
|
|
472
|
+
});
|
|
473
|
+
unifiedDiff = previewFeatureUnifiedDiff(draft.sourceFile, beforeText, afterText);
|
|
474
|
+
} catch (error) {
|
|
475
|
+
if (error instanceof StudioSyncError) {
|
|
476
|
+
unifiedDiffError = error.message;
|
|
477
|
+
} else {
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
return {
|
|
484
|
+
machineKey,
|
|
485
|
+
mode: draft.mode,
|
|
486
|
+
sourceFile: draft.sourceFile,
|
|
487
|
+
hasChanges: semanticDiff.hasChanges,
|
|
488
|
+
semanticDiff,
|
|
489
|
+
semanticSummary,
|
|
490
|
+
...(includeUnified ? { unifiedDiff } : {}),
|
|
491
|
+
...(unifiedDiffError !== undefined ? { unifiedDiffError } : {}),
|
|
492
|
+
};
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
const openComments = doc.comments.filter((c) => c.status === 'open');
|
|
496
|
+
const pendingRevisions = doc.revisions.filter((r) => r.status === 'pending');
|
|
497
|
+
const diskSync = collectDiskSyncPreview(rctx.root, doc);
|
|
498
|
+
|
|
499
|
+
const payload = {
|
|
500
|
+
stateId: doc.id,
|
|
501
|
+
title: doc.title,
|
|
502
|
+
updatedAt: doc.updatedAt,
|
|
503
|
+
machines: machineDiffs,
|
|
504
|
+
openComments,
|
|
505
|
+
pendingRevisions,
|
|
506
|
+
...(diskSync.stale
|
|
507
|
+
? { stale: true, staleFiles: diskSync.staleFiles, syncItems: diskSync.items }
|
|
508
|
+
: {}),
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
emitStudioOutput(payload, options, () => {
|
|
512
|
+
const lines: string[] = [`# Studio Diff: ${doc.id} — ${doc.title}`];
|
|
513
|
+
for (const m of machineDiffs) {
|
|
514
|
+
lines.push('', `## ${m.machineKey} (${m.mode}) [${m.sourceFile}]`, m.semanticSummary);
|
|
515
|
+
if (includeUnified && m.unifiedDiff) {
|
|
516
|
+
lines.push('', '### Unified Diff Preview', m.unifiedDiff.trimEnd());
|
|
517
|
+
} else if (m.unifiedDiffError) {
|
|
518
|
+
lines.push('', `[preview unavailable: ${m.unifiedDiffError}]`);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (diskSync.stale) {
|
|
522
|
+
lines.push('', '## 文件和画布对不上');
|
|
523
|
+
for (const item of diskSync.items) {
|
|
524
|
+
const left = item.labelOurs ?? '(画布没有这一条)';
|
|
525
|
+
const right = item.labelTheirs ?? '(文件没有这一条)';
|
|
526
|
+
lines.push(`- ${left} / ${right}`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
if (openComments.length > 0) {
|
|
530
|
+
lines.push('', `## Open Comments (${String(openComments.length)})`);
|
|
531
|
+
for (const c of openComments) {
|
|
532
|
+
lines.push(`- [${c.id}] (${c.author}, ${formatAnchor(c.anchor)}): ${c.body}`);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (pendingRevisions.length > 0) {
|
|
536
|
+
lines.push('', `## Pending Revisions (${String(pendingRevisions.length)})`);
|
|
537
|
+
for (const r of pendingRevisions) {
|
|
538
|
+
lines.push(
|
|
539
|
+
`- [${r.id}] (${r.machineKey}): ${r.rationale} (${String(r.ops.length)} op(s))`,
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return lines.join('\n');
|
|
544
|
+
});
|
|
545
|
+
},
|
|
546
|
+
);
|
|
547
|
+
|
|
548
|
+
const validateCmd = studio
|
|
549
|
+
.command('validate')
|
|
550
|
+
.description(
|
|
551
|
+
'Run graph validation on a draft or on machines extracted from specs (machine/flow/decision)',
|
|
552
|
+
)
|
|
553
|
+
.argument('[state-id]', 'studio draft state id (auto-selected when exactly one exists)')
|
|
554
|
+
.option(
|
|
555
|
+
'--patch <path>',
|
|
556
|
+
'JSON RevisionOp[] patch file or "-" for stdin (in-memory preview only)',
|
|
557
|
+
)
|
|
558
|
+
.option('--machine <key>', 'target machine key when --patch is a bare RevisionOp[] array')
|
|
559
|
+
.option('--specs', 'validate machines extracted from llmanspec/specs/ (ignore drafts)');
|
|
560
|
+
addJsonFlags(validateCmd);
|
|
561
|
+
addSpecDirOption(validateCmd);
|
|
562
|
+
validateCmd.action(
|
|
563
|
+
(
|
|
564
|
+
stateIdArg: string | undefined,
|
|
565
|
+
options: {
|
|
566
|
+
patch?: string;
|
|
567
|
+
machine?: string;
|
|
568
|
+
json?: boolean;
|
|
569
|
+
compactJson?: boolean;
|
|
570
|
+
directory?: string;
|
|
571
|
+
specs?: boolean;
|
|
572
|
+
},
|
|
573
|
+
) => {
|
|
574
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
575
|
+
const io = makeNodeStudioStateIo(rctx.root);
|
|
576
|
+
if (options.specs === true && options.patch !== undefined) {
|
|
577
|
+
throw new CliError('--specs cannot be combined with --patch', 2);
|
|
578
|
+
}
|
|
579
|
+
const noDrafts = listStudioStates(io).length === 0;
|
|
580
|
+
const useSpecs =
|
|
581
|
+
options.specs === true ||
|
|
582
|
+
(stateIdArg === undefined && noDrafts && options.patch === undefined);
|
|
583
|
+
if (useSpecs) {
|
|
584
|
+
const extracted = extractStudioMachines(loadRootSpecEntries(undefined, rctx.io));
|
|
585
|
+
const results: MachineValidationSummary[] = [];
|
|
586
|
+
let errorCount = 0;
|
|
587
|
+
let warningCount = 0;
|
|
588
|
+
for (const item of extracted) {
|
|
589
|
+
const diagnostics = validateMachineGraph(item.machine);
|
|
590
|
+
for (const d of diagnostics) {
|
|
591
|
+
if (d.severity === 'error') errorCount += 1;
|
|
592
|
+
else warningCount += 1;
|
|
593
|
+
}
|
|
594
|
+
results.push({
|
|
595
|
+
machineKey: item.machine.machineKey,
|
|
596
|
+
mode: item.draft.mode,
|
|
597
|
+
sourceFile: item.draft.sourceFile,
|
|
598
|
+
valid: !hasBlockingDiagnostics(diagnostics),
|
|
599
|
+
diagnostics,
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
const valid = errorCount === 0;
|
|
603
|
+
const payload = {
|
|
604
|
+
source: 'specs' as const,
|
|
605
|
+
stateId: '',
|
|
606
|
+
valid,
|
|
607
|
+
patched: false,
|
|
608
|
+
errorCount,
|
|
609
|
+
warningCount,
|
|
610
|
+
machines: results,
|
|
611
|
+
};
|
|
612
|
+
emitStudioOutput(payload, options, () => {
|
|
613
|
+
const lines: string[] = ['source: specs'];
|
|
614
|
+
for (const m of results) {
|
|
615
|
+
lines.push(`${m.valid ? 'PASS' : 'FAIL'} ${m.machineKey} (${m.sourceFile})`);
|
|
616
|
+
for (const d of m.diagnostics) {
|
|
617
|
+
const loc = d.targetId ? `${d.targetKind}:${d.targetId}` : d.targetKind;
|
|
618
|
+
lines.push(` [${d.code}/${d.severity}] (${loc}) ${d.message}`);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
lines.push(
|
|
622
|
+
`studio validate (specs): ${valid ? 'PASS' : 'FAIL'} (${String(errorCount)} error(s), ${String(warningCount)} warning(s))`,
|
|
623
|
+
);
|
|
624
|
+
return lines.join('\n');
|
|
625
|
+
});
|
|
626
|
+
if (!valid) {
|
|
627
|
+
const isJson = options.json === true || options.compactJson === true;
|
|
628
|
+
if (!isJson) {
|
|
629
|
+
const allDiags = results.flatMap((m) => m.diagnostics);
|
|
630
|
+
const ordered = [
|
|
631
|
+
...allDiags.filter((d) => d.severity === 'error'),
|
|
632
|
+
...allDiags.filter((d) => d.severity !== 'error'),
|
|
633
|
+
];
|
|
634
|
+
const firstFix = ordered
|
|
635
|
+
.map((d) => hintForStudioDiagnostic(d.code))
|
|
636
|
+
.find((h) => h !== null);
|
|
637
|
+
emitCliHint(firstFix, 'human');
|
|
638
|
+
}
|
|
639
|
+
exitWith(1);
|
|
640
|
+
}
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
const stateId = resolveStateIdOrThrow(io, stateIdArg);
|
|
644
|
+
const doc = readStudioStateOrThrow(io, stateId);
|
|
645
|
+
|
|
646
|
+
const workingMachines: Record<string, MachineDraft> = {};
|
|
647
|
+
for (const [k, d] of Object.entries(doc.machines)) {
|
|
648
|
+
workingMachines[k] = cloneMachineDraft(d);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
if (options.patch !== undefined) {
|
|
652
|
+
const rawText = readInputText(ctx.cwd, options.patch);
|
|
653
|
+
const { machineKey, ops } = parseRevisionPayload(rawText, doc, options.machine);
|
|
654
|
+
const targetDraft = workingMachines[machineKey];
|
|
655
|
+
if (!targetDraft || !targetDraft.current) {
|
|
656
|
+
throw new CliError(`cannot patch machine without current graph: ${machineKey}`, 1);
|
|
657
|
+
}
|
|
658
|
+
targetDraft.current = applyRevisionOpsToMachine(targetDraft.current, ops);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const results: MachineValidationSummary[] = [];
|
|
662
|
+
let errorCount = 0;
|
|
663
|
+
let warningCount = 0;
|
|
664
|
+
|
|
665
|
+
for (const [machineKey, draft] of Object.entries(workingMachines)) {
|
|
666
|
+
if (draft.mode === 'remove') {
|
|
667
|
+
results.push({
|
|
668
|
+
machineKey,
|
|
669
|
+
mode: draft.mode,
|
|
670
|
+
sourceFile: draft.sourceFile,
|
|
671
|
+
valid: true,
|
|
672
|
+
diagnostics: [],
|
|
673
|
+
});
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
const diagnostics = draft.current
|
|
677
|
+
? validateMachineGraph(draft.current)
|
|
678
|
+
: [
|
|
679
|
+
{
|
|
680
|
+
code: 'E1',
|
|
681
|
+
severity: 'error' as const,
|
|
682
|
+
targetKind: 'machine' as const,
|
|
683
|
+
targetId: null,
|
|
684
|
+
message: 'E1 structure: machine draft has no current graph',
|
|
685
|
+
},
|
|
686
|
+
];
|
|
687
|
+
for (const d of diagnostics) {
|
|
688
|
+
if (d.severity === 'error') errorCount += 1;
|
|
689
|
+
else warningCount += 1;
|
|
690
|
+
}
|
|
691
|
+
results.push({
|
|
692
|
+
machineKey,
|
|
693
|
+
mode: draft.mode,
|
|
694
|
+
sourceFile: draft.sourceFile,
|
|
695
|
+
valid: !hasBlockingDiagnostics(diagnostics),
|
|
696
|
+
diagnostics,
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
const valid = errorCount === 0;
|
|
701
|
+
const payload = {
|
|
702
|
+
stateId: doc.id,
|
|
703
|
+
valid,
|
|
704
|
+
patched: options.patch !== undefined,
|
|
705
|
+
errorCount,
|
|
706
|
+
warningCount,
|
|
707
|
+
machines: results,
|
|
708
|
+
};
|
|
709
|
+
|
|
710
|
+
emitStudioOutput(payload, options, () => {
|
|
711
|
+
const lines: string[] = [];
|
|
712
|
+
for (const m of results) {
|
|
713
|
+
lines.push(`${m.valid ? 'PASS' : 'FAIL'} ${m.machineKey} (${m.sourceFile})`);
|
|
714
|
+
for (const d of m.diagnostics) {
|
|
715
|
+
const loc = d.targetId ? `${d.targetKind}:${d.targetId}` : d.targetKind;
|
|
716
|
+
lines.push(` [${d.code}/${d.severity}] (${loc}) ${d.message}`);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
lines.push(
|
|
720
|
+
`studio validate (${doc.id}): ${valid ? 'PASS' : 'FAIL'} (${String(errorCount)} error(s), ${String(warningCount)} warning(s))`,
|
|
721
|
+
);
|
|
722
|
+
return lines.join('\n');
|
|
723
|
+
});
|
|
724
|
+
|
|
725
|
+
if (!valid) {
|
|
726
|
+
const isJson = options.json === true || options.compactJson === true;
|
|
727
|
+
if (!isJson) {
|
|
728
|
+
const allDiags = results.flatMap((m) => m.diagnostics);
|
|
729
|
+
const ordered = [
|
|
730
|
+
...allDiags.filter((d) => d.severity === 'error'),
|
|
731
|
+
...allDiags.filter((d) => d.severity !== 'error'),
|
|
732
|
+
];
|
|
733
|
+
const firstFix = ordered
|
|
734
|
+
.map((d) => hintForStudioDiagnostic(d.code))
|
|
735
|
+
.find((h) => h !== null);
|
|
736
|
+
emitCliHint(firstFix, 'human');
|
|
737
|
+
}
|
|
738
|
+
exitWith(1);
|
|
739
|
+
}
|
|
740
|
+
},
|
|
741
|
+
);
|
|
742
|
+
|
|
743
|
+
const promptCmd = studio
|
|
744
|
+
.command('prompt')
|
|
745
|
+
.description('Emit a structured Agent negotiation prompt for a Studio draft')
|
|
746
|
+
.argument('[state-id]', 'studio draft state id (auto-selected when exactly one exists)')
|
|
747
|
+
.option('--copy', 'also copy prompt text to system clipboard when available');
|
|
748
|
+
addSpecDirOption(promptCmd);
|
|
749
|
+
promptCmd.action(
|
|
750
|
+
(stateIdArg: string | undefined, options: { copy?: boolean; directory?: string }) => {
|
|
751
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
752
|
+
const io = makeNodeStudioStateIo(rctx.root);
|
|
753
|
+
const stateId = resolveStateIdOrThrow(io, stateIdArg, EMPTY_DRAFT_NEXT.prompt);
|
|
754
|
+
const doc = readStudioStateOrThrow(io, stateId);
|
|
755
|
+
|
|
756
|
+
const lines: string[] = [
|
|
757
|
+
`# Studio Negotiation Prompt: ${doc.title}`,
|
|
758
|
+
'',
|
|
759
|
+
`- State ID: \`${doc.id}\``,
|
|
760
|
+
`- Updated: ${doc.updatedAt}`,
|
|
761
|
+
'',
|
|
762
|
+
'## Machines & Semantic Diffs',
|
|
763
|
+
];
|
|
764
|
+
|
|
765
|
+
for (const [machineKey, draft] of Object.entries(doc.machines)) {
|
|
766
|
+
const diff = computeMachineDiff(draft);
|
|
767
|
+
const summary = formatSemanticDiff(diff, draft);
|
|
768
|
+
lines.push(
|
|
769
|
+
'',
|
|
770
|
+
`### \`${machineKey}\` (${draft.mode}, \`${draft.sourceFile}\`)`,
|
|
771
|
+
'```diff',
|
|
772
|
+
summary,
|
|
773
|
+
'```',
|
|
774
|
+
);
|
|
775
|
+
if (draft.mode !== 'remove' && draft.current) {
|
|
776
|
+
const diags = validateMachineGraph(draft.current);
|
|
777
|
+
if (diags.length > 0) {
|
|
778
|
+
lines.push('', 'Diagnostics:');
|
|
779
|
+
for (const d of diags) {
|
|
780
|
+
lines.push(`- [${d.code}/${d.severity}] ${d.message}`);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const openComments = doc.comments.filter((c) => c.status === 'open');
|
|
787
|
+
if (openComments.length > 0) {
|
|
788
|
+
lines.push('', '## Open Comments');
|
|
789
|
+
for (const c of openComments) {
|
|
790
|
+
lines.push(`- \`${c.id}\` (${c.author}, ${formatAnchor(c.anchor)}): ${c.body}`);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const pendingRevisions = doc.revisions.filter((r) => r.status === 'pending');
|
|
795
|
+
if (pendingRevisions.length > 0) {
|
|
796
|
+
lines.push('', '## Pending Revisions');
|
|
797
|
+
for (const r of pendingRevisions) {
|
|
798
|
+
lines.push(
|
|
799
|
+
`- \`${r.id}\` (${r.machineKey}): ${r.rationale} (${String(r.ops.length)} op(s))`,
|
|
800
|
+
);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
lines.push(
|
|
805
|
+
'',
|
|
806
|
+
'## CLI Callback Commands',
|
|
807
|
+
`- Inspect full diff: \`llman-sdd studio diff ${doc.id}\``,
|
|
808
|
+
`- Pre-validate a patch: \`llman-sdd studio validate ${doc.id} --patch -\``,
|
|
809
|
+
`- Reply to a comment: \`llman-sdd studio comment reply ${doc.id} <comment-id> --body "<reply>"\``,
|
|
810
|
+
`- Propose non-destructive revision: \`llman-sdd studio revise ${doc.id} --file <ops.json> --rationale "<why>"\``,
|
|
811
|
+
`- Preview .feature sync: \`llman-sdd studio apply ${doc.id} --dry-run\``,
|
|
812
|
+
'- Never edit `llmanspec/specs/` on the default branch; run `llman-sdd change start <id>` before `llman-sdd studio apply`.',
|
|
813
|
+
);
|
|
814
|
+
|
|
815
|
+
const promptText = lines.join('\n');
|
|
816
|
+
console.log(promptText);
|
|
817
|
+
|
|
818
|
+
if (options.copy === true) {
|
|
819
|
+
const copied = tryCopyToClipboard(promptText);
|
|
820
|
+
if (copied) {
|
|
821
|
+
console.error('Copied prompt to clipboard.');
|
|
822
|
+
} else {
|
|
823
|
+
console.error('[WARNING] clipboard utility not available; prompt printed to stdout');
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
},
|
|
827
|
+
);
|
|
828
|
+
|
|
829
|
+
const commentGroup = studio
|
|
830
|
+
.command('comment')
|
|
831
|
+
.description('Reply to anchored Studio draft comments');
|
|
832
|
+
|
|
833
|
+
const commentReply = commentGroup
|
|
834
|
+
.command('reply')
|
|
835
|
+
.description('Append an Agent reply to an existing draft comment')
|
|
836
|
+
.argument('<state-id>', 'studio draft state id')
|
|
837
|
+
.argument('<comment-id>', 'target comment id')
|
|
838
|
+
.requiredOption('--body <text>', 'reply message body')
|
|
839
|
+
.option('--resolve', 'mark the target comment as resolved');
|
|
840
|
+
addSpecDirOption(commentReply);
|
|
841
|
+
commentReply.action(
|
|
842
|
+
(
|
|
843
|
+
stateIdArg: string,
|
|
844
|
+
commentId: string,
|
|
845
|
+
options: { body: string; resolve?: boolean; directory?: string },
|
|
846
|
+
) => {
|
|
847
|
+
if (options.body.trim() === '') {
|
|
848
|
+
throw new CliError('--body must not be empty', 2);
|
|
849
|
+
}
|
|
850
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
851
|
+
const io = makeNodeStudioStateIo(rctx.root);
|
|
852
|
+
const stateId = validateStateId(stateIdArg);
|
|
853
|
+
const doc = readStudioStateOrThrow(io, stateId);
|
|
854
|
+
const nextDoc = replyStudioComment(doc, commentId, {
|
|
855
|
+
author: 'agent',
|
|
856
|
+
body: options.body,
|
|
857
|
+
createdAt: io.now().toISOString(),
|
|
858
|
+
resolve: options.resolve === true,
|
|
859
|
+
});
|
|
860
|
+
writeStudioState(io, nextDoc);
|
|
861
|
+
const replyId = nextDoc.comments.at(-1)?.id ?? '';
|
|
862
|
+
console.log(
|
|
863
|
+
`Replied to ${commentId} as ${replyId}${options.resolve ? ' (resolved)' : ''} in studio state ${doc.id}`,
|
|
864
|
+
);
|
|
865
|
+
},
|
|
866
|
+
);
|
|
867
|
+
|
|
868
|
+
const reviseCmd = studio
|
|
869
|
+
.command('revise')
|
|
870
|
+
.description('Append a non-destructive Agent revision proposal from JSON stdin or --file')
|
|
871
|
+
.argument('<state-id>', 'studio draft state id')
|
|
872
|
+
.option(
|
|
873
|
+
'--file <path>',
|
|
874
|
+
'JSON file containing RevisionOp[] or { machineKey?, rationale?, ops }',
|
|
875
|
+
)
|
|
876
|
+
.option('--rationale <text>', 'rationale for the proposed revision')
|
|
877
|
+
.option('--machine <key>', 'target machine key when input is a bare RevisionOp[] array');
|
|
878
|
+
addSpecDirOption(reviseCmd);
|
|
879
|
+
reviseCmd.action(
|
|
880
|
+
(
|
|
881
|
+
stateIdArg: string,
|
|
882
|
+
options: { file?: string; rationale?: string; machine?: string; directory?: string },
|
|
883
|
+
) => {
|
|
884
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
885
|
+
const io = makeNodeStudioStateIo(rctx.root);
|
|
886
|
+
const stateId = validateStateId(stateIdArg);
|
|
887
|
+
const doc = readStudioStateOrThrow(io, stateId);
|
|
888
|
+
const rawText = readInputText(ctx.cwd, options.file);
|
|
889
|
+
const { machineKey, ops, rationale } = parseRevisionPayload(
|
|
890
|
+
rawText,
|
|
891
|
+
doc,
|
|
892
|
+
options.machine,
|
|
893
|
+
options.rationale,
|
|
894
|
+
);
|
|
895
|
+
const nextDoc = proposeRevision(doc, {
|
|
896
|
+
machineKey,
|
|
897
|
+
rationale,
|
|
898
|
+
ops,
|
|
899
|
+
createdAt: io.now().toISOString(),
|
|
900
|
+
source: 'agent',
|
|
901
|
+
});
|
|
902
|
+
writeStudioState(io, nextDoc);
|
|
903
|
+
const revId = nextDoc.revisions.at(-1)?.id ?? '';
|
|
904
|
+
console.log(
|
|
905
|
+
`Proposed revision ${revId} for ${machineKey} (${String(ops.length)} op(s), status: pending) in studio state ${doc.id}`,
|
|
906
|
+
);
|
|
907
|
+
},
|
|
908
|
+
);
|
|
909
|
+
|
|
910
|
+
const applyCmd = studio
|
|
911
|
+
.command('apply')
|
|
912
|
+
.description('Semantically write validated Studio drafts back into llmanspec/specs/')
|
|
913
|
+
.argument('<state-id>', 'studio draft state id')
|
|
914
|
+
.option('--dry-run', 'preview Unified Diff to stdout on any branch without modifying files');
|
|
915
|
+
addSpecDirOption(applyCmd);
|
|
916
|
+
applyCmd.action((stateIdArg: string, options: { dryRun?: boolean; directory?: string }) => {
|
|
917
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
918
|
+
const io = makeNodeStudioStateIo(rctx.root);
|
|
919
|
+
const stateId = validateStateId(stateIdArg);
|
|
920
|
+
const doc = readStudioStateOrThrow(io, stateId);
|
|
921
|
+
|
|
922
|
+
const blockingLines: string[] = [];
|
|
923
|
+
for (const [machineKey, draft] of Object.entries(doc.machines)) {
|
|
924
|
+
if (draft.mode === 'remove') continue;
|
|
925
|
+
if (!draft.current) {
|
|
926
|
+
blockingLines.push(`- ${machineKey}: E1 structure: machine draft has no current graph`);
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
const diags = validateMachineGraph(draft.current).filter((d) => d.severity === 'error');
|
|
930
|
+
for (const d of diags) {
|
|
931
|
+
const loc = d.targetId ? `${d.targetKind}:${d.targetId}` : d.targetKind;
|
|
932
|
+
blockingLines.push(`- ${machineKey} [${d.code}] (${loc}): ${d.message}`);
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (blockingLines.length > 0) {
|
|
936
|
+
throw new CliError(
|
|
937
|
+
`cannot apply studio state '${doc.id}': blocking graph diagnostics found:\n${blockingLines.join('\n')}`,
|
|
938
|
+
1,
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
const plan = planStudioApply(doc, usedReqIds(rctx.io, resolveRootSpecsDir(undefined, rctx.io)));
|
|
943
|
+
|
|
944
|
+
const originalByFile = new Map<string, string | null>();
|
|
945
|
+
const renderedByFile = new Map<string, string>();
|
|
946
|
+
|
|
947
|
+
for (const rawDraft of Object.values(plan.doc.machines)) {
|
|
948
|
+
const diff = computeMachineDiff(rawDraft);
|
|
949
|
+
if (!diff.hasChanges) continue;
|
|
950
|
+
|
|
951
|
+
const draft = cloneMachineDraft(rawDraft);
|
|
952
|
+
if (!originalByFile.has(draft.sourceFile)) {
|
|
953
|
+
const orig = rctx.io.exists(draft.sourceFile) ? rctx.io.readText(draft.sourceFile) : null;
|
|
954
|
+
originalByFile.set(draft.sourceFile, orig);
|
|
955
|
+
}
|
|
956
|
+
const baseText = renderedByFile.has(draft.sourceFile)
|
|
957
|
+
? renderedByFile.get(draft.sourceFile)!
|
|
958
|
+
: originalByFile.get(draft.sourceFile)!;
|
|
959
|
+
const updated = renderUpdatedFeatureSource(baseText, draft, {
|
|
960
|
+
existingReqIds: plan.usedReqIds,
|
|
961
|
+
});
|
|
962
|
+
renderedByFile.set(draft.sourceFile, updated);
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
const patches: Array<{ file: string; patch: string; nextText: string }> = [];
|
|
966
|
+
for (const [file, nextText] of renderedByFile.entries()) {
|
|
967
|
+
const beforeText = originalByFile.get(file) ?? null;
|
|
968
|
+
const patch = previewFeatureUnifiedDiff(file, beforeText, nextText);
|
|
969
|
+
patches.push({ file, patch, nextText });
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
if (options.dryRun === true) {
|
|
973
|
+
if (patches.length === 0) {
|
|
974
|
+
console.log(`No spec changes to apply for studio state ${doc.id}.`);
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
977
|
+
console.log(patches.map((p) => p.patch.trimEnd()).join('\n\n'));
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
assertNonDefaultBranch(rctx.git);
|
|
982
|
+
|
|
983
|
+
if (patches.length === 0) {
|
|
984
|
+
console.log(`No spec changes to apply for studio state ${doc.id}.`);
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
for (const p of patches) {
|
|
989
|
+
rctx.io.writeText(p.file, p.nextText);
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
if (plan.allocations.length > 0) {
|
|
993
|
+
writeStudioState(io, {
|
|
994
|
+
...plan.doc,
|
|
995
|
+
updatedAt: new Date().toISOString(),
|
|
996
|
+
revision: (doc.revision ?? 0) + 1,
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
console.log(`Applied studio state '${doc.id}' to ${String(patches.length)} file(s):`);
|
|
1001
|
+
for (const p of patches) {
|
|
1002
|
+
console.log(` - ${p.file}`);
|
|
1003
|
+
}
|
|
1004
|
+
for (const a of plan.allocations) {
|
|
1005
|
+
console.log(` allocated @req:${a.reqId} for ${a.machineKey}`);
|
|
1006
|
+
}
|
|
1007
|
+
console.log("Next: run 'llman-sdd validate' and commit the updated specs.");
|
|
1008
|
+
});
|
|
1009
|
+
|
|
1010
|
+
const driftCmd = studio
|
|
1011
|
+
.command('drift')
|
|
1012
|
+
.description(
|
|
1013
|
+
'0-Token offline Runtime Trace reconciliation and @llmanspec: minimal slice packet',
|
|
1014
|
+
)
|
|
1015
|
+
.option('--trace <path>', 'cross-language JSONL runtime trace file (or "-" for stdin)')
|
|
1016
|
+
.option('--since <git-ref>', 'git ref to diff against for @llmanspec: minimal slice packet')
|
|
1017
|
+
.option(
|
|
1018
|
+
'--write-state',
|
|
1019
|
+
'write detected shadow transitions as pending drift-trace proposals into .llman-sdd/studio/states/',
|
|
1020
|
+
)
|
|
1021
|
+
.option(
|
|
1022
|
+
'--fail-on-shadow',
|
|
1023
|
+
'exit with code 1 when --trace detects shadow transitions (pure --since mode always exits 0)',
|
|
1024
|
+
);
|
|
1025
|
+
addJsonFlags(driftCmd);
|
|
1026
|
+
addSpecDirOption(driftCmd);
|
|
1027
|
+
driftCmd.action(
|
|
1028
|
+
(options: {
|
|
1029
|
+
trace?: string;
|
|
1030
|
+
since?: string;
|
|
1031
|
+
writeState?: boolean;
|
|
1032
|
+
failOnShadow?: boolean;
|
|
1033
|
+
json?: boolean;
|
|
1034
|
+
compactJson?: boolean;
|
|
1035
|
+
directory?: string;
|
|
1036
|
+
}) => {
|
|
1037
|
+
if (options.trace === undefined && options.since === undefined) {
|
|
1038
|
+
throw new CliError('specify at least one of --trace <path> or --since <git-ref>', 2);
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
const rctx = reRootContext(ctx, options.directory);
|
|
1042
|
+
const specsDir = resolveRootSpecsDir(undefined, rctx.io);
|
|
1043
|
+
const entries = discoverSpecs(specsDir, rctx.io);
|
|
1044
|
+
const extracted = extractStudioMachines(entries);
|
|
1045
|
+
const machines = extracted.map((m) => m.machine);
|
|
1046
|
+
|
|
1047
|
+
let parseErrors: RuntimeTraceParseError[] = [];
|
|
1048
|
+
let reconcile: RuntimeTraceReconcileResult | null = null;
|
|
1049
|
+
let writtenState: { stateId: string; path: string; addedProposalIds: string[] } | null = null;
|
|
1050
|
+
let slicePacket: DriftSlicePacket | null = null;
|
|
1051
|
+
|
|
1052
|
+
if (options.trace !== undefined) {
|
|
1053
|
+
const rawTrace = readInputText(ctx.cwd, options.trace);
|
|
1054
|
+
const parsed = parseRuntimeTraceJsonl(rawTrace);
|
|
1055
|
+
parseErrors = parsed.errors;
|
|
1056
|
+
reconcile = reconcileRuntimeTrace(machines, parsed.events);
|
|
1057
|
+
|
|
1058
|
+
if (options.writeState === true && reconcile.shadowTransitions.length > 0) {
|
|
1059
|
+
const stateIo = makeNodeStudioStateIo(rctx.root);
|
|
1060
|
+
const now = stateIo.now().toISOString();
|
|
1061
|
+
const existingStates = listStudioStates(stateIo);
|
|
1062
|
+
let doc: StudioStateDoc = existingStates[0]
|
|
1063
|
+
? readStudioState(stateIo, existingStates[0].id)
|
|
1064
|
+
: createStudioStateDoc({
|
|
1065
|
+
id: 'workspace-draft',
|
|
1066
|
+
title: 'Workspace Studio Drift Draft',
|
|
1067
|
+
createdAt: now,
|
|
1068
|
+
drafts: extracted.map((e) => e.draft),
|
|
1069
|
+
});
|
|
1070
|
+
|
|
1071
|
+
const missingMachines: Record<string, MachineDraft> = {};
|
|
1072
|
+
for (const sh of reconcile.shadowTransitions) {
|
|
1073
|
+
if (!doc.machines[sh.machineKey]) {
|
|
1074
|
+
const found = extracted.find((e) => e.machine.machineKey === sh.machineKey);
|
|
1075
|
+
if (found) missingMachines[sh.machineKey] = cloneMachineDraft(found.draft);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
if (Object.keys(missingMachines).length > 0) {
|
|
1079
|
+
doc = { ...doc, machines: { ...doc.machines, ...missingMachines } };
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
const applied = applyDriftProposalsToStateDoc(doc, reconcile.shadowTransitions, now);
|
|
1083
|
+
const nextDoc: StudioStateDoc = {
|
|
1084
|
+
...applied.doc,
|
|
1085
|
+
revision: (applied.doc.revision ?? 0) + 1,
|
|
1086
|
+
updatedAt: now,
|
|
1087
|
+
};
|
|
1088
|
+
const relPath = writeStudioState(stateIo, nextDoc);
|
|
1089
|
+
writtenState = {
|
|
1090
|
+
stateId: nextDoc.id,
|
|
1091
|
+
path: relPath,
|
|
1092
|
+
addedProposalIds: applied.addedProposalIds,
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
if (options.since !== undefined) {
|
|
1098
|
+
let diffText: string;
|
|
1099
|
+
try {
|
|
1100
|
+
diffText = rctx.git.run(['diff', '-U3', options.since]);
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
throw new CliError(
|
|
1103
|
+
`git diff against '${options.since}' failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
1104
|
+
1,
|
|
1105
|
+
);
|
|
1106
|
+
}
|
|
1107
|
+
const parsedDiffs = parseUnifiedDiffHunks(diffText);
|
|
1108
|
+
const diffFiles = parsedDiffs.map((pf) => ({
|
|
1109
|
+
file: pf.file,
|
|
1110
|
+
content: rctx.io.exists(pf.file) ? rctx.io.readText(pf.file) : '',
|
|
1111
|
+
hunks: pf.hunks,
|
|
1112
|
+
}));
|
|
1113
|
+
slicePacket = buildDriftSlicePacket({
|
|
1114
|
+
sinceRef: options.since,
|
|
1115
|
+
diffFiles,
|
|
1116
|
+
specEntries: entries,
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
const payload = {
|
|
1121
|
+
mode:
|
|
1122
|
+
options.trace !== undefined && options.since !== undefined
|
|
1123
|
+
? 'trace+since'
|
|
1124
|
+
: options.trace !== undefined
|
|
1125
|
+
? 'trace'
|
|
1126
|
+
: 'since',
|
|
1127
|
+
parseErrors,
|
|
1128
|
+
reconcile,
|
|
1129
|
+
writtenState,
|
|
1130
|
+
slicePacket,
|
|
1131
|
+
};
|
|
1132
|
+
|
|
1133
|
+
emitStudioOutput(payload, options, () => {
|
|
1134
|
+
const lines: string[] = ['# Studio Drift Report (0-Token Offline)'];
|
|
1135
|
+
if (parseErrors.length > 0) {
|
|
1136
|
+
lines.push('', `## Trace Parse Errors (${String(parseErrors.length)})`);
|
|
1137
|
+
for (const err of parseErrors) {
|
|
1138
|
+
lines.push(`- L${String(err.line)}: ${err.message}`);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
if (reconcile) {
|
|
1142
|
+
lines.push(
|
|
1143
|
+
'',
|
|
1144
|
+
`## Runtime Trace Reconciliation (${String(reconcile.totalEvents)} events, ${String(reconcile.matchedEvents)} matched)`,
|
|
1145
|
+
`- Shadow transitions: ${String(reconcile.shadowTransitions.length)}`,
|
|
1146
|
+
`- Uncovered spec transitions: ${String(reconcile.uncoveredTransitions.length)}`,
|
|
1147
|
+
`- Unknown machines: ${String(reconcile.unknownMachines.length)}`,
|
|
1148
|
+
);
|
|
1149
|
+
for (const sh of reconcile.shadowTransitions) {
|
|
1150
|
+
const g = sh.condition ? ` [${sh.condition}]` : '';
|
|
1151
|
+
lines.push(
|
|
1152
|
+
` [SHADOW] ${sh.machineKey}: ${sh.from} --[${sh.event}${g}]--> ${sh.to} (x${String(sh.count)}, L${sh.sampleLines.join(',L')})`,
|
|
1153
|
+
);
|
|
1154
|
+
}
|
|
1155
|
+
for (const un of reconcile.unknownMachines) {
|
|
1156
|
+
lines.push(
|
|
1157
|
+
` [UNKNOWN] ${un.machine} (${un.reason}, x${String(un.count)}, L${un.sampleLines.join(',L')})`,
|
|
1158
|
+
);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
if (writtenState) {
|
|
1162
|
+
lines.push(
|
|
1163
|
+
'',
|
|
1164
|
+
`Wrote drift-trace proposal(s) [${writtenState.addedProposalIds.join(', ') || 'unchanged'}] to ${writtenState.path} (state: ${writtenState.stateId}; llmanspec/specs/ untouched).`,
|
|
1165
|
+
);
|
|
1166
|
+
}
|
|
1167
|
+
if (slicePacket) {
|
|
1168
|
+
lines.push(
|
|
1169
|
+
'',
|
|
1170
|
+
`## Minimal Anchor Slice (--since ${slicePacket.sinceRef ?? ''})`,
|
|
1171
|
+
`- Changed files: ${String(slicePacket.changedFileCount)} (anchored: ${String(slicePacket.matchedFiles.length)}, unanchored: ${String(slicePacket.unanchoredFiles.length)})`,
|
|
1172
|
+
`- Impacted specs: ${String(slicePacket.impactedSpecs.length)}`,
|
|
1173
|
+
);
|
|
1174
|
+
for (const sp of slicePacket.impactedSpecs) {
|
|
1175
|
+
lines.push(
|
|
1176
|
+
` - [${sp.kind}] ${sp.capability}${sp.reqId ? ` (@req:${sp.reqId})` : ''}: ${sp.title} (${sp.sourceFile})`,
|
|
1177
|
+
);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
return lines.join('\n');
|
|
1181
|
+
});
|
|
1182
|
+
|
|
1183
|
+
if (parseErrors.length > 0) {
|
|
1184
|
+
exitWith(1);
|
|
1185
|
+
}
|
|
1186
|
+
if (
|
|
1187
|
+
options.failOnShadow === true &&
|
|
1188
|
+
options.trace !== undefined &&
|
|
1189
|
+
(reconcile?.shadowTransitions.length ?? 0) > 0
|
|
1190
|
+
) {
|
|
1191
|
+
exitWith(1);
|
|
1192
|
+
}
|
|
1193
|
+
},
|
|
1194
|
+
);
|
|
1195
|
+
|
|
1196
|
+
const openInBrowser = (targetUrl: string): void => {
|
|
1197
|
+
const cmd =
|
|
1198
|
+
process.platform === 'darwin'
|
|
1199
|
+
? ['open', targetUrl]
|
|
1200
|
+
: process.platform === 'win32'
|
|
1201
|
+
? ['cmd', '/c', 'start', '', targetUrl]
|
|
1202
|
+
: ['xdg-open', targetUrl];
|
|
1203
|
+
const [bin, ...args] = cmd;
|
|
1204
|
+
if (bin) spawnSync(bin, args, { stdio: 'ignore' });
|
|
1205
|
+
};
|
|
1206
|
+
|
|
1207
|
+
const registerServeOpts = (cmd: Command): Command =>
|
|
1208
|
+
cmd
|
|
1209
|
+
.option('--port <port>', 'port to listen on', '4710')
|
|
1210
|
+
.option('--host <addr>', 'loopback host address', '127.0.0.1')
|
|
1211
|
+
.option('--no-open', 'do not open browser automatically')
|
|
1212
|
+
.option('--foreground', 'run server in the foreground')
|
|
1213
|
+
.option('--demo', 'load built-in self-hosting studio-web and sample drafts')
|
|
1214
|
+
.option('--directory <path>', 'target project directory');
|
|
1215
|
+
|
|
1216
|
+
interface ServeCliOpts {
|
|
1217
|
+
port?: string;
|
|
1218
|
+
host?: string;
|
|
1219
|
+
open?: boolean;
|
|
1220
|
+
foreground?: boolean;
|
|
1221
|
+
demo?: boolean;
|
|
1222
|
+
directory?: string;
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
const parseServeBind = (options: ServeCliOpts): { host: string; port: number; dir: string } => {
|
|
1226
|
+
const port = Number(options.port ?? '4710');
|
|
1227
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
1228
|
+
throw new CliError(`invalid --port value: ${String(options.port)}`, 2);
|
|
1229
|
+
}
|
|
1230
|
+
const host = options.host ?? '127.0.0.1';
|
|
1231
|
+
if (!isLoopbackHost(host)) {
|
|
1232
|
+
throw new CliError(
|
|
1233
|
+
'studio server only binds to loopback addresses (127.0.0.1 / localhost)',
|
|
1234
|
+
2,
|
|
1235
|
+
);
|
|
1236
|
+
}
|
|
1237
|
+
return { host, port, dir: options.directory ?? ctx.cwd };
|
|
1238
|
+
};
|
|
1239
|
+
|
|
1240
|
+
const runStudioHubForeground = async (options: ServeCliOpts): Promise<void> => {
|
|
1241
|
+
const { host, port, dir } = parseServeBind(options);
|
|
1242
|
+
const hub = await startStudioHub({
|
|
1243
|
+
initialDirectory: dir,
|
|
1244
|
+
host,
|
|
1245
|
+
port,
|
|
1246
|
+
version: cliVersion,
|
|
1247
|
+
demo: options.demo === true,
|
|
1248
|
+
});
|
|
1249
|
+
const wsUrl = `${hub.url}/p/${encodeURIComponent(hub.activeWsKey)}`;
|
|
1250
|
+
console.log(`Studio: ${hub.url}/ (workspace ${hub.activeWsKey})`);
|
|
1251
|
+
if (options.open !== false) openInBrowser(wsUrl);
|
|
1252
|
+
const shutdown = (): void => {
|
|
1253
|
+
void hub.close().finally(() => process.exit(0));
|
|
1254
|
+
};
|
|
1255
|
+
process.once('SIGINT', shutdown);
|
|
1256
|
+
process.once('SIGTERM', shutdown);
|
|
1257
|
+
await new Promise<void>(() => {});
|
|
1258
|
+
};
|
|
1259
|
+
|
|
1260
|
+
registerServeOpts(
|
|
1261
|
+
studio.command('serve').description('Start the local Studio Web workbench server on 127.0.0.1'),
|
|
1262
|
+
).action(async (options: ServeCliOpts) => {
|
|
1263
|
+
await runStudioHubForeground(options);
|
|
1264
|
+
});
|
|
1265
|
+
|
|
1266
|
+
registerServeOpts(
|
|
1267
|
+
studio
|
|
1268
|
+
.command('open')
|
|
1269
|
+
.description('Open Studio Web in the browser (reuses running local Hub if available)'),
|
|
1270
|
+
).action(async (options: ServeCliOpts) => {
|
|
1271
|
+
const { dir } = parseServeBind(options);
|
|
1272
|
+
const live = await resolveLiveHub(defaultHubFilePath());
|
|
1273
|
+
if (live) {
|
|
1274
|
+
const liveBase = formatLoopbackUrl(live.info.host, live.info.port);
|
|
1275
|
+
try {
|
|
1276
|
+
const res = await fetch(`${liveBase}/api/workspaces`, {
|
|
1277
|
+
method: 'POST',
|
|
1278
|
+
headers: {
|
|
1279
|
+
'content-type': 'application/json',
|
|
1280
|
+
'x-studio-token': live.info.token,
|
|
1281
|
+
},
|
|
1282
|
+
body: JSON.stringify({ directory: dir }),
|
|
1283
|
+
});
|
|
1284
|
+
if (res.ok) {
|
|
1285
|
+
const payload = (await res.json()) as { activeWsKey: string };
|
|
1286
|
+
const wsUrl = `${liveBase}/p/${encodeURIComponent(payload.activeWsKey)}`;
|
|
1287
|
+
console.log(`Studio: ${liveBase}/ (workspace ${payload.activeWsKey})`);
|
|
1288
|
+
if (options.open !== false) openInBrowser(wsUrl);
|
|
1289
|
+
return;
|
|
1290
|
+
}
|
|
1291
|
+
} catch {}
|
|
1292
|
+
}
|
|
1293
|
+
await runStudioHubForeground(options);
|
|
1294
|
+
});
|
|
1295
|
+
|
|
1296
|
+
studio
|
|
1297
|
+
.command('stop')
|
|
1298
|
+
.description('Stop the running local Studio Hub')
|
|
1299
|
+
.option('-d, --directory <dir>', 'Project root directory')
|
|
1300
|
+
.action(async () => {
|
|
1301
|
+
const hubFile = defaultHubFilePath();
|
|
1302
|
+
const live = await resolveLiveHub(hubFile);
|
|
1303
|
+
if (!live) {
|
|
1304
|
+
console.log('No running llman-sdd Studio Hub found.');
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
try {
|
|
1308
|
+
process.kill(live.info.pid, 'SIGTERM');
|
|
1309
|
+
} catch {}
|
|
1310
|
+
removeHubInfoFile(hubFile);
|
|
1311
|
+
console.log(`Stopped llman-sdd Studio Hub (pid ${String(live.info.pid)}).`);
|
|
1312
|
+
});
|
|
1313
|
+
|
|
1314
|
+
registerStudioMcp(studio, ctx);
|
|
1315
|
+
}
|