@yutaura/live-spec 0.0.0-stage → 0.2.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 (67) hide show
  1. package/.claude-plugin/plugin.json +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +205 -2
  4. package/dist/cli.d.ts +20 -0
  5. package/dist/cli.js +219 -0
  6. package/dist/diff.d.ts +123 -0
  7. package/dist/diff.js +178 -0
  8. package/dist/ensure-scope.d.ts +9 -0
  9. package/dist/ensure-scope.js +81 -0
  10. package/dist/ensure.d.ts +9 -0
  11. package/dist/ensure.js +35 -0
  12. package/dist/explore.d.ts +25 -0
  13. package/dist/explore.js +292 -0
  14. package/dist/generate.d.ts +21 -0
  15. package/dist/generate.js +159 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +2 -0
  18. package/dist/load.d.ts +58 -0
  19. package/dist/load.js +79 -0
  20. package/dist/model.d.ts +487 -0
  21. package/dist/model.js +209 -0
  22. package/dist/mutation.d.ts +3 -0
  23. package/dist/mutation.js +51 -0
  24. package/dist/omission.d.ts +6 -0
  25. package/dist/omission.js +177 -0
  26. package/dist/project-diff.d.ts +24 -0
  27. package/dist/project-diff.js +76 -0
  28. package/dist/render/collapse.d.ts +4 -0
  29. package/dist/render/collapse.js +22 -0
  30. package/dist/render/diff-html.d.ts +2 -0
  31. package/dist/render/diff-html.js +148 -0
  32. package/dist/render/diff-markdown.d.ts +11 -0
  33. package/dist/render/diff-markdown.js +70 -0
  34. package/dist/render/ensures.d.ts +2 -0
  35. package/dist/render/ensures.js +21 -0
  36. package/dist/render/escape.d.ts +1 -0
  37. package/dist/render/escape.js +2 -0
  38. package/dist/render/html.d.ts +13 -0
  39. package/dist/render/html.js +717 -0
  40. package/dist/render/layout.d.ts +39 -0
  41. package/dist/render/layout.js +74 -0
  42. package/dist/render/markdown.d.ts +20 -0
  43. package/dist/render/markdown.js +248 -0
  44. package/dist/render/review.d.ts +17 -0
  45. package/dist/render/review.js +17 -0
  46. package/dist/render/summary.d.ts +62 -0
  47. package/dist/render/summary.js +119 -0
  48. package/dist/render/union.d.ts +23 -0
  49. package/dist/render/union.js +43 -0
  50. package/dist/render/wireframe.d.ts +3 -0
  51. package/dist/render/wireframe.js +62 -0
  52. package/dist/serve.d.ts +8 -0
  53. package/dist/serve.js +71 -0
  54. package/dist/skills.d.ts +8 -0
  55. package/dist/skills.js +20 -0
  56. package/dist/spec-loader.d.ts +2 -0
  57. package/dist/spec-loader.js +24 -0
  58. package/dist/static.d.ts +15 -0
  59. package/dist/static.js +151 -0
  60. package/dist/surface.d.ts +59 -0
  61. package/dist/surface.js +44 -0
  62. package/dist/watch.d.ts +10 -0
  63. package/dist/watch.js +47 -0
  64. package/package.json +60 -4
  65. package/skills/live-spec-authoring/SKILL.md +190 -0
  66. package/skills/live-spec-from-code/SKILL.md +93 -0
  67. package/skills/live-spec-review/SKILL.md +71 -0
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "live-spec",
3
+ "version": "0.2.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,206 @@
1
- # Temporary Holding Version
1
+ # live-spec
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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/ --base main --head feature # ブランチ間で、仕様の振る舞いの変化を出す(--head を省くと作業ツリー)
133
+ npx live-spec diff specs/ --base main --html --out diff.html # 重ね合わせた状態遷移図と、画面の変更前・変更後を並べた HTML
134
+ ```
135
+
136
+ ## spec の書き方
137
+
138
+ **1 つの spec ファイルが 1 つのドメインオブジェクト**です(記事、注文、ジョブ、サーバ、ブラウザのタブ…)。プロジェクトの仕様は `specs/` のようなディレクトリに並べます。1 つの spec の状態が 10 個を超えるようなら、関心の違うものを混ぜていないかを疑い、分けてください。このリポジトリ自身の仕様も [specs/](specs/) にあります。
139
+
140
+ spec ファイルは素の TypeScript です。export の名前で役割が決まります。
141
+
142
+ | export | 必須 | 役割 |
143
+ |---|---|---|
144
+ | `initial` | ✓ | 初期状態 |
145
+ | `actors` | ✓ | 探索に使う登場人物の具体例。ロールに加えて「本人かどうか」も表せる |
146
+ | 上記以外の関数 | | 操作。`(状態, 登場人物, ...入力) => 次の状態`。できないときは `ensure(条件, "理由")` で止める |
147
+ | `invariants` | | 不変条件。`{ 説明: (状態) => boolean }` |
148
+ | `inputs` | | 3 つ目以降の引数の例。`{ 操作名: { 例の名前: [引数...] } }` |
149
+ | `reviewed` | | 確かめてほしい点のうち、意図どおりと判断したもの。`{ "候補の ID": "理由" }` |
150
+ | `scenarios` | | シナリオ。`{ 名前: [{ do: 操作の関数, by: "登場人物", input?: "入力の例の名前", expect?: { 項目: 値 }, denied?: "理由" }] }`。初期状態から順に実行し、止まったり期待と違ったりしたら検査結果に出る。`denied` を付けた手順は「断られるはず」で、実行できてしまうと失敗する |
151
+ | `questions` | | 未決事項。`[{ ask: "質問", about?: 操作の関数 \| { 項目: 値 }, note?: "補足" }]`。仕様書の上のほうと、図・操作カードに印が出る |
152
+ | `links` | | ほかのドメインオブジェクトとのつながり。`[{ from?: 操作の関数, to: "相手の名前", action?: "相手の操作名", label: "説明" }]`。一覧ページに関係図が出る |
153
+ | `decisions` | | ルールの判断表。`{ 名前: { decide: (入力) => 結果, cases: [{ input, expect? }] } }`。各例を実行して「条件 × 結果」の表を作り、期待と違えば検査結果に出る |
154
+ | `glossary` | | 用語集。`{ 用語: "説明" }`。状態の型の各項目に付けた JSDoc と合わせて「用語」の節に並ぶ |
155
+ | `surface` | | 画面。`(状態, 登場人物) => ui.screen(...)`。ボタンには操作の関数を渡す。API なら `api.response(...)`、CLI なら `cli.output(...)` を返す。見える画面がない人には `null` |
156
+
157
+ 型と関数の JSDoc は、仕様書の見出しと説明に使われます(最初の段落まで)。操作の関数の中に `// 根拠: src/foo.ts:42` と書くと、仕様書の操作カードに「根拠」として表示されます。
158
+
159
+ 書くときのコツ:
160
+
161
+ - 状態には、振る舞い(できる・できない)に関係する値だけを入れる。タイトルのような値まで入れると状態が増えて図が読めなくなる
162
+ - `ensure` の理由は、そのまま「できない理由」として表示される。読み手に伝わる文にする
163
+ - 「できない」は `ensure` で表す。普通の `throw` は仕様のバグとして検出される
164
+
165
+ ### 漏れを見つける手がかり
166
+
167
+ AI が書いた spec の条件の書き忘れ・書き間違いを、人が見つけやすいように、live-spec は spec を実行した結果から次を出します。
168
+
169
+ - **確かめてほしい点**(ページの上部): 誰でもできる・いつでもできる・入力を見ていない操作、本人と別人を区別しない操作、結果がまったく同じ入力の例や登場人物、どの可否にも影響しない項目、意図がほかに書かれていない条件(`ensure` を外しても不変条件・シナリオ・画面のボタンのどれも気づかないもの)。意図どおりなら `export const reviewed = { "ID": "理由" }` に書くと「確認済み」に移る
170
+ - **条件の「通るのは」**(操作の節): `ensure` ごとに、理由の文と、その条件だけを効かせて実行して求めた「通るのは〜のとき」を並べる。「実行中のときだけ」なのに「通るのは status が queued のとき」なら、条件か理由の書き間違い
171
+ - **外したときの効き目**: その `ensure` を外すと何が起き、何が気づくか
172
+
173
+ ## 制約
174
+
175
+ - 型の静的解析は構文解析なので、同じファイルの `type` / `interface` だけを辿ります
176
+ - `--watch` / `--serve` で読み直すのは spec ファイル本体だけです。spec から import した別ファイルの変更では生成し直しません
177
+ - 実装したアプリに対してテストを生成する機能はまだありません。今の「実行可能」は、spec の関数そのものを全状態で実行して検査するという意味です
178
+
179
+ ## ステータス
180
+
181
+ Phase 1(MVP)を進めています。進捗は [docs/plan.md](docs/plan.md) を参照してください。
182
+
183
+ ## 開発(このリポジトリ)
184
+
185
+ ```sh
186
+ direnv allow && pnpm install
187
+ pnpm test && pnpm typecheck
188
+ pnpm spec specs/ --serve # このリポジトリ自身の仕様を見る(src を直接実行する)
189
+ pnpm build # dist/ に配布用の JS と型定義を出す(pnpm pack の前に自動で走る)
190
+ ```
191
+
192
+ ## ドキュメント
193
+
194
+ - [docs/charter.md](docs/charter.md): 存在意義・スコープ・撤退条件 🪨
195
+ - [docs/plan.md](docs/plan.md): フェーズとマイルストーン 🌀
196
+ - [docs/architecture.md](docs/architecture.md): 技術スタックと設計判断 🌊
197
+ - [docs/research/2026-11-prior-art.md](docs/research/2026-11-prior-art.md): 既存ツールの調査
198
+ - [docs/decisions/](docs/decisions/): Architecture Decision Records
199
+
200
+ ## 貢献
201
+
202
+ 当面はメンテナ 1 人の個人プロジェクトです。外部からの貢献の方針は、OSS として公開するときに決めます。
203
+
204
+ ## ライセンス
205
+
206
+ 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,219 @@
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, writeOutput, writeProjectOutput } from "./generate.js";
6
+ import { diffProject } from "./project-diff.js";
7
+ import { renderDiffHtml } from "./render/diff-html.js";
8
+ import { renderDiffMarkdown } from "./render/diff-markdown.js";
9
+ import { startServer } from "./serve.js";
10
+ import { registerSpecLoader } from "./spec-loader.js";
11
+ import { installSkills } from "./skills.js";
12
+ import { watchSpec } from "./watch.js";
13
+ export { expandSpecPaths, generate, generateProject, specNameOf } from "./generate.js";
14
+ const DEFAULT_PORT = 4747;
15
+ export const outputFormatOf = (flags) => flags.includes("--html") ? "html" : flags.includes("--json") ? "json" : "markdown";
16
+ export const parseCliArgs = (argv) => {
17
+ const { values, positionals } = parseArgs({
18
+ args: [...argv],
19
+ allowPositionals: true,
20
+ options: {
21
+ html: { type: "boolean" },
22
+ json: { type: "boolean" },
23
+ out: { type: "string" },
24
+ watch: { type: "boolean" },
25
+ serve: { type: "boolean" },
26
+ port: { type: "string" },
27
+ title: { type: "string" },
28
+ },
29
+ });
30
+ if (positionals.length === 0)
31
+ throw new Error("spec ファイル(またはそれを含むディレクトリ)のパスを指定してください");
32
+ const out = values.out ?? null;
33
+ const serve = values.serve ?? false;
34
+ const watch = serve || (values.watch ?? false);
35
+ if (watch && !serve && out === null) {
36
+ throw new Error("--watch には --out <file> が必要です(標準出力には繰り返し書き出せないため)");
37
+ }
38
+ // 組み合わせをエラーにする理由: 片方を黙って無視すると、利用者は意図と違う出力を受け取ったことに気づけない。
39
+ if (values.html && values.json)
40
+ throw new Error("--html と --json は同時に指定できません");
41
+ if (serve && values.json)
42
+ throw new Error("--serve と --json は同時に指定できません(--serve は HTML だけを配信します)");
43
+ if (values.port !== undefined && !serve)
44
+ throw new Error("--port は --serve と一緒に指定してください");
45
+ const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
46
+ if (values.port?.trim() === "" || !Number.isInteger(port) || port < 0 || port > 65535) {
47
+ throw new Error(`--port には 0〜65535 の整数を指定してください: "${values.port}"`);
48
+ }
49
+ const format = serve || values.html ? "html" : values.json ? "json" : "markdown";
50
+ return { paths: positionals, format, out, watch, serve, port, title: values.title ?? null };
51
+ };
52
+ const USAGE = "usage: live-spec <file.spec.ts | dir>... [--html | --json] [--out <file | dir>] [--watch] [--serve [--port <n>]] [--title <名前>]";
53
+ const wantsHelp = (argv) => argv.includes("--help") || argv.includes("-h");
54
+ const messageOf = (e) => (e instanceof Error ? e.message : String(e));
55
+ // 終了コードを返す関数にしている理由: 失敗したときの終わり方(メッセージと終了コード)をテストで確かめるため。
56
+ // 監視を始めた場合は、プロセスを終わらせないので null を返す。
57
+ const DIFF_USAGE = "usage: live-spec diff <file.spec.ts | dir>... [--base <リビジョン>](既定は HEAD) [--head <リビジョン>](省くと作業ツリー) [--html | --json] [--out <file>]";
58
+ const runDiff = async (argv, io) => {
59
+ if (wantsHelp(argv)) {
60
+ io.stdout(`${DIFF_USAGE}\n`);
61
+ return 0;
62
+ }
63
+ let parsed;
64
+ try {
65
+ parsed = parseArgs({
66
+ args: [...argv],
67
+ allowPositionals: true,
68
+ options: { base: { type: "string" }, head: { type: "string" }, html: { type: "boolean" }, json: { type: "boolean" }, out: { type: "string" } },
69
+ });
70
+ }
71
+ catch (e) {
72
+ io.stderr(`${messageOf(e)}\n${DIFF_USAGE}\n`);
73
+ return 2;
74
+ }
75
+ if (parsed.positionals.length === 0) {
76
+ io.stderr(`比べる spec ファイル(またはディレクトリ)を指定してください\n${DIFF_USAGE}\n`);
77
+ return 2;
78
+ }
79
+ if (parsed.values.html && parsed.values.json) {
80
+ io.stderr(`--html と --json は同時に指定できません\n${DIFF_USAGE}\n`);
81
+ return 2;
82
+ }
83
+ let result;
84
+ try {
85
+ result = await diffProject({
86
+ paths: parsed.positionals,
87
+ base: parsed.values.base ?? "HEAD",
88
+ ...(parsed.values.head === undefined ? {} : { head: parsed.values.head }),
89
+ });
90
+ }
91
+ catch (e) {
92
+ io.stderr(`差分を取れませんでした: ${messageOf(e)}\n`);
93
+ return 1;
94
+ }
95
+ const output = parsed.values.html
96
+ ? await renderDiffHtml(result)
97
+ : parsed.values.json
98
+ ? JSON.stringify({ base: result.base, head: result.head, objects: result.objects.map((o) => ({ name: o.name, status: o.status, diff: o.diff })) }, null, 2)
99
+ : renderDiffMarkdown(result);
100
+ if (parsed.values.out === undefined)
101
+ io.stdout(output.endsWith("\n") ? output : output + "\n");
102
+ else
103
+ await writeOutput(parsed.values.out, output);
104
+ return 0;
105
+ };
106
+ const SKILLS_USAGE = "usage: live-spec skills install [--dir <path>](既定は .claude/skills) [--force]";
107
+ const runSkills = (argv, io) => {
108
+ if (wantsHelp(argv)) {
109
+ io.stdout(`${SKILLS_USAGE}\n`);
110
+ return 0;
111
+ }
112
+ let parsed;
113
+ try {
114
+ parsed = parseArgs({
115
+ args: [...argv],
116
+ allowPositionals: true,
117
+ options: { dir: { type: "string" }, force: { type: "boolean" } },
118
+ });
119
+ }
120
+ catch (e) {
121
+ io.stderr(`${messageOf(e)}\n${SKILLS_USAGE}\n`);
122
+ return 2;
123
+ }
124
+ if (parsed.positionals[0] !== "install") {
125
+ io.stderr(`${SKILLS_USAGE}\n`);
126
+ return 2;
127
+ }
128
+ const dir = parsed.values.dir ?? ".claude/skills";
129
+ const label = { installed: "入れました", updated: "上書きしました", skipped: "すでにあるので飛ばしました(--force で上書き)" };
130
+ for (const r of installSkills(dir, { force: parsed.values.force ?? false }))
131
+ io.stdout(`${r.name}: ${label[r.status]}\n`);
132
+ io.stdout(`${dir} に live-spec の skill を置きました。Claude Code を起動し直すと使えます。\n`);
133
+ return 0;
134
+ };
135
+ export const runCli = async (argv, io) => {
136
+ if (argv[0] === "diff")
137
+ return runDiff(argv.slice(1), io);
138
+ if (argv[0] === "skills")
139
+ return runSkills(argv.slice(1), io);
140
+ if (wantsHelp(argv)) {
141
+ io.stdout(`${[USAGE, DIFF_USAGE, SKILLS_USAGE].join("\n")}\n`);
142
+ return 0;
143
+ }
144
+ let options;
145
+ try {
146
+ options = parseCliArgs(argv);
147
+ }
148
+ catch (e) {
149
+ io.stderr(`${messageOf(e)}\n${USAGE}\n`);
150
+ return 2;
151
+ }
152
+ if (options.serve) {
153
+ let server;
154
+ try {
155
+ server = await startServer(options.port);
156
+ }
157
+ catch (e) {
158
+ const inUse = e.code === "EADDRINUSE";
159
+ io.stderr(inUse
160
+ ? `ポート ${options.port} は使用中です。--port で別の番号を指定してください(0 なら空いている番号を使います)\n`
161
+ : `サーバを起動できませんでした: ${messageOf(e)}\n`);
162
+ return 1;
163
+ }
164
+ io.stderr(`${server.url} で仕様書を配信しています。spec を保存するとブラウザが自動で再読み込みします\n`);
165
+ watchSpec({ paths: options.paths, out: options.out, format: "html", title: options.title, onBuilt: (html) => server.update(html) });
166
+ return null;
167
+ }
168
+ if (options.watch) {
169
+ watchSpec({ paths: options.paths, out: options.out, format: options.format, title: options.title });
170
+ return null;
171
+ }
172
+ const paths = expandSpecPaths(options.paths);
173
+ if (paths.length === 0) {
174
+ io.stderr(`spec ファイル(*.spec.ts)が見つかりません: ${options.paths.join(", ")}\n`);
175
+ return 2;
176
+ }
177
+ let output;
178
+ try {
179
+ output = await generateProject(paths, options.format, options.title ?? undefined);
180
+ }
181
+ catch (e) {
182
+ io.stderr(`生成に失敗しました: ${messageOf(e)}\n`);
183
+ return 1;
184
+ }
185
+ if (options.out !== null) {
186
+ await writeProjectOutput(options.out, output);
187
+ return 0;
188
+ }
189
+ if (output.kind === "files") {
190
+ io.stderr(`ドメインオブジェクトが複数あるので、Markdown はファイルに分けて書き出します。--out <ディレクトリ> を指定してください\n${USAGE}\n`);
191
+ return 2;
192
+ }
193
+ io.stdout(output.content + "\n");
194
+ return 0;
195
+ };
196
+ // realpath で比べる理由: pnpm などで bin として入れると node_modules/.bin のシンボリックリンク経由で
197
+ // 起動され、process.argv[1] がリンクのパスになる。素朴に比べると一致せず、CLI が何もせずに終わる。
198
+ export const isMain = (moduleUrl, argv1) => {
199
+ if (argv1 === undefined)
200
+ return false;
201
+ try {
202
+ // 両側とも realpath にそろえる。macOS の /var → /private/var のように、モジュール自身のパスも
203
+ // シンボリックリンクを含むことがあるため。
204
+ return pathToFileURL(realpathSync(fileURLToPath(moduleUrl))).href === pathToFileURL(realpathSync(argv1)).href;
205
+ }
206
+ catch {
207
+ return false;
208
+ }
209
+ };
210
+ if (isMain(import.meta.url, process.argv[1])) {
211
+ // CLI として起動したときだけ登録する。ライブラリとして読み込んだ側(テストランナーなど)の読み込み方には手を出さない。
212
+ registerSpecLoader();
213
+ const code = await runCli(process.argv.slice(2), {
214
+ stdout: (text) => process.stdout.write(text),
215
+ stderr: (text) => process.stderr.write(text),
216
+ });
217
+ if (code !== null)
218
+ process.exitCode = code;
219
+ }
package/dist/diff.d.ts ADDED
@@ -0,0 +1,123 @@
1
+ interface Model {
2
+ readonly actors?: ReadonlyArray<{
3
+ readonly name: string;
4
+ }>;
5
+ readonly inputs?: Readonly<Record<string, ReadonlyArray<string>>>;
6
+ readonly actions?: ReadonlyArray<string | {
7
+ readonly name: string;
8
+ }>;
9
+ readonly states: ReadonlyArray<{
10
+ readonly id: string;
11
+ readonly label: string;
12
+ readonly values?: unknown;
13
+ }>;
14
+ readonly transitions: ReadonlyArray<{
15
+ readonly from: string;
16
+ readonly to: string;
17
+ readonly action: string;
18
+ }>;
19
+ readonly availability: ReadonlyArray<FlatAvailability | CompactAvailability>;
20
+ readonly findings: ReadonlyArray<Readonly<Record<string, unknown>>>;
21
+ readonly surfaces?: ReadonlyArray<{
22
+ readonly state: string;
23
+ readonly actor: string;
24
+ readonly surface: unknown;
25
+ }>;
26
+ readonly scenarios?: ReadonlyArray<{
27
+ readonly name: string;
28
+ readonly passed: boolean;
29
+ }>;
30
+ readonly questions?: ReadonlyArray<{
31
+ readonly ask: string;
32
+ }>;
33
+ }
34
+ interface FlatAvailability {
35
+ readonly state: string;
36
+ readonly action: string;
37
+ readonly actor: string;
38
+ readonly input: string | null;
39
+ readonly enabled: boolean;
40
+ readonly to: string | null;
41
+ readonly reason: string | null;
42
+ }
43
+ interface CompactAvailability {
44
+ readonly state: string;
45
+ readonly action: string;
46
+ readonly outcomes: ReadonlyArray<{
47
+ readonly enabled: boolean;
48
+ readonly to: string | null;
49
+ readonly reason: string | null;
50
+ readonly cases: "*" | Readonly<Record<string, "*" | ReadonlyArray<string>>>;
51
+ }>;
52
+ }
53
+ export interface ModelDiff {
54
+ readonly actions: {
55
+ readonly added: ReadonlyArray<string>;
56
+ readonly removed: ReadonlyArray<string>;
57
+ };
58
+ readonly states: {
59
+ readonly added: ReadonlyArray<string>;
60
+ readonly removed: ReadonlyArray<string>;
61
+ };
62
+ readonly transitions: {
63
+ readonly added: ReadonlyArray<string>;
64
+ readonly removed: ReadonlyArray<string>;
65
+ };
66
+ readonly availability: ReadonlyArray<{
67
+ readonly state: string;
68
+ readonly action: string;
69
+ readonly actor: string;
70
+ readonly input: string | null;
71
+ readonly before: string;
72
+ readonly after: string;
73
+ }>;
74
+ readonly findings: {
75
+ readonly added: ReadonlyArray<unknown>;
76
+ readonly removed: ReadonlyArray<unknown>;
77
+ };
78
+ readonly surfaces: ReadonlyArray<{
79
+ readonly state: string;
80
+ readonly actor: string;
81
+ }>;
82
+ readonly scenarios: {
83
+ readonly added: ReadonlyArray<string>;
84
+ readonly removed: ReadonlyArray<string>;
85
+ readonly changed: ReadonlyArray<{
86
+ readonly name: string;
87
+ readonly before: boolean;
88
+ readonly after: boolean;
89
+ }>;
90
+ };
91
+ readonly questions: {
92
+ readonly added: ReadonlyArray<string>;
93
+ readonly removed: ReadonlyArray<string>;
94
+ };
95
+ }
96
+ export declare const EMPTY_MODEL: Model;
97
+ export declare const diffModels: (beforeRaw: unknown, afterRaw: unknown) => ModelDiff;
98
+ export declare const describeFinding: (f: unknown) => string;
99
+ type AvailabilityChange = ModelDiff["availability"][number];
100
+ export interface ReasonOnlyGroup {
101
+ readonly action: string;
102
+ readonly before: string;
103
+ readonly after: string;
104
+ readonly count: number;
105
+ readonly cases: ReadonlyArray<AvailabilityChange>;
106
+ }
107
+ export declare const groupAvailability: (changes: ReadonlyArray<AvailabilityChange>) => {
108
+ flipped: {
109
+ readonly state: string;
110
+ readonly action: string;
111
+ readonly actor: string;
112
+ readonly input: string | null;
113
+ readonly before: string;
114
+ readonly after: string;
115
+ }[];
116
+ reasonOnly: ReasonOnlyGroup[];
117
+ };
118
+ export declare const whoOf: (a: AvailabilityChange) => string;
119
+ export declare const isEmptyDiff: (d: ModelDiff) => boolean;
120
+ export declare const renderDiff: (d: ModelDiff, options?: {
121
+ readonly heading?: boolean;
122
+ }) => string;
123
+ export {};