@yutaura/live-spec 0.1.0 → 0.3.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 (50) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +15 -2
  3. package/dist/check.d.ts +5 -0
  4. package/dist/check.js +40 -0
  5. package/dist/cli.js +116 -10
  6. package/dist/diff.d.ts +92 -2
  7. package/dist/diff.js +101 -64
  8. package/dist/ensure-scope.d.ts +9 -0
  9. package/dist/ensure-scope.js +81 -0
  10. package/dist/ensure.d.ts +4 -0
  11. package/dist/ensure.js +27 -2
  12. package/dist/evidence.d.ts +3 -0
  13. package/dist/evidence.js +46 -0
  14. package/dist/explore.d.ts +20 -1
  15. package/dist/explore.js +38 -12
  16. package/dist/generate.d.ts +7 -0
  17. package/dist/generate.js +18 -5
  18. package/dist/load.d.ts +11 -1
  19. package/dist/load.js +9 -0
  20. package/dist/model.d.ts +127 -0
  21. package/dist/model.js +40 -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 +235 -0
  26. package/dist/project-diff.d.ts +24 -0
  27. package/dist/project-diff.js +76 -0
  28. package/dist/render/diff-html.d.ts +2 -0
  29. package/dist/render/diff-html.js +148 -0
  30. package/dist/render/diff-markdown.d.ts +11 -0
  31. package/dist/render/diff-markdown.js +70 -0
  32. package/dist/render/ensures.d.ts +2 -0
  33. package/dist/render/ensures.js +21 -0
  34. package/dist/render/html.d.ts +1 -0
  35. package/dist/render/html.js +42 -10
  36. package/dist/render/layout.d.ts +2 -0
  37. package/dist/render/layout.js +1 -1
  38. package/dist/render/markdown.js +30 -3
  39. package/dist/render/review.d.ts +17 -0
  40. package/dist/render/review.js +17 -0
  41. package/dist/render/union.d.ts +23 -0
  42. package/dist/render/union.js +43 -0
  43. package/dist/spec-loader.d.ts +2 -0
  44. package/dist/spec-loader.js +24 -0
  45. package/dist/static.d.ts +7 -0
  46. package/dist/static.js +74 -0
  47. package/package.json +7 -1
  48. package/skills/live-spec-authoring/SKILL.md +59 -7
  49. package/skills/live-spec-from-code/SKILL.md +2 -0
  50. package/skills/live-spec-review/SKILL.md +16 -10
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "live-spec",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "AI が書き、人が見て理解できる「生きた仕様書」を作るツール。素の TypeScript で書いた仕様を実行し、状態遷移図・画面・できる/できない理由・検査結果をまとめた仕様書を生成する",
5
5
  "keywords": [
6
6
  "specification",
package/README.md CHANGED
@@ -129,7 +129,9 @@ npx live-spec specs/ --out docs/spec/ # ドメインオブジ
129
129
  npx live-spec specs/ --serve # ブラウザで見ながら書く(保存すると自動で再読み込み)
130
130
  npx live-spec specs/order.spec.ts # spec が 1 つなら Markdown を標準出力に出す
131
131
  npx live-spec specs/ --json # 正規化モデル(差分レビュー用)
132
- npx live-spec diff specs/order.spec.ts [--base <rev>] # 変更前と比べて、振る舞いの変化を出す
132
+ npx live-spec check specs/ # 型チェックと検査。問題があれば終了コード 1(CI 向け)
133
+ npx live-spec diff specs/ --base main --head feature # ブランチ間で、仕様の振る舞いの変化を出す(--head を省くと作業ツリー)
134
+ npx live-spec diff specs/ --base main --html --out diff.html # 重ね合わせた状態遷移図と、画面の変更前・変更後を並べた HTML
133
135
  ```
134
136
 
135
137
  ## spec の書き方
@@ -145,7 +147,10 @@ spec ファイルは素の TypeScript です。export の名前で役割が決
145
147
  | 上記以外の関数 | | 操作。`(状態, 登場人物, ...入力) => 次の状態`。できないときは `ensure(条件, "理由")` で止める |
146
148
  | `invariants` | | 不変条件。`{ 説明: (状態) => boolean }` |
147
149
  | `inputs` | | 3 つ目以降の引数の例。`{ 操作名: { 例の名前: [引数...] } }` |
148
- | `scenarios` | | シナリオ。`{ 名前: [{ do: 操作の関数, by: "登場人物", input?: "入力の例の名前", expect?: { 項目: 値 } }] }`。初期状態から順に実行し、止まったり期待と違ったりしたら検査結果に出る |
150
+ | `evidenceRoot` | | 根拠(`// 根拠: path:line`)のパスを解決する起点。spec のファイルからの相対。書かなければ git のルートなどから探す。根拠のファイルが無い・行が範囲の外なら検査結果に出る |
151
+ | `goals` | | 目指す状態。`{ 名前: (状態) => boolean }`。書くと、終端ではないのにどの目指す状態にもたどり着けない状態(袋小路)の入口を「確かめてほしい点」に出す |
152
+ | `reviewed` | | 確かめてほしい点のうち、意図どおりと判断したもの。`{ "候補の ID": "理由" }` |
153
+ | `scenarios` | | シナリオ。`{ 名前: [{ do: 操作の関数, by: "登場人物", input?: "入力の例の名前", expect?: { 項目: 値 }, denied?: "理由" }] }`。初期状態から順に実行し、止まったり期待と違ったりしたら検査結果に出る。`denied` を付けた手順は「断られるはず」で、実行できてしまうと失敗する |
149
154
  | `questions` | | 未決事項。`[{ ask: "質問", about?: 操作の関数 \| { 項目: 値 }, note?: "補足" }]`。仕様書の上のほうと、図・操作カードに印が出る |
150
155
  | `links` | | ほかのドメインオブジェクトとのつながり。`[{ from?: 操作の関数, to: "相手の名前", action?: "相手の操作名", label: "説明" }]`。一覧ページに関係図が出る |
151
156
  | `decisions` | | ルールの判断表。`{ 名前: { decide: (入力) => 結果, cases: [{ input, expect? }] } }`。各例を実行して「条件 × 結果」の表を作り、期待と違えば検査結果に出る |
@@ -160,6 +165,14 @@ spec ファイルは素の TypeScript です。export の名前で役割が決
160
165
  - `ensure` の理由は、そのまま「できない理由」として表示される。読み手に伝わる文にする
161
166
  - 「できない」は `ensure` で表す。普通の `throw` は仕様のバグとして検出される
162
167
 
168
+ ### 漏れを見つける手がかり
169
+
170
+ AI が書いた spec の条件の書き忘れ・書き間違いを、人が見つけやすいように、live-spec は spec を実行した結果から次を出します。
171
+
172
+ - **確かめてほしい点**(ページの上部): 誰でもできる・いつでもできる・入力を見ていない操作、本人と別人を区別しない操作、結果がまったく同じ入力の例や登場人物、どの可否にも影響しない項目、意図がほかに書かれていない条件(`ensure` を外しても不変条件・シナリオ・画面のボタンのどれも気づかないもの)。意図どおりなら `export const reviewed = { "ID": "理由" }` に書くと「確認済み」に移る
173
+ - **条件の「通るのは」**(操作の節): `ensure` ごとに、理由の文と、その条件だけを効かせて実行して求めた「通るのは〜のとき」を並べる。「実行中のときだけ」なのに「通るのは status が queued のとき」なら、条件か理由の書き間違い
174
+ - **外したときの効き目**: その `ensure` を外すと何が起き、何が気づくか
175
+
163
176
  ## 制約
164
177
 
165
178
  - 型の静的解析は構文解析なので、同じファイルの `type` / `interface` だけを辿ります
@@ -0,0 +1,5 @@
1
+ export declare const findTsc: (cwd: string) => string | null;
2
+ export declare const typecheck: (tsc: string, files: ReadonlyArray<string>) => {
3
+ readonly ok: boolean;
4
+ readonly output: string;
5
+ };
package/dist/check.js ADDED
@@ -0,0 +1,40 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { dirname, join } from "node:path";
5
+ // spec はほかのファイルと別に、単独で型を確かめる(利用側の tsconfig.json の設定に左右されないため)。
6
+ // --allowImportingTsExtensions を付ける理由: spec は Node で直接実行するので、相対 import に .ts の拡張子を書くことがある。
7
+ const TSC_FLAGS = [
8
+ "--noEmit",
9
+ "--strict",
10
+ "--module",
11
+ "nodenext",
12
+ "--moduleResolution",
13
+ "nodenext",
14
+ "--target",
15
+ "es2024",
16
+ "--skipLibCheck",
17
+ "--allowImportingTsExtensions",
18
+ ];
19
+ // live-spec に typescript を同梱しない理由: 利用側の typescript の版と型の解決(@types など)に合わせるため。
20
+ export const findTsc = (cwd) => {
21
+ try {
22
+ const pkgPath = createRequire(join(cwd, "package.json")).resolve("typescript/package.json");
23
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
24
+ const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.tsc;
25
+ return bin === undefined ? null : join(dirname(pkgPath), bin);
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ };
31
+ export const typecheck = (tsc, files) => {
32
+ const run = (extra) => spawnSync(process.execPath, [tsc, ...TSC_FLAGS, ...extra, ...files], { encoding: "utf8" });
33
+ // --ignoreConfig は、ファイルを指定しても tsconfig.json を読もうとする TypeScript 6 以降で要る。
34
+ // 5 系はこのオプションを知らないので、知らないと言われたら外して実行し直す。
35
+ let result = run(["--ignoreConfig"]);
36
+ const text = `${result.stdout}${result.stderr}`;
37
+ if (/ignoreConfig/.test(text) && /unknown/i.test(text))
38
+ result = run([]);
39
+ return { ok: result.status === 0, output: `${result.stdout}${result.stderr}`.trim() };
40
+ };
package/dist/cli.js CHANGED
@@ -2,9 +2,16 @@
2
2
  import { realpathSync } from "node:fs";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
4
  import { parseArgs } from "node:util";
5
- import { expandSpecPaths, generateProject, writeProjectOutput } from "./generate.js";
6
- import { diffSpec } from "./diff.js";
5
+ import { resolve } from "node:path";
6
+ import { findTsc, typecheck } from "./check.js";
7
+ import { expandSpecPaths, generateProject, loadObject, resolveLinks, specNameOf, writeOutput, writeProjectOutput } from "./generate.js";
8
+ import { describeFinding } from "./render/markdown.js";
9
+ import { reviewItems } from "./render/review.js";
10
+ import { diffProject } from "./project-diff.js";
11
+ import { renderDiffHtml } from "./render/diff-html.js";
12
+ import { renderDiffMarkdown } from "./render/diff-markdown.js";
7
13
  import { startServer } from "./serve.js";
14
+ import { registerSpecLoader } from "./spec-loader.js";
8
15
  import { installSkills } from "./skills.js";
9
16
  import { watchSpec } from "./watch.js";
10
17
  export { expandSpecPaths, generate, generateProject, specNameOf } from "./generate.js";
@@ -46,36 +53,127 @@ export const parseCliArgs = (argv) => {
46
53
  const format = serve || values.html ? "html" : values.json ? "json" : "markdown";
47
54
  return { paths: positionals, format, out, watch, serve, port, title: values.title ?? null };
48
55
  };
49
- const USAGE = "usage: pnpm spec <file.spec.ts | dir>... [--html | --json] [--out <file | dir>] [--watch] [--serve [--port <n>]] [--title <名前>]";
56
+ const USAGE = "usage: live-spec <file.spec.ts | dir>... [--html | --json] [--out <file | dir>] [--watch] [--serve [--port <n>]] [--title <名前>]";
57
+ const wantsHelp = (argv) => argv.includes("--help") || argv.includes("-h");
50
58
  const messageOf = (e) => (e instanceof Error ? e.message : String(e));
51
59
  // 終了コードを返す関数にしている理由: 失敗したときの終わり方(メッセージと終了コード)をテストで確かめるため。
52
60
  // 監視を始めた場合は、プロセスを終わらせないので null を返す。
53
- const DIFF_USAGE = "usage: live-spec diff <file.spec.ts> [--base <リビジョン>](既定の base は HEAD)";
61
+ const DIFF_USAGE = "usage: live-spec diff <file.spec.ts | dir>... [--base <リビジョン>](既定は HEAD) [--head <リビジョン>](省くと作業ツリー) [--html | --json] [--out <file>]";
54
62
  const runDiff = async (argv, io) => {
63
+ if (wantsHelp(argv)) {
64
+ io.stdout(`${DIFF_USAGE}\n`);
65
+ return 0;
66
+ }
55
67
  let parsed;
56
68
  try {
57
- parsed = parseArgs({ args: [...argv], allowPositionals: true, options: { base: { type: "string" } } });
69
+ parsed = parseArgs({
70
+ args: [...argv],
71
+ allowPositionals: true,
72
+ options: { base: { type: "string" }, head: { type: "string" }, html: { type: "boolean" }, json: { type: "boolean" }, out: { type: "string" } },
73
+ });
58
74
  }
59
75
  catch (e) {
60
76
  io.stderr(`${messageOf(e)}\n${DIFF_USAGE}\n`);
61
77
  return 2;
62
78
  }
63
- const path = parsed.positionals[0];
64
- if (path === undefined) {
65
- io.stderr(`比べる spec ファイルを指定してください\n${DIFF_USAGE}\n`);
79
+ if (parsed.positionals.length === 0) {
80
+ io.stderr(`比べる spec ファイル(またはディレクトリ)を指定してください\n${DIFF_USAGE}\n`);
81
+ return 2;
82
+ }
83
+ if (parsed.values.html && parsed.values.json) {
84
+ io.stderr(`--html と --json は同時に指定できません\n${DIFF_USAGE}\n`);
66
85
  return 2;
67
86
  }
87
+ let result;
68
88
  try {
69
- io.stdout(await diffSpec(path, parsed.values.base ?? "HEAD"));
70
- return 0;
89
+ result = await diffProject({
90
+ paths: parsed.positionals,
91
+ base: parsed.values.base ?? "HEAD",
92
+ ...(parsed.values.head === undefined ? {} : { head: parsed.values.head }),
93
+ });
71
94
  }
72
95
  catch (e) {
73
96
  io.stderr(`差分を取れませんでした: ${messageOf(e)}\n`);
74
97
  return 1;
75
98
  }
99
+ const output = parsed.values.html
100
+ ? await renderDiffHtml(result)
101
+ : parsed.values.json
102
+ ? JSON.stringify({ base: result.base, head: result.head, objects: result.objects.map((o) => ({ name: o.name, status: o.status, diff: o.diff })) }, null, 2)
103
+ : renderDiffMarkdown(result);
104
+ if (parsed.values.out === undefined)
105
+ io.stdout(output.endsWith("\n") ? output : output + "\n");
106
+ else
107
+ await writeOutput(parsed.values.out, output);
108
+ return 0;
109
+ };
110
+ const CHECK_USAGE = "usage: live-spec check <file.spec.ts | dir>... [--cwd <dir>](typescript を探すディレクトリ。既定は今のディレクトリ)";
111
+ const indent = (text) => text
112
+ .split("\n")
113
+ .map((l) => ` ${l}`)
114
+ .join("\n");
115
+ // CI で使うために、問題が 1 つでもあれば 1 で終わる。未決事項(questions)は人の判断待ちで、正常な状態なので失敗にしない。
116
+ const runCheck = async (argv, io) => {
117
+ if (wantsHelp(argv)) {
118
+ io.stdout(`${CHECK_USAGE}\n`);
119
+ return 0;
120
+ }
121
+ let parsed;
122
+ try {
123
+ parsed = parseArgs({ args: [...argv], allowPositionals: true, options: { cwd: { type: "string" } } });
124
+ }
125
+ catch (e) {
126
+ io.stderr(`${messageOf(e)}\n${CHECK_USAGE}\n`);
127
+ return 2;
128
+ }
129
+ const paths = expandSpecPaths(parsed.positionals);
130
+ if (paths.length === 0) {
131
+ io.stderr(`spec ファイル(*.spec.ts)を指定してください\n${CHECK_USAGE}\n`);
132
+ return 2;
133
+ }
134
+ let failed = false;
135
+ const tsc = findTsc(parsed.values.cwd ?? process.cwd());
136
+ if (tsc === null) {
137
+ io.stderr("typescript が見つからないので、型チェックを飛ばしました(--cwd で typescript を入れたディレクトリを指定できます)\n");
138
+ }
139
+ else {
140
+ const result = typecheck(tsc, paths.map((p) => resolve(p)));
141
+ failed ||= !result.ok;
142
+ io.stdout(result.ok ? "✓ 型チェック\n" : `✗ 型チェック\n${indent(result.output)}\n`);
143
+ }
144
+ const loaded = [];
145
+ for (const path of paths) {
146
+ try {
147
+ loaded.push(await loadObject(path));
148
+ }
149
+ catch (e) {
150
+ failed = true;
151
+ io.stdout(`✗ ${specNameOf(path)}: 読み込めない: ${messageOf(e)}\n`);
152
+ }
153
+ }
154
+ for (const { spec, graph } of resolveLinks(loaded)) {
155
+ const labels = new Map(graph.states.map((s) => [s.id, s.label]));
156
+ const labelOf = (id) => labels.get(id) ?? id;
157
+ const pending = reviewItems(spec, graph).pending;
158
+ if (graph.findings.length + pending.length === 0) {
159
+ io.stdout(`✓ ${spec.name}\n`);
160
+ continue;
161
+ }
162
+ failed = true;
163
+ io.stdout([
164
+ `✗ ${spec.name}: 検査結果 ${graph.findings.length} 件、確かめてほしい点 ${pending.length} 件`,
165
+ ...graph.findings.map((f) => ` - ${describeFinding(f, labelOf)}`),
166
+ ...pending.map((i) => ` - ${i.message}(${i.id})`),
167
+ ].join("\n") + "\n");
168
+ }
169
+ return failed ? 1 : 0;
76
170
  };
77
171
  const SKILLS_USAGE = "usage: live-spec skills install [--dir <path>](既定は .claude/skills) [--force]";
78
172
  const runSkills = (argv, io) => {
173
+ if (wantsHelp(argv)) {
174
+ io.stdout(`${SKILLS_USAGE}\n`);
175
+ return 0;
176
+ }
79
177
  let parsed;
80
178
  try {
81
179
  parsed = parseArgs({
@@ -104,6 +202,12 @@ export const runCli = async (argv, io) => {
104
202
  return runDiff(argv.slice(1), io);
105
203
  if (argv[0] === "skills")
106
204
  return runSkills(argv.slice(1), io);
205
+ if (argv[0] === "check")
206
+ return runCheck(argv.slice(1), io);
207
+ if (wantsHelp(argv)) {
208
+ io.stdout(`${[USAGE, DIFF_USAGE, CHECK_USAGE, SKILLS_USAGE].join("\n")}\n`);
209
+ return 0;
210
+ }
107
211
  let options;
108
212
  try {
109
213
  options = parseCliArgs(argv);
@@ -171,6 +275,8 @@ export const isMain = (moduleUrl, argv1) => {
171
275
  }
172
276
  };
173
277
  if (isMain(import.meta.url, process.argv[1])) {
278
+ // CLI として起動したときだけ登録する。ライブラリとして読み込んだ側(テストランナーなど)の読み込み方には手を出さない。
279
+ registerSpecLoader();
174
280
  const code = await runCli(process.argv.slice(2), {
175
281
  stdout: (text) => process.stdout.write(text),
176
282
  stderr: (text) => process.stderr.write(text),
package/dist/diff.d.ts CHANGED
@@ -1,3 +1,55 @@
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
+ }
1
53
  export interface ModelDiff {
2
54
  readonly actions: {
3
55
  readonly added: ReadonlyArray<string>;
@@ -27,7 +79,45 @@ export interface ModelDiff {
27
79
  readonly state: string;
28
80
  readonly actor: string;
29
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
+ };
30
95
  }
96
+ export declare const EMPTY_MODEL: Model;
31
97
  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>;
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 {};
package/dist/diff.js CHANGED
@@ -1,14 +1,14 @@
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 は幅優先探索で見つけた順に振られるので、
1
+ export const EMPTY_MODEL = { states: [], transitions: [], availability: [], findings: [], surfaces: [] };
2
+ // 状態 ID(s0, s1…)ではなく状態の値で比べる理由: ID は幅優先探索で見つけた順に振られるので、
7
3
  // 状態が 1 つ増えるだけで後ろの ID がずれ、何も変わっていない状態まで「変わった」ことになるため。
4
+ // 名前(label)で比べない理由: 名前は initial に書いた項目の順に並ぶので、書き順を変えただけで変わってしまう。
5
+ // 値を持たない古い形式の JSON だけは名前で比べる。
6
+ const keyOfState = (s) => (s.values === undefined ? s.label : JSON.stringify(s.values));
8
7
  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));
8
+ const keys = new Map(model.states.map((s) => [s.id, keyOfState(s)]));
9
+ return (id) => (id === null ? "" : (keys.get(id) ?? id));
11
10
  };
11
+ const ENABLED_PREFIX = "✅ → ";
12
12
  const setDiff = (before, after) => ({
13
13
  added: after.filter((x) => !before.includes(x)),
14
14
  removed: before.filter((x) => !after.includes(x)),
@@ -36,8 +36,16 @@ export const diffModels = (beforeRaw, afterRaw) => {
36
36
  const after = afterRaw;
37
37
  const lb = labeler(before);
38
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)}`);
39
+ // 変更後の名前を優先する理由: レビューする人が読むのは変更後の spec なので。
40
+ const names = new Map([...before.states, ...after.states].map((s) => [keyOfState(s), s.label]));
41
+ const show = (key) => names.get(key) ?? key;
42
+ const showCell = (cell) => (cell.startsWith(ENABLED_PREFIX) ? ENABLED_PREFIX + show(cell.slice(ENABLED_PREFIX.length)) : cell);
43
+ const cellOf = (a, l) => (a.enabled ? `${ENABLED_PREFIX}${l(a.to)}` : `❌ ${a.reason ?? "エラー"}`);
44
+ const transitionKeys = (m, l) => m.transitions.map((t) => JSON.stringify([l(t.from), t.action, l(t.to)]));
45
+ const showTransition = (key) => {
46
+ const [from, action, to] = JSON.parse(key);
47
+ return `${show(from)} -${action}-> ${show(to)}`;
48
+ };
41
49
  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
50
  const ab = availabilityOf(before, lb);
43
51
  const aa = availabilityOf(after, la);
@@ -47,43 +55,95 @@ export const diffModels = (beforeRaw, afterRaw) => {
47
55
  if (old === undefined || old === cell)
48
56
  continue;
49
57
  const [state, action, actor, input] = JSON.parse(key);
50
- availability.push({ state, action, actor, input, before: old, after: cell });
58
+ availability.push({ state: show(state), action, actor, input, before: showCell(old), after: showCell(cell) });
51
59
  }
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));
60
+ // 最短の手順(path)を除いて突き合わせる理由: 違反そのものが同じでも、権限を変えると探索の順が変わり、
61
+ // 手順に出てくる人が入れ替わることがある。それを「違反が消えて別の違反が出た」と見せると誤解を招く。
62
+ const findingKeyOf = (f, l) => {
63
+ const { path: _path, ...rest } = f;
64
+ return JSON.stringify(typeof rest.state === "string" ? { ...rest, state: l(rest.state) } : rest);
65
+ };
66
+ const findingsOf = (m, l) => new Map(m.findings.map((f) => [findingKeyOf(f, l), typeof f.state === "string" ? { ...f, state: l(f.state) } : f]));
67
+ const fb = findingsOf(before, lb);
68
+ const fa = findingsOf(after, la);
69
+ const fd = setDiff([...fb.keys()], [...fa.keys()]);
70
+ const showFinding = (f) => f !== undefined && typeof f.state === "string" ? { ...f, state: show(f.state) } : f;
54
71
  const surfacesOf = (m, l) => new Map((m.surfaces ?? []).map((s) => [JSON.stringify([l(s.state), s.actor]), JSON.stringify(s.surface)]));
55
72
  const sb = surfacesOf(before, lb);
56
73
  const sa = surfacesOf(after, la);
57
74
  const surfaces = [];
75
+ const afterKeys = new Set(after.states.map(keyOfState));
58
76
  for (const key of new Set([...sb.keys(), ...sa.keys()])) {
59
77
  if (sb.get(key) === sa.get(key))
60
78
  continue;
61
79
  const [state, actor] = JSON.parse(key);
62
- surfaces.push({ state, actor });
80
+ // 消えた状態の画面は出さない(状態ごと消えたことは「状態」の差分と図でわかる)。増えた状態の画面は、レビューで見たいので出す。
81
+ if (!afterKeys.has(state))
82
+ continue;
83
+ surfaces.push({ state: show(state), actor });
63
84
  }
64
85
  const actionNames = (m) => (m.actions ?? []).map((a) => (typeof a === "string" ? a : a.name));
86
+ const scenarioNames = (m) => (m.scenarios ?? []).map((s) => s.name);
87
+ const passedOf = (m, name) => m.scenarios?.find((s) => s.name === name)?.passed;
88
+ const sd = setDiff(scenarioNames(before), scenarioNames(after));
65
89
  return {
90
+ scenarios: {
91
+ ...sd,
92
+ changed: scenarioNames(after)
93
+ .filter((n) => scenarioNames(before).includes(n) && passedOf(before, n) !== passedOf(after, n))
94
+ .map((name) => ({ name, before: passedOf(before, name) ?? false, after: passedOf(after, name) ?? false })),
95
+ },
96
+ questions: setDiff((before.questions ?? []).map((q) => q.ask), (after.questions ?? []).map((q) => q.ask)),
66
97
  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)),
98
+ states: (({ added, removed }) => ({ added: added.map(show), removed: removed.map(show) }))(setDiff(before.states.map(keyOfState), after.states.map(keyOfState))),
99
+ transitions: (({ added, removed }) => ({ added: added.map(showTransition), removed: removed.map(showTransition) }))(setDiff(transitionKeys(before, lb), transitionKeys(after, la))),
69
100
  availability,
70
- findings: { added: fd.added.map((s) => JSON.parse(s)), removed: fd.removed.map((s) => JSON.parse(s)) },
101
+ findings: { added: fd.added.map((k) => showFinding(fa.get(k))), removed: fd.removed.map((k) => showFinding(fb.get(k))) },
71
102
  surfaces,
72
103
  };
73
104
  };
74
- const describeFinding = (f) => {
105
+ const isStep = (v) => typeof v === "object" && v !== null && "action" in v && "actor" in v;
106
+ export const describeFinding = (f) => {
75
107
  const { kind, ...rest } = f;
76
108
  return `${String(kind)}: ${Object.entries(rest)
77
- .map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`)
109
+ .map(([k, v]) => Array.isArray(v) && v.every(isStep)
110
+ ? `${k}=${v.map((s) => `${s.action}(${s.actor})`).join(" → ")}`
111
+ : `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`)
78
112
  .join(", ")}`;
79
113
  };
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)
114
+ const enabledOf = (cell) => cell.startsWith("✅");
115
+ // できない理由の文言だけが変わったものを、操作 × 変更前 × 変更後でまとめる。権限の条件を 1 つ変えると、
116
+ // 「できない」のままの組み合わせの理由がまとめて書き換わり、本当に変わった行(できる/できないの入れ替わり)が埋もれるため。
117
+ export const groupAvailability = (changes) => {
118
+ const flipped = changes.filter((a) => enabledOf(a.before) || enabledOf(a.after));
119
+ const groups = new Map();
120
+ for (const a of changes.filter((x) => !enabledOf(x.before) && !enabledOf(x.after))) {
121
+ const key = JSON.stringify([a.action, a.before, a.after]);
122
+ groups.set(key, [...(groups.get(key) ?? []), a]);
123
+ }
124
+ const reasonOnly = [...groups.values()].map((cases) => ({
125
+ action: cases[0].action,
126
+ before: cases[0].before,
127
+ after: cases[0].after,
128
+ count: cases.length,
129
+ cases,
130
+ }));
131
+ return { flipped, reasonOnly };
132
+ };
133
+ export const whoOf = (a) => (a.input === null ? a.actor : `${a.actor}(${a.input})`);
134
+ export const isEmptyDiff = (d) => d.actions.added.length + d.actions.removed.length + d.states.added.length + d.states.removed.length +
135
+ d.transitions.added.length + d.transitions.removed.length + d.availability.length +
136
+ d.findings.added.length + d.findings.removed.length + d.surfaces.length +
137
+ d.scenarios.added.length + d.scenarios.removed.length + d.scenarios.changed.length +
138
+ d.questions.added.length + d.questions.removed.length ===
139
+ 0;
140
+ const passed = (p) => (p ? "通る" : "止まる");
141
+ // heading を外から切り替えられるようにしている理由: 1 つの spec の差分では「## 振る舞いの変化」を見出しにし、
142
+ // プロジェクト全体の差分ではドメインオブジェクトの見出しの下に節だけを並べたいため。
143
+ export const renderDiff = (d, options = {}) => {
144
+ if (isEmptyDiff(d))
85
145
  return "振る舞いの変化はありません。\n";
86
- const lines = ["## 振る舞いの変化", ""];
146
+ const lines = options.heading === false ? [] : ["## 振る舞いの変化", ""];
87
147
  const addRemove = (title, diff, show) => {
88
148
  if (diff.added.length + diff.removed.length === 0)
89
149
  return;
@@ -92,50 +152,27 @@ export const renderDiff = (d) => {
92
152
  addRemove("操作", d.actions, String);
93
153
  addRemove("状態", d.states, String);
94
154
  addRemove("遷移", d.transitions, String);
95
- if (d.availability.length > 0) {
155
+ const g = groupAvailability(d.availability);
156
+ if (g.flipped.length > 0) {
96
157
  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
- }
158
+ for (const a of g.flipped)
159
+ lines.push(`| ${a.state} | ${a.action} | ${whoOf(a)} | ${a.before} | ${a.after} |`);
160
+ lines.push("");
161
+ }
162
+ if (g.reasonOnly.length > 0) {
163
+ lines.push("### できない理由の言い方だけが変わったもの", "", "| 操作 | 変更前 | 変更後 | 件数 |", "|---|---|---|---|");
164
+ for (const r of g.reasonOnly)
165
+ lines.push(`| ${r.action} | ${r.before} | ${r.after} | ${r.count} |`);
101
166
  lines.push("");
102
167
  }
168
+ if (d.scenarios.added.length + d.scenarios.removed.length + d.scenarios.changed.length > 0) {
169
+ lines.push("### シナリオ", "", ...d.scenarios.added.map((n) => `- + ${n}`), ...d.scenarios.removed.map((n) => `- - ${n}`), ...d.scenarios.changed.map((c) => `- ${c.name}: ${passed(c.before)} → ${passed(c.after)}`), "");
170
+ }
171
+ if (d.questions.added.length + d.questions.removed.length > 0) {
172
+ lines.push("### 未決事項", "", ...d.questions.added.map((q) => `- + ${q}`), ...d.questions.removed.map((q) => `- - ${q}(解決したか、取り下げた)`), "");
173
+ }
103
174
  addRemove("検査結果", d.findings, describeFinding);
104
175
  if (d.surfaces.length > 0)
105
176
  lines.push("### 画面が変わったところ", "", ...d.surfaces.map((s) => `- ${s.state}(${s.actor})`), "");
106
177
  return lines.join("\n");
107
178
  };
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
- };
@@ -0,0 +1,9 @@
1
+ import type { Spec } from "./load.js";
2
+ import type { Graph } from "./model.js";
3
+ export interface EnsureScope {
4
+ /** 何によって通る・止まるが決まるか */
5
+ readonly dimension: "state" | "actor" | "input" | "relation" | "mixed" | "none" | "always";
6
+ /** 通るのがどんなときかを、人が理由の文と見比べられる言葉で表したもの */
7
+ readonly passes: string;
8
+ }
9
+ export declare const ensureScope: (spec: Spec, graph: Graph, action: string, reason: string) => EnsureScope;