@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
@@ -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
+ };
package/dist/ensure.d.ts CHANGED
@@ -2,4 +2,8 @@ export declare class NotAllowed extends Error {
2
2
  readonly _tag = "NotAllowed";
3
3
  }
4
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;
5
9
  export declare const isNotAllowed: (u: unknown) => u is NotAllowed;
package/dist/ensure.js CHANGED
@@ -1,10 +1,35 @@
1
1
  export class NotAllowed extends Error {
2
2
  _tag = "NotAllowed";
3
3
  }
4
+ // 外す ensure を globalThis に Symbol.for で置く理由: spec ファイルと live-spec 本体が別々に読み込まれて
5
+ // このモジュールが 2 つ存在する場合でも、同じ設定を見られるようにするため(isNotAllowed を _tag で判定するのと同じ事情)。
6
+ const BYPASS = Symbol.for("live-spec.ensure.bypass");
4
7
  export function ensure(condition, reason) {
5
- if (!condition)
6
- throw new NotAllowed(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);
7
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);
8
33
  // instanceof ではなく _tag で判定する理由: spec ファイルと live-spec 本体が別々に
9
34
  // 読み込まれて NotAllowed クラスが 2 つ存在する場合でも、正しく判定できるようにするため。
10
35
  export const isNotAllowed = (u) => u instanceof Error && u._tag === "NotAllowed";
@@ -0,0 +1,3 @@
1
+ import type { Spec } from "./load.js";
2
+ import type { Finding } from "./model.js";
3
+ export declare const checkEvidence: (spec: Spec, specPath: string) => Array<Finding>;
@@ -0,0 +1,46 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { dirname, join, parse, resolve } from "node:path";
4
+ import { splitEvidence } from "./render/markdown.js";
5
+ const LOCATION = /^(.+?)(?::(\d+)(?:-(\d+))?)?$/;
6
+ const gitRoot = (dir) => {
7
+ try {
8
+ return execFileSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ };
14
+ // 起点の候補を順に試す理由: 既存のコードから書き起こした spec は、根拠のコードとは別の場所(別のリポジトリなど)に
15
+ // 置かれることがある。evidenceRoot を書けばそこを、書かなければ spec のある git のルート、spec の上のディレクトリを探す。
16
+ const rootsFor = (spec, specPath) => {
17
+ const specDir = dirname(resolve(specPath));
18
+ const ancestors = [];
19
+ for (let dir = specDir;; dir = dirname(dir)) {
20
+ ancestors.push(dir);
21
+ if (dir === parse(dir).root)
22
+ break;
23
+ }
24
+ if (spec.evidenceRoot !== null)
25
+ return [resolve(specDir, spec.evidenceRoot)];
26
+ const git = gitRoot(specDir);
27
+ return git === null ? ancestors : [git, ...ancestors];
28
+ };
29
+ const lineCount = (path) => readFileSync(path, "utf8").replace(/\n$/, "").split("\n").length;
30
+ export const checkEvidence = (spec, specPath) => {
31
+ const roots = rootsFor(spec, specPath);
32
+ return Object.entries(spec.evidence).flatMap(([action, items]) => items.flatMap((evidence) => {
33
+ const m = LOCATION.exec(splitEvidence(evidence).path);
34
+ if (m === null)
35
+ return [];
36
+ const [, path, start, end] = m;
37
+ const file = roots.map((root) => join(root, path)).find((p) => existsSync(p));
38
+ if (file === undefined)
39
+ return [{ kind: "evidence-missing", action, evidence }];
40
+ const last = Number(end ?? start ?? 0);
41
+ if (last === 0)
42
+ return [];
43
+ const lines = lineCount(file);
44
+ return last > lines ? [{ kind: "evidence-out-of-range", action, evidence, lines }] : [];
45
+ }));
46
+ };
package/dist/explore.d.ts CHANGED
@@ -1,6 +1,25 @@
1
- import type { Spec } from "./load.js";
1
+ import type { Spec, State } from "./load.js";
2
2
  import { type Graph } from "./model.js";
3
3
  export interface ExploreOptions {
4
4
  readonly maxStates?: number;
5
+ /** この操作の、この理由の ensure を外して探索する(ensure のミューテーション) */
6
+ readonly bypassEnsure?: {
7
+ readonly action: string;
8
+ readonly reason: string;
9
+ };
5
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;
6
24
  export declare const explore: (spec: Spec, options?: ExploreOptions) => Graph;
25
+ export {};
package/dist/explore.js CHANGED
@@ -1,8 +1,10 @@
1
- import { isNotAllowed } from "./ensure.js";
1
+ import { isNotAllowed, withEnsureBypassed } from "./ensure.js";
2
2
  import { canonical } from "./model.js";
3
3
  import { buttonsOf } from "./surface.js";
4
4
  const DEFAULT_MAX_STATES = 500;
5
- const run = (fn, state, actor, args) => {
5
+ export const runAction = (fn, state, actor, args, bypassReason) => {
6
+ if (bypassReason !== null)
7
+ return withEnsureBypassed(bypassReason, () => runAction(fn, state, actor, args, null));
6
8
  try {
7
9
  // structuredClone を渡す理由: 関数が引数を破壊的に変更しても、探索済みの状態が壊れないようにするため。
8
10
  const next = fn(structuredClone(state), structuredClone(actor), ...structuredClone(args));
@@ -28,6 +30,7 @@ const invariantHolds = (holds, values) => {
28
30
  };
29
31
  export const explore = (spec, options = {}) => {
30
32
  const maxStates = options.maxStates ?? DEFAULT_MAX_STATES;
33
+ const bypassFor = (action) => (options.bypassEnsure?.action === action ? options.bypassEnsure.reason : null);
31
34
  const ids = new Map();
32
35
  const valuesById = new Map();
33
36
  const queue = [];
@@ -77,7 +80,7 @@ export const explore = (spec, options = {}) => {
77
80
  for (const [action, fn] of runnable) {
78
81
  for (const [actor, actorValue] of spec.actors) {
79
82
  for (const [input, args] of spec.inputs[action] ?? NO_INPUT) {
80
- const outcome = run(fn, values, actorValue, args);
83
+ const outcome = runAction(fn, values, actorValue, args, bypassFor(action));
81
84
  if (outcome.kind !== "ok") {
82
85
  if (outcome.kind === "error")
83
86
  findings.push({ kind: "action-error", action, actor, state: from, message: outcome.message });
@@ -103,7 +106,7 @@ export const explore = (spec, options = {}) => {
103
106
  }
104
107
  processed.add(from);
105
108
  }
106
- const labelOf = labeler([...valuesById.values()]);
109
+ const labelOf = labeler([...valuesById.values()], Object.keys(spec.initial));
107
110
  const states = [...valuesById.entries()].map(([id, values]) => ({
108
111
  id,
109
112
  label: labelOf(values),
@@ -119,6 +122,10 @@ export const explore = (spec, options = {}) => {
119
122
  findings.push({ kind: "unreachable-value", field, value });
120
123
  }
121
124
  }
125
+ for (const [goal, holds] of spec.goals) {
126
+ if (!states.some((s) => invariantHolds(holds, s.values)))
127
+ findings.push({ kind: "goal-unreachable", goal });
128
+ }
122
129
  for (const action of missingInputs)
123
130
  findings.push({ kind: "missing-inputs", action });
124
131
  for (const action of Object.keys(spec.inputs)) {
@@ -130,7 +137,7 @@ export const explore = (spec, options = {}) => {
130
137
  findings.push({ kind: "never-enabled-action", action });
131
138
  }
132
139
  const surfaces = spec.surface === null ? [] : checkSurfaces(spec.surface, spec, [...processed], valuesById, availability, findings);
133
- const scenarios = runScenarios(spec, (values) => ids.get(JSON.stringify(values)) ?? null, findings);
140
+ const scenarios = runScenarios(spec, (values) => ids.get(JSON.stringify(values)) ?? null, findings, bypassFor);
134
141
  const questions = spec.questions.map((q) => {
135
142
  const about = q.about;
136
143
  const action = typeof about === "function" ? about.name : null;
@@ -167,13 +174,13 @@ export const explore = (spec, options = {}) => {
167
174
  const show = (v) => (typeof v === "string" ? v : JSON.stringify(v));
168
175
  // シナリオは探索とは別に、初期状態から手順どおりに実行する。探索は「到達できるか」を確かめるが、
169
176
  // シナリオは「この業務の流れが、この順番で通るか」を名指しで確かめる(受け入れテストの役割)。
170
- const runScenarios = (spec, idOf, findings) => spec.scenarios.map(([name, steps]) => {
177
+ const runScenarios = (spec, idOf, findings, bypassFor) => spec.scenarios.map(([name, steps]) => {
171
178
  let values = canonical(spec.initial);
172
179
  const records = [];
173
180
  for (const [i, step] of steps.entries()) {
174
181
  const action = step.do.name;
175
182
  const fail = (reason) => {
176
- records.push({ action, actor: step.by, input: step.input ?? null, from: idOf(values), to: null, ok: false, reason });
183
+ records.push({ action, actor: step.by, input: step.input ?? null, from: idOf(values), to: null, ok: false, reason, denied: step.denied !== undefined });
177
184
  findings.push({ kind: "scenario-failed", scenario: name, step: i + 1, reason });
178
185
  };
179
186
  const actor = spec.actors.find(([n]) => n === step.by);
@@ -195,7 +202,24 @@ const runScenarios = (spec, idOf, findings) => spec.scenarios.map(([name, steps]
195
202
  fail("この操作には入力の例(input)を指定する");
196
203
  break;
197
204
  }
198
- const outcome = run(step.do, values, actor[1], args);
205
+ const outcome = runAction(step.do, values, actor[1], args, bypassFor(action));
206
+ if (step.denied !== undefined) {
207
+ if (outcome.kind === "ok") {
208
+ fail("断られるはずが、実行できた");
209
+ break;
210
+ }
211
+ if (outcome.kind !== "not-allowed") {
212
+ fail(outcome.kind === "error" ? `例外: ${outcome.message}` : "オブジェクトを返さなかった");
213
+ break;
214
+ }
215
+ if (typeof step.denied === "string" && outcome.reason !== step.denied) {
216
+ fail(`断られる理由が違う: 期待「${step.denied}」、実際「${outcome.reason}」`);
217
+ break;
218
+ }
219
+ const here = idOf(values);
220
+ records.push({ action, actor: step.by, input: step.input ?? null, from: here, to: here, ok: true, reason: outcome.reason, denied: true });
221
+ continue;
222
+ }
199
223
  if (outcome.kind !== "ok") {
200
224
  fail(outcome.kind === "not-allowed" ? outcome.reason : outcome.kind === "error" ? `例外: ${outcome.message}` : "オブジェクトを返さなかった");
201
225
  break;
@@ -206,7 +230,7 @@ const runScenarios = (spec, idOf, findings) => spec.scenarios.map(([name, steps]
206
230
  fail(`期待: ${k} = ${show(v)}、実際: ${k} = ${show(outcome.next[k])}`);
207
231
  break;
208
232
  }
209
- records.push({ action, actor: step.by, input: step.input ?? null, from: idOf(values), to: idOf(outcome.next), ok: true, reason: null });
233
+ records.push({ action, actor: step.by, input: step.input ?? null, from: idOf(values), to: idOf(outcome.next), ok: true, reason: null, denied: false });
210
234
  values = outcome.next;
211
235
  }
212
236
  return { name, passed: records.length === steps.length && records.every((r) => r.ok), steps: records };
@@ -251,10 +275,13 @@ const checkSurfaces = (surface, spec, states, valuesById, availability, findings
251
275
  // ラベルに「状態によって値が変わる項目」だけを使う理由: authorId のように
252
276
  // どの状態でも同じ値の項目まで並べると、状態を区別する情報が埋もれるため。
253
277
  // 文字列の項目を先に並べるのは、status のような主たる区分を先頭に見せるため。
254
- const labeler = (all) => {
278
+ // initial に書いた順に並べる理由: 書き手は、読み手に最初に見せたい項目を先に書く。
279
+ // 状態の値そのもの(canonical)はキーを並べ替えて持つので、その順番は使わない。
280
+ const labeler = (all, declared) => {
281
+ const position = (k) => (declared.includes(k) ? declared.indexOf(k) : declared.length);
255
282
  const keys = [...new Set(all.flatMap((v) => Object.keys(v)))]
256
283
  .filter((k) => new Set(all.map((v) => JSON.stringify(v[k]))).size > 1)
257
- .sort((a, b) => rank(all[0][a]) - rank(all[0][b]) || a.localeCompare(b));
284
+ .sort((a, b) => position(a) - position(b) || a.localeCompare(b));
258
285
  return (values) => {
259
286
  const parts = keys.flatMap((k) => {
260
287
  const v = values[k];
@@ -267,4 +294,3 @@ const labeler = (all) => {
267
294
  return parts.length > 0 ? parts.join(" · ") : "初期状態";
268
295
  };
269
296
  };
270
- const rank = (v) => (typeof v === "string" ? 0 : typeof v === "boolean" ? 1 : 2);
@@ -1,3 +1,4 @@
1
+ import { type DomainObject } from "./render/html.js";
1
2
  export type OutputFormat = "markdown" | "json" | "html";
2
3
  export type Output = {
3
4
  readonly kind: "text";
@@ -8,7 +9,13 @@ export type Output = {
8
9
  };
9
10
  export declare const specNameOf: (path: string) => string;
10
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>;
11
17
  export declare const generateProject: (paths: ReadonlyArray<string>, format: OutputFormat, title?: string) => Promise<Output>;
18
+ export declare const resolveLinks: (objects: ReadonlyArray<DomainObject>) => Array<DomainObject>;
12
19
  export declare const failureOutput: (format: OutputFormat, paths: ReadonlyArray<string>, error: unknown) => Output;
13
20
  export declare const generate: (path: string, format: OutputFormat) => Promise<string>;
14
21
  export declare const writeOutput: (out: string, content: string) => Promise<void>;
package/dist/generate.js CHANGED
@@ -11,6 +11,10 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
11
11
  import { basename, dirname, join, resolve } from "node:path";
12
12
  import { pathToFileURL } from "node:url";
13
13
  import { explore } from "./explore.js";
14
+ import { checkEvidence } from "./evidence.js";
15
+ import { checkEnsures } from "./mutation.js";
16
+ import { findOmissionHints } from "./omission.js";
17
+ import { unguardedId } from "./render/review.js";
14
18
  import { loadSpec } from "./load.js";
15
19
  import { normalize } from "./model.js";
16
20
  import { renderErrorHtml, renderProjectHtml } from "./render/html.js";
@@ -37,15 +41,24 @@ export const expandSpecPaths = (paths) => paths.flatMap((p) => {
37
41
  // --watch で spec を読み直しても古い内容のまま生成されてしまう。クエリが違えば別モジュールとして読み込まれる。
38
42
  // spec から import しているファイル(共通の型など)は読み直されない点に注意。
39
43
  let importVersion = 0;
40
- const loadObject = async (path) => {
44
+ // 名前とソースを外から渡せるようにしている理由: 差分を取るとき、git から取り出した spec を一時ファイルに書いて
45
+ // 読み込むので、ファイル名からではなく元の spec の名前で扱う必要があるため。
46
+ export const loadObject = async (path, options = {}) => {
41
47
  const url = pathToFileURL(resolve(path));
42
48
  url.search = `?v=${++importVersion}`;
43
49
  const mod = (await import(__rewriteRelativeImportExtension(url.href)));
44
- const spec = loadSpec(specNameOf(path), mod, { source: await readFile(path, "utf8") });
45
- return { spec, graph: explore(spec) };
50
+ const spec = loadSpec(options.name ?? specNameOf(path), mod, { source: options.source ?? (await readFile(path, "utf8")) });
51
+ const graph = explore(spec);
52
+ const ensures = checkEnsures(spec, graph);
53
+ const omissions = findOmissionHints(spec, graph);
54
+ const known = new Set([...omissions.map((h) => h.id), ...ensures.filter((e) => e.verdict === "unguarded").map(unguardedId)]);
55
+ const unmatched = Object.keys(spec.reviewed)
56
+ .filter((id) => !known.has(id))
57
+ .map((id) => ({ kind: "reviewed-unmatched", id }));
58
+ return { spec, graph: { ...graph, ensures, omissions, findings: [...graph.findings, ...checkEvidence(spec, path), ...unmatched] } };
46
59
  };
47
60
  export const generateProject = async (paths, format, title) => {
48
- const objects = resolveLinks(await Promise.all(paths.map(loadObject)));
61
+ const objects = resolveLinks(await Promise.all(paths.map((p) => loadObject(p))));
49
62
  const names = objects.map((o) => o.spec.name);
50
63
  const duplicated = names.find((n, i) => names.indexOf(n) !== i);
51
64
  if (duplicated !== undefined)
@@ -69,7 +82,7 @@ export const generateProject = async (paths, format, title) => {
69
82
  };
70
83
  // つながりの名前の誤りをプロジェクトを読み込んだ時点で調べる理由: 相手のドメインオブジェクトは別の spec にあり、
71
84
  // 1 つの spec を探索するだけでは確かめられないため。spec が 1 つのときは相手がいないので調べない。
72
- const resolveLinks = (objects) => objects.map((o) => {
85
+ export const resolveLinks = (objects) => objects.map((o) => {
73
86
  if (objects.length < 2)
74
87
  return o;
75
88
  const unresolved = o.graph.links.filter((l) => {
package/dist/load.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type FieldValue } from "./static.js";
1
+ import { type EnsureCall, type FieldValue } from "./static.js";
2
2
  export type State = Readonly<Record<string, unknown>>;
3
3
  export type ActionFn = (state: never, actor: never) => unknown;
4
4
  export type InvariantFn = (state: never) => unknown;
@@ -26,6 +26,8 @@ export interface ScenarioStep {
26
26
  readonly by: string;
27
27
  readonly input?: string;
28
28
  readonly expect?: Readonly<Record<string, unknown>>;
29
+ /** この手順は断られるはず。文字列なら、その理由で断られるはず */
30
+ readonly denied?: string | true;
29
31
  }
30
32
  export interface Spec {
31
33
  readonly name: string;
@@ -33,6 +35,8 @@ export interface Spec {
33
35
  readonly actors: ReadonlyArray<readonly [name: string, actor: unknown]>;
34
36
  readonly actions: ReadonlyArray<readonly [name: string, fn: ActionFn]>;
35
37
  readonly invariants: ReadonlyArray<readonly [name: string, fn: InvariantFn]>;
38
+ /** 目指す状態。たどり着けない状態(袋小路)を見つけるのに使う */
39
+ readonly goals: ReadonlyArray<readonly [name: string, fn: InvariantFn]>;
36
40
  readonly inputs: Readonly<Record<string, ReadonlyArray<readonly [label: string, args: ReadonlyArray<unknown>]>>>;
37
41
  readonly surface: SurfaceFn | null;
38
42
  readonly scenarios: ReadonlyArray<readonly [name: string, steps: ReadonlyArray<ScenarioStep>]>;
@@ -42,7 +46,13 @@ export interface Spec {
42
46
  readonly docs: Readonly<Record<string, string>>;
43
47
  readonly fieldDocs: Readonly<Record<string, string>>;
44
48
  readonly evidence: Readonly<Record<string, ReadonlyArray<string>>>;
49
+ /** 根拠のパスを解決する起点(spec のファイルからの相対)。無ければ git のルートなどから探す */
50
+ readonly evidenceRoot: string | null;
51
+ /** 操作ごとの ensure(静的解析で読んだもの。ソースがなければ空) */
52
+ readonly ensures: Readonly<Record<string, ReadonlyArray<EnsureCall>>>;
45
53
  readonly glossary: Readonly<Record<string, string>>;
54
+ /** 確かめてほしい点のうち、人や AI が「意図どおり」と答えたもの(キーは候補の id、値はその理由) */
55
+ readonly reviewed: Readonly<Record<string, string>>;
46
56
  readonly fields: Readonly<Record<string, ReadonlyArray<FieldValue>>>;
47
57
  readonly stateDoc: string | null;
48
58
  }
package/dist/load.js CHANGED
@@ -10,6 +10,9 @@ const RESERVED = new Set([
10
10
  "links",
11
11
  "glossary",
12
12
  "decisions",
13
+ "reviewed",
14
+ "goals",
15
+ "evidenceRoot",
13
16
  ]);
14
17
  const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
15
18
  export const loadSpec = (name, mod, options = {}) => {
@@ -27,6 +30,7 @@ export const loadSpec = (name, mod, options = {}) => {
27
30
  invariants: isRecord(mod.invariants)
28
31
  ? Object.entries(mod.invariants).filter((e) => typeof e[1] === "function")
29
32
  : [],
33
+ goals: isRecord(mod.goals) ? Object.entries(mod.goals).filter((e) => typeof e[1] === "function") : [],
30
34
  inputs: inputsOf(mod.inputs),
31
35
  surface: typeof mod.surface === "function" ? mod.surface : null,
32
36
  questions: Array.isArray(mod.questions)
@@ -44,6 +48,11 @@ export const loadSpec = (name, mod, options = {}) => {
44
48
  docs: info?.docs ?? {},
45
49
  fieldDocs: info?.fieldDocs ?? {},
46
50
  evidence: info?.evidence ?? {},
51
+ evidenceRoot: typeof mod.evidenceRoot === "string" ? mod.evidenceRoot : null,
52
+ ensures: info?.ensures ?? {},
53
+ reviewed: isRecord(mod.reviewed)
54
+ ? Object.fromEntries(Object.entries(mod.reviewed).filter((e) => typeof e[1] === "string"))
55
+ : {},
47
56
  glossary: isRecord(mod.glossary)
48
57
  ? Object.fromEntries(Object.entries(mod.glossary).filter((e) => typeof e[1] === "string"))
49
58
  : {},