@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,184 @@
1
+ /**
2
+ * Dual-mode Studio Web static asset resolver (studio-web r147):
3
+ * 1. Compiled single-binary mode: serves embedded assets from LLMAN_SDD_DEV_BUILD_EMBEDDED_STUDIO_ASSETS
4
+ * 2. Source / npm / dev mode: falls back cleanly to apps/studio/dist/ on disk.
5
+ * Zero Bun.* APIs; uses import.meta.dirname per monorepo-structure r3.
6
+ */
7
+ import { existsSync, readFileSync, statSync } from 'node:fs';
8
+ import { extname, join, posix, resolve, sep } from 'node:path';
9
+
10
+ import type { StudioFocusContext } from '@llman-sdd/core';
11
+
12
+ export interface EmbeddedAssetEntry {
13
+ encoding: 'utf8' | 'base64';
14
+ content: string;
15
+ }
16
+
17
+ export interface ResolvedStaticAsset {
18
+ bytes: Uint8Array;
19
+ contentType: string;
20
+ }
21
+
22
+ const MIME_BY_EXT: Readonly<Record<string, string>> = {
23
+ '.html': 'text/html; charset=utf-8',
24
+ '.js': 'text/javascript; charset=utf-8',
25
+ '.mjs': 'text/javascript; charset=utf-8',
26
+ '.css': 'text/css; charset=utf-8',
27
+ '.json': 'application/json; charset=utf-8',
28
+ '.svg': 'image/svg+xml',
29
+ '.png': 'image/png',
30
+ '.jpg': 'image/jpeg',
31
+ '.jpeg': 'image/jpeg',
32
+ '.webp': 'image/webp',
33
+ '.ico': 'image/x-icon',
34
+ '.woff2': 'font/woff2',
35
+ '.woff': 'font/woff',
36
+ '.map': 'application/json; charset=utf-8',
37
+ };
38
+
39
+ function mimeForPath(relPath: string): string {
40
+ return MIME_BY_EXT[extname(relPath).toLowerCase()] ?? 'application/octet-stream';
41
+ }
42
+
43
+ let cachedEmbeddedAssets: Record<string, EmbeddedAssetEntry> | null | undefined;
44
+
45
+ export function resetEmbeddedStudioAssetsCache(): void {
46
+ cachedEmbeddedAssets = undefined;
47
+ }
48
+
49
+ export function parseEmbeddedStudioAssets(raw: unknown): Record<string, EmbeddedAssetEntry> | null {
50
+ if (!raw) return null;
51
+ if (typeof raw === 'object' && !Array.isArray(raw)) {
52
+ return raw as Record<string, EmbeddedAssetEntry>;
53
+ }
54
+ if (typeof raw === 'string') {
55
+ try {
56
+ const parsed = JSON.parse(raw) as unknown;
57
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
58
+ return parsed as Record<string, EmbeddedAssetEntry>;
59
+ }
60
+ } catch {}
61
+ }
62
+ return null;
63
+ }
64
+
65
+ export function resolveEmbeddedStudioAssets(): Record<string, EmbeddedAssetEntry> | null {
66
+ if (cachedEmbeddedAssets !== undefined) return cachedEmbeddedAssets;
67
+ // Bun.build --define injects an object literal directly; runtime env vars are JSON strings. ~keep
68
+ const raw = process.env.LLMAN_SDD_DEV_BUILD_EMBEDDED_STUDIO_ASSETS as unknown;
69
+ cachedEmbeddedAssets = parseEmbeddedStudioAssets(raw);
70
+ return cachedEmbeddedAssets;
71
+ }
72
+
73
+ /** Locate apps/studio/dist relative to this file in source/workspace/npm layouts. */
74
+ export function resolveStudioDistDir(overrideDir?: string): string | null {
75
+ if (overrideDir && existsSync(overrideDir)) return resolve(overrideDir);
76
+ const candidates = [
77
+ resolve(import.meta.dirname, '..', '..', '..', 'studio', 'dist'),
78
+ resolve(import.meta.dirname, '..', '..', 'studio-dist'),
79
+ ];
80
+ for (const dir of candidates) {
81
+ if (existsSync(join(dir, 'index.html'))) return dir;
82
+ }
83
+ return null;
84
+ }
85
+
86
+ function normalizeAssetKey(requestPath: string): string | null {
87
+ const stripped = requestPath.replace(/^\/+/u, '');
88
+ const normalized = posix.normalize(stripped === '' ? 'index.html' : stripped);
89
+ if (normalized.startsWith('..') || posix.isAbsolute(normalized)) return null;
90
+ return normalized;
91
+ }
92
+
93
+ export function loadStudioAsset(
94
+ requestPath: string,
95
+ overrideDistDir?: string,
96
+ ): ResolvedStaticAsset | null {
97
+ const key = normalizeAssetKey(requestPath);
98
+ if (!key) return null;
99
+
100
+ const embedded = resolveEmbeddedStudioAssets();
101
+ if (embedded) {
102
+ const hit = embedded[key];
103
+ if (hit) {
104
+ const bytes =
105
+ hit.encoding === 'base64'
106
+ ? Uint8Array.from(Buffer.from(hit.content, 'base64'))
107
+ : new TextEncoder().encode(hit.content);
108
+ return { bytes, contentType: mimeForPath(key) };
109
+ }
110
+ }
111
+
112
+ const distDir = resolveStudioDistDir(overrideDistDir);
113
+ if (!distDir) return null;
114
+ const fullPath = resolve(distDir, key);
115
+ if (fullPath !== distDir && !fullPath.startsWith(`${distDir}${sep}`)) return null;
116
+ if (!existsSync(fullPath) || !statSync(fullPath).isFile()) return null;
117
+ return {
118
+ bytes: new Uint8Array(readFileSync(fullPath)),
119
+ contentType: mimeForPath(key),
120
+ };
121
+ }
122
+
123
+ const FALLBACK_SPA_HTML = `<!doctype html>
124
+ <html lang="zh-CN" data-skin="linear">
125
+ <head>
126
+ <meta charset="UTF-8" />
127
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
128
+ <title>llman-sdd Studio — Static Assets Missing</title>
129
+ <style>
130
+ body { font-family: ui-sans-serif, system-ui, sans-serif; margin: 48px auto; max-width: 680px; padding: 0 20px; color: #1f2937; line-height: 1.6; }
131
+ code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; background: #f3f4f6; border-radius: 6px; }
132
+ code { padding: 2px 6px; }
133
+ pre { padding: 12px 14px; overflow-x: auto; }
134
+ .card { border: 1px solid #d1d5db; border-radius: 10px; padding: 20px 24px; background: #ffffff; }
135
+ h1 { font-size: 18px; margin: 0 0 8px; }
136
+ p { margin: 8px 0; font-size: 14px; }
137
+ </style>
138
+ </head>
139
+ <body>
140
+ <div id="root">
141
+ <main class="card" data-studio-fallback="missing-assets">
142
+ <h1>llman-sdd Studio Web static assets not found</h1>
143
+ <p>The Studio API server is running, but the compiled Web UI bundle (<code>index.html</code>) could not be resolved from embedded binary assets, <code>apps/studio/dist/</code>, or <code>studio-dist/</code>.</p>
144
+ <p>How to fix:</p>
145
+ <pre><code># Source / workspace checkout:
146
+ bun --filter '@llman-sdd/studio' build
147
+
148
+ # npm package installation:
149
+ # Upgrade or reinstall @llman-sdd/cli (&gt;= 0.12.0), or download the standalone binary from GitHub Releases.</code></pre>
150
+ </main>
151
+ </div>
152
+ <script type="application/json" id="studio-focus-context">{}</script>
153
+ </body>
154
+ </html>`;
155
+
156
+ let warnedMissingAssets = false;
157
+
158
+ export function renderSpaHtmlWithFocus(
159
+ focusCtx: StudioFocusContext,
160
+ overrideDistDir?: string,
161
+ ): string {
162
+ const asset = loadStudioAsset('index.html', overrideDistDir);
163
+ if (!asset && !warnedMissingAssets) {
164
+ warnedMissingAssets = true;
165
+ console.error(
166
+ '[WARNING] Studio Web static assets (index.html) not found; serving diagnostic fallback. ' +
167
+ "Run `bun --filter '@llman-sdd/studio' build` in a source checkout or reinstall `@llman-sdd/cli`.",
168
+ );
169
+ }
170
+ const html = asset ? new TextDecoder().decode(asset.bytes) : FALLBACK_SPA_HTML;
171
+ const safeJson = JSON.stringify(focusCtx)
172
+ .replaceAll('<', '\\u003c')
173
+ .replaceAll('>', '\\u003e')
174
+ .replaceAll('\u2028', '\\u2028')
175
+ .replaceAll('\u2029', '\\u2029');
176
+ const scriptTag = `<script type="application/json" id="studio-focus-context">${safeJson}</script>`;
177
+ if (html.includes('id="studio-focus-context"')) {
178
+ return html.replace(
179
+ /<script[^>]*id="studio-focus-context"[^>]*>[\s\S]*?<\/script>/u,
180
+ () => scriptTag,
181
+ );
182
+ }
183
+ return html.replace('</body>', () => `${scriptTag}\n</body>`);
184
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Disk-backed Studio sync preview (CLI + Hub). Reads .feature files and re-extracts
3
+ * THEIRS IR; never writes llmanspec/specs/. Hashing and fs stay in this adapter.
4
+ */
5
+ import { createHash } from 'node:crypto';
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { resolve } from 'node:path';
8
+
9
+ import {
10
+ buildDocSyncItems,
11
+ buildSyncItems,
12
+ extractStudioMachines,
13
+ machineDomainEquals,
14
+ parseCapability,
15
+ type SpecEntry,
16
+ type StudioMachineIR,
17
+ type StudioStateDoc,
18
+ type SyncItem,
19
+ } from '@llman-sdd/core';
20
+
21
+ export function sha256Hex(text: string): string {
22
+ return createHash('sha256').update(text, 'utf8').digest('hex');
23
+ }
24
+
25
+ export function readWorkspaceFile(instanceRoot: string, relPath: string): string | null {
26
+ const abs = resolve(instanceRoot, relPath);
27
+ return existsSync(abs) ? readFileSync(abs, 'utf8') : null;
28
+ }
29
+
30
+ export function extractTheirsMachine(
31
+ instanceRoot: string,
32
+ sourceFile: string,
33
+ machineKey: string,
34
+ ): StudioMachineIR | null {
35
+ const text = readWorkspaceFile(instanceRoot, sourceFile);
36
+ if (text === null) return null;
37
+ const entry: SpecEntry = {
38
+ fileName: sourceFile,
39
+ specId: sourceFile.replace(/^.*\//u, '').replace(/\.feature$/u, ''),
40
+ doc: parseCapability(text, sourceFile),
41
+ };
42
+ const hit = extractStudioMachines([entry]).find(
43
+ (m) => (m.machine.machineKey ?? m.draft.current?.machineKey) === machineKey,
44
+ );
45
+ return hit?.machine ?? null;
46
+ }
47
+
48
+ export interface DiskSyncPreview {
49
+ stale: boolean;
50
+ staleFiles: string[];
51
+ items: SyncItem[];
52
+ diskHashes: Record<string, string>;
53
+ }
54
+
55
+ export function collectDiskSyncPreview(instanceRoot: string, doc: StudioStateDoc): DiskSyncPreview {
56
+ const staleFiles: string[] = [];
57
+ const diskHashes: Record<string, string> = {};
58
+ const items: SyncItem[] = [];
59
+
60
+ const consider = (file: string, text: string | null): void => {
61
+ if (text === null) return;
62
+ const hash = sha256Hex(text);
63
+ diskHashes[file] = hash;
64
+ const expected = doc.baseHashes?.[file];
65
+ if (expected !== undefined && expected !== hash && !staleFiles.includes(file)) {
66
+ staleFiles.push(file);
67
+ }
68
+ };
69
+
70
+ for (const draft of Object.values(doc.machines)) {
71
+ const text = readWorkspaceFile(instanceRoot, draft.sourceFile);
72
+ consider(draft.sourceFile, text);
73
+ if (text === null) continue;
74
+ const expected = doc.baseHashes?.[draft.sourceFile];
75
+ const hash = sha256Hex(text);
76
+ if (expected !== undefined && expected !== hash) {
77
+ const machineKey = draft.current?.machineKey ?? draft.baseline?.machineKey ?? '';
78
+ const theirs = extractTheirsMachine(instanceRoot, draft.sourceFile, machineKey);
79
+ items.push(...buildSyncItems(draft, theirs));
80
+ }
81
+ }
82
+
83
+ for (const [capId, docDraft] of Object.entries(doc.docDrafts ?? {})) {
84
+ void capId;
85
+ const text = readWorkspaceFile(instanceRoot, docDraft.sourceFile);
86
+ consider(docDraft.sourceFile, text);
87
+ if (text === null) continue;
88
+ const expected = doc.baseHashes?.[docDraft.sourceFile] ?? docDraft.baseHash;
89
+ if (expected !== sha256Hex(text)) {
90
+ items.push(...buildDocSyncItems(docDraft.sourceFile, docDraft.currentText, text));
91
+ }
92
+ }
93
+
94
+ return { stale: staleFiles.length > 0, staleFiles, items, diskHashes };
95
+ }
96
+
97
+ /** True when every draft for `file` is domain-equivalent to the on-disk reparse (layout ignored). */
98
+ export function fileDomainMatchesDisk(
99
+ instanceRoot: string,
100
+ doc: StudioStateDoc,
101
+ file: string,
102
+ ): boolean {
103
+ const text = readWorkspaceFile(instanceRoot, file);
104
+ if (text === null) return false;
105
+ for (const draft of Object.values(doc.machines)) {
106
+ if (draft.sourceFile !== file) continue;
107
+ const machineKey = draft.current?.machineKey ?? draft.baseline?.machineKey ?? '';
108
+ const theirs = extractTheirsMachine(instanceRoot, file, machineKey);
109
+ if (!machineDomainEquals(draft.current, theirs)) return false;
110
+ }
111
+ for (const docDraft of Object.values(doc.docDrafts ?? {})) {
112
+ if (docDraft.sourceFile !== file) continue;
113
+ if (docDraft.currentText !== text) return false;
114
+ }
115
+ return true;
116
+ }
@@ -0,0 +1,53 @@
1
+ import { currentBranch, defaultBranch, readBinding } from '@llman-sdd/core';
2
+
3
+ import type { CliContext } from '../cli-shared.ts';
4
+
5
+ function boundBaseRef(ctx: CliContext, branch: string | null): string | null {
6
+ if (branch === null) return null;
7
+ const changesDir = 'llmanspec/changes';
8
+ if (!ctx.io.exists(changesDir)) return null;
9
+ for (const dir of ctx.io.listDir(changesDir)) {
10
+ const proposal = `${changesDir}/${dir}/proposal.md`;
11
+ if (!ctx.io.exists(proposal)) continue;
12
+ const binding = readBinding(ctx.io.readText(proposal));
13
+ if (binding === null || binding.branch !== branch) continue;
14
+ return binding.baseSha !== '' ? binding.baseSha : binding.baseBranch;
15
+ }
16
+ return null;
17
+ }
18
+
19
+ export function mergeBaseOrSelf(ctx: CliContext, ref: string): string {
20
+ const base = ctx.git.runOpt(['merge-base', ref, 'HEAD']);
21
+ return base !== null && base !== '' ? base : ref;
22
+ }
23
+
24
+ function defaultBaseRef(ctx: CliContext): string | null {
25
+ try {
26
+ return defaultBranch(ctx.git);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ function rootCommit(ctx: CliContext): string | null {
33
+ const root = ctx.git.runOpt(['rev-list', '--max-parents=0', 'HEAD']);
34
+ if (root === null || root === '') return null;
35
+ return root.split('\n')[0] ?? null;
36
+ }
37
+
38
+ /**
39
+ * Resolve the baseline to diff HEAD against. Order: explicit --base, the bound
40
+ * change's recorded fork point, the default branch, then the root commit. Only
41
+ * a repository with no commits yields null (the caller then skips the diff).
42
+ */
43
+ export function resolveBaseRef(ctx: CliContext, explicit?: string): string | null {
44
+ if (explicit !== undefined && explicit.trim() !== '') {
45
+ return mergeBaseOrSelf(ctx, explicit.trim());
46
+ }
47
+ const branch = currentBranch(ctx.git);
48
+ const bound = boundBaseRef(ctx, branch);
49
+ if (bound !== null) return mergeBaseOrSelf(ctx, bound);
50
+ const def = defaultBaseRef(ctx);
51
+ if (def !== null) return mergeBaseOrSelf(ctx, def);
52
+ return rootCommit(ctx);
53
+ }
@@ -0,0 +1,90 @@
1
+ import type { TheoremValidationResult } from '@llman-sdd/core';
2
+
3
+ export const THEOREM_STATE_CODES = [
4
+ 'S0_ABSENT',
5
+ 'S1_EMPTY',
6
+ 'S2_LOCKED_STRONG',
7
+ 'S3_LOCKED_WEAK',
8
+ 'S4_UNLOCKED',
9
+ 'S5_SPLIT_BRAIN',
10
+ 'S6_SCHEMA_INVALID',
11
+ 'S7_LEGACY_CONFLICT',
12
+ 'S8_UNSUPPORTED_FS',
13
+ ] as const;
14
+
15
+ export type TheoremStateCode = (typeof THEOREM_STATE_CODES)[number];
16
+
17
+ export const UNHEALTHY_STATES: readonly TheoremStateCode[] = [
18
+ 'S4_UNLOCKED',
19
+ 'S5_SPLIT_BRAIN',
20
+ 'S6_SCHEMA_INVALID',
21
+ 'S7_LEGACY_CONFLICT',
22
+ 'S8_UNSUPPORTED_FS',
23
+ ];
24
+
25
+ export const RECOVERY_ACTIONS: Readonly<Record<TheoremStateCode, string>> = {
26
+ S0_ABSENT: 'Run `llman-sdd theorem add` to declare the first theorem.',
27
+ S1_EMPTY: 'Run `llman-sdd theorem add` to add the first theorem file.',
28
+ S2_LOCKED_STRONG: 'Healthy: every theorem is valid and natively locked.',
29
+ S3_LOCKED_WEAK: 'Run `llman-sdd theorem lock` from a filesystem that supports strong locks.',
30
+ S4_UNLOCKED: 'Run `llman-sdd theorem lock` to apply native OS locks.',
31
+ S5_SPLIT_BRAIN: 'Audit the listed files, then run `llman-sdd theorem lock` to unify locks.',
32
+ S6_SCHEMA_INVALID: 'Fix the reported YAML/id errors, then run `llman-sdd theorem edit <id>`.',
33
+ S7_LEGACY_CONFLICT: 'Run `llman-sdd theorem migrate` to convert legacy Markdown files.',
34
+ S8_UNSUPPORTED_FS: 'Re-run with `--fallback-readonly` or move to a filesystem with strong locks.',
35
+ };
36
+
37
+ export interface TheoremFileState {
38
+ filePath: string;
39
+ strength: 'strong' | 'weak' | 'none';
40
+ untracked: boolean;
41
+ }
42
+
43
+ export interface DiagnoseInput {
44
+ directoryExists: boolean;
45
+ validation: TheoremValidationResult;
46
+ legacyFiles: readonly string[];
47
+ files: readonly TheoremFileState[];
48
+ capabilitySupported: boolean;
49
+ }
50
+
51
+ export interface Diagnosis {
52
+ code: TheoremStateCode;
53
+ culprits: string[];
54
+ recovery: string;
55
+ }
56
+
57
+ function verdict(code: TheoremStateCode, culprits: string[] = []): Diagnosis {
58
+ return { code, culprits, recovery: RECOVERY_ACTIONS[code] };
59
+ }
60
+
61
+ export function diagnoseTheoremWorkspace(input: DiagnoseInput): Diagnosis {
62
+ if (!input.directoryExists) return verdict('S0_ABSENT');
63
+ if (input.legacyFiles.length > 0) return verdict('S7_LEGACY_CONFLICT', [...input.legacyFiles]);
64
+ if (input.validation.theorems.length === 0 && input.validation.issues.length === 0) {
65
+ return verdict('S1_EMPTY');
66
+ }
67
+ if (input.validation.issues.length > 0) {
68
+ return verdict(
69
+ 'S6_SCHEMA_INVALID',
70
+ input.validation.issues.map((issue) => issue.filePath),
71
+ );
72
+ }
73
+ const untracked = input.files.filter((file) => file.untracked).map((file) => file.filePath);
74
+ if (untracked.length > 0) return verdict('S5_SPLIT_BRAIN', untracked);
75
+ const strengths = new Set(input.files.map((file) => file.strength));
76
+ if (strengths.size > 1) {
77
+ const mixed = input.files
78
+ .filter((file) => file.strength !== 'strong')
79
+ .map((file) => file.filePath);
80
+ return verdict('S5_SPLIT_BRAIN', mixed);
81
+ }
82
+ if (strengths.has('strong')) return verdict('S2_LOCKED_STRONG');
83
+ if (strengths.has('weak')) return verdict('S3_LOCKED_WEAK');
84
+ if (!input.capabilitySupported) return verdict('S8_UNSUPPORTED_FS');
85
+ return verdict('S4_UNLOCKED');
86
+ }
87
+
88
+ export function isUnhealthy(code: TheoremStateCode): boolean {
89
+ return UNHEALTHY_STATES.includes(code);
90
+ }
@@ -0,0 +1,252 @@
1
+ import {
2
+ THEOREMS_DIR_REL,
3
+ THEOREM_ID_RE,
4
+ renderTheoremYaml,
5
+ type TheoremDocument,
6
+ type TheoremSeverity,
7
+ type TheoremStatus,
8
+ } from '@llman-sdd/core';
9
+
10
+ import { PromptAborted, type TheoremPromptPort } from './prompts.ts';
11
+
12
+ export interface TheoremDraft {
13
+ doc: TheoremDocument;
14
+ yaml: string;
15
+ filePath: string;
16
+ }
17
+
18
+ export interface DraftScope {
19
+ existingIds: readonly string[];
20
+ groups: readonly string[];
21
+ }
22
+
23
+ export function splitList(value: string): string[] {
24
+ return value
25
+ .split(/[,\n]/u)
26
+ .map((item) => item.trim())
27
+ .filter((item) => item !== '');
28
+ }
29
+
30
+ export function idValidator(existingIds: readonly string[]): (value: string) => true | string {
31
+ return (value) => {
32
+ const id = value.trim();
33
+ if (!THEOREM_ID_RE.test(id)) {
34
+ return 'id must be kebab-case ([a-z0-9] then [a-z0-9-])';
35
+ }
36
+ if (existingIds.includes(id)) return 'id "' + id + '" already exists';
37
+ return true;
38
+ };
39
+ }
40
+
41
+ export function timeoutValidator(value: string): true | string {
42
+ const trimmed = value.trim();
43
+ if (trimmed === '') return true;
44
+ const parsed = Number.parseInt(trimmed, 10);
45
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 600) {
46
+ return 'timeout_sec must be an integer between 1 and 600';
47
+ }
48
+ return true;
49
+ }
50
+
51
+ async function askText(
52
+ prompt: TheoremPromptPort,
53
+ message: string,
54
+ current: string,
55
+ ): Promise<string> {
56
+ return (await prompt.input(message, { default: current })).trim();
57
+ }
58
+
59
+ async function askBlock(
60
+ prompt: TheoremPromptPort,
61
+ message: string,
62
+ current: string,
63
+ ): Promise<string> {
64
+ const entered = await prompt.editor(message, current === '' ? {} : { default: current });
65
+ const trimmed = entered.trim();
66
+ return trimmed === '' ? current : trimmed;
67
+ }
68
+
69
+ export function theoremPathOf(id: string, group: string): string {
70
+ const clean = group.trim().replace(/^\/+|\/+$/gu, '');
71
+ return clean === ''
72
+ ? THEOREMS_DIR_REL + '/' + id + '.yaml'
73
+ : THEOREMS_DIR_REL + '/' + clean + '/' + id + '.yaml';
74
+ }
75
+
76
+ export async function promptNewTheorem(
77
+ prompt: TheoremPromptPort,
78
+ scope: DraftScope,
79
+ ): Promise<TheoremDraft> {
80
+ const id = (
81
+ await prompt.input('Theorem id (kebab-case, used as the file name)', {
82
+ validate: idValidator(scope.existingIds),
83
+ })
84
+ ).trim();
85
+
86
+ const choices = [
87
+ { name: '(no group)', value: '' },
88
+ ...scope.groups.map((group) => ({ name: group, value: group })),
89
+ { name: '(type a new group)', value: ' NEW ' },
90
+ ];
91
+ const picked = await prompt.select('Subdirectory group', choices, { default: '' });
92
+ const group =
93
+ picked.trim() === 'NEW' ? await askText(prompt, 'New group name', '') : picked.trim();
94
+
95
+ const title = await askText(prompt, 'Title (one line)', '');
96
+ const statement = await askBlock(
97
+ prompt,
98
+ 'Statement (the invariant itself; empty keeps it blank)',
99
+ '',
100
+ );
101
+ const rationale = await askBlock(
102
+ prompt,
103
+ 'Rationale (why this invariant exists; empty keeps it blank)',
104
+ '',
105
+ );
106
+ const severity = await prompt.select<TheoremSeverity>(
107
+ 'Severity',
108
+ [
109
+ { name: 'hard (blocks and escalates)', value: 'hard' },
110
+ { name: 'advisory (allows documented drift)', value: 'advisory' },
111
+ ],
112
+ { default: 'hard' },
113
+ );
114
+ const status = await prompt.select<TheoremStatus>(
115
+ 'Status',
116
+ [
117
+ { name: 'active', value: 'active' },
118
+ { name: 'deprecated', value: 'deprecated' },
119
+ ],
120
+ { default: 'active' },
121
+ );
122
+ const scopeCsv = await askText(
123
+ prompt,
124
+ 'Scope globs (comma or newline separated; empty means project-wide)',
125
+ '',
126
+ );
127
+ const tagsCsv = await askText(prompt, 'Tags (comma separated; empty for none)', '');
128
+ const verifyCommand = await askText(
129
+ prompt,
130
+ 'Verify command (empty to skip; the gate runs it under timeout_sec)',
131
+ '',
132
+ );
133
+ const timeoutRaw =
134
+ verifyCommand === ''
135
+ ? ''
136
+ : await prompt.input('Verify timeout_sec (1..600)', {
137
+ default: '60',
138
+ validate: timeoutValidator,
139
+ });
140
+
141
+ const scopeList = splitList(scopeCsv);
142
+ const tags = splitList(tagsCsv);
143
+ const verify =
144
+ verifyCommand === ''
145
+ ? undefined
146
+ : { command: verifyCommand, timeout_sec: Number.parseInt(timeoutRaw.trim(), 10) || 60 };
147
+
148
+ const doc: TheoremDocument = {
149
+ id,
150
+ title,
151
+ statement,
152
+ rationale,
153
+ severity,
154
+ status,
155
+ ...(scopeList.length > 0 ? { scope: scopeList } : {}),
156
+ ...(tags.length > 0 ? { tags } : {}),
157
+ ...(verify === undefined ? {} : { verify }),
158
+ };
159
+ return { doc, yaml: renderTheoremYaml(doc), filePath: theoremPathOf(id, group) };
160
+ }
161
+
162
+ const EDITABLE_FIELDS = [
163
+ { name: 'title', value: 'title' },
164
+ { name: 'statement', value: 'statement' },
165
+ { name: 'rationale', value: 'rationale' },
166
+ { name: 'severity', value: 'severity' },
167
+ { name: 'status', value: 'status' },
168
+ { name: 'scope', value: 'scope' },
169
+ { name: 'tags', value: 'tags' },
170
+ { name: 'verify', value: 'verify' },
171
+ ] as const;
172
+
173
+ type EditableField = (typeof EDITABLE_FIELDS)[number]['value'];
174
+
175
+ export async function promptEditTheorem(
176
+ prompt: TheoremPromptPort,
177
+ current: TheoremDocument,
178
+ currentPath: string,
179
+ ): Promise<TheoremDraft> {
180
+ const doc: TheoremDocument = { ...current };
181
+ let editing = true;
182
+ while (editing) {
183
+ const field = await prompt.select<EditableField | 'done'>(
184
+ 'Which field do you want to change?',
185
+ [...EDITABLE_FIELDS, { name: '(finish editing)', value: 'done' }],
186
+ { default: 'done' },
187
+ );
188
+ if (field === 'done') {
189
+ editing = false;
190
+ continue;
191
+ }
192
+ if (field === 'title') doc.title = await askText(prompt, 'Title', doc.title);
193
+ else if (field === 'statement') {
194
+ doc.statement = await askBlock(prompt, 'Statement', doc.statement);
195
+ } else if (field === 'rationale') {
196
+ doc.rationale = await askBlock(prompt, 'Rationale', doc.rationale);
197
+ } else if (field === 'severity') {
198
+ doc.severity = await prompt.select<TheoremSeverity>(
199
+ 'Severity',
200
+ [
201
+ { name: 'hard (blocks and escalates)', value: 'hard' },
202
+ { name: 'advisory (allows documented drift)', value: 'advisory' },
203
+ ],
204
+ { default: doc.severity },
205
+ );
206
+ } else if (field === 'status') {
207
+ doc.status = await prompt.select<TheoremStatus>(
208
+ 'Status',
209
+ [
210
+ { name: 'active', value: 'active' },
211
+ { name: 'deprecated', value: 'deprecated' },
212
+ ],
213
+ { default: doc.status },
214
+ );
215
+ } else if (field === 'scope') {
216
+ const entered = await askText(
217
+ prompt,
218
+ 'Scope globs (comma separated)',
219
+ (doc.scope ?? []).join(', '),
220
+ );
221
+ const list = splitList(entered);
222
+ if (list.length === 0) delete doc.scope;
223
+ else doc.scope = list;
224
+ } else if (field === 'tags') {
225
+ const entered = await askText(prompt, 'Tags (comma separated)', (doc.tags ?? []).join(', '));
226
+ const list = splitList(entered);
227
+ if (list.length === 0) delete doc.tags;
228
+ else doc.tags = list;
229
+ } else {
230
+ const command = await askText(
231
+ prompt,
232
+ 'Verify command (empty removes it)',
233
+ doc.verify?.command ?? '',
234
+ );
235
+ if (command === '') {
236
+ delete doc.verify;
237
+ } else {
238
+ const timeoutRaw = await prompt.input('Verify timeout_sec (1..600)', {
239
+ default: String(doc.verify?.timeout_sec ?? 60),
240
+ validate: timeoutValidator,
241
+ });
242
+ doc.verify = { command, timeout_sec: Number.parseInt(timeoutRaw.trim(), 10) || 60 };
243
+ }
244
+ }
245
+ }
246
+ return { doc, yaml: renderTheoremYaml(doc), filePath: currentPath };
247
+ }
248
+
249
+ /** Re-throw only prompt interruptions: every other failure is a real bug. */
250
+ export function isAborted(error: unknown): boolean {
251
+ return error instanceof PromptAborted;
252
+ }