@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
package/dist/diff.js ADDED
@@ -0,0 +1,178 @@
1
+ export const EMPTY_MODEL = { states: [], transitions: [], availability: [], findings: [], surfaces: [] };
2
+ // 状態 ID(s0, s1…)ではなく状態の値で比べる理由: ID は幅優先探索で見つけた順に振られるので、
3
+ // 状態が 1 つ増えるだけで後ろの ID がずれ、何も変わっていない状態まで「変わった」ことになるため。
4
+ // 名前(label)で比べない理由: 名前は initial に書いた項目の順に並ぶので、書き順を変えただけで変わってしまう。
5
+ // 値を持たない古い形式の JSON だけは名前で比べる。
6
+ const keyOfState = (s) => (s.values === undefined ? s.label : JSON.stringify(s.values));
7
+ const labeler = (model) => {
8
+ const keys = new Map(model.states.map((s) => [s.id, keyOfState(s)]));
9
+ return (id) => (id === null ? "" : (keys.get(id) ?? id));
10
+ };
11
+ const ENABLED_PREFIX = "✅ → ";
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
+ // 変更後の名前を優先する理由: レビューする人が読むのは変更後の 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
+ };
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)]));
50
+ const ab = availabilityOf(before, lb);
51
+ const aa = availabilityOf(after, la);
52
+ const availability = [];
53
+ for (const [key, cell] of aa) {
54
+ const old = ab.get(key);
55
+ if (old === undefined || old === cell)
56
+ continue;
57
+ const [state, action, actor, input] = JSON.parse(key);
58
+ availability.push({ state: show(state), action, actor, input, before: showCell(old), after: showCell(cell) });
59
+ }
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;
71
+ const surfacesOf = (m, l) => new Map((m.surfaces ?? []).map((s) => [JSON.stringify([l(s.state), s.actor]), JSON.stringify(s.surface)]));
72
+ const sb = surfacesOf(before, lb);
73
+ const sa = surfacesOf(after, la);
74
+ const surfaces = [];
75
+ const afterKeys = new Set(after.states.map(keyOfState));
76
+ for (const key of new Set([...sb.keys(), ...sa.keys()])) {
77
+ if (sb.get(key) === sa.get(key))
78
+ continue;
79
+ const [state, actor] = JSON.parse(key);
80
+ // 消えた状態の画面は出さない(状態ごと消えたことは「状態」の差分と図でわかる)。増えた状態の画面は、レビューで見たいので出す。
81
+ if (!afterKeys.has(state))
82
+ continue;
83
+ surfaces.push({ state: show(state), actor });
84
+ }
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));
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)),
97
+ actions: setDiff(actionNames(before), actionNames(after)),
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))),
100
+ availability,
101
+ findings: { added: fd.added.map((k) => showFinding(fa.get(k))), removed: fd.removed.map((k) => showFinding(fb.get(k))) },
102
+ surfaces,
103
+ };
104
+ };
105
+ const isStep = (v) => typeof v === "object" && v !== null && "action" in v && "actor" in v;
106
+ export const describeFinding = (f) => {
107
+ const { kind, ...rest } = f;
108
+ return `${String(kind)}: ${Object.entries(rest)
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)}`)
112
+ .join(", ")}`;
113
+ };
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))
145
+ return "振る舞いの変化はありません。\n";
146
+ const lines = options.heading === false ? [] : ["## 振る舞いの変化", ""];
147
+ const addRemove = (title, diff, show) => {
148
+ if (diff.added.length + diff.removed.length === 0)
149
+ return;
150
+ lines.push(`### ${title}`, "", ...diff.added.map((x) => `- + ${show(x)}`), ...diff.removed.map((x) => `- - ${show(x)}`), "");
151
+ };
152
+ addRemove("操作", d.actions, String);
153
+ addRemove("状態", d.states, String);
154
+ addRemove("遷移", d.transitions, String);
155
+ const g = groupAvailability(d.availability);
156
+ if (g.flipped.length > 0) {
157
+ lines.push("### できる/できないの変化", "", "| 状態 | 操作 | 登場人物 | 変更前 | 変更後 |", "|---|---|---|---|---|");
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} |`);
166
+ lines.push("");
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
+ }
174
+ addRemove("検査結果", d.findings, describeFinding);
175
+ if (d.surfaces.length > 0)
176
+ lines.push("### 画面が変わったところ", "", ...d.surfaces.map((s) => `- ${s.state}(${s.actor})`), "");
177
+ return lines.join("\n");
178
+ };
@@ -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;
@@ -0,0 +1,81 @@
1
+ import { withOnlyEnsure } from "./ensure.js";
2
+ import { runAction } from "./explore.js";
3
+ const MAX_STATES = 200;
4
+ const MAX_LISTED = 4;
5
+ const isPlainObject = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
6
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
7
+ const uniformBy = (cells, keyOf) => {
8
+ const result = new Map();
9
+ for (const c of cells) {
10
+ const known = result.get(keyOf(c));
11
+ if (known !== undefined && known !== c.blocked)
12
+ return null;
13
+ result.set(keyOf(c), c.blocked);
14
+ }
15
+ return result;
16
+ };
17
+ const ordered = (values, preferred) => {
18
+ const list = [...values];
19
+ return preferred === undefined ? list : list.sort((a, b) => preferred.indexOf(a) - preferred.indexOf(b));
20
+ };
21
+ export const ensureScope = (spec, graph, action, reason) => {
22
+ const fn = spec.actions.find(([name]) => name === action)?.[1];
23
+ if (fn === undefined)
24
+ throw new Error(`操作 ${action} は spec にない`);
25
+ const inputs = spec.inputs[action] ?? [[null, []]];
26
+ const cells = [];
27
+ for (const state of graph.states.slice(0, MAX_STATES)) {
28
+ for (const [actor, actorValue] of spec.actors) {
29
+ for (const [input, args] of inputs) {
30
+ const outcome = withOnlyEnsure(reason, () => runAction(fn, state.values, actorValue, args, null));
31
+ cells.push({ state, actor, actorValue, input, blocked: outcome.kind === "not-allowed" && outcome.reason === reason });
32
+ }
33
+ }
34
+ }
35
+ if (cells.every((c) => !c.blocked))
36
+ return { dimension: "none", passes: "到達できるどの場合も通る(この条件で止まることがない)" };
37
+ if (cells.every((c) => c.blocked))
38
+ return { dimension: "always", passes: "到達できるどの場合も止まる" };
39
+ // 関係を先に調べる理由: 所有者の条件は、到達できる状態で持ち主が 1 人しかいないと「その人のとき」とも読めてしまう。
40
+ // 「持ち主と同じとき」のほうが、理由の文(「作った人だけ」)と見比べやすい。
41
+ // initial に書いた順に試す理由: 到達できる状態で連動している項目(status と dispatch など)は、どちらでも
42
+ // 言い表せる。書き手が先に書いた、読み手に見せたい項目で言い表すほうが、理由の文と見比べやすい。
43
+ const declared = Object.keys(spec.initial);
44
+ const fields = [...new Set([...declared, ...cells.flatMap((c) => Object.keys(c.state.values))])].filter((f) => cells.some((c) => f in c.state.values));
45
+ const actorKeys = [...new Set(cells.flatMap((c) => (isPlainObject(c.actorValue) ? Object.keys(c.actorValue) : [])))];
46
+ for (const field of fields) {
47
+ for (const key of actorKeys) {
48
+ const equal = (c) => isPlainObject(c.actorValue) && same(c.state.values[field], c.actorValue[key]);
49
+ if (!cells.some(equal) || cells.every(equal))
50
+ continue;
51
+ if (cells.every((c) => c.blocked === !equal(c)))
52
+ return { dimension: "relation", passes: `${field} が登場人物の ${key} と同じとき` };
53
+ if (cells.every((c) => c.blocked === equal(c)))
54
+ return { dimension: "relation", passes: `${field} が登場人物の ${key} と違うとき` };
55
+ }
56
+ }
57
+ const byState = uniformBy(cells, (c) => c.state.id);
58
+ if (byState !== null) {
59
+ const pass = graph.states.filter((s) => byState.get(s.id) === false);
60
+ const block = graph.states.filter((s) => byState.get(s.id) === true);
61
+ for (const field of fields) {
62
+ const passValues = new Set(pass.map((s) => JSON.stringify(s.values[field])));
63
+ if (block.some((s) => passValues.has(JSON.stringify(s.values[field]))))
64
+ continue;
65
+ const values = ordered([...passValues].map((v) => JSON.parse(v)), spec.fields[field]);
66
+ return { dimension: "state", passes: `${field} が ${values.map(String).join(", ")} のとき` };
67
+ }
68
+ return { dimension: "state", passes: `${pass.map((s) => s.label).join(", ")} のとき` };
69
+ }
70
+ const byActor = uniformBy(cells, (c) => c.actor);
71
+ if (byActor !== null) {
72
+ return { dimension: "actor", passes: `${spec.actors.map(([name]) => name).filter((n) => byActor.get(n) === false).join(", ")} のとき` };
73
+ }
74
+ const byInput = uniformBy(cells, (c) => c.input ?? "");
75
+ if (byInput !== null) {
76
+ return { dimension: "input", passes: `入力が ${inputs.map(([label]) => label ?? "").filter((l) => byInput.get(l) === false).join(", ")} のとき` };
77
+ }
78
+ const passing = cells.filter((c) => !c.blocked);
79
+ const listed = passing.slice(0, MAX_LISTED).map((c) => [c.state.label, c.actor, ...(c.input === null ? [] : [c.input])].join("・"));
80
+ return { dimension: "mixed", passes: `${listed.join("、")}${passing.length > MAX_LISTED ? ` ほか ${passing.length - MAX_LISTED} 通り` : ""} のとき` };
81
+ };
@@ -0,0 +1,9 @@
1
+ export declare class NotAllowed extends Error {
2
+ readonly _tag = "NotAllowed";
3
+ }
4
+ export declare function ensure(condition: unknown, reason: string): asserts condition;
5
+ /** fn を実行している間だけ、理由が reason の ensure を素通りさせる(ミューテーションで使う) */
6
+ export declare const withEnsureBypassed: <A>(reason: string, fn: () => A) => A;
7
+ /** fn を実行している間だけ、理由が reason の ensure 以外を素通りさせる(その ensure が実際に止める範囲を求めるのに使う) */
8
+ export declare const withOnlyEnsure: <A>(reason: string, fn: () => A) => A;
9
+ export declare const isNotAllowed: (u: unknown) => u is NotAllowed;
package/dist/ensure.js ADDED
@@ -0,0 +1,35 @@
1
+ export class NotAllowed extends Error {
2
+ _tag = "NotAllowed";
3
+ }
4
+ // 外す ensure を globalThis に Symbol.for で置く理由: spec ファイルと live-spec 本体が別々に読み込まれて
5
+ // このモジュールが 2 つ存在する場合でも、同じ設定を見られるようにするため(isNotAllowed を _tag で判定するのと同じ事情)。
6
+ const BYPASS = Symbol.for("live-spec.ensure.bypass");
7
+ export function ensure(condition, reason) {
8
+ if (condition)
9
+ return;
10
+ const bypass = globalThis[BYPASS];
11
+ if (bypass !== undefined && (bypass.mode === "skip" ? bypass.reason === reason : bypass.reason !== reason))
12
+ return;
13
+ throw new NotAllowed(reason);
14
+ }
15
+ const withBypass = (mode, fn) => {
16
+ const holder = globalThis;
17
+ const previous = holder[BYPASS];
18
+ holder[BYPASS] = mode;
19
+ try {
20
+ return fn();
21
+ }
22
+ finally {
23
+ if (previous === undefined)
24
+ delete holder[BYPASS];
25
+ else
26
+ holder[BYPASS] = previous;
27
+ }
28
+ };
29
+ /** fn を実行している間だけ、理由が reason の ensure を素通りさせる(ミューテーションで使う) */
30
+ export const withEnsureBypassed = (reason, fn) => withBypass({ mode: "skip", reason }, fn);
31
+ /** fn を実行している間だけ、理由が reason の ensure 以外を素通りさせる(その ensure が実際に止める範囲を求めるのに使う) */
32
+ export const withOnlyEnsure = (reason, fn) => withBypass({ mode: "only", reason }, fn);
33
+ // instanceof ではなく _tag で判定する理由: spec ファイルと live-spec 本体が別々に
34
+ // 読み込まれて NotAllowed クラスが 2 つ存在する場合でも、正しく判定できるようにするため。
35
+ export const isNotAllowed = (u) => u instanceof Error && u._tag === "NotAllowed";
@@ -0,0 +1,25 @@
1
+ import type { Spec, State } from "./load.js";
2
+ import { type Graph } from "./model.js";
3
+ export interface ExploreOptions {
4
+ readonly maxStates?: number;
5
+ /** この操作の、この理由の ensure を外して探索する(ensure のミューテーション) */
6
+ readonly bypassEnsure?: {
7
+ readonly action: string;
8
+ readonly reason: string;
9
+ };
10
+ }
11
+ type Outcome = {
12
+ readonly kind: "ok";
13
+ readonly next: State;
14
+ } | {
15
+ readonly kind: "not-allowed";
16
+ readonly reason: string;
17
+ } | {
18
+ readonly kind: "error";
19
+ readonly message: string;
20
+ } | {
21
+ readonly kind: "invalid-return";
22
+ };
23
+ export declare const runAction: (fn: Spec["actions"][number][1], state: State, actor: unknown, args: ReadonlyArray<unknown>, bypassReason: string | null) => Outcome;
24
+ export declare const explore: (spec: Spec, options?: ExploreOptions) => Graph;
25
+ export {};
@@ -0,0 +1,292 @@
1
+ import { isNotAllowed, withEnsureBypassed } from "./ensure.js";
2
+ import { canonical } from "./model.js";
3
+ import { buttonsOf } from "./surface.js";
4
+ const DEFAULT_MAX_STATES = 500;
5
+ export const runAction = (fn, state, actor, args, bypassReason) => {
6
+ if (bypassReason !== null)
7
+ return withEnsureBypassed(bypassReason, () => runAction(fn, state, actor, args, null));
8
+ try {
9
+ // structuredClone を渡す理由: 関数が引数を破壊的に変更しても、探索済みの状態が壊れないようにするため。
10
+ const next = fn(structuredClone(state), structuredClone(actor), ...structuredClone(args));
11
+ if (typeof next !== "object" || next === null || Array.isArray(next))
12
+ return { kind: "invalid-return" };
13
+ return { kind: "ok", next: canonical(next) };
14
+ }
15
+ catch (e) {
16
+ if (isNotAllowed(e))
17
+ return { kind: "not-allowed", reason: e.message };
18
+ return { kind: "error", message: e instanceof Error ? e.message : String(e) };
19
+ }
20
+ };
21
+ // 例外を違反として扱う理由: 不変条件の関数が想定外の状態で落ちること自体が、
22
+ // その状態が書き手の想定を外れている(=不変条件を満たすと言えない)ことを示すため。
23
+ const invariantHolds = (holds, values) => {
24
+ try {
25
+ return Boolean(holds(structuredClone(values)));
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ };
31
+ export const explore = (spec, options = {}) => {
32
+ const maxStates = options.maxStates ?? DEFAULT_MAX_STATES;
33
+ const bypassFor = (action) => (options.bypassEnsure?.action === action ? options.bypassEnsure.reason : null);
34
+ const ids = new Map();
35
+ const valuesById = new Map();
36
+ const queue = [];
37
+ const parents = new Map();
38
+ const violations = [];
39
+ const register = (values, via) => {
40
+ const key = JSON.stringify(values);
41
+ const known = ids.get(key);
42
+ if (known !== undefined)
43
+ return known;
44
+ if (ids.size >= maxStates)
45
+ return undefined;
46
+ const id = `s${ids.size}`;
47
+ ids.set(key, id);
48
+ valuesById.set(id, values);
49
+ queue.push(id);
50
+ if (via !== undefined)
51
+ parents.set(id, via);
52
+ for (const [invariant, holds] of spec.invariants) {
53
+ if (!invariantHolds(holds, values))
54
+ violations.push({ invariant, state: id });
55
+ }
56
+ return id;
57
+ };
58
+ // 幅優先探索で最初に見つけた親をたどるので、得られる手順は初期状態からの最短手順になる。
59
+ const pathTo = (id) => {
60
+ const steps = [];
61
+ for (let p = parents.get(id); p !== undefined; p = parents.get(p.from))
62
+ steps.unshift({ action: p.action, actor: p.actor });
63
+ return steps;
64
+ };
65
+ const transitions = new Map();
66
+ const availability = [];
67
+ const findings = [];
68
+ const processed = new Set();
69
+ // 3 つ目以降の引数がある操作は、inputs に例がなければ実行しない。
70
+ // undefined を渡して実行すると TypeError などが「仕様のバグ」として大量に出て、本当の原因が埋もれるため。
71
+ const missingInputs = spec.actions.filter(([name, fn]) => fn.length > 2 && spec.inputs[name] === undefined).map(([name]) => name);
72
+ const runnable = spec.actions.filter(([name]) => !missingInputs.includes(name));
73
+ const NO_INPUT = [[null, []]];
74
+ register(canonical(spec.initial));
75
+ // 幅優先探索の理由: 状態 ID と表の行の並びを「初期状態からの近さ」順に固定し、
76
+ // spec の書き換えで出力の順序が揺れないようにするため(差分レビューの前提)。
77
+ explore: for (let i = 0; i < queue.length; i++) {
78
+ const from = queue[i];
79
+ const values = valuesById.get(from);
80
+ for (const [action, fn] of runnable) {
81
+ for (const [actor, actorValue] of spec.actors) {
82
+ for (const [input, args] of spec.inputs[action] ?? NO_INPUT) {
83
+ const outcome = runAction(fn, values, actorValue, args, bypassFor(action));
84
+ if (outcome.kind !== "ok") {
85
+ if (outcome.kind === "error")
86
+ findings.push({ kind: "action-error", action, actor, state: from, message: outcome.message });
87
+ if (outcome.kind === "invalid-return")
88
+ findings.push({ kind: "invalid-return", action, actor, state: from });
89
+ const reason = outcome.kind === "not-allowed" ? outcome.reason : null;
90
+ availability.push({ state: from, action, actor, input, enabled: false, to: null, reason });
91
+ continue;
92
+ }
93
+ const to = register(outcome.next, { from, action, actor });
94
+ if (to === undefined) {
95
+ findings.push({ kind: "state-limit", maxStates });
96
+ break explore;
97
+ }
98
+ availability.push({ state: from, action, actor, input, enabled: true, to, reason: null });
99
+ const key = `${from}|${action}|${to}`;
100
+ const t = transitions.get(key) ?? { from, to, action, actors: [] };
101
+ if (!t.actors.includes(actor))
102
+ t.actors.push(actor);
103
+ transitions.set(key, t);
104
+ }
105
+ }
106
+ }
107
+ processed.add(from);
108
+ }
109
+ const labelOf = labeler([...valuesById.values()], Object.keys(spec.initial));
110
+ const states = [...valuesById.entries()].map(([id, values]) => ({
111
+ id,
112
+ label: labelOf(values),
113
+ values,
114
+ initial: id === "s0",
115
+ terminal: processed.has(id) && !availability.some((a) => a.state === id && a.enabled),
116
+ }));
117
+ for (const v of violations)
118
+ findings.push({ kind: "invariant-violation", ...v, path: pathTo(v.state) });
119
+ for (const [field, values] of Object.entries(spec.fields)) {
120
+ for (const value of values) {
121
+ if (!states.some((s) => s.values[field] === value))
122
+ findings.push({ kind: "unreachable-value", field, value });
123
+ }
124
+ }
125
+ for (const action of missingInputs)
126
+ findings.push({ kind: "missing-inputs", action });
127
+ for (const action of Object.keys(spec.inputs)) {
128
+ if (!spec.actions.some(([name]) => name === action))
129
+ findings.push({ kind: "unknown-inputs", action });
130
+ }
131
+ for (const [action] of runnable) {
132
+ if (!availability.some((a) => a.action === action && a.enabled))
133
+ findings.push({ kind: "never-enabled-action", action });
134
+ }
135
+ const surfaces = spec.surface === null ? [] : checkSurfaces(spec.surface, spec, [...processed], valuesById, availability, findings);
136
+ const scenarios = runScenarios(spec, (values) => ids.get(JSON.stringify(values)) ?? null, findings, bypassFor);
137
+ const questions = spec.questions.map((q) => {
138
+ const about = q.about;
139
+ const action = typeof about === "function" ? about.name : null;
140
+ const matched = about === undefined || typeof about === "function"
141
+ ? []
142
+ : states
143
+ .filter((s) => Object.entries(about).every(([k, v]) => JSON.stringify(canonical(v)) === JSON.stringify(s.values[k])))
144
+ .map((s) => s.id);
145
+ if (about !== undefined && typeof about !== "function" && matched.length === 0)
146
+ findings.push({ kind: "question-unmatched", ask: q.ask });
147
+ return { ask: q.ask, note: q.note ?? null, action, states: matched };
148
+ });
149
+ const decisions = spec.decisions.map(([name, d]) => {
150
+ const columns = [...new Set(d.cases.flatMap((c) => (typeof c.input === "object" && c.input !== null ? Object.keys(c.input) : ["入力"])))];
151
+ const rows = d.cases.map((c, i) => {
152
+ let result;
153
+ try {
154
+ result = d.decide(structuredClone(c.input));
155
+ }
156
+ catch (e) {
157
+ findings.push({ kind: "decision-error", decision: name, row: i + 1, message: e instanceof Error ? e.message : String(e) });
158
+ return { input: c.input, result: null, expect: c.expect ?? null, ok: false };
159
+ }
160
+ const ok = !("expect" in c) || JSON.stringify(canonical(c.expect)) === JSON.stringify(canonical(result));
161
+ if (!ok)
162
+ findings.push({ kind: "decision-mismatch", decision: name, row: i + 1, expected: show(c.expect), actual: show(result) });
163
+ return { input: c.input, result, expect: "expect" in c ? c.expect : null, ok };
164
+ });
165
+ return { name, columns, rows };
166
+ });
167
+ const links = spec.links.map((l) => ({ from: l.from?.name ?? null, to: l.to, action: l.action ?? null, label: l.label }));
168
+ return { states, transitions: [...transitions.values()], availability, findings, surfaces, decisions, links, questions, scenarios };
169
+ };
170
+ const show = (v) => (typeof v === "string" ? v : JSON.stringify(v));
171
+ // シナリオは探索とは別に、初期状態から手順どおりに実行する。探索は「到達できるか」を確かめるが、
172
+ // シナリオは「この業務の流れが、この順番で通るか」を名指しで確かめる(受け入れテストの役割)。
173
+ const runScenarios = (spec, idOf, findings, bypassFor) => spec.scenarios.map(([name, steps]) => {
174
+ let values = canonical(spec.initial);
175
+ const records = [];
176
+ for (const [i, step] of steps.entries()) {
177
+ const action = step.do.name;
178
+ const fail = (reason) => {
179
+ records.push({ action, actor: step.by, input: step.input ?? null, from: idOf(values), to: null, ok: false, reason, denied: step.denied !== undefined });
180
+ findings.push({ kind: "scenario-failed", scenario: name, step: i + 1, reason });
181
+ };
182
+ const actor = spec.actors.find(([n]) => n === step.by);
183
+ if (actor === undefined) {
184
+ fail(`登場人物「${step.by}」は actors にない`);
185
+ break;
186
+ }
187
+ if (!spec.actions.some(([n]) => n === action)) {
188
+ fail(`操作「${action}」はこの spec にない`);
189
+ break;
190
+ }
191
+ const examples = spec.inputs[action];
192
+ const args = step.input === undefined ? [] : examples?.find(([label]) => label === step.input)?.[1];
193
+ if (args === undefined) {
194
+ fail(`入力の例「${step.input}」は inputs にない`);
195
+ break;
196
+ }
197
+ if (step.input === undefined && step.do.length > 2) {
198
+ fail("この操作には入力の例(input)を指定する");
199
+ break;
200
+ }
201
+ const outcome = runAction(step.do, values, actor[1], args, bypassFor(action));
202
+ if (step.denied !== undefined) {
203
+ if (outcome.kind === "ok") {
204
+ fail("断られるはずが、実行できた");
205
+ break;
206
+ }
207
+ if (outcome.kind !== "not-allowed") {
208
+ fail(outcome.kind === "error" ? `例外: ${outcome.message}` : "オブジェクトを返さなかった");
209
+ break;
210
+ }
211
+ if (typeof step.denied === "string" && outcome.reason !== step.denied) {
212
+ fail(`断られる理由が違う: 期待「${step.denied}」、実際「${outcome.reason}」`);
213
+ break;
214
+ }
215
+ const here = idOf(values);
216
+ records.push({ action, actor: step.by, input: step.input ?? null, from: here, to: here, ok: true, reason: outcome.reason, denied: true });
217
+ continue;
218
+ }
219
+ if (outcome.kind !== "ok") {
220
+ fail(outcome.kind === "not-allowed" ? outcome.reason : outcome.kind === "error" ? `例外: ${outcome.message}` : "オブジェクトを返さなかった");
221
+ break;
222
+ }
223
+ const mismatch = Object.entries(step.expect ?? {}).find(([k, v]) => JSON.stringify(canonical(v)) !== JSON.stringify(outcome.next[k]));
224
+ if (mismatch !== undefined) {
225
+ const [k, v] = mismatch;
226
+ fail(`期待: ${k} = ${show(v)}、実際: ${k} = ${show(outcome.next[k])}`);
227
+ break;
228
+ }
229
+ records.push({ action, actor: step.by, input: step.input ?? null, from: idOf(values), to: idOf(outcome.next), ok: true, reason: null, denied: false });
230
+ values = outcome.next;
231
+ }
232
+ return { name, passed: records.length === steps.length && records.every((r) => r.ok), steps: records };
233
+ });
234
+ // 画面のボタンと探索の結果を突き合わせる。画面と状態遷移が同じ spec から作られているので、
235
+ // 「押しても実行できないボタン」「実行できるのに画面から辿れない操作」を機械的に見つけられる。
236
+ const checkSurfaces = (surface, spec, states, valuesById, availability, findings) => {
237
+ const result = [];
238
+ for (const state of states) {
239
+ for (const [actor, actorValue] of spec.actors) {
240
+ let node;
241
+ try {
242
+ node = surface(structuredClone(valuesById.get(state)), structuredClone(actorValue));
243
+ }
244
+ catch (e) {
245
+ findings.push({ kind: "surface-error", state, actor, message: e instanceof Error ? e.message : String(e) });
246
+ continue;
247
+ }
248
+ // null は「この人に見える画面はない」(API を呼ばないワーカーなど)。記録も検査もしない。
249
+ if (node === null || node === undefined)
250
+ continue;
251
+ result.push({ state, actor, surface: node });
252
+ const allowed = new Set(availability.filter((a) => a.state === state && a.actor === actor && a.enabled).map((a) => a.action));
253
+ const buttons = buttonsOf(node).filter((b) => b.action !== undefined);
254
+ const shown = new Set(buttons.filter((b) => b.disabled !== true).map((b) => b.action));
255
+ for (const action of shown) {
256
+ if (!allowed.has(action))
257
+ findings.push({ kind: "surface-action-not-allowed", state, actor, action });
258
+ }
259
+ // ボタンの欠落を確かめるのは UI の画面(ui.screen)だけ。API の応答や CLI の出力には
260
+ // ボタンという概念がないので、操作に対応する要素がなくても欠落とは言えない。
261
+ if (node.kind !== "screen")
262
+ continue;
263
+ for (const action of allowed) {
264
+ if (!shown.has(action))
265
+ findings.push({ kind: "surface-action-missing", state, actor, action });
266
+ }
267
+ }
268
+ }
269
+ return result;
270
+ };
271
+ // ラベルに「状態によって値が変わる項目」だけを使う理由: authorId のように
272
+ // どの状態でも同じ値の項目まで並べると、状態を区別する情報が埋もれるため。
273
+ // 文字列の項目を先に並べるのは、status のような主たる区分を先頭に見せるため。
274
+ // initial に書いた順に並べる理由: 書き手は、読み手に最初に見せたい項目を先に書く。
275
+ // 状態の値そのもの(canonical)はキーを並べ替えて持つので、その順番は使わない。
276
+ const labeler = (all, declared) => {
277
+ const position = (k) => (declared.includes(k) ? declared.indexOf(k) : declared.length);
278
+ const keys = [...new Set(all.flatMap((v) => Object.keys(v)))]
279
+ .filter((k) => new Set(all.map((v) => JSON.stringify(v[k]))).size > 1)
280
+ .sort((a, b) => position(a) - position(b) || a.localeCompare(b));
281
+ return (values) => {
282
+ const parts = keys.flatMap((k) => {
283
+ const v = values[k];
284
+ if (typeof v === "string")
285
+ return [v];
286
+ if (typeof v === "boolean")
287
+ return v ? [k] : [];
288
+ return [`${k}=${JSON.stringify(v)}`];
289
+ });
290
+ return parts.length > 0 ? parts.join(" · ") : "初期状態";
291
+ };
292
+ };
@@ -0,0 +1,21 @@
1
+ import { type DomainObject } from "./render/html.js";
2
+ export type OutputFormat = "markdown" | "json" | "html";
3
+ export type Output = {
4
+ readonly kind: "text";
5
+ readonly content: string;
6
+ } | {
7
+ readonly kind: "files";
8
+ readonly files: Readonly<Record<string, string>>;
9
+ };
10
+ export declare const specNameOf: (path: string) => string;
11
+ export declare const expandSpecPaths: (paths: ReadonlyArray<string>) => Array<string>;
12
+ export interface LoadObjectOptions {
13
+ readonly name?: string;
14
+ readonly source?: string;
15
+ }
16
+ export declare const loadObject: (path: string, options?: LoadObjectOptions) => Promise<DomainObject>;
17
+ export declare const generateProject: (paths: ReadonlyArray<string>, format: OutputFormat, title?: string) => Promise<Output>;
18
+ export declare const failureOutput: (format: OutputFormat, paths: ReadonlyArray<string>, error: unknown) => Output;
19
+ export declare const generate: (path: string, format: OutputFormat) => Promise<string>;
20
+ export declare const writeOutput: (out: string, content: string) => Promise<void>;
21
+ export declare const writeProjectOutput: (out: string, output: Output) => Promise<void>;