@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.
- package/package.json +13 -5
- package/src/cli-shared.ts +87 -62
- package/src/commands/archive.ts +4 -19
- package/src/commands/change.ts +132 -172
- package/src/commands/config.ts +1 -29
- package/src/commands/init.ts +39 -11
- package/src/commands/list.ts +0 -2
- package/src/commands/project.ts +25 -115
- 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 +6 -86
- 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 -16
- 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
- package/src/commands/context.ts +0 -88
- package/src/commands/index.ts +0 -53
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only git change-scope probe for Studio local server (studio-web r199).
|
|
3
|
+
* Reuses core `base_branch` resolution order, supports worktrees, never writes `llmanspec/specs/`,
|
|
4
|
+
* and strictly uses standard Node APIs (zero `Bun.*` calls).
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
7
|
+
import { basename, join, relative, sep } from 'node:path';
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
computeFeatureChangeDiff,
|
|
11
|
+
currentBranch,
|
|
12
|
+
defaultBranch,
|
|
13
|
+
EMPTY_CHANGE_SCOPE,
|
|
14
|
+
makeSpawnGit,
|
|
15
|
+
readBinding,
|
|
16
|
+
resolveChangeScopeActivation,
|
|
17
|
+
type StudioChangeItemStatus,
|
|
18
|
+
type StudioChangeScope,
|
|
19
|
+
type StudioMachineIR,
|
|
20
|
+
type StudioTouchedSpec,
|
|
21
|
+
} from '@llman-sdd/core';
|
|
22
|
+
|
|
23
|
+
interface BoundChangeMeta {
|
|
24
|
+
id: string;
|
|
25
|
+
title: string | null;
|
|
26
|
+
baseBranch: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function toPosixPath(p: string): string {
|
|
30
|
+
return sep === '/' ? p : p.split(sep).join('/');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function extractProposalTitle(raw: string): string | null {
|
|
34
|
+
const fmMatch = /^---\r?\n([\s\S]*?)\r?\n---/u.exec(raw);
|
|
35
|
+
if (fmMatch) {
|
|
36
|
+
const titleLine = /^title:\s*(.+)$/mu.exec(fmMatch[1] ?? '');
|
|
37
|
+
if (titleLine) {
|
|
38
|
+
const val = (titleLine[1] ?? '').trim().replace(/^["']|["']$/gu, '');
|
|
39
|
+
if (val && val !== 'TODO') return val;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const h1Match = /^#\s+(.+)$/mu.exec(raw);
|
|
43
|
+
return h1Match ? (h1Match[1] ?? '').trim() : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function findBoundChangeForBranch(instanceRoot: string, branch: string): BoundChangeMeta | null {
|
|
47
|
+
const changesDir = join(instanceRoot, 'llmanspec', 'changes');
|
|
48
|
+
if (!existsSync(changesDir)) return null;
|
|
49
|
+
|
|
50
|
+
const walk = (dir: string, depth: number): BoundChangeMeta | null => {
|
|
51
|
+
if (depth > 4) return null;
|
|
52
|
+
let entries: string[];
|
|
53
|
+
try {
|
|
54
|
+
entries = readdirSync(dir);
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
for (const name of entries) {
|
|
59
|
+
if (name === 'archive' && depth === 0) continue;
|
|
60
|
+
const full = join(dir, name);
|
|
61
|
+
let isDir = false;
|
|
62
|
+
try {
|
|
63
|
+
isDir = statSync(full).isDirectory();
|
|
64
|
+
} catch {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (!isDir) continue;
|
|
68
|
+
|
|
69
|
+
const proposalPath = join(full, 'proposal.md');
|
|
70
|
+
if (existsSync(proposalPath)) {
|
|
71
|
+
try {
|
|
72
|
+
const text = readFileSync(proposalPath, 'utf8');
|
|
73
|
+
const binding = readBinding(text);
|
|
74
|
+
if (binding && binding.branch === branch) {
|
|
75
|
+
return {
|
|
76
|
+
id: name,
|
|
77
|
+
title: extractProposalTitle(text),
|
|
78
|
+
baseBranch: binding.baseBranch,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
} catch {}
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const nested = walk(full, depth + 1);
|
|
85
|
+
if (nested) return nested;
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
return walk(changesDir, 0);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function resolveBaseBranchForWorkspace(
|
|
94
|
+
worktreePath: string,
|
|
95
|
+
curBranch: string | null,
|
|
96
|
+
boundChange: BoundChangeMeta | null,
|
|
97
|
+
defBranch: string,
|
|
98
|
+
): string {
|
|
99
|
+
if (boundChange?.baseBranch) return boundChange.baseBranch;
|
|
100
|
+
|
|
101
|
+
const git = makeSpawnGit(worktreePath);
|
|
102
|
+
if (curBranch) {
|
|
103
|
+
const configured = git.runOpt(['config', '--get', `branch.${curBranch}.base`])?.trim();
|
|
104
|
+
if (configured) return configured;
|
|
105
|
+
|
|
106
|
+
const upstream = git
|
|
107
|
+
.runOpt(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])
|
|
108
|
+
?.trim();
|
|
109
|
+
if (upstream) {
|
|
110
|
+
const slash = upstream.indexOf('/');
|
|
111
|
+
const localCandidate = slash >= 0 ? upstream.slice(slash + 1) : upstream;
|
|
112
|
+
if (localCandidate && localCandidate !== curBranch) {
|
|
113
|
+
const exists = git.runOpt(['show-ref', '--verify', `refs/heads/${localCandidate}`]);
|
|
114
|
+
if (exists !== null) return localCandidate;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return defBranch;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function capIdFromSpecsRelPath(relUnderSpecs: string): string | null {
|
|
123
|
+
const norm = toPosixPath(relUnderSpecs).replace(/^\/+/u, '');
|
|
124
|
+
if (!norm.endsWith('.feature')) return null;
|
|
125
|
+
const parts = norm.split('/');
|
|
126
|
+
if (parts.length === 1) {
|
|
127
|
+
return basename(parts[0]!, '.feature');
|
|
128
|
+
}
|
|
129
|
+
if (parts.length === 2 && parts[1] === `${parts[0]}.feature`) {
|
|
130
|
+
return parts[0]!;
|
|
131
|
+
}
|
|
132
|
+
return parts[0] || basename(norm, '.feature');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function unquoteGitPath(rawPath: string): string {
|
|
136
|
+
const trimmed = rawPath.trim();
|
|
137
|
+
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
138
|
+
return trimmed.slice(1, -1).replace(/\\"/gu, '"').replace(/\\\\/gu, '\\');
|
|
139
|
+
}
|
|
140
|
+
return trimmed;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function computeWorkspaceChangeScope(instanceRoot: string): StudioChangeScope {
|
|
144
|
+
const git = makeSpawnGit(instanceRoot);
|
|
145
|
+
const rawTopLevel = git.runOpt(['rev-parse', '--show-toplevel'])?.trim();
|
|
146
|
+
if (!rawTopLevel) return EMPTY_CHANGE_SCOPE;
|
|
147
|
+
|
|
148
|
+
const topLevel = existsSync(rawTopLevel) ? realpathSync(rawTopLevel) : rawTopLevel;
|
|
149
|
+
const resolvedInstanceRoot = existsSync(instanceRoot) ? realpathSync(instanceRoot) : instanceRoot;
|
|
150
|
+
|
|
151
|
+
const curBranch = currentBranch(git);
|
|
152
|
+
let defBranch: string;
|
|
153
|
+
try {
|
|
154
|
+
defBranch = defaultBranch(git);
|
|
155
|
+
} catch {
|
|
156
|
+
defBranch = 'main';
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const boundChange = curBranch ? findBoundChangeForBranch(resolvedInstanceRoot, curBranch) : null;
|
|
160
|
+
const baseBranch = resolveBaseBranchForWorkspace(
|
|
161
|
+
resolvedInstanceRoot,
|
|
162
|
+
curBranch,
|
|
163
|
+
boundChange,
|
|
164
|
+
defBranch,
|
|
165
|
+
);
|
|
166
|
+
const isDefaultBranch = curBranch === null || curBranch === defBranch;
|
|
167
|
+
|
|
168
|
+
const specsAbsDir = join(resolvedInstanceRoot, 'llmanspec', 'specs');
|
|
169
|
+
const specsGitPrefix = toPosixPath(relative(topLevel, specsAbsDir)).replace(/\/+$/u, '');
|
|
170
|
+
if (!specsGitPrefix || specsGitPrefix.startsWith('..')) {
|
|
171
|
+
return {
|
|
172
|
+
...EMPTY_CHANGE_SCOPE,
|
|
173
|
+
branch: curBranch,
|
|
174
|
+
baseBranch,
|
|
175
|
+
boundChangeId: boundChange?.id ?? null,
|
|
176
|
+
boundChangeTitle: boundChange?.title ?? null,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
let mergeBaseSha: string | null = null;
|
|
181
|
+
const committedByGitPath = new Map<string, StudioChangeItemStatus>();
|
|
182
|
+
if (curBranch && baseBranch && curBranch !== baseBranch) {
|
|
183
|
+
const mb = git.runOpt(['merge-base', 'HEAD', baseBranch])?.trim() || null;
|
|
184
|
+
if (mb) {
|
|
185
|
+
mergeBaseSha = mb;
|
|
186
|
+
const diffOut =
|
|
187
|
+
git.runOpt(['diff', '--name-status', `${mb}...HEAD`, '--', specsGitPrefix]) ?? '';
|
|
188
|
+
for (const rawLine of diffOut.split(/\r?\n/u)) {
|
|
189
|
+
const line = rawLine.trim();
|
|
190
|
+
if (!line) continue;
|
|
191
|
+
const cols = line.split('\t');
|
|
192
|
+
const code = cols[0] ?? '';
|
|
193
|
+
if (code.startsWith('R') && cols.length >= 3) {
|
|
194
|
+
const oldPath = unquoteGitPath(cols[1]!);
|
|
195
|
+
const newPath = unquoteGitPath(cols[2]!);
|
|
196
|
+
if (oldPath.endsWith('.feature')) committedByGitPath.set(oldPath, 'deleted');
|
|
197
|
+
if (newPath.endsWith('.feature')) committedByGitPath.set(newPath, 'added');
|
|
198
|
+
} else if (cols.length >= 2) {
|
|
199
|
+
const filePath = unquoteGitPath(cols[1]!);
|
|
200
|
+
if (!filePath.endsWith('.feature')) continue;
|
|
201
|
+
if (code.startsWith('A')) committedByGitPath.set(filePath, 'added');
|
|
202
|
+
else if (code.startsWith('D')) committedByGitPath.set(filePath, 'deleted');
|
|
203
|
+
else committedByGitPath.set(filePath, 'modified');
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const uncommittedByGitPath = new Map<string, StudioChangeItemStatus>();
|
|
210
|
+
const statusOut = git.runOpt(['status', '--porcelain=v1', '-uall', '--', specsGitPrefix]) ?? '';
|
|
211
|
+
for (const rawLine of statusOut.split(/\r?\n/u)) {
|
|
212
|
+
if (rawLine.length < 4) continue;
|
|
213
|
+
const xy = rawLine.slice(0, 2);
|
|
214
|
+
const rest = rawLine.slice(3).trim();
|
|
215
|
+
if (!rest) continue;
|
|
216
|
+
if (rest.includes(' -> ')) {
|
|
217
|
+
const [oldRaw, newRaw] = rest.split(' -> ');
|
|
218
|
+
const oldPath = unquoteGitPath(oldRaw ?? '');
|
|
219
|
+
const newPath = unquoteGitPath(newRaw ?? '');
|
|
220
|
+
if (oldPath.endsWith('.feature')) uncommittedByGitPath.set(oldPath, 'deleted');
|
|
221
|
+
if (newPath.endsWith('.feature')) uncommittedByGitPath.set(newPath, 'added');
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const filePath = unquoteGitPath(rest);
|
|
225
|
+
if (!filePath.endsWith('.feature')) continue;
|
|
226
|
+
if (xy === '??' || xy.includes('A')) uncommittedByGitPath.set(filePath, 'added');
|
|
227
|
+
else if (xy.includes('D')) uncommittedByGitPath.set(filePath, 'deleted');
|
|
228
|
+
else uncommittedByGitPath.set(filePath, 'modified');
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const allGitPaths = new Set<string>([
|
|
232
|
+
...committedByGitPath.keys(),
|
|
233
|
+
...uncommittedByGitPath.keys(),
|
|
234
|
+
]);
|
|
235
|
+
|
|
236
|
+
const baseRef = mergeBaseSha ?? 'HEAD';
|
|
237
|
+
const touchedByCap = new Map<string, StudioTouchedSpec>();
|
|
238
|
+
const baseMachines: Record<string, StudioMachineIR> = {};
|
|
239
|
+
|
|
240
|
+
for (const gitPath of allGitPaths) {
|
|
241
|
+
const prefixWithSlash = `${specsGitPrefix}/`;
|
|
242
|
+
if (!gitPath.startsWith(prefixWithSlash)) continue;
|
|
243
|
+
const relUnderSpecs = gitPath.slice(prefixWithSlash.length);
|
|
244
|
+
const capId = capIdFromSpecsRelPath(relUnderSpecs);
|
|
245
|
+
if (!capId) continue;
|
|
246
|
+
|
|
247
|
+
const committedStatus = committedByGitPath.get(gitPath);
|
|
248
|
+
const uncommittedStatus = uncommittedByGitPath.get(gitPath);
|
|
249
|
+
const hasUncommitted = uncommittedStatus !== undefined;
|
|
250
|
+
|
|
251
|
+
const absPath = join(topLevel, gitPath);
|
|
252
|
+
const currentRaw = existsSync(absPath) ? readFileSync(absPath, 'utf8') : null;
|
|
253
|
+
const baseRaw = git.runOpt(['show', `${baseRef}:${gitPath}`]);
|
|
254
|
+
|
|
255
|
+
let status: StudioChangeItemStatus;
|
|
256
|
+
if (baseRaw === null && currentRaw !== null) {
|
|
257
|
+
status = 'added';
|
|
258
|
+
} else if (baseRaw !== null && currentRaw === null) {
|
|
259
|
+
status = 'deleted';
|
|
260
|
+
} else {
|
|
261
|
+
status = committedStatus ?? uncommittedStatus ?? 'modified';
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const detail = computeFeatureChangeDiff(baseRaw, currentRaw, capId);
|
|
265
|
+
Object.assign(baseMachines, detail.baseMachines);
|
|
266
|
+
|
|
267
|
+
touchedByCap.set(capId, {
|
|
268
|
+
capId,
|
|
269
|
+
status,
|
|
270
|
+
hasUncommitted,
|
|
271
|
+
touchedReqIds: detail.touchedReqIds,
|
|
272
|
+
reqStatuses: detail.reqStatuses,
|
|
273
|
+
touchedGraphIds: detail.touchedGraphIds,
|
|
274
|
+
graphStatuses: detail.graphStatuses,
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const touchedSpecs = [...touchedByCap.values()].sort((a, b) => a.capId.localeCompare(b.capId));
|
|
279
|
+
const activation = resolveChangeScopeActivation({
|
|
280
|
+
isDefaultBranch,
|
|
281
|
+
hasCommittedSpecDiff: committedByGitPath.size > 0,
|
|
282
|
+
hasUncommittedSpecDiff: uncommittedByGitPath.size > 0,
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
return {
|
|
286
|
+
active: activation.active,
|
|
287
|
+
branch: curBranch,
|
|
288
|
+
baseBranch,
|
|
289
|
+
mergeBaseSha: mergeBaseSha ? mergeBaseSha.slice(0, 7) : null,
|
|
290
|
+
boundChangeId: boundChange?.id ?? null,
|
|
291
|
+
boundChangeTitle: boundChange?.title ?? null,
|
|
292
|
+
touchedSpecs,
|
|
293
|
+
...(Object.keys(baseMachines).length > 0 ? { baseMachines } : {}),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-demand single-instance Hub registry (~/.llman-sdd/studio-hub.json) with /api/health probing
|
|
3
|
+
* and zombie-lock self-healing (studio-web r144). Dual-runtime safe (node:fs + node:os + fetch).
|
|
4
|
+
*/
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
healthResponseSchema,
|
|
11
|
+
hubInfoSchema,
|
|
12
|
+
type HealthResponse,
|
|
13
|
+
type HubInfo,
|
|
14
|
+
} from '@llman-sdd/core';
|
|
15
|
+
|
|
16
|
+
let tmpCounter = 0;
|
|
17
|
+
|
|
18
|
+
export function isLoopbackHost(host: string): boolean {
|
|
19
|
+
const norm = host.trim().toLowerCase();
|
|
20
|
+
return norm === '127.0.0.1' || norm === 'localhost' || norm === '::1';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function formatLoopbackUrl(host: string, port: number): string {
|
|
24
|
+
const hostPart = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
|
|
25
|
+
return `http://${hostPart}:${String(port)}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function defaultHubFilePath(): string {
|
|
29
|
+
return join(homedir(), '.llman-sdd', 'studio-hub.json');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function readHubInfoFile(hubFilePath: string): HubInfo | null {
|
|
33
|
+
if (!existsSync(hubFilePath)) return null;
|
|
34
|
+
try {
|
|
35
|
+
const raw = JSON.parse(readFileSync(hubFilePath, 'utf8')) as unknown;
|
|
36
|
+
const parsed = hubInfoSchema.safeParse(raw);
|
|
37
|
+
return parsed.success ? parsed.data : null;
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function writeHubInfoFile(hubFilePath: string, info: HubInfo): void {
|
|
44
|
+
const checked = hubInfoSchema.parse(info);
|
|
45
|
+
mkdirSync(dirname(hubFilePath), { recursive: true });
|
|
46
|
+
tmpCounter += 1;
|
|
47
|
+
const tmpPath = `${hubFilePath}.tmp.${String(process.pid)}.${String(tmpCounter)}`;
|
|
48
|
+
writeFileSync(tmpPath, `${JSON.stringify(checked, null, 2)}\n`, 'utf8');
|
|
49
|
+
renameSync(tmpPath, hubFilePath);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function removeHubInfoFile(hubFilePath: string): void {
|
|
53
|
+
if (existsSync(hubFilePath)) {
|
|
54
|
+
rmSync(hubFilePath, { force: true });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function probeHubHealth(
|
|
59
|
+
host: string,
|
|
60
|
+
port: number,
|
|
61
|
+
timeoutMs = 1500,
|
|
62
|
+
): Promise<HealthResponse | null> {
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
65
|
+
try {
|
|
66
|
+
const res = await fetch(`${formatLoopbackUrl(host, port)}/api/health`, {
|
|
67
|
+
signal: controller.signal,
|
|
68
|
+
headers: { accept: 'application/json' },
|
|
69
|
+
});
|
|
70
|
+
if (!res.ok) return null;
|
|
71
|
+
const json = (await res.json()) as unknown;
|
|
72
|
+
const parsed = healthResponseSchema.safeParse(json);
|
|
73
|
+
return parsed.success ? parsed.data : null;
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
} finally {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Inspect studio-hub.json, probe live health, and automatically clean up stale/zombie lock files.
|
|
83
|
+
*/
|
|
84
|
+
export async function resolveLiveHub(
|
|
85
|
+
hubFilePath = defaultHubFilePath(),
|
|
86
|
+
): Promise<{ info: HubInfo; health: HealthResponse } | null> {
|
|
87
|
+
const info = readHubInfoFile(hubFilePath);
|
|
88
|
+
if (!info) {
|
|
89
|
+
removeHubInfoFile(hubFilePath);
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
const health = await probeHubHealth(info.host, info.port);
|
|
93
|
+
if (!health || health.pid !== info.pid) {
|
|
94
|
+
removeHubInfoFile(hubFilePath);
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
return { info, health };
|
|
98
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transparent HTTP GET Content Negotiation for Canonical Deep-Links `/p/:wsKey/*` (studio-web r145).
|
|
3
|
+
* - Browser (`Accept: text/html` or `?format=html`): SPA HTML with embedded `#studio-focus-context`
|
|
4
|
+
* - Machine / Agent (`?format=json` or `Accept: application/json`): structured JSON
|
|
5
|
+
* - Non-browser default (`curl` / Agent `fetch` / `?format=markdown`): token-efficient Markdown + routing tip
|
|
6
|
+
*/
|
|
7
|
+
import type { SpecIndexItem, StudioFocusContext, WorkspaceItem } from '@llman-sdd/core';
|
|
8
|
+
|
|
9
|
+
export type NegotiatedFormat = 'html' | 'json' | 'markdown';
|
|
10
|
+
|
|
11
|
+
export function resolveNegotiatedFormat(
|
|
12
|
+
acceptHeader: string | undefined,
|
|
13
|
+
formatQuery: string | undefined,
|
|
14
|
+
): NegotiatedFormat {
|
|
15
|
+
const explicit = (formatQuery ?? '').trim().toLowerCase();
|
|
16
|
+
if (explicit === 'json') return 'json';
|
|
17
|
+
if (explicit === 'html') return 'html';
|
|
18
|
+
if (explicit === 'md' || explicit === 'markdown') return 'markdown';
|
|
19
|
+
|
|
20
|
+
const accept = (acceptHeader ?? '').toLowerCase();
|
|
21
|
+
if (accept.includes('text/html') || accept.includes('application/xhtml+xml')) {
|
|
22
|
+
return 'html';
|
|
23
|
+
}
|
|
24
|
+
if (accept.includes('application/json')) {
|
|
25
|
+
return 'json';
|
|
26
|
+
}
|
|
27
|
+
return 'markdown';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function renderNegotiatedMarkdown(input: {
|
|
31
|
+
workspace: WorkspaceItem;
|
|
32
|
+
focus: StudioFocusContext;
|
|
33
|
+
specs: readonly SpecIndexItem[];
|
|
34
|
+
openCommentCount: number;
|
|
35
|
+
baseUrl: string;
|
|
36
|
+
}): string {
|
|
37
|
+
const { workspace, focus, specs, openCommentCount, baseUrl } = input;
|
|
38
|
+
const lines = [
|
|
39
|
+
`# llman-sdd Studio · ${workspace.repo} (${workspace.branch})`,
|
|
40
|
+
'',
|
|
41
|
+
`- Workspace: \`${workspace.wsKey}\` (${workspace.protected ? 'protected branch' : 'writable branch'})`,
|
|
42
|
+
`- Focus: \`${focus.targetKind}:${focus.targetId}\` — ${focus.summary}`,
|
|
43
|
+
...(focus.nest && focus.nest.length > 0 ? [`- Nest: \`${focus.nest.join(' > ')}\``] : []),
|
|
44
|
+
...(focus.focus ? [`- Focus object: \`${focus.focus.kind}:${focus.focus.id}\``] : []),
|
|
45
|
+
`- Specs: ${String(specs.length)} | Open comments: ${String(openCommentCount)}`,
|
|
46
|
+
`- Canonical URL: ${focus.canonicalUrl}`,
|
|
47
|
+
'',
|
|
48
|
+
'## Specs Overview',
|
|
49
|
+
'',
|
|
50
|
+
...specs.map(
|
|
51
|
+
(s) =>
|
|
52
|
+
`- **${s.id}** (\`${s.kind}\`, ${String(s.ruleCount)} rules, ${String(s.scenarioCount)} scenarios): ${s.summary}`,
|
|
53
|
+
),
|
|
54
|
+
'',
|
|
55
|
+
'---',
|
|
56
|
+
`> Routing tip: append \`?format=json\` for structured JSON (${baseUrl}/p/${encodeURIComponent(workspace.wsKey)}?format=json), or \`?format=html\` for the interactive browser workbench.`,
|
|
57
|
+
'',
|
|
58
|
+
];
|
|
59
|
+
return lines.join('\n');
|
|
60
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loopback security guards for local Studio Hub (studio-web r144).
|
|
3
|
+
* Blocks DNS Rebinding (Host check) and cross-site CSRF writes (Origin + X-Studio-Token).
|
|
4
|
+
* Pure node:crypto + Hono middleware — zero Bun.* APIs.
|
|
5
|
+
*/
|
|
6
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
7
|
+
|
|
8
|
+
import type { MiddlewareHandler } from 'hono';
|
|
9
|
+
|
|
10
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']);
|
|
11
|
+
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
12
|
+
|
|
13
|
+
export function generateStudioToken(): string {
|
|
14
|
+
return randomBytes(24).toString('hex');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function isLoopbackHostHeader(hostHeader: string | undefined): boolean {
|
|
18
|
+
if (!hostHeader) return true;
|
|
19
|
+
const trimmed = hostHeader.trim().toLowerCase();
|
|
20
|
+
if (trimmed === '') return false;
|
|
21
|
+
if (trimmed.startsWith('[')) {
|
|
22
|
+
const closeIdx = trimmed.indexOf(']');
|
|
23
|
+
if (closeIdx === -1) return false;
|
|
24
|
+
return LOOPBACK_HOSTS.has(trimmed.slice(0, closeIdx + 1));
|
|
25
|
+
}
|
|
26
|
+
const hostname = trimmed.split(':')[0] ?? '';
|
|
27
|
+
return LOOPBACK_HOSTS.has(hostname);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function isLoopbackOriginHeader(originHeader: string | undefined): boolean {
|
|
31
|
+
if (!originHeader) return true;
|
|
32
|
+
try {
|
|
33
|
+
const parsed = new URL(originHeader);
|
|
34
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
|
|
35
|
+
return LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase());
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function tokensEqual(a: string, b: string): boolean {
|
|
42
|
+
const bufA = Buffer.from(a, 'utf8');
|
|
43
|
+
const bufB = Buffer.from(b, 'utf8');
|
|
44
|
+
if (bufA.length !== bufB.length) return false;
|
|
45
|
+
return timingSafeEqual(bufA, bufB);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Enforces loopback Host on every request and Origin + X-Studio-Token on all mutating routes.
|
|
50
|
+
*/
|
|
51
|
+
export function createLoopbackSecurityMiddleware(expectedToken: string): MiddlewareHandler {
|
|
52
|
+
return async (c, next) => {
|
|
53
|
+
const host = c.req.header('host');
|
|
54
|
+
if (!isLoopbackHostHeader(host)) {
|
|
55
|
+
return c.json({ error: 'forbidden: non-loopback Host header rejected' }, 403);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (MUTATING_METHODS.has(c.req.method.toUpperCase())) {
|
|
59
|
+
const origin = c.req.header('origin');
|
|
60
|
+
if (!isLoopbackOriginHeader(origin)) {
|
|
61
|
+
return c.json({ error: 'forbidden: non-loopback Origin header rejected' }, 403);
|
|
62
|
+
}
|
|
63
|
+
const provided = c.req.header('x-studio-token') ?? c.req.query('token') ?? '';
|
|
64
|
+
if (provided === '' || !tokensEqual(provided, expectedToken)) {
|
|
65
|
+
return c.json({ error: 'forbidden: missing or invalid X-Studio-Token' }, 403);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
await next();
|
|
70
|
+
};
|
|
71
|
+
}
|