@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.
- package/.claude-plugin/plugin.json +12 -0
- package/LICENSE +21 -0
- package/README.md +195 -2
- package/dist/cli.d.ts +20 -0
- package/dist/cli.js +180 -0
- package/dist/diff.d.ts +33 -0
- package/dist/diff.js +141 -0
- package/dist/ensure.d.ts +5 -0
- package/dist/ensure.js +10 -0
- package/dist/explore.d.ts +6 -0
- package/dist/explore.js +270 -0
- package/dist/generate.d.ts +15 -0
- package/dist/generate.js +147 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/load.d.ts +52 -0
- package/dist/load.js +74 -0
- package/dist/model.d.ts +402 -0
- package/dist/model.js +175 -0
- package/dist/render/collapse.d.ts +4 -0
- package/dist/render/collapse.js +22 -0
- package/dist/render/escape.d.ts +1 -0
- package/dist/render/escape.js +2 -0
- package/dist/render/html.d.ts +12 -0
- package/dist/render/html.js +685 -0
- package/dist/render/layout.d.ts +37 -0
- package/dist/render/layout.js +74 -0
- package/dist/render/markdown.d.ts +20 -0
- package/dist/render/markdown.js +227 -0
- package/dist/render/summary.d.ts +62 -0
- package/dist/render/summary.js +119 -0
- package/dist/render/wireframe.d.ts +3 -0
- package/dist/render/wireframe.js +62 -0
- package/dist/serve.d.ts +8 -0
- package/dist/serve.js +71 -0
- package/dist/skills.d.ts +8 -0
- package/dist/skills.js +20 -0
- package/dist/static.d.ts +10 -0
- package/dist/static.js +117 -0
- package/dist/surface.d.ts +59 -0
- package/dist/surface.js +44 -0
- package/dist/watch.d.ts +10 -0
- package/dist/watch.js +47 -0
- package/package.json +54 -4
- package/skills/live-spec-authoring/SKILL.md +160 -0
- package/skills/live-spec-from-code/SKILL.md +93 -0
- package/skills/live-spec-review/SKILL.md +65 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "live-spec",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "AI が書き、人が見て理解できる「生きた仕様書」を作るツール。素の TypeScript で書いた仕様を実行し、状態遷移図・画面・できる/できない理由・検査結果をまとめた仕様書を生成する",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"specification",
|
|
7
|
+
"living-documentation",
|
|
8
|
+
"state-machine",
|
|
9
|
+
"spec-driven-development",
|
|
10
|
+
"wireframe"
|
|
11
|
+
]
|
|
12
|
+
}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 YutaUra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,196 @@
|
|
|
1
|
-
#
|
|
1
|
+
# live-spec
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
AI が書き、人が見て理解できる「生きた仕様書」を作るツール。
|
|
4
|
+
|
|
5
|
+
仕様は素の TypeScript の型と関数で書きます。live-spec はそれを実行して、状態遷移図、画面のワイヤーフレーム、「誰が・いつ・何を入力したらできないか」の一覧、検査結果をまとめた仕様書を生成します。
|
|
6
|
+
|
|
7
|
+
## なぜ作ったか
|
|
8
|
+
|
|
9
|
+
OpenSpec、GitHub Spec Kit、Kiro などの spec-driven development ツールでは、仕様の実体はほぼ markdown です。AI が読むには十分ですが、人がレビューするには量が多すぎます。Spec Kit を検証した記事では、コード 689 行に対して 2,577 行の markdown が生成されていました。
|
|
10
|
+
|
|
11
|
+
live-spec では、人は markdown を読みません。図と画面と一覧を見て、仕様を理解して承認します。詳しくは [docs/charter.md](docs/charter.md) を参照してください。
|
|
12
|
+
|
|
13
|
+
## 例
|
|
14
|
+
|
|
15
|
+
[examples/minimal.spec.ts](examples/minimal.spec.ts) の全文です(このリポジトリの中なので `../src/index.ts` から読み込んでいます。利用するときは `from "@yutaura/live-spec"` です)。登場人物を増やし、不変条件や入力の例、詳しい画面を加えた版が [examples/article.spec.ts](examples/article.spec.ts) にあります。API の例は [examples/job-api.spec.ts](examples/job-api.spec.ts) です(ワーカーを登場人物として扱い、`GET /jobs/{id}` の応答を状態ごとに示します)。
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { ensure, ui } from "../src/index.ts";
|
|
19
|
+
|
|
20
|
+
/** ブログ記事。著者が書き、編集者がレビューして公開する。 */
|
|
21
|
+
export type Article = { status: "draft" | "inReview" | "published"; authorId: string };
|
|
22
|
+
type User = { id: string; role: "author" | "editor" | "admin" };
|
|
23
|
+
|
|
24
|
+
export const initial: Article = { status: "draft", authorId: "alice" };
|
|
25
|
+
|
|
26
|
+
export const actors: Record<string, User> = {
|
|
27
|
+
著者alice: { id: "alice", role: "author" },
|
|
28
|
+
別の著者bob: { id: "bob", role: "author" },
|
|
29
|
+
編集者eve: { id: "eve", role: "editor" },
|
|
30
|
+
管理者root: { id: "root", role: "admin" },
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** レビューに出す */
|
|
34
|
+
export function submit(article: Article, user: User): Article {
|
|
35
|
+
ensure(user.id === article.authorId, "自分の記事だけ");
|
|
36
|
+
ensure(article.status === "draft", "下書きのときだけ");
|
|
37
|
+
return { ...article, status: "inReview" };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 公開する */
|
|
41
|
+
export function publish(article: Article, user: User): Article {
|
|
42
|
+
ensure(user.role === "editor" || user.role === "admin", "編集者か管理者だけ");
|
|
43
|
+
ensure(article.status === "inReview", "レビュー中のときだけ");
|
|
44
|
+
return { ...article, status: "published" };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** 記事の詳細画面 */
|
|
48
|
+
export function surface(article: Article, user: User) {
|
|
49
|
+
const isAuthor = user.id === article.authorId;
|
|
50
|
+
return ui.screen(
|
|
51
|
+
"記事の詳細",
|
|
52
|
+
ui.badge(article.status),
|
|
53
|
+
isAuthor && article.status === "draft" && ui.button("レビューに出す", submit),
|
|
54
|
+
user.role !== "author" && article.status === "inReview" && ui.button("公開する", publish),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
pnpm spec examples/minimal.spec.ts --serve # http://127.0.0.1:4747/ をブラウザで開く
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
生成される仕様書のうち、`publish` の節:
|
|
64
|
+
|
|
65
|
+
```markdown
|
|
66
|
+
### 公開する(`publish`)
|
|
67
|
+
|
|
68
|
+
- **できる人**: 編集者eve, 管理者root(ほかの人は「編集者か管理者だけ」)
|
|
69
|
+
- **できるとき**: inReview → published
|
|
70
|
+
- **できないとき**: draft, published(レビュー中のときだけ)
|
|
71
|
+
- **結果**: status → published
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## できること
|
|
75
|
+
|
|
76
|
+
- **状態遷移図を計算する**: 状態は手で列挙しません。初期状態から「状態 × 操作 × 登場人物」をすべて実行し、到達できる状態と遷移を求めます。書いた人が想定していなかった状態の組み合わせも図に現れます
|
|
77
|
+
- **できない理由を 3 つの軸に分ける**: `ensure` を並べるだけで、それが「誰が」「いつ」「何を入力したら」のどれの条件なのかを、実行結果から振り分けます。入力をとる操作では、入力ごとにどの状態へ移るか(またはなぜできないか)も示します
|
|
78
|
+
- **不変条件を検査する**: 破る状態が見つかったら、初期状態からそこに至る最短の手順を示します
|
|
79
|
+
- **画面(サーフェス)を描く**: 状態と見る人ごとの画面をワイヤーフレームで描きます。API の応答や CLI の出力も書けます。押しても実行できないボタンや、実行できるのにボタンがない操作も検出します
|
|
80
|
+
- **wireflow 表示**: 状態遷移図のノードを画面のサムネイルにして、視点(誰に見えるか)を切り替えられます
|
|
81
|
+
- **ほかの検査**: 誰も実行できない操作、型には書いてあるのに到達しない値、`ensure` 以外の例外(仕様のバグ)
|
|
82
|
+
- **出力**: ドメインオブジェクトごとのページ(`#/<名前>`)を持つ 1 ファイルの HTML、ドメインオブジェクトごとの Markdown、差分レビュー用の JSON
|
|
83
|
+
- **AI と並走する**: `--serve` を付けると、spec を保存するたびにブラウザが自動で再読み込みします
|
|
84
|
+
|
|
85
|
+
## インストール
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
npm i -D @yutaura/live-spec # pnpm add -D @yutaura/live-spec / yarn add -D @yutaura/live-spec
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Node.js 22.18 以上が必要です(spec ファイルの TypeScript をそのまま実行するため)。パッケージ名は `@yutaura/live-spec`、コマンド名は `live-spec` です。
|
|
92
|
+
|
|
93
|
+
### Claude Code の skill を入れる
|
|
94
|
+
|
|
95
|
+
live-spec のパッケージには、3 つの skill が `skills/<名前>/SKILL.md` として入っています。入れ方は 3 通りあります。
|
|
96
|
+
|
|
97
|
+
**1. pnpm install / npm install のたびに自動で入れる(推奨)**
|
|
98
|
+
|
|
99
|
+
[skills-npm](https://github.com/antfu/skills-npm)(または `skills` CLI の `experimental_sync`)を使うと、依存パッケージに入っている skill が `.claude/skills/` などに自動でリンクされます。live-spec を更新すれば skill も一緒に更新されます。
|
|
100
|
+
|
|
101
|
+
```sh
|
|
102
|
+
npm i -D skills-npm
|
|
103
|
+
npx skills-npm setup # package.json の prepare に組み込み、最初の同期をする
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
**2. live-spec のコマンドでコピーする**
|
|
107
|
+
|
|
108
|
+
```sh
|
|
109
|
+
npx live-spec skills install # .claude/skills/ にコピー(既にあるものは上書きしない。--force で上書き)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
**3. Claude Code の plugin として入れる**
|
|
113
|
+
|
|
114
|
+
パッケージは Claude Code の plugin の構成(`.claude-plugin/plugin.json` と `skills/`)にもなっているので、marketplace の npm source から入れられます。
|
|
115
|
+
|
|
116
|
+
入る skill:
|
|
117
|
+
|
|
118
|
+
- **live-spec-authoring**: spec の書き方の規約と、検査結果の直し方
|
|
119
|
+
- **live-spec-from-code**: 既存のコードから spec を書き起こす。根拠(ファイルと行)を残し、分からないことは質問として返す
|
|
120
|
+
- **live-spec-review**: spec の変更を、振る舞いの変化(誰が何をできるようになったか など)として要約する
|
|
121
|
+
|
|
122
|
+
Claude Code に「このリポジトリの注文まわりの仕様を書き起こして」のように頼むと使われます。
|
|
123
|
+
|
|
124
|
+
## 使い方
|
|
125
|
+
|
|
126
|
+
```sh
|
|
127
|
+
npx live-spec specs/ --html --out spec.html # ドメインオブジェクトごとのページを持つ 1 つの HTML
|
|
128
|
+
npx live-spec specs/ --out docs/spec/ # ドメインオブジェクトごとの Markdown と一覧の README.md
|
|
129
|
+
npx live-spec specs/ --serve # ブラウザで見ながら書く(保存すると自動で再読み込み)
|
|
130
|
+
npx live-spec specs/order.spec.ts # spec が 1 つなら Markdown を標準出力に出す
|
|
131
|
+
npx live-spec specs/ --json # 正規化モデル(差分レビュー用)
|
|
132
|
+
npx live-spec diff specs/order.spec.ts [--base <rev>] # 変更前と比べて、振る舞いの変化を出す
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## spec の書き方
|
|
136
|
+
|
|
137
|
+
**1 つの spec ファイルが 1 つのドメインオブジェクト**です(記事、注文、ジョブ、サーバ、ブラウザのタブ…)。プロジェクトの仕様は `specs/` のようなディレクトリに並べます。1 つの spec の状態が 10 個を超えるようなら、関心の違うものを混ぜていないかを疑い、分けてください。このリポジトリ自身の仕様も [specs/](specs/) にあります。
|
|
138
|
+
|
|
139
|
+
spec ファイルは素の TypeScript です。export の名前で役割が決まります。
|
|
140
|
+
|
|
141
|
+
| export | 必須 | 役割 |
|
|
142
|
+
|---|---|---|
|
|
143
|
+
| `initial` | ✓ | 初期状態 |
|
|
144
|
+
| `actors` | ✓ | 探索に使う登場人物の具体例。ロールに加えて「本人かどうか」も表せる |
|
|
145
|
+
| 上記以外の関数 | | 操作。`(状態, 登場人物, ...入力) => 次の状態`。できないときは `ensure(条件, "理由")` で止める |
|
|
146
|
+
| `invariants` | | 不変条件。`{ 説明: (状態) => boolean }` |
|
|
147
|
+
| `inputs` | | 3 つ目以降の引数の例。`{ 操作名: { 例の名前: [引数...] } }` |
|
|
148
|
+
| `scenarios` | | シナリオ。`{ 名前: [{ do: 操作の関数, by: "登場人物", input?: "入力の例の名前", expect?: { 項目: 値 } }] }`。初期状態から順に実行し、止まったり期待と違ったりしたら検査結果に出る |
|
|
149
|
+
| `questions` | | 未決事項。`[{ ask: "質問", about?: 操作の関数 \| { 項目: 値 }, note?: "補足" }]`。仕様書の上のほうと、図・操作カードに印が出る |
|
|
150
|
+
| `links` | | ほかのドメインオブジェクトとのつながり。`[{ from?: 操作の関数, to: "相手の名前", action?: "相手の操作名", label: "説明" }]`。一覧ページに関係図が出る |
|
|
151
|
+
| `decisions` | | ルールの判断表。`{ 名前: { decide: (入力) => 結果, cases: [{ input, expect? }] } }`。各例を実行して「条件 × 結果」の表を作り、期待と違えば検査結果に出る |
|
|
152
|
+
| `glossary` | | 用語集。`{ 用語: "説明" }`。状態の型の各項目に付けた JSDoc と合わせて「用語」の節に並ぶ |
|
|
153
|
+
| `surface` | | 画面。`(状態, 登場人物) => ui.screen(...)`。ボタンには操作の関数を渡す。API なら `api.response(...)`、CLI なら `cli.output(...)` を返す。見える画面がない人には `null` |
|
|
154
|
+
|
|
155
|
+
型と関数の JSDoc は、仕様書の見出しと説明に使われます(最初の段落まで)。操作の関数の中に `// 根拠: src/foo.ts:42` と書くと、仕様書の操作カードに「根拠」として表示されます。
|
|
156
|
+
|
|
157
|
+
書くときのコツ:
|
|
158
|
+
|
|
159
|
+
- 状態には、振る舞い(できる・できない)に関係する値だけを入れる。タイトルのような値まで入れると状態が増えて図が読めなくなる
|
|
160
|
+
- `ensure` の理由は、そのまま「できない理由」として表示される。読み手に伝わる文にする
|
|
161
|
+
- 「できない」は `ensure` で表す。普通の `throw` は仕様のバグとして検出される
|
|
162
|
+
|
|
163
|
+
## 制約
|
|
164
|
+
|
|
165
|
+
- 型の静的解析は構文解析なので、同じファイルの `type` / `interface` だけを辿ります
|
|
166
|
+
- `--watch` / `--serve` で読み直すのは spec ファイル本体だけです。spec から import した別ファイルの変更では生成し直しません
|
|
167
|
+
- 実装したアプリに対してテストを生成する機能はまだありません。今の「実行可能」は、spec の関数そのものを全状態で実行して検査するという意味です
|
|
168
|
+
|
|
169
|
+
## ステータス
|
|
170
|
+
|
|
171
|
+
Phase 1(MVP)を進めています。進捗は [docs/plan.md](docs/plan.md) を参照してください。
|
|
172
|
+
|
|
173
|
+
## 開発(このリポジトリ)
|
|
174
|
+
|
|
175
|
+
```sh
|
|
176
|
+
direnv allow && pnpm install
|
|
177
|
+
pnpm test && pnpm typecheck
|
|
178
|
+
pnpm spec specs/ --serve # このリポジトリ自身の仕様を見る(src を直接実行する)
|
|
179
|
+
pnpm build # dist/ に配布用の JS と型定義を出す(pnpm pack の前に自動で走る)
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## ドキュメント
|
|
183
|
+
|
|
184
|
+
- [docs/charter.md](docs/charter.md): 存在意義・スコープ・撤退条件 🪨
|
|
185
|
+
- [docs/plan.md](docs/plan.md): フェーズとマイルストーン 🌀
|
|
186
|
+
- [docs/architecture.md](docs/architecture.md): 技術スタックと設計判断 🌊
|
|
187
|
+
- [docs/research/2026-11-prior-art.md](docs/research/2026-11-prior-art.md): 既存ツールの調査
|
|
188
|
+
- [docs/decisions/](docs/decisions/): Architecture Decision Records
|
|
189
|
+
|
|
190
|
+
## 貢献
|
|
191
|
+
|
|
192
|
+
当面はメンテナ 1 人の個人プロジェクトです。外部からの貢献の方針は、OSS として公開するときに決めます。
|
|
193
|
+
|
|
194
|
+
## ライセンス
|
|
195
|
+
|
|
196
|
+
MIT([LICENSE](LICENSE))
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { type OutputFormat } from "./generate.js";
|
|
3
|
+
export { expandSpecPaths, generate, generateProject, specNameOf, type OutputFormat } from "./generate.js";
|
|
4
|
+
export interface CliOptions {
|
|
5
|
+
readonly paths: ReadonlyArray<string>;
|
|
6
|
+
readonly format: OutputFormat;
|
|
7
|
+
readonly out: string | null;
|
|
8
|
+
readonly watch: boolean;
|
|
9
|
+
readonly serve: boolean;
|
|
10
|
+
readonly port: number;
|
|
11
|
+
readonly title: string | null;
|
|
12
|
+
}
|
|
13
|
+
export declare const outputFormatOf: (flags: ReadonlyArray<string>) => OutputFormat;
|
|
14
|
+
export declare const parseCliArgs: (argv: ReadonlyArray<string>) => CliOptions;
|
|
15
|
+
export interface CliIo {
|
|
16
|
+
readonly stdout: (text: string) => void;
|
|
17
|
+
readonly stderr: (text: string) => void;
|
|
18
|
+
}
|
|
19
|
+
export declare const runCli: (argv: ReadonlyArray<string>, io: CliIo) => Promise<number | null>;
|
|
20
|
+
export declare const isMain: (moduleUrl: string, argv1: string | undefined) => boolean;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { expandSpecPaths, generateProject, writeProjectOutput } from "./generate.js";
|
|
6
|
+
import { diffSpec } from "./diff.js";
|
|
7
|
+
import { startServer } from "./serve.js";
|
|
8
|
+
import { installSkills } from "./skills.js";
|
|
9
|
+
import { watchSpec } from "./watch.js";
|
|
10
|
+
export { expandSpecPaths, generate, generateProject, specNameOf } from "./generate.js";
|
|
11
|
+
const DEFAULT_PORT = 4747;
|
|
12
|
+
export const outputFormatOf = (flags) => flags.includes("--html") ? "html" : flags.includes("--json") ? "json" : "markdown";
|
|
13
|
+
export const parseCliArgs = (argv) => {
|
|
14
|
+
const { values, positionals } = parseArgs({
|
|
15
|
+
args: [...argv],
|
|
16
|
+
allowPositionals: true,
|
|
17
|
+
options: {
|
|
18
|
+
html: { type: "boolean" },
|
|
19
|
+
json: { type: "boolean" },
|
|
20
|
+
out: { type: "string" },
|
|
21
|
+
watch: { type: "boolean" },
|
|
22
|
+
serve: { type: "boolean" },
|
|
23
|
+
port: { type: "string" },
|
|
24
|
+
title: { type: "string" },
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
if (positionals.length === 0)
|
|
28
|
+
throw new Error("spec ファイル(またはそれを含むディレクトリ)のパスを指定してください");
|
|
29
|
+
const out = values.out ?? null;
|
|
30
|
+
const serve = values.serve ?? false;
|
|
31
|
+
const watch = serve || (values.watch ?? false);
|
|
32
|
+
if (watch && !serve && out === null) {
|
|
33
|
+
throw new Error("--watch には --out <file> が必要です(標準出力には繰り返し書き出せないため)");
|
|
34
|
+
}
|
|
35
|
+
// 組み合わせをエラーにする理由: 片方を黙って無視すると、利用者は意図と違う出力を受け取ったことに気づけない。
|
|
36
|
+
if (values.html && values.json)
|
|
37
|
+
throw new Error("--html と --json は同時に指定できません");
|
|
38
|
+
if (serve && values.json)
|
|
39
|
+
throw new Error("--serve と --json は同時に指定できません(--serve は HTML だけを配信します)");
|
|
40
|
+
if (values.port !== undefined && !serve)
|
|
41
|
+
throw new Error("--port は --serve と一緒に指定してください");
|
|
42
|
+
const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
|
|
43
|
+
if (values.port?.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) {
|
|
44
|
+
throw new Error(`--port には 0〜65535 の整数を指定してください: "${values.port}"`);
|
|
45
|
+
}
|
|
46
|
+
const format = serve || values.html ? "html" : values.json ? "json" : "markdown";
|
|
47
|
+
return { paths: positionals, format, out, watch, serve, port, title: values.title ?? null };
|
|
48
|
+
};
|
|
49
|
+
const USAGE = "usage: pnpm spec <file.spec.ts | dir>... [--html | --json] [--out <file | dir>] [--watch] [--serve [--port <n>]] [--title <名前>]";
|
|
50
|
+
const messageOf = (e) => (e instanceof Error ? e.message : String(e));
|
|
51
|
+
// 終了コードを返す関数にしている理由: 失敗したときの終わり方(メッセージと終了コード)をテストで確かめるため。
|
|
52
|
+
// 監視を始めた場合は、プロセスを終わらせないので null を返す。
|
|
53
|
+
const DIFF_USAGE = "usage: live-spec diff <file.spec.ts> [--base <リビジョン>](既定の base は HEAD)";
|
|
54
|
+
const runDiff = async (argv, io) => {
|
|
55
|
+
let parsed;
|
|
56
|
+
try {
|
|
57
|
+
parsed = parseArgs({ args: [...argv], allowPositionals: true, options: { base: { type: "string" } } });
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
io.stderr(`${messageOf(e)}\n${DIFF_USAGE}\n`);
|
|
61
|
+
return 2;
|
|
62
|
+
}
|
|
63
|
+
const path = parsed.positionals[0];
|
|
64
|
+
if (path === undefined) {
|
|
65
|
+
io.stderr(`比べる spec ファイルを指定してください\n${DIFF_USAGE}\n`);
|
|
66
|
+
return 2;
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
io.stdout(await diffSpec(path, parsed.values.base ?? "HEAD"));
|
|
70
|
+
return 0;
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
io.stderr(`差分を取れませんでした: ${messageOf(e)}\n`);
|
|
74
|
+
return 1;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const SKILLS_USAGE = "usage: live-spec skills install [--dir <path>](既定は .claude/skills) [--force]";
|
|
78
|
+
const runSkills = (argv, io) => {
|
|
79
|
+
let parsed;
|
|
80
|
+
try {
|
|
81
|
+
parsed = parseArgs({
|
|
82
|
+
args: [...argv],
|
|
83
|
+
allowPositionals: true,
|
|
84
|
+
options: { dir: { type: "string" }, force: { type: "boolean" } },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
io.stderr(`${messageOf(e)}\n${SKILLS_USAGE}\n`);
|
|
89
|
+
return 2;
|
|
90
|
+
}
|
|
91
|
+
if (parsed.positionals[0] !== "install") {
|
|
92
|
+
io.stderr(`${SKILLS_USAGE}\n`);
|
|
93
|
+
return 2;
|
|
94
|
+
}
|
|
95
|
+
const dir = parsed.values.dir ?? ".claude/skills";
|
|
96
|
+
const label = { installed: "入れました", updated: "上書きしました", skipped: "すでにあるので飛ばしました(--force で上書き)" };
|
|
97
|
+
for (const r of installSkills(dir, { force: parsed.values.force ?? false }))
|
|
98
|
+
io.stdout(`${r.name}: ${label[r.status]}\n`);
|
|
99
|
+
io.stdout(`${dir} に live-spec の skill を置きました。Claude Code を起動し直すと使えます。\n`);
|
|
100
|
+
return 0;
|
|
101
|
+
};
|
|
102
|
+
export const runCli = async (argv, io) => {
|
|
103
|
+
if (argv[0] === "diff")
|
|
104
|
+
return runDiff(argv.slice(1), io);
|
|
105
|
+
if (argv[0] === "skills")
|
|
106
|
+
return runSkills(argv.slice(1), io);
|
|
107
|
+
let options;
|
|
108
|
+
try {
|
|
109
|
+
options = parseCliArgs(argv);
|
|
110
|
+
}
|
|
111
|
+
catch (e) {
|
|
112
|
+
io.stderr(`${messageOf(e)}\n${USAGE}\n`);
|
|
113
|
+
return 2;
|
|
114
|
+
}
|
|
115
|
+
if (options.serve) {
|
|
116
|
+
let server;
|
|
117
|
+
try {
|
|
118
|
+
server = await startServer(options.port);
|
|
119
|
+
}
|
|
120
|
+
catch (e) {
|
|
121
|
+
const inUse = e.code === "EADDRINUSE";
|
|
122
|
+
io.stderr(inUse
|
|
123
|
+
? `ポート ${options.port} は使用中です。--port で別の番号を指定してください(0 なら空いている番号を使います)\n`
|
|
124
|
+
: `サーバを起動できませんでした: ${messageOf(e)}\n`);
|
|
125
|
+
return 1;
|
|
126
|
+
}
|
|
127
|
+
io.stderr(`${server.url} で仕様書を配信しています。spec を保存するとブラウザが自動で再読み込みします\n`);
|
|
128
|
+
watchSpec({ paths: options.paths, out: options.out, format: "html", title: options.title, onBuilt: (html) => server.update(html) });
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
if (options.watch) {
|
|
132
|
+
watchSpec({ paths: options.paths, out: options.out, format: options.format, title: options.title });
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
const paths = expandSpecPaths(options.paths);
|
|
136
|
+
if (paths.length === 0) {
|
|
137
|
+
io.stderr(`spec ファイル(*.spec.ts)が見つかりません: ${options.paths.join(", ")}\n`);
|
|
138
|
+
return 2;
|
|
139
|
+
}
|
|
140
|
+
let output;
|
|
141
|
+
try {
|
|
142
|
+
output = await generateProject(paths, options.format, options.title ?? undefined);
|
|
143
|
+
}
|
|
144
|
+
catch (e) {
|
|
145
|
+
io.stderr(`生成に失敗しました: ${messageOf(e)}\n`);
|
|
146
|
+
return 1;
|
|
147
|
+
}
|
|
148
|
+
if (options.out !== null) {
|
|
149
|
+
await writeProjectOutput(options.out, output);
|
|
150
|
+
return 0;
|
|
151
|
+
}
|
|
152
|
+
if (output.kind === "files") {
|
|
153
|
+
io.stderr(`ドメインオブジェクトが複数あるので、Markdown はファイルに分けて書き出します。--out <ディレクトリ> を指定してください\n${USAGE}\n`);
|
|
154
|
+
return 2;
|
|
155
|
+
}
|
|
156
|
+
io.stdout(output.content + "\n");
|
|
157
|
+
return 0;
|
|
158
|
+
};
|
|
159
|
+
// realpath で比べる理由: pnpm などで bin として入れると node_modules/.bin のシンボリックリンク経由で
|
|
160
|
+
// 起動され、process.argv[1] がリンクのパスになる。素朴に比べると一致せず、CLI が何もせずに終わる。
|
|
161
|
+
export const isMain = (moduleUrl, argv1) => {
|
|
162
|
+
if (argv1 === undefined)
|
|
163
|
+
return false;
|
|
164
|
+
try {
|
|
165
|
+
// 両側とも realpath にそろえる。macOS の /var → /private/var のように、モジュール自身のパスも
|
|
166
|
+
// シンボリックリンクを含むことがあるため。
|
|
167
|
+
return pathToFileURL(realpathSync(fileURLToPath(moduleUrl))).href === pathToFileURL(realpathSync(argv1)).href;
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
if (isMain(import.meta.url, process.argv[1])) {
|
|
174
|
+
const code = await runCli(process.argv.slice(2), {
|
|
175
|
+
stdout: (text) => process.stdout.write(text),
|
|
176
|
+
stderr: (text) => process.stderr.write(text),
|
|
177
|
+
});
|
|
178
|
+
if (code !== null)
|
|
179
|
+
process.exitCode = code;
|
|
180
|
+
}
|
package/dist/diff.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface ModelDiff {
|
|
2
|
+
readonly actions: {
|
|
3
|
+
readonly added: ReadonlyArray<string>;
|
|
4
|
+
readonly removed: ReadonlyArray<string>;
|
|
5
|
+
};
|
|
6
|
+
readonly states: {
|
|
7
|
+
readonly added: ReadonlyArray<string>;
|
|
8
|
+
readonly removed: ReadonlyArray<string>;
|
|
9
|
+
};
|
|
10
|
+
readonly transitions: {
|
|
11
|
+
readonly added: ReadonlyArray<string>;
|
|
12
|
+
readonly removed: ReadonlyArray<string>;
|
|
13
|
+
};
|
|
14
|
+
readonly availability: ReadonlyArray<{
|
|
15
|
+
readonly state: string;
|
|
16
|
+
readonly action: string;
|
|
17
|
+
readonly actor: string;
|
|
18
|
+
readonly input: string | null;
|
|
19
|
+
readonly before: string;
|
|
20
|
+
readonly after: string;
|
|
21
|
+
}>;
|
|
22
|
+
readonly findings: {
|
|
23
|
+
readonly added: ReadonlyArray<unknown>;
|
|
24
|
+
readonly removed: ReadonlyArray<unknown>;
|
|
25
|
+
};
|
|
26
|
+
readonly surfaces: ReadonlyArray<{
|
|
27
|
+
readonly state: string;
|
|
28
|
+
readonly actor: string;
|
|
29
|
+
}>;
|
|
30
|
+
}
|
|
31
|
+
export declare const diffModels: (beforeRaw: unknown, afterRaw: unknown) => ModelDiff;
|
|
32
|
+
export declare const renderDiff: (d: ModelDiff) => string;
|
|
33
|
+
export declare const diffSpec: (specPath: string, base?: string) => Promise<string>;
|
package/dist/diff.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
4
|
+
import { generateProject } from "./generate.js";
|
|
5
|
+
const EMPTY = { states: [], transitions: [], availability: [], findings: [], surfaces: [] };
|
|
6
|
+
// 状態 ID(s0, s1…)ではなくラベルで比べる理由: ID は幅優先探索で見つけた順に振られるので、
|
|
7
|
+
// 状態が 1 つ増えるだけで後ろの ID がずれ、何も変わっていない状態まで「変わった」ことになるため。
|
|
8
|
+
const labeler = (model) => {
|
|
9
|
+
const labels = new Map(model.states.map((s) => [s.id, s.label]));
|
|
10
|
+
return (id) => (id === null ? "" : (labels.get(id) ?? id));
|
|
11
|
+
};
|
|
12
|
+
const setDiff = (before, after) => ({
|
|
13
|
+
added: after.filter((x) => !before.includes(x)),
|
|
14
|
+
removed: before.filter((x) => !after.includes(x)),
|
|
15
|
+
});
|
|
16
|
+
// 1 件ずつに戻してから比べる理由: まとめ方は結果の分かれ方で変わるので、まとめた形のまま比べると、
|
|
17
|
+
// 振る舞いが同じでも差分が出てしまうため。"*" は全員(登場人物 × その操作の入力の例)。
|
|
18
|
+
const expandAvailability = (m) => m.availability.flatMap((a) => {
|
|
19
|
+
if (!("outcomes" in a))
|
|
20
|
+
return [a];
|
|
21
|
+
const inputsOf = () => m.inputs?.[a.action] ?? [null];
|
|
22
|
+
const everyone = () => (m.actors ?? []).flatMap((actor) => inputsOf().map((input) => ({ actor: actor.name, input })));
|
|
23
|
+
const expand = (cases) => Object.entries(cases).flatMap(([actor, inputs]) => (inputs === "*" ? inputsOf() : inputs).map((input) => ({ actor, input })));
|
|
24
|
+
return a.outcomes.flatMap((o) => (o.cases === "*" ? everyone() : expand(o.cases)).map((c) => ({
|
|
25
|
+
state: a.state,
|
|
26
|
+
action: a.action,
|
|
27
|
+
actor: c.actor,
|
|
28
|
+
input: c.input,
|
|
29
|
+
enabled: o.enabled,
|
|
30
|
+
to: o.to,
|
|
31
|
+
reason: o.reason,
|
|
32
|
+
})));
|
|
33
|
+
});
|
|
34
|
+
export const diffModels = (beforeRaw, afterRaw) => {
|
|
35
|
+
const before = beforeRaw;
|
|
36
|
+
const after = afterRaw;
|
|
37
|
+
const lb = labeler(before);
|
|
38
|
+
const la = labeler(after);
|
|
39
|
+
const cellOf = (a, l) => (a.enabled ? `✅ → ${l(a.to)}` : `❌ ${a.reason ?? "エラー"}`);
|
|
40
|
+
const transitionKeys = (m, l) => m.transitions.map((t) => `${l(t.from)} -${t.action}-> ${l(t.to)}`);
|
|
41
|
+
const availabilityOf = (m, l) => new Map(expandAvailability(m).map((a) => [JSON.stringify([l(a.state), a.action, a.actor, a.input]), cellOf(a, l)]));
|
|
42
|
+
const ab = availabilityOf(before, lb);
|
|
43
|
+
const aa = availabilityOf(after, la);
|
|
44
|
+
const availability = [];
|
|
45
|
+
for (const [key, cell] of aa) {
|
|
46
|
+
const old = ab.get(key);
|
|
47
|
+
if (old === undefined || old === cell)
|
|
48
|
+
continue;
|
|
49
|
+
const [state, action, actor, input] = JSON.parse(key);
|
|
50
|
+
availability.push({ state, action, actor, input, before: old, after: cell });
|
|
51
|
+
}
|
|
52
|
+
const findingKeys = (m, l) => m.findings.map((f) => JSON.stringify(typeof f.state === "string" ? { ...f, state: l(f.state) } : f));
|
|
53
|
+
const fd = setDiff(findingKeys(before, lb), findingKeys(after, la));
|
|
54
|
+
const surfacesOf = (m, l) => new Map((m.surfaces ?? []).map((s) => [JSON.stringify([l(s.state), s.actor]), JSON.stringify(s.surface)]));
|
|
55
|
+
const sb = surfacesOf(before, lb);
|
|
56
|
+
const sa = surfacesOf(after, la);
|
|
57
|
+
const surfaces = [];
|
|
58
|
+
for (const key of new Set([...sb.keys(), ...sa.keys()])) {
|
|
59
|
+
if (sb.get(key) === sa.get(key))
|
|
60
|
+
continue;
|
|
61
|
+
const [state, actor] = JSON.parse(key);
|
|
62
|
+
surfaces.push({ state, actor });
|
|
63
|
+
}
|
|
64
|
+
const actionNames = (m) => (m.actions ?? []).map((a) => (typeof a === "string" ? a : a.name));
|
|
65
|
+
return {
|
|
66
|
+
actions: setDiff(actionNames(before), actionNames(after)),
|
|
67
|
+
states: setDiff(before.states.map((s) => s.label), after.states.map((s) => s.label)),
|
|
68
|
+
transitions: setDiff(transitionKeys(before, lb), transitionKeys(after, la)),
|
|
69
|
+
availability,
|
|
70
|
+
findings: { added: fd.added.map((s) => JSON.parse(s)), removed: fd.removed.map((s) => JSON.parse(s)) },
|
|
71
|
+
surfaces,
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
const describeFinding = (f) => {
|
|
75
|
+
const { kind, ...rest } = f;
|
|
76
|
+
return `${String(kind)}: ${Object.entries(rest)
|
|
77
|
+
.map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`)
|
|
78
|
+
.join(", ")}`;
|
|
79
|
+
};
|
|
80
|
+
export const renderDiff = (d) => {
|
|
81
|
+
const count = d.actions.added.length + d.actions.removed.length + d.states.added.length + d.states.removed.length +
|
|
82
|
+
d.transitions.added.length + d.transitions.removed.length + d.availability.length +
|
|
83
|
+
d.findings.added.length + d.findings.removed.length + d.surfaces.length;
|
|
84
|
+
if (count === 0)
|
|
85
|
+
return "振る舞いの変化はありません。\n";
|
|
86
|
+
const lines = ["## 振る舞いの変化", ""];
|
|
87
|
+
const addRemove = (title, diff, show) => {
|
|
88
|
+
if (diff.added.length + diff.removed.length === 0)
|
|
89
|
+
return;
|
|
90
|
+
lines.push(`### ${title}`, "", ...diff.added.map((x) => `- + ${show(x)}`), ...diff.removed.map((x) => `- - ${show(x)}`), "");
|
|
91
|
+
};
|
|
92
|
+
addRemove("操作", d.actions, String);
|
|
93
|
+
addRemove("状態", d.states, String);
|
|
94
|
+
addRemove("遷移", d.transitions, String);
|
|
95
|
+
if (d.availability.length > 0) {
|
|
96
|
+
lines.push("### できる/できないの変化", "", "| 状態 | 操作 | 登場人物 | 変更前 | 変更後 |", "|---|---|---|---|---|");
|
|
97
|
+
for (const a of d.availability) {
|
|
98
|
+
const who = a.input === null ? a.actor : `${a.actor}(${a.input})`;
|
|
99
|
+
lines.push(`| ${a.state} | ${a.action} | ${who} | ${a.before} | ${a.after} |`);
|
|
100
|
+
}
|
|
101
|
+
lines.push("");
|
|
102
|
+
}
|
|
103
|
+
addRemove("検査結果", d.findings, describeFinding);
|
|
104
|
+
if (d.surfaces.length > 0)
|
|
105
|
+
lines.push("### 画面が変わったところ", "", ...d.surfaces.map((s) => `- ${s.state}(${s.actor})`), "");
|
|
106
|
+
return lines.join("\n");
|
|
107
|
+
};
|
|
108
|
+
const modelOf = async (path) => {
|
|
109
|
+
const out = await generateProject([path], "json");
|
|
110
|
+
if (out.kind !== "text")
|
|
111
|
+
throw new Error("1 つの spec からは 1 つの JSON が生成されるはず");
|
|
112
|
+
return JSON.parse(out.content);
|
|
113
|
+
};
|
|
114
|
+
export const diffSpec = async (specPath, base = "HEAD") => {
|
|
115
|
+
const spec = resolve(specPath);
|
|
116
|
+
const root = execFileSync("git", ["-C", dirname(spec), "rev-parse", "--show-toplevel"], { encoding: "utf8" }).trim();
|
|
117
|
+
let baseSource;
|
|
118
|
+
try {
|
|
119
|
+
baseSource = execFileSync("git", ["-C", root, "show", `${base}:${relative(root, spec)}`], {
|
|
120
|
+
encoding: "utf8",
|
|
121
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
baseSource = undefined; // base には spec がない(新しく作った spec)
|
|
126
|
+
}
|
|
127
|
+
let before = EMPTY;
|
|
128
|
+
if (baseSource !== undefined) {
|
|
129
|
+
// 元の spec と同じディレクトリに置く理由: spec が相対パスで import しているファイルを、
|
|
130
|
+
// 変更前の spec からも同じように解決できるようにするため。
|
|
131
|
+
const tmp = join(dirname(spec), `.${basename(spec).replace(/\.ts$/, "")}.base.ts`);
|
|
132
|
+
writeFileSync(tmp, baseSource);
|
|
133
|
+
try {
|
|
134
|
+
before = await modelOf(tmp);
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
rmSync(tmp, { force: true });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return renderDiff(diffModels(before, await modelOf(spec)));
|
|
141
|
+
};
|
package/dist/ensure.d.ts
ADDED
package/dist/ensure.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export class NotAllowed extends Error {
|
|
2
|
+
_tag = "NotAllowed";
|
|
3
|
+
}
|
|
4
|
+
export function ensure(condition, reason) {
|
|
5
|
+
if (!condition)
|
|
6
|
+
throw new NotAllowed(reason);
|
|
7
|
+
}
|
|
8
|
+
// instanceof ではなく _tag で判定する理由: spec ファイルと live-spec 本体が別々に
|
|
9
|
+
// 読み込まれて NotAllowed クラスが 2 つ存在する場合でも、正しく判定できるようにするため。
|
|
10
|
+
export const isNotAllowed = (u) => u instanceof Error && u._tag === "NotAllowed";
|