@llman-sdd/cli 0.10.1 → 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.
Files changed (48) hide show
  1. package/package.json +13 -5
  2. package/src/cli-shared.ts +87 -62
  3. package/src/commands/archive.ts +4 -19
  4. package/src/commands/change.ts +132 -172
  5. package/src/commands/config.ts +1 -29
  6. package/src/commands/init.ts +39 -11
  7. package/src/commands/list.ts +0 -2
  8. package/src/commands/project.ts +25 -115
  9. package/src/commands/review.ts +0 -1
  10. package/src/commands/self.ts +3 -1
  11. package/src/commands/show.ts +8 -46
  12. package/src/commands/spec.ts +6 -86
  13. package/src/commands/studio.ts +1315 -0
  14. package/src/commands/studioMcp.ts +862 -0
  15. package/src/commands/studioShared.ts +87 -0
  16. package/src/commands/theorem-write.ts +608 -0
  17. package/src/commands/theorem.ts +479 -0
  18. package/src/commands/validate.ts +108 -47
  19. package/src/io.ts +0 -1
  20. package/src/main.ts +3 -18
  21. package/src/program.ts +16 -16
  22. package/src/progress.ts +1 -3
  23. package/src/studio-server/changeScope.ts +295 -0
  24. package/src/studio-server/hub.ts +98 -0
  25. package/src/studio-server/negotiate.ts +60 -0
  26. package/src/studio-server/security.ts +71 -0
  27. package/src/studio-server/server.ts +1694 -0
  28. package/src/studio-server/static.ts +184 -0
  29. package/src/studio-server/syncDisk.ts +116 -0
  30. package/src/theorems/base.ts +53 -0
  31. package/src/theorems/diagnose.ts +90 -0
  32. package/src/theorems/draft.ts +252 -0
  33. package/src/theorems/os-lock.ts +364 -0
  34. package/src/theorems/paths.ts +11 -0
  35. package/src/theorems/prompts.ts +79 -0
  36. package/src/theorems/quiet.ts +21 -0
  37. package/src/theorems/runner.ts +48 -0
  38. package/src/theorems/transaction.ts +272 -0
  39. package/src/theorems/workspace.ts +103 -0
  40. package/studio-dist/index.html +14 -0
  41. package/studio-dist/static/css/index.00cf48cf.css +1 -0
  42. package/studio-dist/static/js/610.51883f69.js +218 -0
  43. package/studio-dist/static/js/610.51883f69.js.LICENSE.txt +26 -0
  44. package/studio-dist/static/js/index.c5f7c530.js +13 -0
  45. package/studio-dist/static/js/lib-react.a4b07007.js +2 -0
  46. package/studio-dist/static/js/lib-react.a4b07007.js.LICENSE.txt +49 -0
  47. package/src/commands/context.ts +0 -88
  48. package/src/commands/index.ts +0 -53
@@ -0,0 +1,1694 @@
1
+ /**
2
+ * Hono + @hono/node-server local Studio Hub (studio-web r144, r145, r147).
3
+ * - Pure Web Standard Request/Response + node:* (zero Bun.* APIs, dual-runtime compliant)
4
+ * - Shared Zod v4 contracts from @llman-sdd/core
5
+ * - Loopback security, lazy spec loading, optimistic revision locking, SSE with .git/HEAD & echo filter
6
+ */
7
+ import { createHash } from 'node:crypto';
8
+ import {
9
+ existsSync,
10
+ mkdirSync,
11
+ readdirSync,
12
+ readFileSync,
13
+ renameSync,
14
+ statSync,
15
+ watch,
16
+ writeFileSync,
17
+ type FSWatcher,
18
+ } from 'node:fs';
19
+ import { createServer as createNetServer, type AddressInfo } from 'node:net';
20
+ import { basename, dirname, join, relative, resolve } from 'node:path';
21
+
22
+ import { serve, type ServerType } from '@hono/node-server';
23
+ import {
24
+ acceptRevisionProposal,
25
+ applyDocSyncPicks,
26
+ applySyncPicks,
27
+ mergeDemoDraftsWithExtracted,
28
+ buildForestGraph,
29
+ buildProposalDraft,
30
+ buildWorkspaceSearchDocuments,
31
+ computeMachineDiff,
32
+ createStudioStateDoc,
33
+ currentBranch,
34
+ defaultBranch,
35
+ detectConvertibleStructure,
36
+ discoverRoots,
37
+ discoverSpecs,
38
+ exportProposalRequestSchema,
39
+ extractDecisionTables,
40
+ extractStudioMachines,
41
+ fillMissingExtractedMachines,
42
+ foldFeatureAst,
43
+ foldPlainText,
44
+ formatSemanticDiff,
45
+ graphMermaid,
46
+ listStudioStates,
47
+ makeSpawnGit,
48
+ parseCapability,
49
+ previewFeatureUnifiedDiff,
50
+ pruneStudioTimelines,
51
+ putLayoutRequestSchema,
52
+ putStateRequestSchema,
53
+ putViewsRequestSchema,
54
+ readStudioState,
55
+ readStudioViews,
56
+ registerWorkspaceRequestSchema,
57
+ planStudioApply,
58
+ rejectRevisionProposal,
59
+ renderUpdatedFeatureSource,
60
+ resolveInstanceRoot,
61
+ ruleHasRunnableScenario,
62
+ closeSyncSnapshot,
63
+ searchWorkspaceBm25,
64
+ snapshotBeforeSync,
65
+ specIdOf,
66
+ SPECS_DIR,
67
+ studioSearchRequestSchema,
68
+ syncApplyRequestSchema,
69
+ syncApplyResponseSchema,
70
+ syncPreviewResponseSchema,
71
+ textfoldRequestSchema,
72
+ usedReqIds,
73
+ validateStateId,
74
+ worktreeList,
75
+ writeStudioState,
76
+ writeStudioViews,
77
+ type BootstrapResponse,
78
+ type HealthResponse,
79
+ type SpecDetailResponse,
80
+ type StudioSearchHit,
81
+ type StudioSearchResponse,
82
+ type SpecEntry,
83
+ type SpecIndexEdge,
84
+ type SpecIndexItem,
85
+ formatStudioFocusToken,
86
+ formatStudioNestToken,
87
+ parseStudioDeepLink,
88
+ studioDeepLinkJsonSchema,
89
+ type StudioFocusContext,
90
+ type StudioSseEvent,
91
+ type StudioStateDoc,
92
+ type StudioTheoremDto,
93
+ type TextfoldResponse,
94
+ type TheoremEntry,
95
+ type TheoremProtectionSummary,
96
+ type WorkspaceItem,
97
+ } from '@llman-sdd/core';
98
+ import { Hono, type Context } from 'hono';
99
+ import { streamSSE } from 'hono/streaming';
100
+
101
+ import { makeNodeStudioStateIo } from '../commands/studioShared.ts';
102
+ import { makeIo } from '../io.ts';
103
+ import { currentPlatform, makeCommandRunner } from '../theorems/runner.ts';
104
+ import { loadTheoremWorkspace } from '../theorems/workspace.ts';
105
+ import { computeWorkspaceChangeScope } from './changeScope.ts';
106
+ import {
107
+ defaultHubFilePath,
108
+ formatLoopbackUrl,
109
+ isLoopbackHost,
110
+ removeHubInfoFile,
111
+ writeHubInfoFile,
112
+ } from './hub.ts';
113
+ import { renderNegotiatedMarkdown, resolveNegotiatedFormat } from './negotiate.ts';
114
+ import { createLoopbackSecurityMiddleware, generateStudioToken } from './security.ts';
115
+ import { loadStudioAsset, renderSpaHtmlWithFocus } from './static.ts';
116
+ import { collectDiskSyncPreview, fileDomainMatchesDisk } from './syncDisk.ts';
117
+
118
+ function pruneStateDocBeforeWrite(doc: StudioStateDoc): StudioStateDoc {
119
+ const nowIso = new Date().toISOString();
120
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
121
+ return pruneStudioTimelines(doc, nowIso, timeZone, 30);
122
+ }
123
+
124
+ function loadStudioTheorems(instanceRoot: string): {
125
+ theorems: StudioTheoremDto[];
126
+ entries: TheoremEntry[];
127
+ summary: TheoremProtectionSummary;
128
+ } {
129
+ const workspace = loadTheoremWorkspace({
130
+ io: makeIo(instanceRoot),
131
+ root: instanceRoot,
132
+ run: makeCommandRunner({ cwd: instanceRoot }),
133
+ platform: currentPlatform(),
134
+ });
135
+ const theorems: StudioTheoremDto[] = workspace.theorems.map((theorem) => ({
136
+ id: theorem.id,
137
+ title: theorem.title,
138
+ statement: theorem.statement,
139
+ rationale: theorem.rationale,
140
+ severity: theorem.severity,
141
+ status: theorem.status,
142
+ ...(theorem.scope !== undefined ? { scope: theorem.scope } : {}),
143
+ ...(theorem.tags.length > 0 ? { tags: theorem.tags } : {}),
144
+ ...(theorem.verify !== undefined ? { verify: theorem.verify } : {}),
145
+ filePath: theorem.filePath,
146
+ lockStrength: workspace.lockStrengthByFile[theorem.filePath] ?? 'none',
147
+ }));
148
+ const strong = theorems.filter((theorem) => theorem.lockStrength === 'strong').length;
149
+ const weak = theorems.filter((theorem) => theorem.lockStrength === 'weak').length;
150
+ return {
151
+ theorems,
152
+ entries: workspace.theorems,
153
+ summary: {
154
+ stateCode: workspace.diagnosis.code,
155
+ total: theorems.length,
156
+ strongLocked: strong,
157
+ weakLocked: weak,
158
+ unlocked: theorems.length - strong - weak,
159
+ },
160
+ };
161
+ }
162
+ export interface StudioHubOptions {
163
+ initialDirectory: string;
164
+ host?: string;
165
+ port?: number;
166
+ demo?: boolean;
167
+ version?: string;
168
+ hubFilePath?: string;
169
+ writeHubFile?: boolean;
170
+ studioDistDir?: string;
171
+ }
172
+
173
+ export interface RunningStudioHub {
174
+ app: Hono;
175
+ host: string;
176
+ port: number;
177
+ url: string;
178
+ token: string;
179
+ activeWsKey: string;
180
+ registerWorkspace: (directory: string) => WorkspaceItem;
181
+ broadcastEvent: (event: StudioSseEvent) => void;
182
+ close: () => Promise<void>;
183
+ }
184
+
185
+ interface WorkspaceRecord {
186
+ item: WorkspaceItem;
187
+ demoMode: boolean;
188
+ }
189
+
190
+ function sha256Hex(text: string): string {
191
+ return createHash('sha256').update(text, 'utf8').digest('hex');
192
+ }
193
+
194
+ let atomicWriteSeq = 0;
195
+
196
+ function makeWsKey(repo: string, branch: string, instanceRel: string): string {
197
+ const safeBranch = branch.replaceAll(/[^\w.-]+/gu, '-').replace(/\.+$/u, '') || 'branch';
198
+ const safeRel =
199
+ instanceRel === '' || instanceRel === '.'
200
+ ? 'root'
201
+ : instanceRel.replaceAll('\\', '/').replaceAll('/', '_').replace(/\.+$/u, '') || 'root';
202
+ return `${repo}@${safeBranch}@${safeRel}`;
203
+ }
204
+
205
+ function resolveGitDir(worktreePath: string): string | null {
206
+ const dotGit = join(worktreePath, '.git');
207
+ if (!existsSync(dotGit)) return null;
208
+ try {
209
+ const st = statSync(dotGit);
210
+ if (st.isDirectory()) return dotGit;
211
+ if (st.isFile()) {
212
+ const content = readFileSync(dotGit, 'utf8').trim();
213
+ const m = /^gitdir:\s*(.+)$/mu.exec(content);
214
+ if (m?.[1]) return resolve(dirname(dotGit), m[1].trim());
215
+ }
216
+ } catch {
217
+ return null;
218
+ }
219
+ return null;
220
+ }
221
+
222
+ function isProtectedBranchName(branch: string, defBranch: string): boolean {
223
+ return branch === defBranch || branch === 'main' || branch === 'master';
224
+ }
225
+
226
+ function discoverWorkspaceRecord(directory: string, demoMode: boolean): WorkspaceRecord {
227
+ const absDir = resolve(directory);
228
+ const io = makeIo(absDir);
229
+ const instanceRoot = resolveInstanceRoot(absDir, io) ?? absDir;
230
+ const git = makeSpawnGit(instanceRoot);
231
+ let branch = 'main';
232
+ let defBranch = 'main';
233
+ let repoRoot = instanceRoot;
234
+ try {
235
+ branch = currentBranch(git) || 'main';
236
+ defBranch = defaultBranch(git) || 'main';
237
+ const wts = worktreeList(git);
238
+ if (wts[0]?.path) repoRoot = wts[0].path;
239
+ } catch {}
240
+ const repo = basename(repoRoot) || 'workspace';
241
+ const relRaw = relative(repoRoot, instanceRoot).replaceAll('\\', '/');
242
+ const instanceRel = relRaw === '' || relRaw.startsWith('..') ? '.' : relRaw;
243
+ const specIo = makeIo(instanceRoot);
244
+ const entries = discoverSpecs('llmanspec/specs', specIo);
245
+ const wsKey = makeWsKey(repo, branch, instanceRel);
246
+ return {
247
+ item: {
248
+ wsKey,
249
+ repo,
250
+ branch,
251
+ worktreePath: repoRoot,
252
+ instanceRoot,
253
+ instanceRel,
254
+ protected: isProtectedBranchName(branch, defBranch),
255
+ specCount: entries.length,
256
+ },
257
+ demoMode,
258
+ };
259
+ }
260
+
261
+ function discoverPeerWorktrees(ws: WorkspaceItem): WorkspaceItem[] {
262
+ const peers: WorkspaceItem[] = [];
263
+ try {
264
+ const git = makeSpawnGit(ws.instanceRoot);
265
+ const defBranch = defaultBranch(git) || 'main';
266
+ const wts = worktreeList(git);
267
+ for (const wt of wts) {
268
+ if (resolve(wt.path) === resolve(ws.worktreePath)) continue;
269
+ const targetRoot = ws.instanceRel === '.' ? wt.path : join(wt.path, ws.instanceRel);
270
+ if (!existsSync(targetRoot)) continue;
271
+ const br = wt.branch || 'detached';
272
+ const entries = discoverSpecs('llmanspec/specs', makeIo(targetRoot));
273
+ peers.push({
274
+ wsKey: makeWsKey(ws.repo, br, ws.instanceRel),
275
+ repo: ws.repo,
276
+ branch: br,
277
+ worktreePath: wt.path,
278
+ instanceRoot: targetRoot,
279
+ instanceRel: ws.instanceRel,
280
+ protected: isProtectedBranchName(br, defBranch),
281
+ specCount: entries.length,
282
+ });
283
+ }
284
+ } catch {}
285
+ return peers;
286
+ }
287
+
288
+ function readSpecSource(instanceRoot: string, fileName: string): string {
289
+ const abs = resolve(instanceRoot, fileName);
290
+ return existsSync(abs) ? readFileSync(abs, 'utf8') : '';
291
+ }
292
+
293
+ function buildSpecIndex(
294
+ instanceRoot: string,
295
+ entries: readonly SpecEntry[],
296
+ stateDoc: StudioStateDoc,
297
+ ): {
298
+ specs: SpecIndexItem[];
299
+ edges: SpecIndexEdge[];
300
+ staleFiles: string[];
301
+ } {
302
+ const forest = buildForestGraph(entries);
303
+ const staleFiles: string[] = [];
304
+
305
+ const specs: SpecIndexItem[] = forest.nodes.map((node) => {
306
+ const rawSource = readSpecSource(instanceRoot, node.file);
307
+ const expectedHash = stateDoc.baseHashes?.[node.file];
308
+ const stale = expectedHash !== undefined && expectedHash !== sha256Hex(rawSource);
309
+ if (stale) staleFiles.push(node.file);
310
+ return {
311
+ id: node.id,
312
+ title: node.title,
313
+ file: node.file,
314
+ kind: node.kind,
315
+ hardness: node.hardness,
316
+ ruleCount: node.ruleCount,
317
+ scenarioCount: node.scenarioCount,
318
+ decisionTableCount: node.decisionTableCount,
319
+ machineKeys: node.machineKeys,
320
+ ...(node.graphItems ? { graphItems: node.graphItems } : {}),
321
+ ...(node.kindCounts ? { kindCounts: node.kindCounts } : {}),
322
+ summary: node.summary,
323
+ reqPreview: node.reqPreview,
324
+ tags: node.tags,
325
+ stale,
326
+ };
327
+ });
328
+
329
+ const edges: SpecIndexEdge[] = forest.edges.map((e) => ({
330
+ id: e.id,
331
+ from: e.from,
332
+ to: e.to,
333
+ label: e.label,
334
+ kind: e.kind,
335
+ evidence: e.evidence,
336
+ }));
337
+
338
+ return { specs, edges, staleFiles };
339
+ }
340
+
341
+ function mergeColdLayouts(instanceRoot: string, doc: StudioStateDoc): StudioStateDoc {
342
+ const dir = join(instanceRoot, '.llman-sdd', 'studio', 'layouts');
343
+ if (!existsSync(dir)) return doc;
344
+ const layouts: StudioStateDoc['layouts'] = { ...doc.layouts };
345
+ const edgeBends: NonNullable<StudioStateDoc['edgeBends']> = { ...doc.edgeBends };
346
+ let changed = false;
347
+ try {
348
+ for (const file of readdirSync(dir)) {
349
+ if (!file.endsWith('.json') || file.startsWith('.')) continue;
350
+ try {
351
+ const parsed = JSON.parse(readFileSync(join(dir, file), 'utf8')) as {
352
+ machineKey?: string;
353
+ positions?: Record<string, { x: number; y: number }>;
354
+ edgeBends?: Record<string, { dx: number; dy: number }>;
355
+ };
356
+ if (typeof parsed.machineKey !== 'string' || parsed.machineKey === '') continue;
357
+ if (parsed.positions && typeof parsed.positions === 'object') {
358
+ layouts[parsed.machineKey] = {
359
+ ...layouts[parsed.machineKey],
360
+ ...parsed.positions,
361
+ };
362
+ changed = true;
363
+ }
364
+ if (parsed.edgeBends && typeof parsed.edgeBends === 'object') {
365
+ edgeBends[parsed.machineKey] = {
366
+ ...edgeBends[parsed.machineKey],
367
+ ...parsed.edgeBends,
368
+ };
369
+ changed = true;
370
+ }
371
+ } catch {}
372
+ }
373
+ } catch {
374
+ return doc;
375
+ }
376
+ return changed ? { ...doc, layouts, edgeBends } : doc;
377
+ }
378
+
379
+ function fillLeftoverFromDisk(instanceRoot: string, doc: StudioStateDoc): StudioStateDoc {
380
+ const entries = discoverSpecs('llmanspec/specs', makeIo(instanceRoot));
381
+ return fillMissingExtractedMachines(doc, extractStudioMachines(entries));
382
+ }
383
+
384
+ function loadOrCreateActiveStateDoc(
385
+ instanceRoot: string,
386
+ entries: readonly SpecEntry[],
387
+ demoMode: boolean,
388
+ ): StudioStateDoc {
389
+ const stateIo = makeNodeStudioStateIo(instanceRoot);
390
+ const existing = listStudioStates(stateIo);
391
+ if (existing[0]) {
392
+ const leftover = mergeColdLayouts(instanceRoot, readStudioState(stateIo, existing[0].id));
393
+ return fillMissingExtractedMachines(leftover, extractStudioMachines(entries));
394
+ }
395
+ const extracted = extractStudioMachines(entries).map((m) => m.draft);
396
+ const drafts = demoMode ? mergeDemoDraftsWithExtracted(extracted) : extracted;
397
+ const baseHashes: Record<string, string> = {};
398
+ for (const e of entries) {
399
+ baseHashes[e.fileName] = sha256Hex(readSpecSource(instanceRoot, e.fileName));
400
+ }
401
+ const now = new Date().toISOString();
402
+ const doc = createStudioStateDoc({
403
+ id: 'workspace-draft',
404
+ title: `${basename(instanceRoot)} Studio Draft`,
405
+ createdAt: now,
406
+ drafts,
407
+ });
408
+ return mergeColdLayouts(instanceRoot, { ...doc, revision: 0, baseHashes });
409
+ }
410
+
411
+ function buildSpecDetail(
412
+ instanceRoot: string,
413
+ entry: SpecEntry,
414
+ machineKeys: string[],
415
+ ): SpecDetailResponse {
416
+ const rawText = readSpecSource(instanceRoot, entry.fileName);
417
+ const decisionTables = extractDecisionTables(entry.doc);
418
+ const kind: SpecDetailResponse['kind'] =
419
+ machineKeys.length > 0 ? 'machine' : decisionTables.length > 0 ? 'decision' : 'doc';
420
+ const foldLevels = foldFeatureAst(entry.doc, rawText);
421
+ const rules = entry.doc.rules.map((r) => ({
422
+ reqId: r.reqId || null,
423
+ title: r.title,
424
+ description: r.description,
425
+ hardness: (ruleHasRunnableScenario(r) ? 'tested' : 'doc') as 'tested' | 'doc',
426
+ scenarioCount: r.scenarios.length,
427
+ scenarios: r.scenarios.map((sc) => ({
428
+ name: sc.name,
429
+ steps: sc.steps.map((st) => `${st.kind}: ${st.text}`),
430
+ })),
431
+ }));
432
+ return {
433
+ id: specIdOf(entry),
434
+ file: entry.fileName,
435
+ purpose: entry.doc.header.purpose ?? '',
436
+ kind,
437
+ baseHash: sha256Hex(rawText),
438
+ rawText,
439
+ foldLevels,
440
+ rules,
441
+ decisionTables,
442
+ machineKeys,
443
+ convertibleHint: detectConvertibleStructure(
444
+ entry.doc,
445
+ machineKeys.length > 0,
446
+ decisionTables.length > 0,
447
+ ),
448
+ };
449
+ }
450
+
451
+ interface CachedTextfoldEntry {
452
+ provider: 'local-ast' | 'external-serve';
453
+ levels: [string, string, string, string, string];
454
+ }
455
+
456
+ function readTextfoldCache(instanceRoot: string): Record<string, CachedTextfoldEntry> {
457
+ const p = join(instanceRoot, '.llman-sdd', 'studio', 'textfold-cache.json');
458
+ if (!existsSync(p)) return {};
459
+ try {
460
+ const raw = JSON.parse(readFileSync(p, 'utf8')) as Record<string, unknown>;
461
+ const out: Record<string, CachedTextfoldEntry> = {};
462
+ for (const [k, v] of Object.entries(raw)) {
463
+ if (Array.isArray(v) && v.length === 5 && v.every((x) => typeof x === 'string')) {
464
+ out[k] = { provider: 'local-ast', levels: v as [string, string, string, string, string] };
465
+ } else if (typeof v === 'object' && v !== null) {
466
+ const obj = v as { provider?: unknown; levels?: unknown };
467
+ if (
468
+ (obj.provider === 'local-ast' || obj.provider === 'external-serve') &&
469
+ Array.isArray(obj.levels) &&
470
+ obj.levels.length === 5 &&
471
+ obj.levels.every((x) => typeof x === 'string')
472
+ ) {
473
+ out[k] = {
474
+ provider: obj.provider,
475
+ levels: obj.levels as [string, string, string, string, string],
476
+ };
477
+ }
478
+ }
479
+ }
480
+ return out;
481
+ } catch {
482
+ return {};
483
+ }
484
+ }
485
+
486
+ function writeTextfoldCache(
487
+ instanceRoot: string,
488
+ cache: Record<string, CachedTextfoldEntry>,
489
+ ): void {
490
+ const dir = join(instanceRoot, '.llman-sdd', 'studio');
491
+ mkdirSync(dir, { recursive: true });
492
+ const target = join(dir, 'textfold-cache.json');
493
+ atomicWriteSeq += 1;
494
+ const tmp = join(dir, `.textfold-cache.tmp.${String(process.pid)}.${String(atomicWriteSeq)}`);
495
+ writeFileSync(tmp, `${JSON.stringify(cache, null, 2)}\n`, 'utf8');
496
+ renameSync(tmp, target);
497
+ }
498
+
499
+ async function findAvailablePort(host: string, preferredPort: number): Promise<number> {
500
+ if (preferredPort === 0) return 0;
501
+ for (let offset = 0; offset < 25; offset += 1) {
502
+ const candidate = preferredPort + offset;
503
+ const ok = await new Promise<boolean>((resolvePromise) => {
504
+ const probe = createNetServer();
505
+ probe.once('error', () => resolvePromise(false));
506
+ probe.listen(candidate, host, () => {
507
+ probe.close(() => resolvePromise(true));
508
+ });
509
+ });
510
+ if (ok) return candidate;
511
+ }
512
+ return 0;
513
+ }
514
+
515
+ export interface CreatedStudioHubApp {
516
+ app: Hono;
517
+ host: string;
518
+ token: string;
519
+ activeWsKey: string;
520
+ registerWorkspace: (directory: string) => WorkspaceItem;
521
+ broadcastEvent: (event: StudioSseEvent) => void;
522
+ setBoundPort: (port: number) => void;
523
+ cleanup: () => void;
524
+ }
525
+
526
+ export function createStudioHubApp(options: StudioHubOptions): CreatedStudioHubApp {
527
+ const host = options.host ?? '127.0.0.1';
528
+ if (!isLoopbackHost(host)) {
529
+ throw new Error(`studio server only binds to loopback addresses (got: ${host})`);
530
+ }
531
+ const version = options.version ?? '0.12.0';
532
+ const token = generateStudioToken();
533
+ const demoDefault = options.demo === true;
534
+ let boundPort = options.port ?? 4710;
535
+
536
+ const workspaces = new Map<string, WorkspaceRecord>();
537
+ const registerWorkspace = (dir: string): WorkspaceItem => {
538
+ const absDir = resolve(dir);
539
+ const io = makeIo(absDir);
540
+ const discoveredRoots = discoverRoots(absDir, io);
541
+ const roots = discoveredRoots.length > 0 ? discoveredRoots.map((r) => r.rootDir) : [absDir];
542
+ let firstItem: WorkspaceItem | null = null;
543
+ for (const rootDir of roots) {
544
+ const rec = discoverWorkspaceRecord(rootDir, demoDefault);
545
+ workspaces.set(rec.item.wsKey, rec);
546
+ if (!firstItem) firstItem = rec.item;
547
+ }
548
+ return firstItem ?? discoverWorkspaceRecord(absDir, demoDefault).item;
549
+ };
550
+
551
+ const primaryWs = registerWorkspace(options.initialDirectory);
552
+ let activeWsKey = primaryWs.wsKey;
553
+
554
+ const subscribers = new Set<(event: StudioSseEvent) => void>();
555
+ const sseClosers = new Set<() => void>();
556
+ const broadcastEvent = (event: StudioSseEvent): void => {
557
+ for (const fn of subscribers) {
558
+ try {
559
+ fn(event);
560
+ } catch {}
561
+ }
562
+ };
563
+
564
+ const watchers: FSWatcher[] = [];
565
+ const watchedWsKeys = new Set<string>();
566
+ const watchTimers = new Map<string, ReturnType<typeof setTimeout>>();
567
+ let lastSelfStateWriteAt = 0;
568
+ const attachWatchers = (ws: WorkspaceItem): void => {
569
+ if (watchedWsKeys.has(ws.wsKey)) return;
570
+ watchedWsKeys.add(ws.wsKey);
571
+ const gitDir = resolveGitDir(ws.worktreePath);
572
+ const watchTargets: Array<{ dir: string; kind: 'specs' | 'git' | 'states' }> = [
573
+ { dir: join(ws.instanceRoot, 'llmanspec', 'specs'), kind: 'specs' },
574
+ { dir: join(ws.instanceRoot, 'llmanspec', 'changes'), kind: 'specs' },
575
+ { dir: join(ws.instanceRoot, '.llman-sdd', 'studio', 'states'), kind: 'states' },
576
+ ...(gitDir ? [{ dir: gitDir, kind: 'git' as const }] : []),
577
+ ];
578
+ for (const { dir: target, kind } of watchTargets) {
579
+ if (!existsSync(target)) continue;
580
+ const timerKey = `${ws.wsKey}:${kind}:${target}`;
581
+ try {
582
+ const w = watch(target, { persistent: false }, (_evType, fileName) => {
583
+ if (kind === 'git' && (!fileName || !String(fileName).includes('HEAD'))) return;
584
+ if (kind === 'states') {
585
+ if (Date.now() - lastSelfStateWriteAt < 600) return;
586
+ if (
587
+ fileName &&
588
+ (!String(fileName).endsWith('.json') || String(fileName).startsWith('.'))
589
+ )
590
+ return;
591
+ }
592
+ const prev = watchTimers.get(timerKey);
593
+ if (prev) clearTimeout(prev);
594
+ watchTimers.set(
595
+ timerKey,
596
+ setTimeout(() => {
597
+ watchTimers.delete(timerKey);
598
+ if (kind === 'git') {
599
+ const refreshed = discoverWorkspaceRecord(ws.instanceRoot, demoDefault);
600
+ workspaces.set(ws.wsKey, {
601
+ ...refreshed,
602
+ item: { ...refreshed.item, wsKey: ws.wsKey },
603
+ });
604
+ broadcastEvent({
605
+ type: 'git-head-changed',
606
+ wsKey: ws.wsKey,
607
+ branch: refreshed.item.branch,
608
+ protected: refreshed.item.protected,
609
+ });
610
+ } else if (kind === 'states') {
611
+ const stateId = fileName
612
+ ? String(fileName).replace(/\.json$/u, '')
613
+ : 'workspace-draft';
614
+ broadcastEvent({
615
+ type: 'state-updated',
616
+ wsKey: ws.wsKey,
617
+ stateId,
618
+ revision: 0,
619
+ originClientId: null,
620
+ });
621
+ } else {
622
+ broadcastEvent({
623
+ type: 'specs-changed',
624
+ wsKey: ws.wsKey,
625
+ changedFiles: fileName ? [String(fileName)] : [],
626
+ });
627
+ }
628
+ }, 150),
629
+ );
630
+ });
631
+ watchers.push(w);
632
+ } catch {}
633
+ }
634
+ };
635
+ attachWatchers(primaryWs);
636
+
637
+ const resolveWs = (wsKeyParam?: string): WorkspaceRecord | null => {
638
+ if (!wsKeyParam || wsKeyParam === 'default') {
639
+ return workspaces.get(activeWsKey) ?? workspaces.values().next().value ?? null;
640
+ }
641
+ let decoded: string;
642
+ try {
643
+ decoded = decodeURIComponent(wsKeyParam);
644
+ } catch {
645
+ return null;
646
+ }
647
+ const direct = workspaces.get(decoded);
648
+ if (direct) return direct;
649
+ const normalized = decoded.endsWith('@.')
650
+ ? `${decoded.slice(0, -1)}root`
651
+ : decoded.endsWith('@')
652
+ ? `${decoded}root`
653
+ : decoded;
654
+ return workspaces.get(normalized) ?? null;
655
+ };
656
+
657
+ const app = new Hono();
658
+ app.use('*', createLoopbackSecurityMiddleware(token));
659
+
660
+ app.get('/api/health', (c) => {
661
+ const payload: HealthResponse = {
662
+ ok: true,
663
+ service: 'llman-sdd-studio',
664
+ version,
665
+ pid: process.pid,
666
+ workspaceCount: workspaces.size,
667
+ };
668
+ return c.json(payload);
669
+ });
670
+
671
+ app.get('/api/workspaces', (c) => {
672
+ return c.json({
673
+ activeWsKey,
674
+ workspaces: [...workspaces.values()].map((w) => w.item),
675
+ });
676
+ });
677
+
678
+ app.post('/api/workspaces', async (c) => {
679
+ const raw = (await c.req.json().catch(() => null)) as unknown;
680
+ const parsed = registerWorkspaceRequestSchema.safeParse(raw);
681
+ if (!parsed.success) {
682
+ return c.json({ error: 'invalid request body', issues: parsed.error.issues }, 400);
683
+ }
684
+ if (!existsSync(parsed.data.directory)) {
685
+ return c.json({ error: `directory does not exist: ${parsed.data.directory}` }, 400);
686
+ }
687
+ const item = registerWorkspace(parsed.data.directory);
688
+ activeWsKey = item.wsKey;
689
+ attachWatchers(item);
690
+ return c.json({ activeWsKey, workspace: item }, 201);
691
+ });
692
+
693
+ const handleBootstrap = (wsKeyParam?: string): BootstrapResponse | null => {
694
+ const rec = resolveWs(wsKeyParam);
695
+ if (!rec) return null;
696
+ const io = makeIo(rec.item.instanceRoot);
697
+ const entries = discoverSpecs('llmanspec/specs', io);
698
+ const stateDoc = loadOrCreateActiveStateDoc(rec.item.instanceRoot, entries, rec.demoMode);
699
+ const { specs, edges, staleFiles } = buildSpecIndex(rec.item.instanceRoot, entries, stateDoc);
700
+ let mermaid = 'flowchart TD\n';
701
+ try {
702
+ mermaid = graphMermaid(io, rec.item.instanceRoot).join('\n');
703
+ } catch {}
704
+ const peerWorktrees = discoverPeerWorktrees(rec.item);
705
+ for (const peer of peerWorktrees) {
706
+ if (!workspaces.has(peer.wsKey)) {
707
+ workspaces.set(peer.wsKey, { item: peer, demoMode: rec.demoMode });
708
+ }
709
+ }
710
+ const theoremView = loadStudioTheorems(rec.item.instanceRoot);
711
+ return {
712
+ workspace: { ...rec.item, specCount: specs.length },
713
+ demoMode: rec.demoMode,
714
+ token,
715
+ activeStateId: stateDoc.id,
716
+ stateDoc,
717
+ specs,
718
+ edges,
719
+ staleFiles,
720
+ peerWorktrees,
721
+ graphMermaid: mermaid,
722
+ theorems: theoremView.theorems,
723
+ theoremProtectionSummary: theoremView.summary,
724
+ changeScope: computeWorkspaceChangeScope(rec.item.instanceRoot),
725
+ };
726
+ };
727
+
728
+ app.get('/api/bootstrap', (c) => {
729
+ const data = handleBootstrap(c.req.query('wsKey'));
730
+ if (!data) return c.json({ error: 'workspace not found' }, 404);
731
+ return c.json(data);
732
+ });
733
+
734
+ app.get('/api/p/:wsKey/bootstrap', (c) => {
735
+ const data = handleBootstrap(c.req.param('wsKey'));
736
+ if (!data) return c.json({ error: 'workspace not found' }, 404);
737
+ return c.json(data);
738
+ });
739
+
740
+ const handleSpecDetail = (capId: string, wsKeyParam?: string): SpecDetailResponse | null => {
741
+ const rec = resolveWs(wsKeyParam);
742
+ if (!rec) return null;
743
+ const entries = discoverSpecs('llmanspec/specs', makeIo(rec.item.instanceRoot));
744
+ const entry = entries.find((e) => specIdOf(e) === capId);
745
+ if (!entry) return null;
746
+ const extracted = extractStudioMachines([entry]).map((m) => m.machine.machineKey);
747
+ return buildSpecDetail(rec.item.instanceRoot, entry, extracted);
748
+ };
749
+
750
+ app.get('/api/specs/:capId', (c) => {
751
+ const detail = handleSpecDetail(c.req.param('capId'), c.req.query('wsKey'));
752
+ if (!detail) return c.json({ error: 'spec not found' }, 404);
753
+ return c.json(detail);
754
+ });
755
+
756
+ app.get('/api/p/:wsKey/specs/:capId', (c) => {
757
+ const detail = handleSpecDetail(c.req.param('capId'), c.req.param('wsKey'));
758
+ if (!detail) return c.json({ error: 'spec not found' }, 404);
759
+ return c.json(detail);
760
+ });
761
+
762
+ const handleGetState = (stateId: string, wsKeyParam?: string) => {
763
+ const rec = resolveWs(wsKeyParam);
764
+ if (!rec) return { status: 404 as const, body: { error: 'workspace not found' } };
765
+ try {
766
+ const id = validateStateId(stateId);
767
+ const stateIo = makeNodeStudioStateIo(rec.item.instanceRoot);
768
+ const doc = fillLeftoverFromDisk(
769
+ rec.item.instanceRoot,
770
+ mergeColdLayouts(rec.item.instanceRoot, readStudioState(stateIo, id)),
771
+ );
772
+ return { status: 200 as const, body: doc };
773
+ } catch (error) {
774
+ return {
775
+ status: 404 as const,
776
+ body: { error: error instanceof Error ? error.message : String(error) },
777
+ };
778
+ }
779
+ };
780
+
781
+ app.get('/api/states/:id', (c) => {
782
+ const res = handleGetState(c.req.param('id'), c.req.query('wsKey'));
783
+ return c.json(res.body, res.status);
784
+ });
785
+
786
+ app.get('/api/p/:wsKey/states/:id', (c) => {
787
+ const res = handleGetState(c.req.param('id'), c.req.param('wsKey'));
788
+ return c.json(res.body, res.status);
789
+ });
790
+
791
+ const handlePutState = async (
792
+ stateId: string,
793
+ wsKeyParam: string | undefined,
794
+ rawBody: unknown,
795
+ ifMatchHeader: string | undefined,
796
+ clientIdHeader: string | undefined,
797
+ ) => {
798
+ const rec = resolveWs(wsKeyParam);
799
+ if (!rec) return { status: 404 as const, body: { error: 'workspace not found' } };
800
+
801
+ const parsed = putStateRequestSchema.safeParse(rawBody);
802
+ if (!parsed.success) {
803
+ return {
804
+ status: 400 as const,
805
+ body: { error: 'invalid StudioStateDoc payload', issues: parsed.error.issues },
806
+ };
807
+ }
808
+ let id: string;
809
+ try {
810
+ id = validateStateId(stateId);
811
+ } catch (error) {
812
+ return {
813
+ status: 400 as const,
814
+ body: { error: error instanceof Error ? error.message : 'invalid state id' },
815
+ };
816
+ }
817
+ if (parsed.data.doc.id !== id) {
818
+ return {
819
+ status: 400 as const,
820
+ body: { error: `state id mismatch: url=${id} body=${parsed.data.doc.id}` },
821
+ };
822
+ }
823
+
824
+ const stateIo = makeNodeStudioStateIo(rec.item.instanceRoot);
825
+ let currentRevision = 0;
826
+ let existingDoc: StudioStateDoc | null = null;
827
+ try {
828
+ existingDoc = readStudioState(stateIo, id);
829
+ currentRevision = existingDoc.revision ?? 0;
830
+ } catch {
831
+ existingDoc = null;
832
+ }
833
+
834
+ let headerRev: number | undefined;
835
+ if (ifMatchHeader !== undefined) {
836
+ const cleaned = ifMatchHeader.replaceAll('"', '').trim();
837
+ if (!/^\d+$/u.test(cleaned)) {
838
+ return {
839
+ status: 400 as const,
840
+ body: { error: `malformed If-Match revision header: ${ifMatchHeader}` },
841
+ };
842
+ }
843
+ headerRev = Number(cleaned);
844
+ }
845
+ const expectedRev = parsed.data.expectedRevision ?? headerRev;
846
+
847
+ if (existingDoc !== null && expectedRev !== undefined && expectedRev !== currentRevision) {
848
+ return {
849
+ status: 409 as const,
850
+ body: {
851
+ error: 'revision conflict: state document was updated by another tab or Agent',
852
+ userMessage: '另一扇窗口刚保存了这份草稿',
853
+ conflictKind: 'revision',
854
+ currentRevision,
855
+ latestDoc: existingDoc,
856
+ },
857
+ };
858
+ }
859
+
860
+ const nextRevision = currentRevision + 1;
861
+ const now = new Date().toISOString();
862
+ const nextDoc: StudioStateDoc = {
863
+ ...parsed.data.doc,
864
+ revision: nextRevision,
865
+ updatedAt: now,
866
+ };
867
+ lastSelfStateWriteAt = Date.now();
868
+ writeStudioState(stateIo, pruneStateDocBeforeWrite(nextDoc));
869
+ broadcastEvent({
870
+ type: 'state-updated',
871
+ wsKey: rec.item.wsKey,
872
+ stateId: id,
873
+ revision: nextRevision,
874
+ originClientId: clientIdHeader ?? null,
875
+ });
876
+ return {
877
+ status: 200 as const,
878
+ body: { ok: true as const, revision: nextRevision, updatedAt: now },
879
+ };
880
+ };
881
+
882
+ app.put('/api/states/:id', async (c) => {
883
+ const raw = (await c.req.json().catch(() => null)) as unknown;
884
+ const res = await handlePutState(
885
+ c.req.param('id'),
886
+ c.req.query('wsKey'),
887
+ raw,
888
+ c.req.header('if-match'),
889
+ c.req.header('x-studio-client-id'),
890
+ );
891
+ return c.json(res.body, res.status);
892
+ });
893
+
894
+ app.put('/api/p/:wsKey/states/:id', async (c) => {
895
+ const raw = (await c.req.json().catch(() => null)) as unknown;
896
+ const res = await handlePutState(
897
+ c.req.param('id'),
898
+ c.req.param('wsKey'),
899
+ raw,
900
+ c.req.header('if-match'),
901
+ c.req.header('x-studio-client-id'),
902
+ );
903
+ return c.json(res.body, res.status);
904
+ });
905
+
906
+ app.get('/api/layouts/:machineKey', (c) => {
907
+ const rec = resolveWs(c.req.query('wsKey'));
908
+ if (!rec) return c.json({ error: 'workspace not found' }, 404);
909
+ let key: string;
910
+ try {
911
+ key = decodeURIComponent(c.req.param('machineKey'));
912
+ } catch {
913
+ return c.json({ error: 'invalid machineKey encoding' }, 400);
914
+ }
915
+ const safeName = sha256Hex(key).slice(0, 16);
916
+ const target = join(
917
+ rec.item.instanceRoot,
918
+ '.llman-sdd',
919
+ 'studio',
920
+ 'layouts',
921
+ `${safeName}.json`,
922
+ );
923
+ if (!existsSync(target)) {
924
+ return c.json({ machineKey: key, positions: {}, edgeBends: {} });
925
+ }
926
+ try {
927
+ return c.json(JSON.parse(readFileSync(target, 'utf8')));
928
+ } catch {
929
+ return c.json({ machineKey: key, positions: {}, edgeBends: {} });
930
+ }
931
+ });
932
+
933
+ app.put('/api/layouts/:machineKey', async (c) => {
934
+ const rec = resolveWs(c.req.query('wsKey'));
935
+ if (!rec) return c.json({ error: 'workspace not found' }, 404);
936
+ const raw = (await c.req.json().catch(() => null)) as unknown;
937
+ const parsed = putLayoutRequestSchema.safeParse(raw);
938
+ if (!parsed.success) {
939
+ return c.json({ error: 'invalid layout payload', issues: parsed.error.issues }, 400);
940
+ }
941
+ let key: string;
942
+ try {
943
+ key = decodeURIComponent(c.req.param('machineKey'));
944
+ } catch {
945
+ return c.json({ error: 'invalid machineKey encoding' }, 400);
946
+ }
947
+ const dir = join(rec.item.instanceRoot, '.llman-sdd', 'studio', 'layouts');
948
+ mkdirSync(dir, { recursive: true });
949
+ const safeName = sha256Hex(key).slice(0, 16);
950
+ const target = join(dir, `${safeName}.json`);
951
+ atomicWriteSeq += 1;
952
+ const tmp = join(dir, `.${safeName}.tmp.${String(process.pid)}.${String(atomicWriteSeq)}`);
953
+ writeFileSync(
954
+ tmp,
955
+ `${JSON.stringify({ machineKey: key, ...parsed.data, updatedAt: new Date().toISOString() }, null, 2)}\n`,
956
+ 'utf8',
957
+ );
958
+ renameSync(tmp, target);
959
+ return c.json({ ok: true, machineKey: key });
960
+ });
961
+
962
+ const handleGetViews = (wsKeyParam?: string) => {
963
+ const rec = resolveWs(wsKeyParam);
964
+ if (!rec) return { status: 404 as const, body: { error: 'workspace not found' } };
965
+ const viewsIo = makeNodeStudioStateIo(rec.item.instanceRoot);
966
+ try {
967
+ const viewsDoc = readStudioViews(viewsIo);
968
+ return { status: 200 as const, body: { ok: true as const, viewsDoc } };
969
+ } catch (error) {
970
+ return {
971
+ status: 400 as const,
972
+ body: { error: error instanceof Error ? error.message : String(error) },
973
+ };
974
+ }
975
+ };
976
+
977
+ app.get('/api/views', (c) => {
978
+ const res = handleGetViews(c.req.query('wsKey'));
979
+ return c.json(res.body, res.status);
980
+ });
981
+
982
+ app.get('/api/p/:wsKey/views', (c) => {
983
+ const res = handleGetViews(c.req.param('wsKey'));
984
+ return c.json(res.body, res.status);
985
+ });
986
+
987
+ const handlePutViews = (
988
+ wsKeyParam: string | undefined,
989
+ rawBody: unknown,
990
+ clientIdHeader: string | undefined,
991
+ ) => {
992
+ const rec = resolveWs(wsKeyParam);
993
+ if (!rec) return { status: 404 as const, body: { error: 'workspace not found' } };
994
+ const parsed = putViewsRequestSchema.safeParse(rawBody);
995
+ if (!parsed.success) {
996
+ return {
997
+ status: 400 as const,
998
+ body: { error: 'invalid StudioViewsDoc payload', issues: parsed.error.issues },
999
+ };
1000
+ }
1001
+ const viewsIo = makeNodeStudioStateIo(rec.item.instanceRoot);
1002
+ const nextDoc = {
1003
+ ...parsed.data.viewsDoc,
1004
+ updatedAt: new Date().toISOString(),
1005
+ };
1006
+ writeStudioViews(viewsIo, nextDoc);
1007
+ broadcastEvent({
1008
+ type: 'views-updated',
1009
+ wsKey: rec.item.wsKey,
1010
+ originClientId: clientIdHeader ?? null,
1011
+ });
1012
+ return { status: 200 as const, body: { ok: true as const, viewsDoc: nextDoc } };
1013
+ };
1014
+
1015
+ app.put('/api/views', async (c) => {
1016
+ const raw = (await c.req.json().catch(() => null)) as unknown;
1017
+ const res = handlePutViews(c.req.query('wsKey'), raw, c.req.header('x-studio-client-id'));
1018
+ return c.json(res.body, res.status);
1019
+ });
1020
+
1021
+ app.put('/api/p/:wsKey/views', async (c) => {
1022
+ const raw = (await c.req.json().catch(() => null)) as unknown;
1023
+ const res = handlePutViews(c.req.param('wsKey'), raw, c.req.header('x-studio-client-id'));
1024
+ return c.json(res.body, res.status);
1025
+ });
1026
+
1027
+ app.post('/api/states/:id/revisions/:revId/:action', (c) => {
1028
+ const rec = resolveWs(c.req.query('wsKey'));
1029
+ if (!rec) return c.json({ error: 'workspace not found' }, 404);
1030
+ const action = c.req.param('action');
1031
+ if (action !== 'accept' && action !== 'reject') {
1032
+ return c.json({ error: `unsupported revision action: ${action}` }, 400);
1033
+ }
1034
+ try {
1035
+ const stateIo = makeNodeStudioStateIo(rec.item.instanceRoot);
1036
+ const doc = readStudioState(stateIo, c.req.param('id'));
1037
+ const now = new Date().toISOString();
1038
+ const updated =
1039
+ action === 'accept'
1040
+ ? acceptRevisionProposal(doc, c.req.param('revId'), now)
1041
+ : rejectRevisionProposal(doc, c.req.param('revId'), now);
1042
+ const nextRevision = (doc.revision ?? 0) + 1;
1043
+ const nextDoc: StudioStateDoc = { ...updated, revision: nextRevision };
1044
+ const prunedDoc = pruneStateDocBeforeWrite(nextDoc);
1045
+ lastSelfStateWriteAt = Date.now();
1046
+ writeStudioState(stateIo, prunedDoc);
1047
+ broadcastEvent({
1048
+ type: 'state-updated',
1049
+ wsKey: rec.item.wsKey,
1050
+ stateId: prunedDoc.id,
1051
+ revision: nextRevision,
1052
+ originClientId: c.req.header('x-studio-client-id') ?? null,
1053
+ });
1054
+ return c.json({ ok: true, doc: prunedDoc });
1055
+ } catch (error) {
1056
+ return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
1057
+ }
1058
+ });
1059
+
1060
+ app.post('/api/states/:id/preview-diff', (c) => {
1061
+ const rec = resolveWs(c.req.query('wsKey'));
1062
+ if (!rec) return c.json({ error: 'workspace not found' }, 404);
1063
+ try {
1064
+ const stateIo = makeNodeStudioStateIo(rec.item.instanceRoot);
1065
+ const doc = readStudioState(stateIo, c.req.param('id'));
1066
+ const io = makeIo(rec.item.instanceRoot);
1067
+ const plan = planStudioApply(doc, usedReqIds(io, SPECS_DIR));
1068
+ const diffs = Object.entries(doc.machines).map(([machineKey, originalDraft]) => {
1069
+ const draft = plan.doc.machines[plan.keyMap[machineKey] ?? machineKey] ?? originalDraft;
1070
+ const beforeText = io.exists(draft.sourceFile) ? io.readText(draft.sourceFile) : null;
1071
+ const expectedHash = doc.baseHashes?.[draft.sourceFile];
1072
+ const stale =
1073
+ expectedHash !== undefined &&
1074
+ beforeText !== null &&
1075
+ sha256Hex(beforeText) !== expectedHash;
1076
+ const afterText = renderUpdatedFeatureSource(beforeText, draft, {
1077
+ existingReqIds: plan.usedReqIds,
1078
+ });
1079
+ const unifiedDiff = previewFeatureUnifiedDiff(draft.sourceFile, beforeText, afterText);
1080
+ const semanticDiff = formatSemanticDiff(computeMachineDiff(draft), draft);
1081
+ return { machineKey, sourceFile: draft.sourceFile, unifiedDiff, semanticDiff, stale };
1082
+ });
1083
+ return c.json({ diffs });
1084
+ } catch (error) {
1085
+ return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
1086
+ }
1087
+ });
1088
+
1089
+ const handleSyncPreview = (stateId: string, wsKey: string | undefined) => {
1090
+ const rec = resolveWs(wsKey);
1091
+ if (!rec) return { status: 404 as const, body: { error: 'workspace not found' } };
1092
+ try {
1093
+ const stateIo = makeNodeStudioStateIo(rec.item.instanceRoot);
1094
+ const doc = readStudioState(stateIo, validateStateId(stateId));
1095
+ const preview = collectDiskSyncPreview(rec.item.instanceRoot, doc);
1096
+ const body = syncPreviewResponseSchema.parse({
1097
+ stale: preview.stale,
1098
+ staleFiles: preview.staleFiles,
1099
+ items: preview.items,
1100
+ snapshotTaken: false,
1101
+ });
1102
+ return { status: 200 as const, body };
1103
+ } catch (error) {
1104
+ return {
1105
+ status: 400 as const,
1106
+ body: { error: error instanceof Error ? error.message : String(error) },
1107
+ };
1108
+ }
1109
+ };
1110
+
1111
+ app.post('/api/states/:id/sync-preview', (c) => {
1112
+ const res = handleSyncPreview(c.req.param('id'), c.req.query('wsKey'));
1113
+ return c.json(res.body, res.status);
1114
+ });
1115
+
1116
+ app.post('/api/p/:wsKey/states/:id/sync-preview', (c) => {
1117
+ const res = handleSyncPreview(c.req.param('id'), c.req.param('wsKey'));
1118
+ return c.json(res.body, res.status);
1119
+ });
1120
+
1121
+ const handleSyncApply = async (
1122
+ stateId: string,
1123
+ wsKey: string | undefined,
1124
+ raw: unknown,
1125
+ clientIdHeader: string | undefined,
1126
+ ) => {
1127
+ const rec = resolveWs(wsKey);
1128
+ if (!rec) return { status: 404 as const, body: { error: 'workspace not found' } };
1129
+ const parsed = syncApplyRequestSchema.safeParse(raw);
1130
+ if (!parsed.success) {
1131
+ return {
1132
+ status: 400 as const,
1133
+ body: { error: 'invalid sync-apply payload', issues: parsed.error.issues },
1134
+ };
1135
+ }
1136
+ try {
1137
+ const stateIo = makeNodeStudioStateIo(rec.item.instanceRoot);
1138
+ let doc = fillLeftoverFromDisk(
1139
+ rec.item.instanceRoot,
1140
+ mergeColdLayouts(rec.item.instanceRoot, readStudioState(stateIo, validateStateId(stateId))),
1141
+ );
1142
+ const preview = collectDiskSyncPreview(rec.item.instanceRoot, doc);
1143
+ const now = new Date().toISOString();
1144
+ const blocked: Array<{ itemId: string; reason: string }> = [];
1145
+ const machineKeys = new Set(
1146
+ preview.items.map((item) => item.machineKey).filter((k): k is string => k !== undefined),
1147
+ );
1148
+ for (const mk of machineKeys) {
1149
+ doc = snapshotBeforeSync(doc, mk, now);
1150
+ }
1151
+ for (const mk of machineKeys) {
1152
+ const draft = doc.machines[mk];
1153
+ if (!draft) continue;
1154
+ const machineItems = preview.items.filter((item) => item.machineKey === mk);
1155
+ const result = applySyncPicks(draft, machineItems, parsed.data.picks, now);
1156
+ blocked.push(...result.blocked);
1157
+ doc = {
1158
+ ...doc,
1159
+ machines: { ...doc.machines, [mk]: result.draft },
1160
+ };
1161
+ doc = closeSyncSnapshot(doc, mk);
1162
+ }
1163
+ const nextDocDrafts = { ...doc.docDrafts };
1164
+ let docDraftsChanged = false;
1165
+ for (const [capId, docDraft] of Object.entries(doc.docDrafts ?? {})) {
1166
+ const docItems = preview.items.filter(
1167
+ (item) => item.kind === 'doc-rule' && item.sourceFile === docDraft.sourceFile,
1168
+ );
1169
+ if (docItems.length === 0) continue;
1170
+ const result = applyDocSyncPicks(docDraft, docItems, parsed.data.picks);
1171
+ blocked.push(...result.blocked);
1172
+ nextDocDrafts[capId] = result.docDraft;
1173
+ docDraftsChanged = true;
1174
+ }
1175
+ const appliedDoc = {
1176
+ ...doc,
1177
+ ...(docDraftsChanged ? { docDrafts: nextDocDrafts } : {}),
1178
+ };
1179
+ const takingFile =
1180
+ preview.items.length === 0 ||
1181
+ preview.items.every((item) => parsed.data.picks[item.id] === 'theirs');
1182
+ const nextHashes = { ...doc.baseHashes };
1183
+ for (const file of preview.staleFiles) {
1184
+ const diskHash = preview.diskHashes[file];
1185
+ if (diskHash === undefined) continue;
1186
+ const matches = fileDomainMatchesDisk(rec.item.instanceRoot, appliedDoc, file);
1187
+ if (matches || !takingFile) nextHashes[file] = diskHash;
1188
+ }
1189
+ const nextRevision = (doc.revision ?? 0) + 1;
1190
+ const nextDoc = {
1191
+ ...doc,
1192
+ revision: nextRevision,
1193
+ updatedAt: now,
1194
+ baseHashes: nextHashes,
1195
+ ...(docDraftsChanged ? { docDrafts: nextDocDrafts } : {}),
1196
+ };
1197
+ const prunedDoc = pruneStateDocBeforeWrite(nextDoc);
1198
+ lastSelfStateWriteAt = Date.now();
1199
+ writeStudioState(stateIo, prunedDoc);
1200
+ broadcastEvent({
1201
+ type: 'state-updated',
1202
+ wsKey: rec.item.wsKey,
1203
+ stateId: prunedDoc.id,
1204
+ revision: nextRevision,
1205
+ originClientId: clientIdHeader ?? null,
1206
+ });
1207
+ const body = syncApplyResponseSchema.parse({ ok: true, doc: prunedDoc, blocked });
1208
+ return { status: 200 as const, body };
1209
+ } catch (error) {
1210
+ return {
1211
+ status: 400 as const,
1212
+ body: { error: error instanceof Error ? error.message : String(error) },
1213
+ };
1214
+ }
1215
+ };
1216
+
1217
+ app.post('/api/states/:id/sync-apply', async (c) => {
1218
+ const raw = (await c.req.json().catch(() => null)) as unknown;
1219
+ const res = await handleSyncApply(
1220
+ c.req.param('id'),
1221
+ c.req.query('wsKey'),
1222
+ raw,
1223
+ c.req.header('x-studio-client-id') ?? undefined,
1224
+ );
1225
+ return c.json(res.body, res.status);
1226
+ });
1227
+
1228
+ app.post('/api/p/:wsKey/states/:id/sync-apply', async (c) => {
1229
+ const raw = (await c.req.json().catch(() => null)) as unknown;
1230
+ const res = await handleSyncApply(
1231
+ c.req.param('id'),
1232
+ c.req.param('wsKey'),
1233
+ raw,
1234
+ c.req.header('x-studio-client-id') ?? undefined,
1235
+ );
1236
+ return c.json(res.body, res.status);
1237
+ });
1238
+
1239
+ app.post('/api/states/:id/export-proposal', async (c) => {
1240
+ const rec = resolveWs(c.req.query('wsKey'));
1241
+ if (!rec) return c.json({ error: 'workspace not found' }, 404);
1242
+ const raw = (await c.req.json().catch(() => null)) as unknown;
1243
+ const parsed = exportProposalRequestSchema.safeParse(raw);
1244
+ if (!parsed.success) {
1245
+ return c.json({ error: 'invalid export proposal payload', issues: parsed.error.issues }, 400);
1246
+ }
1247
+ try {
1248
+ const changeId = validateStateId(parsed.data.changeId);
1249
+ const stateIo = makeNodeStudioStateIo(rec.item.instanceRoot);
1250
+ const doc = readStudioState(stateIo, c.req.param('id'));
1251
+ const proposalContent = buildProposalDraft({
1252
+ title: parsed.data.title,
1253
+ why: parsed.data.why,
1254
+ drafts: Object.values(doc.machines),
1255
+ comments: doc.comments.filter((cm) => cm.status === 'open'),
1256
+ dependsOn: parsed.data.dependsOn ?? [],
1257
+ });
1258
+ const relPath = `llmanspec/changes/${changeId}/proposal.md`;
1259
+ const absPath = join(rec.item.instanceRoot, relPath);
1260
+ mkdirSync(join(rec.item.instanceRoot, 'llmanspec', 'changes', changeId), { recursive: true });
1261
+ writeFileSync(absPath, proposalContent, 'utf8');
1262
+ return c.json({ ok: true, changeId, proposalPath: relPath }, 201);
1263
+ } catch (error) {
1264
+ return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
1265
+ }
1266
+ });
1267
+
1268
+ app.post('/api/textfold/fold', async (c) => {
1269
+ const rec = resolveWs(c.req.query('wsKey'));
1270
+ if (!rec) return c.json({ error: 'workspace not found' }, 404);
1271
+ const raw = (await c.req.json().catch(() => null)) as unknown;
1272
+ const parsed = textfoldRequestSchema.safeParse(raw);
1273
+ if (!parsed.success) {
1274
+ return c.json({ error: 'invalid textfold payload', issues: parsed.error.issues }, 400);
1275
+ }
1276
+ const digest = sha256Hex(parsed.data.content);
1277
+ const cache = readTextfoldCache(rec.item.instanceRoot);
1278
+ const cachedEntry = cache[digest];
1279
+ if (cachedEntry) {
1280
+ const hit: TextfoldResponse = {
1281
+ provider: cachedEntry.provider,
1282
+ cached: true,
1283
+ sha256: digest,
1284
+ levels: cachedEntry.levels,
1285
+ };
1286
+ return c.json(hit);
1287
+ }
1288
+
1289
+ const externalEndpoint = parsed.data.endpoint ?? process.env.LLMAN_SDD_TEXTFOLD_URL;
1290
+ if (externalEndpoint) {
1291
+ let parsedUrl: URL;
1292
+ try {
1293
+ parsedUrl = new URL(externalEndpoint);
1294
+ } catch {
1295
+ return c.json({ error: 'invalid external textfold endpoint URL' }, 400);
1296
+ }
1297
+ if (!isLoopbackHost(parsedUrl.hostname)) {
1298
+ return c.json(
1299
+ {
1300
+ error: 'external textfold endpoint must target a loopback host (127.0.0.1 / localhost)',
1301
+ },
1302
+ 400,
1303
+ );
1304
+ }
1305
+ const controller = new AbortController();
1306
+ const timer = setTimeout(() => controller.abort(), 5000);
1307
+ try {
1308
+ const res = await fetch(`${externalEndpoint.replace(/\/+$/u, '')}/fold`, {
1309
+ method: 'POST',
1310
+ headers: { 'content-type': 'application/json' },
1311
+ body: JSON.stringify({ content: parsed.data.content }),
1312
+ signal: controller.signal,
1313
+ });
1314
+ if (res.ok) {
1315
+ const extJson = (await res.json()) as { levels?: unknown };
1316
+ if (
1317
+ Array.isArray(extJson.levels) &&
1318
+ extJson.levels.length === 5 &&
1319
+ extJson.levels.every((x) => typeof x === 'string')
1320
+ ) {
1321
+ const levels = extJson.levels as [string, string, string, string, string];
1322
+ cache[digest] = { provider: 'external-serve', levels };
1323
+ writeTextfoldCache(rec.item.instanceRoot, cache);
1324
+ return c.json({ provider: 'external-serve', cached: false, sha256: digest, levels });
1325
+ }
1326
+ }
1327
+ } catch {
1328
+ } finally {
1329
+ clearTimeout(timer);
1330
+ }
1331
+ }
1332
+
1333
+ let levels: [string, string, string, string, string];
1334
+ try {
1335
+ const doc = parseCapability(
1336
+ parsed.data.content,
1337
+ `${parsed.data.capability ?? 'spec'}.feature`,
1338
+ );
1339
+ levels = foldFeatureAst(doc, parsed.data.content);
1340
+ } catch {
1341
+ levels = foldPlainText(parsed.data.content);
1342
+ }
1343
+ cache[digest] = { provider: 'local-ast', levels };
1344
+ writeTextfoldCache(rec.item.instanceRoot, cache);
1345
+ return c.json({ provider: 'local-ast', cached: false, sha256: digest, levels });
1346
+ });
1347
+
1348
+ const ragCache = new Map<string, { expiresAt: number; response: StudioSearchResponse }>();
1349
+
1350
+ const handleWorkspaceSearch = async (wsKeyParam: string | undefined, rawBody: unknown) => {
1351
+ const rec = resolveWs(wsKeyParam);
1352
+ if (!rec) return { status: 404 as const, body: { error: 'workspace not found' } };
1353
+ const parsed = studioSearchRequestSchema.safeParse(rawBody);
1354
+ if (!parsed.success) {
1355
+ return {
1356
+ status: 400 as const,
1357
+ body: { error: 'invalid search payload', issues: parsed.error.issues },
1358
+ };
1359
+ }
1360
+ const { query, topK = 20, endpoint } = parsed.data;
1361
+ const entries = discoverSpecs('llmanspec/specs', makeIo(rec.item.instanceRoot));
1362
+ const parsedSpecs = entries.map((entry) => ({ capId: specIdOf(entry), doc: entry.doc }));
1363
+ let activeStateDoc = null;
1364
+ try {
1365
+ const stateIo = makeNodeStudioStateIo(rec.item.instanceRoot);
1366
+ const summaries = listStudioStates(stateIo);
1367
+ if (summaries.length > 0) {
1368
+ activeStateDoc = readStudioState(stateIo, summaries[0]!.id);
1369
+ }
1370
+ } catch {
1371
+ activeStateDoc = null;
1372
+ }
1373
+ const theoremView = loadStudioTheorems(rec.item.instanceRoot);
1374
+ const docs = buildWorkspaceSearchDocuments(parsedSpecs, activeStateDoc, theoremView.entries);
1375
+
1376
+ const ragUrl = endpoint ?? process.env.LLMAN_SDD_STUDIO_RAG_URL;
1377
+ let degradedReason: string | undefined;
1378
+ if (ragUrl) {
1379
+ let parsedUrl: URL;
1380
+ try {
1381
+ parsedUrl = new URL(ragUrl);
1382
+ } catch {
1383
+ return { status: 400 as const, body: { error: 'invalid external RAG endpoint URL' } };
1384
+ }
1385
+ if (!isLoopbackHost(parsedUrl.hostname)) {
1386
+ return {
1387
+ status: 400 as const,
1388
+ body: {
1389
+ error: 'external RAG endpoint must target a loopback host (127.0.0.1 / localhost)',
1390
+ },
1391
+ };
1392
+ }
1393
+ const cacheKey = `${rec.item.wsKey}|${ragUrl}|${query}|${String(topK)}`;
1394
+ const cached = ragCache.get(cacheKey);
1395
+ if (cached && cached.expiresAt > Date.now()) {
1396
+ return { status: 200 as const, body: { ...cached.response, cached: true } };
1397
+ }
1398
+ const controller = new AbortController();
1399
+ const timer = setTimeout(() => controller.abort(), 4000);
1400
+ try {
1401
+ const headers: Record<string, string> = { 'content-type': 'application/json' };
1402
+ const bearer = process.env.LLMAN_SDD_STUDIO_RAG_TOKEN;
1403
+ if (bearer) headers['authorization'] = `Bearer ${bearer}`;
1404
+ const res = await fetch(`${ragUrl.replace(/\/+$/u, '')}/search`, {
1405
+ method: 'POST',
1406
+ headers,
1407
+ body: JSON.stringify({ query, workspaceKey: rec.item.wsKey, topK }),
1408
+ signal: controller.signal,
1409
+ });
1410
+ if (res.ok) {
1411
+ const ext = (await res.json()) as { hits?: unknown };
1412
+ if (Array.isArray(ext.hits)) {
1413
+ const mapped: StudioSearchHit[] = [];
1414
+ for (const [idx, rawHit] of ext.hits.entries()) {
1415
+ if (!rawHit || typeof rawHit !== 'object') continue;
1416
+ const h = rawHit as Record<string, unknown>;
1417
+ const targetKind =
1418
+ h.targetKind === 'spec' ||
1419
+ h.targetKind === 'rule' ||
1420
+ h.targetKind === 'state' ||
1421
+ h.targetKind === 'edge' ||
1422
+ h.targetKind === 'decision' ||
1423
+ h.targetKind === 'comment' ||
1424
+ h.targetKind === 'timeline'
1425
+ ? h.targetKind
1426
+ : 'spec';
1427
+ const targetId =
1428
+ typeof h.targetId === 'string' && h.targetId ? h.targetId : `hit-${String(idx)}`;
1429
+ const capId = typeof h.capId === 'string' && h.capId ? h.capId : targetId;
1430
+ mapped.push({
1431
+ id: `rag:${targetKind}:${targetId}:${String(idx)}`,
1432
+ targetKind,
1433
+ targetId,
1434
+ capId,
1435
+ ...(typeof h.machineKey === 'string' && h.machineKey
1436
+ ? { machineKey: h.machineKey }
1437
+ : {}),
1438
+ title: typeof h.title === 'string' && h.title ? h.title : `${capId} · ${targetId}`,
1439
+ snippet: typeof h.snippet === 'string' ? h.snippet : '',
1440
+ score: typeof h.score === 'number' ? h.score : 1,
1441
+ source: 'rag-serve',
1442
+ });
1443
+ }
1444
+ const response: StudioSearchResponse = {
1445
+ provider: 'rag-serve',
1446
+ cached: false,
1447
+ totalIndexed: docs.length,
1448
+ hits: mapped.slice(0, topK),
1449
+ };
1450
+ ragCache.set(cacheKey, { expiresAt: Date.now() + 30_000, response });
1451
+ return { status: 200 as const, body: response };
1452
+ }
1453
+ degradedReason = 'external RAG payload missing hits array';
1454
+ } else {
1455
+ degradedReason = `external RAG returned HTTP ${String(res.status)}`;
1456
+ }
1457
+ } catch (error) {
1458
+ degradedReason = error instanceof Error ? error.message : 'external RAG unreachable';
1459
+ } finally {
1460
+ clearTimeout(timer);
1461
+ }
1462
+ }
1463
+
1464
+ const hits = searchWorkspaceBm25(docs, query, topK);
1465
+ const fallback: StudioSearchResponse = {
1466
+ provider: 'local-bm25',
1467
+ cached: false,
1468
+ ...(degradedReason ? { degradedReason } : {}),
1469
+ totalIndexed: docs.length,
1470
+ hits,
1471
+ };
1472
+ return { status: 200 as const, body: fallback };
1473
+ };
1474
+
1475
+ app.post('/api/search', async (c) => {
1476
+ const raw = (await c.req.json().catch(() => null)) as unknown;
1477
+ const res = await handleWorkspaceSearch(c.req.query('wsKey'), raw);
1478
+ return c.json(res.body, res.status);
1479
+ });
1480
+
1481
+ app.post('/api/p/:wsKey/search', async (c) => {
1482
+ const raw = (await c.req.json().catch(() => null)) as unknown;
1483
+ const res = await handleWorkspaceSearch(c.req.param('wsKey'), raw);
1484
+ return c.json(res.body, res.status);
1485
+ });
1486
+
1487
+ app.get('/api/events', (c) => {
1488
+ return streamSSE(c, async (stream) => {
1489
+ const send = (ev: StudioSseEvent): void => {
1490
+ void stream.writeSSE({ event: ev.type, data: JSON.stringify(ev) });
1491
+ };
1492
+ subscribers.add(send);
1493
+ await stream.writeSSE({
1494
+ event: 'ping',
1495
+ data: JSON.stringify({ type: 'ping', ts: new Date().toISOString() }),
1496
+ });
1497
+ await new Promise<void>((resolveDone) => {
1498
+ const heartbeat = setInterval(() => {
1499
+ void stream.writeSSE({
1500
+ event: 'ping',
1501
+ data: JSON.stringify({ type: 'ping', ts: new Date().toISOString() }),
1502
+ });
1503
+ }, 25000);
1504
+ let closed = false;
1505
+ const closeStream = (): void => {
1506
+ if (closed) return;
1507
+ closed = true;
1508
+ clearInterval(heartbeat);
1509
+ subscribers.delete(send);
1510
+ sseClosers.delete(closeStream);
1511
+ resolveDone();
1512
+ };
1513
+ sseClosers.add(closeStream);
1514
+ stream.onAbort(closeStream);
1515
+ });
1516
+ });
1517
+ });
1518
+
1519
+ const handleDeepLink = (c: Context, wsKeyParam: string) => {
1520
+ const boot = handleBootstrap(wsKeyParam);
1521
+ if (!boot) return c.text('workspace not found', 404);
1522
+ const format = resolveNegotiatedFormat(c.req.header('accept'), c.req.query('format'));
1523
+ const parsed = parseStudioDeepLink(
1524
+ new URLSearchParams({
1525
+ ...(c.req.query('kind') !== undefined ? { kind: c.req.query('kind')! } : {}),
1526
+ ...(c.req.query('target') !== undefined ? { target: c.req.query('target')! } : {}),
1527
+ ...(c.req.query('nest') !== undefined ? { nest: c.req.query('nest')! } : {}),
1528
+ ...(c.req.query('focus') !== undefined ? { focus: c.req.query('focus')! } : {}),
1529
+ ...(c.req.query('tab') !== undefined ? { tab: c.req.query('tab')! } : {}),
1530
+ }),
1531
+ );
1532
+ const targetKind = (
1533
+ ['macro', 'machine', 'doc', 'state', 'edge'].includes(parsed.kind) ? parsed.kind : 'macro'
1534
+ ) as StudioFocusContext['targetKind'];
1535
+ const targetId = parsed.target;
1536
+ const baseUrl = formatLoopbackUrl(host, boundPort);
1537
+ const path = `/p/${encodeURIComponent(boot.workspace.wsKey)}`;
1538
+ const canonParams = new URLSearchParams();
1539
+ canonParams.set('kind', targetKind);
1540
+ canonParams.set('target', targetId);
1541
+ const nestTok = formatStudioNestToken(parsed.nest);
1542
+ if (nestTok !== '') canonParams.set('nest', nestTok);
1543
+ if (parsed.focus) canonParams.set('focus', formatStudioFocusToken(parsed.focus));
1544
+ const canonicalUrl = `${baseUrl}${path}?${canonParams.toString()}`;
1545
+ const focus: StudioFocusContext = {
1546
+ wsKey: boot.workspace.wsKey,
1547
+ repo: boot.workspace.repo,
1548
+ branch: boot.workspace.branch,
1549
+ targetKind,
1550
+ targetId,
1551
+ canonicalUrl,
1552
+ summary: `${boot.workspace.repo} (${boot.workspace.branch}) · ${String(boot.specs.length)} specs`,
1553
+ ...(parsed.nest.length > 0 ? { nest: parsed.nest } : {}),
1554
+ ...(parsed.focus ? { focus: parsed.focus } : {}),
1555
+ };
1556
+
1557
+ if (format === 'json') {
1558
+ return c.json(
1559
+ studioDeepLinkJsonSchema.parse({
1560
+ focus,
1561
+ workspace: boot.workspace,
1562
+ specs: boot.specs,
1563
+ edges: boot.edges,
1564
+ }),
1565
+ );
1566
+ }
1567
+ if (format === 'markdown') {
1568
+ const openComments = boot.stateDoc.comments.filter((cm) => cm.status === 'open').length;
1569
+ return c.text(
1570
+ renderNegotiatedMarkdown({
1571
+ workspace: boot.workspace,
1572
+ focus,
1573
+ specs: boot.specs,
1574
+ openCommentCount: openComments,
1575
+ baseUrl,
1576
+ }),
1577
+ 200,
1578
+ { 'content-type': 'text/markdown; charset=utf-8' },
1579
+ );
1580
+ }
1581
+ return c.html(renderSpaHtmlWithFocus(focus, options.studioDistDir));
1582
+ };
1583
+
1584
+ app.get('/p/:wsKey', (c) => handleDeepLink(c, c.req.param('wsKey')));
1585
+ app.get('/p/:wsKey/*', (c) => handleDeepLink(c, c.req.param('wsKey')));
1586
+
1587
+ app.get('*', (c) => {
1588
+ const reqPath = c.req.path;
1589
+ if (reqPath.startsWith('/api/')) {
1590
+ return c.json({ error: `not found: ${reqPath}` }, 404);
1591
+ }
1592
+ const asset = loadStudioAsset(reqPath, options.studioDistDir);
1593
+ if (asset && reqPath !== '/' && reqPath !== '/index.html') {
1594
+ return new Response(new Uint8Array(asset.bytes), {
1595
+ status: 200,
1596
+ headers: { 'content-type': asset.contentType },
1597
+ });
1598
+ }
1599
+ const boot = handleBootstrap(activeWsKey);
1600
+ const focus: StudioFocusContext = {
1601
+ wsKey: boot?.workspace.wsKey ?? activeWsKey,
1602
+ repo: boot?.workspace.repo ?? primaryWs.repo,
1603
+ branch: boot?.workspace.branch ?? primaryWs.branch,
1604
+ targetKind: 'macro',
1605
+ targetId: 'default',
1606
+ canonicalUrl: `${formatLoopbackUrl(host, boundPort)}/`,
1607
+ summary: `${primaryWs.repo} (${primaryWs.branch})`,
1608
+ };
1609
+ return c.html(renderSpaHtmlWithFocus(focus, options.studioDistDir));
1610
+ });
1611
+
1612
+ return {
1613
+ app,
1614
+ host,
1615
+ token,
1616
+ activeWsKey,
1617
+ registerWorkspace,
1618
+ broadcastEvent,
1619
+ setBoundPort: (p: number) => {
1620
+ boundPort = p;
1621
+ },
1622
+ cleanup: () => {
1623
+ for (const timer of watchTimers.values()) clearTimeout(timer);
1624
+ watchTimers.clear();
1625
+ for (const w of watchers) {
1626
+ try {
1627
+ w.close();
1628
+ } catch {}
1629
+ }
1630
+ for (const closeStream of sseClosers) closeStream();
1631
+ sseClosers.clear();
1632
+ subscribers.clear();
1633
+ },
1634
+ };
1635
+ }
1636
+
1637
+ export async function startStudioHub(options: StudioHubOptions): Promise<RunningStudioHub> {
1638
+ const hubFilePath = options.hubFilePath ?? defaultHubFilePath();
1639
+ const version = options.version ?? '0.12.0';
1640
+ const created = createStudioHubApp(options);
1641
+ const preferredPort = options.port ?? 4710;
1642
+ const listenPort = await findAvailablePort(created.host, preferredPort);
1643
+ let boundPort = listenPort;
1644
+ let serverRef: ServerType;
1645
+ await new Promise<void>((resolveListen, rejectListen) => {
1646
+ serverRef = serve(
1647
+ {
1648
+ fetch: created.app.fetch,
1649
+ hostname: created.host,
1650
+ port: listenPort,
1651
+ },
1652
+ (info: AddressInfo) => {
1653
+ boundPort = info.port;
1654
+ created.setBoundPort(boundPort);
1655
+ resolveListen();
1656
+ },
1657
+ );
1658
+ serverRef.once('error', rejectListen);
1659
+ });
1660
+
1661
+ const url = formatLoopbackUrl(created.host, boundPort);
1662
+ if (options.writeHubFile !== false) {
1663
+ writeHubInfoFile(hubFilePath, {
1664
+ pid: process.pid,
1665
+ port: boundPort,
1666
+ host: created.host,
1667
+ token: created.token,
1668
+ version,
1669
+ startedAt: new Date().toISOString(),
1670
+ });
1671
+ }
1672
+
1673
+ return {
1674
+ app: created.app,
1675
+ host: created.host,
1676
+ port: boundPort,
1677
+ url,
1678
+ token: created.token,
1679
+ activeWsKey: created.activeWsKey,
1680
+ registerWorkspace: created.registerWorkspace,
1681
+ broadcastEvent: created.broadcastEvent,
1682
+ close: async () => {
1683
+ created.cleanup();
1684
+ if (options.writeHubFile !== false) {
1685
+ removeHubInfoFile(hubFilePath);
1686
+ }
1687
+ await new Promise<void>((resolveClose) => {
1688
+ const closable = serverRef as ServerType & { closeAllConnections?: () => void };
1689
+ serverRef.close(() => resolveClose());
1690
+ closable.closeAllConnections?.();
1691
+ });
1692
+ },
1693
+ };
1694
+ }