@yutaura/live-spec 0.0.0-stage → 0.1.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 (47) hide show
  1. package/.claude-plugin/plugin.json +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +195 -2
  4. package/dist/cli.d.ts +20 -0
  5. package/dist/cli.js +180 -0
  6. package/dist/diff.d.ts +33 -0
  7. package/dist/diff.js +141 -0
  8. package/dist/ensure.d.ts +5 -0
  9. package/dist/ensure.js +10 -0
  10. package/dist/explore.d.ts +6 -0
  11. package/dist/explore.js +270 -0
  12. package/dist/generate.d.ts +15 -0
  13. package/dist/generate.js +147 -0
  14. package/dist/index.d.ts +2 -0
  15. package/dist/index.js +2 -0
  16. package/dist/load.d.ts +52 -0
  17. package/dist/load.js +74 -0
  18. package/dist/model.d.ts +402 -0
  19. package/dist/model.js +175 -0
  20. package/dist/render/collapse.d.ts +4 -0
  21. package/dist/render/collapse.js +22 -0
  22. package/dist/render/escape.d.ts +1 -0
  23. package/dist/render/escape.js +2 -0
  24. package/dist/render/html.d.ts +12 -0
  25. package/dist/render/html.js +685 -0
  26. package/dist/render/layout.d.ts +37 -0
  27. package/dist/render/layout.js +74 -0
  28. package/dist/render/markdown.d.ts +20 -0
  29. package/dist/render/markdown.js +227 -0
  30. package/dist/render/summary.d.ts +62 -0
  31. package/dist/render/summary.js +119 -0
  32. package/dist/render/wireframe.d.ts +3 -0
  33. package/dist/render/wireframe.js +62 -0
  34. package/dist/serve.d.ts +8 -0
  35. package/dist/serve.js +71 -0
  36. package/dist/skills.d.ts +8 -0
  37. package/dist/skills.js +20 -0
  38. package/dist/static.d.ts +10 -0
  39. package/dist/static.js +117 -0
  40. package/dist/surface.d.ts +59 -0
  41. package/dist/surface.js +44 -0
  42. package/dist/watch.d.ts +10 -0
  43. package/dist/watch.js +47 -0
  44. package/package.json +54 -4
  45. package/skills/live-spec-authoring/SKILL.md +160 -0
  46. package/skills/live-spec-from-code/SKILL.md +93 -0
  47. package/skills/live-spec-review/SKILL.md +65 -0
package/dist/serve.js ADDED
@@ -0,0 +1,71 @@
1
+ import { createServer } from "node:http";
2
+ export const EVENTS_PATH = "/__live-spec/events";
3
+ // 再読み込みのスクリプトを生成時ではなく配信時に差し込む理由: --out で書き出すファイルは
4
+ // サーバなしで開いても動く単体の HTML のままにしておきたいため。
5
+ // ページに版数を埋め込み、通知の接続がつながったときにサーバの版数と比べる理由:
6
+ // ページを読み込んでから接続がつながるまでの間に生成し直されると、その時点で接続がないので
7
+ // reload の通知を受け取れない。接続時に版数を確かめれば、その間の更新も取りこぼさない。
8
+ export const injectReload = (html, version) => html.replace("</body>", `<script>(function () {
9
+ var version = ${version};
10
+ var es = new EventSource("${EVENTS_PATH}");
11
+ es.onmessage = function (e) {
12
+ if (e.data === "reload" || (e.data.indexOf("version ") === 0 && e.data !== "version " + version)) location.reload();
13
+ };
14
+ // 接続が切れたことを表示する理由: サーバを止めると、開いたままのタブは何も知らせずに古い仕様書を
15
+ // 表示し続けていた(specs/browser-tab.spec.ts の未決事項だったもの)。つなぎ直せたら消す。
16
+ var banner = null;
17
+ es.onerror = function () {
18
+ if (banner) return;
19
+ banner = document.createElement("div");
20
+ banner.textContent = "サーバとの接続が切れました。この仕様書は最新ではないかもしれません。";
21
+ banner.setAttribute("style", "position:fixed;top:0;left:0;right:0;z-index:100;padding:8px 16px;background:#b3501a;color:#fff;font:14px system-ui,sans-serif;text-align:center");
22
+ document.body.append(banner);
23
+ };
24
+ es.onopen = function () { if (banner) { banner.remove(); banner = null; } };
25
+ })();</script>\n</body>`);
26
+ const LOCAL_HOSTS = new Set(["127.0.0.1", "localhost"]);
27
+ export const startServer = (port) => new Promise((resolve, reject) => {
28
+ let html = "<!doctype html><html><body><p>仕様書を生成しています…</p></body></html>";
29
+ let version = 0;
30
+ const clients = new Set();
31
+ const server = createServer((req, res) => {
32
+ // Host ヘッダを確かめる理由: DNS リバインディングで外部のサイトが自分のドメイン名を
33
+ // 127.0.0.1 に向け直すと、このサーバの内容をブラウザ経由で読み取れてしまうため。
34
+ const host = (req.headers.host ?? "").replace(/:\d+$/, "");
35
+ if (!LOCAL_HOSTS.has(host)) {
36
+ res.writeHead(403).end();
37
+ return;
38
+ }
39
+ if (req.url === "/") {
40
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
41
+ res.end(injectReload(html, version));
42
+ return;
43
+ }
44
+ if (req.url === EVENTS_PATH) {
45
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
46
+ res.write(`: connected\n\ndata: version ${version}\n\n`);
47
+ clients.add(res);
48
+ req.on("close", () => clients.delete(res));
49
+ return;
50
+ }
51
+ res.writeHead(404).end();
52
+ });
53
+ server.on("error", reject);
54
+ server.listen(port, "127.0.0.1", () => {
55
+ const { port: actual } = server.address();
56
+ resolve({
57
+ url: `http://127.0.0.1:${actual}/`,
58
+ update(next) {
59
+ html = next;
60
+ version += 1;
61
+ for (const client of clients)
62
+ client.write("data: reload\n\n");
63
+ },
64
+ close() {
65
+ for (const client of clients)
66
+ client.end();
67
+ return new Promise((done) => server.close(() => done()));
68
+ },
69
+ });
70
+ });
71
+ });
@@ -0,0 +1,8 @@
1
+ export declare const bundledSkills: () => Array<string>;
2
+ export interface InstallResult {
3
+ readonly name: string;
4
+ readonly status: "installed" | "updated" | "skipped";
5
+ }
6
+ export declare const installSkills: (targetDir: string, options?: {
7
+ readonly force?: boolean;
8
+ }) => Array<InstallResult>;
package/dist/skills.js ADDED
@@ -0,0 +1,20 @@
1
+ import { cpSync, existsSync, mkdirSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ // 配布物では skills/(skills-npm などの慣習の置き場所。ビルドで .claude/skills からコピーする)、
5
+ // このリポジトリで直接動かすときは原本の .claude/skills から読む。src/ からも dist/ からも 1 つ上がルート。
6
+ const candidates = ["../skills/", "../.claude/skills/"].map((p) => fileURLToPath(new URL(p, import.meta.url)));
7
+ const SKILLS_DIR = candidates.find((dir) => existsSync(dir)) ?? candidates[1];
8
+ export const bundledSkills = () => readdirSync(SKILLS_DIR, { withFileTypes: true })
9
+ .filter((d) => d.isDirectory() && existsSync(join(SKILLS_DIR, d.name, "SKILL.md")))
10
+ .map((d) => d.name)
11
+ .sort();
12
+ export const installSkills = (targetDir, options = {}) => bundledSkills().map((name) => {
13
+ const dest = join(targetDir, name, "SKILL.md");
14
+ const exists = existsSync(dest);
15
+ if (exists && options.force !== true)
16
+ return { name, status: "skipped" };
17
+ mkdirSync(join(targetDir, name), { recursive: true });
18
+ cpSync(join(SKILLS_DIR, name, "SKILL.md"), dest);
19
+ return { name, status: exists ? "updated" : "installed" };
20
+ });
@@ -0,0 +1,10 @@
1
+ export type FieldValue = string | boolean;
2
+ export interface StaticInfo {
3
+ readonly order: ReadonlyArray<string>;
4
+ readonly docs: Readonly<Record<string, string>>;
5
+ readonly fields: Readonly<Record<string, ReadonlyArray<FieldValue>>>;
6
+ readonly stateDoc: string | null;
7
+ readonly fieldDocs: Readonly<Record<string, string>>;
8
+ readonly evidence: Readonly<Record<string, ReadonlyArray<string>>>;
9
+ }
10
+ export declare const analyze: (source: string) => StaticInfo;
package/dist/static.js ADDED
@@ -0,0 +1,117 @@
1
+ import { parse } from "@babel/parser";
2
+ const EVIDENCE = /^\s*根拠[::]\s*(.+?)\s*$/;
3
+ // TypeScript の型チェッカーではなく構文解析にとどめる理由:
4
+ // TypeScript 7 の JS API は typescript/unstable/sync しかなく、まだ不安定。
5
+ // 構文だけでも「同じファイルの type / interface に書かれたリテラル union」と JSDoc は読める。
6
+ // import した型や型の別名をまたぐ解決が必要になったら、この関数だけを差し替える。
7
+ export const analyze = (source) => {
8
+ const file = parse(source, { sourceType: "module", plugins: ["typescript"] });
9
+ const body = file.program.body;
10
+ const comments = file.comments ?? [];
11
+ const evidence = {};
12
+ const order = [];
13
+ const docs = {};
14
+ const types = new Map();
15
+ let initialType = null;
16
+ for (const node of body) {
17
+ const decl = node.type === "ExportNamedDeclaration" ? node.declaration : node;
18
+ const doc = summaryOf(node.leadingComments);
19
+ if (decl == null)
20
+ continue;
21
+ if (decl.type === "TSTypeAliasDeclaration" && decl.typeAnnotation.type === "TSTypeLiteral") {
22
+ types.set(decl.id.name, { members: decl.typeAnnotation.members, doc });
23
+ }
24
+ if (decl.type === "TSInterfaceDeclaration")
25
+ types.set(decl.id.name, { members: decl.body.body, doc });
26
+ for (const [name, typeName] of valueNamesOf(decl)) {
27
+ if (name === "initial")
28
+ initialType = typeName;
29
+ if (node.type !== "ExportNamedDeclaration")
30
+ continue;
31
+ order.push(name);
32
+ if (doc !== null)
33
+ docs[name] = doc;
34
+ // 関数の範囲にある「// 根拠:」をその操作の根拠とする。spec とコードを突き合わせられるように、
35
+ // 書き起こした人が残した場所を仕様書にも出すため。
36
+ const found = comments
37
+ .filter((c) => c.type === "CommentLine" && c.start >= decl.start && c.end <= decl.end)
38
+ .flatMap((c) => {
39
+ const m = EVIDENCE.exec(c.value);
40
+ return m === null ? [] : [m[1]];
41
+ });
42
+ if (found.length > 0)
43
+ evidence[name] = found;
44
+ }
45
+ }
46
+ const stateType = initialType === null ? undefined : types.get(initialType);
47
+ return {
48
+ order,
49
+ docs,
50
+ fields: stateType === undefined ? {} : fieldsOf(stateType.members),
51
+ stateDoc: stateType?.doc ?? null,
52
+ fieldDocs: stateType === undefined ? {} : fieldDocsOf(stateType.members),
53
+ evidence,
54
+ };
55
+ };
56
+ const valueNamesOf = (decl) => {
57
+ if (decl.type === "FunctionDeclaration" && decl.id != null)
58
+ return [[decl.id.name, null]];
59
+ if (decl.type !== "VariableDeclaration")
60
+ return [];
61
+ return decl.declarations.flatMap((d) => {
62
+ if (d.id.type !== "Identifier")
63
+ return [];
64
+ const ann = d.id.typeAnnotation;
65
+ const ref = ann?.type === "TSTypeAnnotation" && ann.typeAnnotation.type === "TSTypeReference" ? ann.typeAnnotation : null;
66
+ const typeName = ref !== null && ref.typeName.type === "Identifier" ? ref.typeName.name : null;
67
+ return [[d.id.name, typeName]];
68
+ });
69
+ };
70
+ const fieldsOf = (members) => {
71
+ const fields = {};
72
+ for (const m of members) {
73
+ if (m.type !== "TSPropertySignature" || m.typeAnnotation == null)
74
+ continue;
75
+ const key = m.key.type === "Identifier" ? m.key.name : m.key.type === "StringLiteral" ? m.key.value : null;
76
+ const values = finiteValuesOf(m.typeAnnotation.typeAnnotation);
77
+ if (key !== null && values !== null)
78
+ fields[key] = values;
79
+ }
80
+ return fields;
81
+ };
82
+ const fieldDocsOf = (members) => {
83
+ const docs = {};
84
+ for (const m of members) {
85
+ if (m.type !== "TSPropertySignature")
86
+ continue;
87
+ const key = m.key.type === "Identifier" ? m.key.name : m.key.type === "StringLiteral" ? m.key.value : null;
88
+ const doc = summaryOf(m.leadingComments);
89
+ if (key !== null && doc !== null)
90
+ docs[key] = doc;
91
+ }
92
+ return docs;
93
+ };
94
+ const finiteValuesOf = (type) => {
95
+ if (type.type === "TSBooleanKeyword")
96
+ return [false, true];
97
+ const members = type.type === "TSUnionType" ? type.types : [type];
98
+ const values = members.map((m) => (m.type === "TSLiteralType" && m.literal.type === "StringLiteral" ? m.literal.value : null));
99
+ return values.every((v) => v !== null) ? values : null;
100
+ };
101
+ // 最初の段落(空行まで)を説明文にする理由: 1 行目だけを取ると、複数行にわたる文が途中で切れてしまうため。
102
+ const summaryOf = (comments) => {
103
+ const jsdoc = comments?.findLast((c) => c.type === "CommentBlock" && c.value.startsWith("*"));
104
+ if (jsdoc === undefined)
105
+ return null;
106
+ const lines = jsdoc.value
107
+ .slice(1)
108
+ .split("\n")
109
+ .map((line) => line.replace(/^\s*\*?\s?/, "").trim());
110
+ const start = lines.findIndex((line) => line !== "");
111
+ if (start === -1)
112
+ return null;
113
+ const end = lines.indexOf("", start);
114
+ return (end === -1 ? lines.slice(start) : lines.slice(start, end)).reduce((text, line) => isCjk(text.at(-1)) || isCjk(line[0]) ? text + line : `${text} ${line}`);
115
+ };
116
+ // 日本語の行のあいだに空白を入れない理由: JSDoc の折り返しは表示上の都合なので、日本語では空白が入ると文が不自然に途切れる。
117
+ const isCjk = (ch) => ch !== undefined && (ch.codePointAt(0) ?? 0) > 0x2e7f;
@@ -0,0 +1,59 @@
1
+ export type SurfaceNode = {
2
+ readonly kind: "screen";
3
+ readonly title: string;
4
+ readonly children: ReadonlyArray<SurfaceNode>;
5
+ } | {
6
+ readonly kind: "section";
7
+ readonly title: string;
8
+ readonly children: ReadonlyArray<SurfaceNode>;
9
+ } | {
10
+ readonly kind: "heading";
11
+ readonly text: string;
12
+ } | {
13
+ readonly kind: "text";
14
+ readonly text: string;
15
+ } | {
16
+ readonly kind: "field";
17
+ readonly label: string;
18
+ readonly value: string;
19
+ } | {
20
+ readonly kind: "button";
21
+ readonly label: string;
22
+ readonly action?: string;
23
+ readonly disabled?: true;
24
+ } | {
25
+ readonly kind: "badge";
26
+ readonly text: string;
27
+ } | {
28
+ readonly kind: "list";
29
+ readonly items: ReadonlyArray<SurfaceNode>;
30
+ } | {
31
+ readonly kind: "code";
32
+ readonly language: string;
33
+ readonly text: string;
34
+ };
35
+ export type Child = SurfaceNode | false | null | undefined;
36
+ type AnyAction = (...args: never) => unknown;
37
+ export declare const ui: {
38
+ screen: (title: string, ...children: ReadonlyArray<Child>) => SurfaceNode;
39
+ section: (title: string, ...children: ReadonlyArray<Child>) => SurfaceNode;
40
+ heading: (text: string) => SurfaceNode;
41
+ text: (text: string) => SurfaceNode;
42
+ field: (label: string, value?: string) => SurfaceNode;
43
+ button: (label: string, action?: AnyAction, options?: {
44
+ readonly disabled?: boolean;
45
+ }) => SurfaceNode;
46
+ badge: (text: string) => SurfaceNode;
47
+ list: (...items: ReadonlyArray<Child>) => SurfaceNode;
48
+ };
49
+ export declare const api: {
50
+ request: (method: string, path: string, body?: unknown) => SurfaceNode;
51
+ response: (status: number, body?: unknown) => SurfaceNode;
52
+ };
53
+ export declare const cli: {
54
+ output: (text: string) => SurfaceNode;
55
+ };
56
+ export declare const buttonsOf: (node: SurfaceNode) => Array<Extract<SurfaceNode, {
57
+ kind: "button";
58
+ }>>;
59
+ export {};
@@ -0,0 +1,44 @@
1
+ const present = (children) => children.filter((c) => c !== false && c !== null && c !== undefined);
2
+ export const ui = {
3
+ screen: (title, ...children) => ({ kind: "screen", title, children: present(children) }),
4
+ section: (title, ...children) => ({
5
+ kind: "section",
6
+ title,
7
+ children: present(children),
8
+ }),
9
+ heading: (text) => ({ kind: "heading", text }),
10
+ text: (text) => ({ kind: "text", text }),
11
+ field: (label, value = "") => ({ kind: "field", label, value }),
12
+ button: (label, action, options = {}) => ({
13
+ kind: "button",
14
+ label,
15
+ ...(action === undefined ? {} : { action: action.name }),
16
+ ...(options.disabled === true ? { disabled: true } : {}),
17
+ }),
18
+ badge: (text) => ({ kind: "badge", text }),
19
+ list: (...items) => ({ kind: "list", items: present(items) }),
20
+ };
21
+ export const api = {
22
+ request: (method, path, body) => ({
23
+ kind: "code",
24
+ language: "http",
25
+ text: body === undefined ? `${method} ${path}` : `${method} ${path}\n${JSON.stringify(body, null, 2)}`,
26
+ }),
27
+ response: (status, body) => ({
28
+ kind: "code",
29
+ language: "http",
30
+ text: body === undefined ? `HTTP ${status}` : `HTTP ${status}\n${JSON.stringify(body, null, 2)}`,
31
+ }),
32
+ };
33
+ export const cli = {
34
+ output: (text) => ({ kind: "code", language: "terminal", text }),
35
+ };
36
+ export const buttonsOf = (node) => {
37
+ if (node.kind === "button")
38
+ return [node];
39
+ if (node.kind === "screen" || node.kind === "section")
40
+ return node.children.flatMap(buttonsOf);
41
+ if (node.kind === "list")
42
+ return node.items.flatMap(buttonsOf);
43
+ return [];
44
+ };
@@ -0,0 +1,10 @@
1
+ import { type FSWatcher } from "node:fs";
2
+ import { type OutputFormat } from "./generate.js";
3
+ export interface WatchOptions {
4
+ readonly paths: ReadonlyArray<string>;
5
+ readonly format: OutputFormat;
6
+ readonly out: string | null;
7
+ readonly title?: string | null;
8
+ readonly onBuilt?: (output: string) => void;
9
+ }
10
+ export declare const watchSpec: (options: WatchOptions, log?: (message: string) => void) => ReadonlyArray<FSWatcher>;
package/dist/watch.js ADDED
@@ -0,0 +1,47 @@
1
+ import { watch } from "node:fs";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import { expandSpecPaths, failureOutput, generateProject, writeProjectOutput } from "./generate.js";
4
+ // 保存後に少し待ってから生成する理由: エディタは 1 回の保存で複数の変更イベントを出すことが多く、
5
+ // そのたびに生成すると書きかけの内容を読んだり、同じ生成を何度も走らせたりするため。
6
+ const DEBOUNCE_MS = 80;
7
+ export const watchSpec = (options, log = console.error) => {
8
+ let timer;
9
+ let queue = Promise.resolve();
10
+ const rebuild = () => {
11
+ queue = queue.then(async () => {
12
+ const started = performance.now();
13
+ // 生成のたびにディレクトリを展開し直す理由: 監視中に spec ファイルが増えても、次の保存で拾えるようにするため。
14
+ const paths = expandSpecPaths(options.paths);
15
+ try {
16
+ const output = await generateProject(paths, options.format, options.title ?? undefined);
17
+ if (options.out !== null)
18
+ await writeProjectOutput(options.out, output);
19
+ if (output.kind === "text")
20
+ options.onBuilt?.(output.content);
21
+ const ms = Math.round(performance.now() - started);
22
+ log(options.out === null ? `✓ 生成しました(${ms}ms)` : `✓ ${options.out} を生成しました(${ms}ms)`);
23
+ }
24
+ catch (e) {
25
+ log(`✗ 生成に失敗しました: ${e instanceof Error ? e.message : String(e)}`);
26
+ // 失敗しても監視は続ける。書きかけの spec が一時的に壊れているのはよくあることなので。
27
+ const failure = failureOutput(options.format, paths, e);
28
+ if (options.out !== null)
29
+ await writeProjectOutput(options.out, failure);
30
+ if (failure.kind === "text")
31
+ options.onBuilt?.(failure.content);
32
+ }
33
+ });
34
+ };
35
+ // ファイルではなくディレクトリを監視する理由: 多くのエディタは「別ファイルに書いてから名前を差し替える」
36
+ // 方式で保存するので、ファイル自体を監視すると最初の保存で追跡が切れる。
37
+ const dirs = [...new Set(expandSpecPaths(options.paths).map((p) => dirname(resolve(p))).concat(options.paths.filter((p) => !p.endsWith(".ts")).map((p) => resolve(p))))];
38
+ const watchers = dirs.map((dir) => watch(dir, { recursive: true }, (_event, filename) => {
39
+ if (filename === null || !basename(filename).endsWith(".spec.ts"))
40
+ return;
41
+ clearTimeout(timer);
42
+ timer = setTimeout(rebuild, DEBOUNCE_MS);
43
+ }));
44
+ log(`${options.paths.join(", ")} を監視しています(Ctrl+C で終了)`);
45
+ rebuild();
46
+ return watchers;
47
+ };
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@yutaura/live-spec",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "description": "AI が書き、人が見て理解できる「生きた仕様書」を作るツール。素の TypeScript で書いた仕様を実行し、状態遷移図・画面・できる/できない理由・検査結果をまとめた仕様書を生成する",
7
+ "keywords": [
8
+ "specification",
9
+ "living-documentation",
10
+ "state-machine",
11
+ "spec-driven-development",
12
+ "wireframe"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "bin": {
21
+ "live-spec": "dist/cli.js"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "skills/*/SKILL.md",
26
+ ".claude-plugin/plugin.json",
27
+ "README.md"
28
+ ],
29
+ "engines": {
30
+ "node": ">=22.18"
31
+ },
32
+ "scripts": {
33
+ "test": "vitest run",
34
+ "test:watch": "vitest",
35
+ "typecheck": "tsc --noEmit",
36
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/rewrite-dts-extensions.mjs dist && node scripts/copy-skills.mjs skills",
37
+ "prepack": "pnpm build",
38
+ "spec": "node src/cli.ts"
39
+ },
40
+ "packageManager": "pnpm@12.23.0",
41
+ "dependencies": {
42
+ "@babel/parser": "8.1.3",
43
+ "effect": "4.1.5",
44
+ "elkjs": "0.12.1"
45
+ },
46
+ "devDependencies": {
47
+ "@babel/types": "8.1.3",
48
+ "@effect/vitest": "4.1.5",
49
+ "@types/node": "^24.19.2",
50
+ "typescript": "7.0.2",
51
+ "vitest": "5.1.1"
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ }
56
+ }
@@ -0,0 +1,160 @@
1
+ ---
2
+ name: live-spec-authoring
3
+ description: live-spec の spec ファイル(*.spec.ts)を書く・直すときの規約と手順。状態の選び方(抽象化)、登場人物(actors)の設計、ensure の理由の書き方、不変条件・入力の例・画面(surface)の書き方、検査結果(findings)の読み方と直し方をまとめる。Use when: (1) 要件・チケット・会話・メモから live-spec の仕様を新しく書くとき、(2) 既存の spec に操作・状態・画面を足す/直すとき、(3) `pnpm spec` / `live-spec` の検査結果を解消したいとき、(4) 「仕様書を作って」「状態遷移を整理して」「この業務フローを spec にして」と言われたとき。既存のコードから書き起こすときは live-spec-from-code、spec の変更をレビューするときは live-spec-review を使う(どちらもこの skill の規約に従う)。
4
+ ---
5
+
6
+ # live-spec の spec を書く
7
+
8
+ live-spec は「AI が書き、人が図と画面で読む」仕様書のツール。spec は素の TypeScript で書き、live-spec がそれを**実行**して、状態遷移図・できる/できない理由・画面・検査結果を生成する。人は spec のコードではなく生成物を読むので、spec は「実行すると正しい図と理由が出る」ように書く。
9
+
10
+ ## 実行のしかた
11
+
12
+ live-spec は npm パッケージ `@yutaura/live-spec`(`npm i -D @yutaura/live-spec` / `pnpm add -D @yutaura/live-spec`)で、`live-spec` コマンドを持つ。
13
+
14
+ | やりたいこと | コマンド |
15
+ |---|---|
16
+ | Markdown を見る | `npx live-spec specs/`(spec が 1 つなら標準出力、複数なら `--out <ディレクトリ>`) |
17
+ | HTML を書き出す | `npx live-spec specs/ --html --out spec.html` |
18
+ | ブラウザで見ながら書く | `npx live-spec specs/ --serve` |
19
+ | 変更前と比べる | `npx live-spec diff <file.spec.ts> [--base <リビジョン>]` |
20
+
21
+ (live-spec リポジトリ自身の中では `pnpm spec ...`)
22
+
23
+ **1 つの spec ファイルが 1 つのドメインオブジェクト**になる。プロジェクトの仕様は `specs/` のようなディレクトリに spec を並べ、ディレクトリごと渡す。
24
+
25
+ - HTML: `live-spec specs/ --html --out spec.html`。ドメインオブジェクトごとのページとタブを持つ 1 つのファイルになる(`#/<名前>` でページを開ける)
26
+ - Markdown: `live-spec specs/ --out docs/spec/`。ドメインオブジェクトごとの `<名前>.md` と一覧の `README.md` を書き出す
27
+
28
+ spec からは `import { ensure, ui, api, cli } from "@yutaura/live-spec"` で読み込む(live-spec リポジトリ自身の `specs/` と `examples/` だけは `../src/index.ts` から読み込む)。
29
+
30
+ 型チェックは live-spec の実行とは別に行う(live-spec は型を消して実行するだけなので、型の誤りでは止まらない):
31
+
32
+ ```sh
33
+ npx tsc --noEmit --ignoreConfig --strict --module nodenext --moduleResolution nodenext --target es2024 --skipLibCheck <file.spec.ts>
34
+ ```
35
+
36
+ ## spec の形
37
+
38
+ | export | 必須 | 役割 |
39
+ |---|---|---|
40
+ | `initial` | ✓ | 初期状態(オブジェクト) |
41
+ | `actors` | ✓ | 探索に使う登場人物の具体例(`{ 名前: 値 }`) |
42
+ | 上記と下記以外の関数 | | 操作。`(状態, 登場人物, ...入力) => 次の状態` |
43
+ | `invariants` | | 不変条件。`{ 説明: (状態) => boolean }` |
44
+ | `inputs` | | 3 つ目以降の引数の例。`{ 操作名: { 例の名前: [引数...] } }` |
45
+ | `surface` | | `(状態, 登場人物) => 画面 \| null` |
46
+ | `scenarios` | | `{ 名前: [{ do: 操作, by: "登場人物", input?: "例の名前", expect?: { 項目: 値 } }] }` |
47
+ | `questions` | | `[{ ask, about?: 操作 \| { 項目: 値 }, note? }]` |
48
+ | `links` | | `[{ from?: 操作, to: "相手の名前", action?: "相手の操作名", label }]` |
49
+ | `decisions` | | `{ 名前: { decide: (入力) => 結果, cases: [{ input, expect? }] } }` |
50
+ | `glossary` | | `{ 用語: "説明" }` |
51
+
52
+ 状態の型の JSDoc は仕様書の冒頭の説明に、関数の JSDoc の最初の段落(空行まで)は操作の見出しになる。読み手が業務の言葉で理解できる文を書く。見出しは短く、詳しい説明は空行のあとの段落に書く(仕様書には出ないが、spec を読む人の役に立つ)。
53
+
54
+ ## モデルの作り方
55
+
56
+ ### 0. ドメインオブジェクトに分ける(最初に決める)
57
+
58
+ 1 つの spec には 1 つのドメインオブジェクト(記事、注文、ジョブ、サーバ、ブラウザのタブ…)だけを書く。**状態は 10 個前後に収まるのが目安**。それを超えるなら、関心の違うものを 1 つに詰め込んでいないかを疑う。
59
+
60
+ - 独立した項目(例: サーバの状態 × ブラウザのタブの状態 × 生成の結果)を 1 つの状態にまとめると、状態が組み合わせの数だけ増え、名前も `none · placeholder · listening · stale` のような読めないものになる。項目ごとに、それを持つドメインオブジェクトへ分ける
61
+ - 分けたオブジェクトどうしの関係(「サーバが止まるとタブは古いまま残る」など)は、それぞれの spec の操作・条件・JSDoc に書く。1 つの状態機械にまとめ直さない
62
+ - 状態の名前(ラベル)は、文字列の項目の値がそのまま使われる。`status: "受付待ち"` のように、読み手の言葉で値を付ける
63
+
64
+ ### 1. 状態には「振る舞いを変える値」だけを入れる
65
+
66
+ live-spec は初期状態から操作を全部実行して、到達できる状態をすべて列挙する。タイトル・本文・金額のような値を状態に入れると、値の数だけ状態が増えて図が読めなくなる(上限 500 で打ち切られる)。
67
+
68
+ - 入れる: `status`、`pinned` のように「できる/できない」を左右する値、所有者の ID(「自分の記事だけ」のため)
69
+ - 入れない: 表示用の文字列、日時、件数。条件に効くなら `hasComment: boolean` のように有限の値に抽象化する
70
+ - 有限の値は文字列リテラルの union か `boolean` で型を書く。型と同じファイルに置くと「型にあるのに到達しない値」を検出できる
71
+
72
+ ### 2. 登場人物は「条件を区別できる最小の組」にする
73
+
74
+ ロールだけでなく、条件を分ける具体例を並べる。所有者の条件があるなら「所有者」と「同じロールの別人」の両方を入れないと、「自分の〜だけ」という理由が表に出てこない。ワーカーやバッチのようなシステムも登場人物にする(クライアントが起こせない遷移を表せる)。
75
+
76
+ ```ts
77
+ export const actors = {
78
+ 著者alice: { id: "alice", role: "author" }, // 所有者
79
+ 別の著者bob: { id: "bob", role: "author" }, // 同じロールの別人
80
+ 編集者eve: { id: "eve", role: "editor" },
81
+ ワーカー: { kind: "worker" },
82
+ };
83
+ ```
84
+
85
+ ### 3. 操作は ensure を「誰が → いつ → 何を入力したら」の順に並べる
86
+
87
+ できない理由として表に出るのは**最初に失敗した ensure** だけ。live-spec は実行結果から「誰が」「いつ」「入力」の軸に振り分けるが、順序をそろえておくと理由が読みやすくなる。
88
+
89
+ - 理由は読み手向けの短い文にする(「編集者だけ」「レビュー中のときだけ」「差し戻し理由が必要」)。同じ条件には同じ文言を使う(表でまとめられる)
90
+ - 新しいオブジェクトを返す。引数を書き換えない
91
+ - 「できない」は ensure で表す。普通の `throw` や、想定外の値による `TypeError` は**仕様のバグ**として検出される
92
+
93
+ ### 4. 不変条件は「1 つの状態について常に成り立つこと」
94
+
95
+ `invariants` の説明文は、破ったときにそのまま表示される。破る状態は、初期状態からの最短手順と一緒に報告される。遷移の前後を比べる性質(「終わったジョブは変わらない」など)はまだ書けないので、報告に残す。
96
+
97
+ ### 5. 入力の例には「通る例」と「止まる例」を両方入れる
98
+
99
+ `inputs` は名前付きの具体例。止まる例がないと「できない入力」の欄が出ない。3 つ以上の引数をとる操作に例がないと、その操作は実行されない(`missing-inputs` として報告される)。
100
+
101
+ ### 6. 画面(surface)は見る人ごとに返す
102
+
103
+ - UI: `ui.screen(title, ...)`。子には `ui.section / heading / text / field / button / badge / list`。`cond && ui.button(...)` のように出し分けてよい
104
+ - ボタンには操作の**関数そのもの**を渡す(`ui.button("公開する", publish)`)。文字列にしない
105
+ - API: `api.request(method, path, body?)` / `api.response(status, body?)`。CLI: `cli.output(text)`
106
+ - 見える画面がない人(API を呼ばないワーカーなど)には `null` を返す
107
+ - UI の画面では、ボタンと実行できる操作が食い違うと検出される。見せるだけのボタンは `{ disabled: true }`
108
+ - **ボタンで起きない操作は `ui.screen` にしない**。ブラウザでページを開く・再読み込みする、ファイルを保存する、外部のイベントが届く、といった操作は画面のボタンでは起きない。`ui.screen` で描くと「実行できるのにボタンがない」が大量に出て、それを消すために架空のボタンを足すと仕様が不正確になる。その人に見えるものを `cli.output` や `api.response` で返すか、見えるものがなければ `null` を返す
109
+
110
+ ### 6.5 用語と項目の説明を書く
111
+
112
+ 状態の名前(`inReview`)や項目(`pinned`)だけでは意味が伝わらないことがある。状態の型の各項目に JSDoc(`/** 公開の段階 */ status: ...`)を付け、値や業務の言葉は `export const glossary = { inReview: "編集者のレビュー待ち" }` に書く。仕様書の「用語」の節に並び、状態遷移図のノードにカーソルを合わせると説明が出る。
113
+
114
+ ### 6.6 条件の組み合わせが多いルールは判断表にする
115
+
116
+ 送料・割引・料金区分のように「入力の組み合わせ → 結果」で決まるルールは、状態遷移ではなく `decisions` に書く。判断の関数(`decide`)と入力の例(`cases`)を書くと、live-spec が実行して表にする。境界の値(4999 円と 5000 円など)を例に入れ、`expect` を付けておくと、期待と違うときに検査結果に出る。
117
+
118
+ ### 7. シナリオで業務の流れを書く
119
+
120
+ 状態の一覧だけでは業務の流れが読めない。代表的な流れ(正常系 1〜2 本と、差し戻し・やり直しのような分岐 1〜2 本)を `scenarios` に書く。各段階には操作の**関数**を渡し、要所に `expect` を書く。シナリオは初期状態から実行され、止まったり期待と違ったりすると検査結果に出るので、受け入れテストを兼ねる。シナリオ名は業務の言葉で(「書いて公開するまで」)。
121
+
122
+ ### 8. 判断できないことは未決事項にする
123
+
124
+ 要件やコードから決められないこと(「アーカイブした記事を戻せるか?」)は、推測で spec に書かずに `questions` に書く。対象の操作(関数)か状態(`{ status: "archived" }`)を `about` に付けると、仕様書の図とカードに印が出る。人は未決事項だけを見れば判断すべき点が分かる。
125
+
126
+ ### 9. ほかのドメインオブジェクトとのつながりを書く
127
+
128
+ ある操作がほかのオブジェクトの操作を引き起こすなら(「注文したら支払いを確定する」)、送り出す側の spec に `links` を書く。相手は名前の**文字列**で書く(関数を import しない。--watch で読み直すときに別の実体になり、照合できないため)。名前の誤りはプロジェクト全体を生成したときに検出される。
129
+
130
+ ## 手順
131
+
132
+ 1. ドメインオブジェクトを洗い出し、1 オブジェクト 1 ファイルで `specs/` などに置く
133
+ 2. 状態の型・初期状態・登場人物を書く
134
+ 3. 操作を書く。JSDoc の 1 行目は業務の言葉で
135
+ 4. 生成して読む: `pnpm spec <file>`(Markdown が標準出力に出る)
136
+ 5. 「検査結果」を 1 件ずつ判断する(下の表)。モデルの誤りなら直し、仕様として正しい/判断できないものは報告に残す
137
+ 6. 型チェックを通す
138
+ 7. 人に見せる: `live-spec specs/ --serve`(ブラウザで自動更新)か `--html --out <file>`。生成した HTML は**自分でも開いて見る**(状態遷移図が読めるか、操作カードが状態名の壁になっていないか)。検査が通っても、人が読めなければ仕様書としては失敗
139
+
140
+ ## 検査結果の読み方
141
+
142
+ | 検査結果 | 意味 | よくある直し方 |
143
+ |---|---|---|
144
+ | 不変条件を破る | ある操作の結果が条件に反する | 操作の戻り値を直す。仕様として正しいなら不変条件を見直す |
145
+ | 誰も実行できない操作 | どの状態・登場人物でも ensure を通らない | 到達できる状態に条件を合わせる/必要な登場人物を足す |
146
+ | 型にあるのに到達しない値 | union の値に遷移する操作がない | 操作を足す。不要な値なら型から消す |
147
+ | 例外を投げた | ensure 以外の例外(仕様のバグ) | 想定外の状態での参照を直す。止めたいなら ensure にする |
148
+ | オブジェクトを返さなかった | 操作の戻り値が不正 | 新しい状態オブジェクトを返す |
149
+ | inputs に例がない/存在しない操作 | 引数の例の不足・名前の誤り | `inputs` を直す |
150
+ | ボタンが見えるが実行できない/実行できるがボタンがない | 画面と操作の食い違い | 表示条件を ensure にそろえる。意図的なら `disabled` |
151
+ | 状態数の上限で打ち切り | 値が増え続ける項目がある | その項目を状態から外すか、有限の値に抽象化する |
152
+
153
+ ## 人への渡し方
154
+
155
+ 生成物(HTML)と一緒に、次を短く伝える。人は spec のコードを読まない前提で書く。
156
+
157
+ - 何をモデルにしたか(対象、状態、登場人物)
158
+ - どこを抽象化したか(状態から外した値と理由)
159
+ - 検査結果のうち、あえて残したものと理由
160
+ - 判断が必要な点(質問の形で)