@yutaura/live-spec 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/.claude-plugin/plugin.json +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +205 -2
  4. package/dist/cli.d.ts +20 -0
  5. package/dist/cli.js +219 -0
  6. package/dist/diff.d.ts +123 -0
  7. package/dist/diff.js +178 -0
  8. package/dist/ensure-scope.d.ts +9 -0
  9. package/dist/ensure-scope.js +81 -0
  10. package/dist/ensure.d.ts +9 -0
  11. package/dist/ensure.js +35 -0
  12. package/dist/explore.d.ts +25 -0
  13. package/dist/explore.js +292 -0
  14. package/dist/generate.d.ts +21 -0
  15. package/dist/generate.js +159 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +2 -0
  18. package/dist/load.d.ts +58 -0
  19. package/dist/load.js +79 -0
  20. package/dist/model.d.ts +487 -0
  21. package/dist/model.js +209 -0
  22. package/dist/mutation.d.ts +3 -0
  23. package/dist/mutation.js +51 -0
  24. package/dist/omission.d.ts +6 -0
  25. package/dist/omission.js +177 -0
  26. package/dist/project-diff.d.ts +24 -0
  27. package/dist/project-diff.js +76 -0
  28. package/dist/render/collapse.d.ts +4 -0
  29. package/dist/render/collapse.js +22 -0
  30. package/dist/render/diff-html.d.ts +2 -0
  31. package/dist/render/diff-html.js +148 -0
  32. package/dist/render/diff-markdown.d.ts +11 -0
  33. package/dist/render/diff-markdown.js +70 -0
  34. package/dist/render/ensures.d.ts +2 -0
  35. package/dist/render/ensures.js +21 -0
  36. package/dist/render/escape.d.ts +1 -0
  37. package/dist/render/escape.js +2 -0
  38. package/dist/render/html.d.ts +13 -0
  39. package/dist/render/html.js +717 -0
  40. package/dist/render/layout.d.ts +39 -0
  41. package/dist/render/layout.js +74 -0
  42. package/dist/render/markdown.d.ts +20 -0
  43. package/dist/render/markdown.js +248 -0
  44. package/dist/render/review.d.ts +17 -0
  45. package/dist/render/review.js +17 -0
  46. package/dist/render/summary.d.ts +62 -0
  47. package/dist/render/summary.js +119 -0
  48. package/dist/render/union.d.ts +23 -0
  49. package/dist/render/union.js +43 -0
  50. package/dist/render/wireframe.d.ts +3 -0
  51. package/dist/render/wireframe.js +62 -0
  52. package/dist/serve.d.ts +8 -0
  53. package/dist/serve.js +71 -0
  54. package/dist/skills.d.ts +8 -0
  55. package/dist/skills.js +20 -0
  56. package/dist/spec-loader.d.ts +2 -0
  57. package/dist/spec-loader.js +24 -0
  58. package/dist/static.d.ts +15 -0
  59. package/dist/static.js +151 -0
  60. package/dist/surface.d.ts +59 -0
  61. package/dist/surface.js +44 -0
  62. package/dist/watch.d.ts +10 -0
  63. package/dist/watch.js +47 -0
  64. package/package.json +60 -4
  65. package/skills/live-spec-authoring/SKILL.md +190 -0
  66. package/skills/live-spec-from-code/SKILL.md +93 -0
  67. package/skills/live-spec-review/SKILL.md +71 -0
@@ -0,0 +1,159 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
10
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
11
+ import { basename, dirname, join, resolve } from "node:path";
12
+ import { pathToFileURL } from "node:url";
13
+ import { explore } from "./explore.js";
14
+ import { checkEnsures } from "./mutation.js";
15
+ import { findOmissionHints } from "./omission.js";
16
+ import { unguardedId } from "./render/review.js";
17
+ import { loadSpec } from "./load.js";
18
+ import { normalize } from "./model.js";
19
+ import { renderErrorHtml, renderProjectHtml } from "./render/html.js";
20
+ import { renderIndexMarkdown, renderMarkdown } from "./render/markdown.js";
21
+ export const specNameOf = (path) => basename(path).replace(/(\.spec)?\.[cm]?ts$/, "");
22
+ // ディレクトリを渡せるようにする理由: 1 つの spec ファイルを 1 つのドメインオブジェクトとして扱うので、
23
+ // プロジェクトの仕様は複数のファイルになる。specs/ のようなディレクトリをまとめて渡せる方が自然。
24
+ export const expandSpecPaths = (paths) => paths.flatMap((p) => {
25
+ let isDir = false;
26
+ try {
27
+ isDir = statSync(p).isDirectory();
28
+ }
29
+ catch {
30
+ return [p];
31
+ }
32
+ if (!isDir)
33
+ return [p];
34
+ return readdirSync(p, { recursive: true })
35
+ .filter((f) => f.endsWith(".spec.ts") && !basename(f).startsWith("."))
36
+ .sort()
37
+ .map((f) => join(p, f));
38
+ });
39
+ // import のたびにクエリを変える理由: ESM は同じ URL のモジュールをキャッシュするので、
40
+ // --watch で spec を読み直しても古い内容のまま生成されてしまう。クエリが違えば別モジュールとして読み込まれる。
41
+ // spec から import しているファイル(共通の型など)は読み直されない点に注意。
42
+ let importVersion = 0;
43
+ // 名前とソースを外から渡せるようにしている理由: 差分を取るとき、git から取り出した spec を一時ファイルに書いて
44
+ // 読み込むので、ファイル名からではなく元の spec の名前で扱う必要があるため。
45
+ export const loadObject = async (path, options = {}) => {
46
+ const url = pathToFileURL(resolve(path));
47
+ url.search = `?v=${++importVersion}`;
48
+ const mod = (await import(__rewriteRelativeImportExtension(url.href)));
49
+ const spec = loadSpec(options.name ?? specNameOf(path), mod, { source: options.source ?? (await readFile(path, "utf8")) });
50
+ const graph = explore(spec);
51
+ const ensures = checkEnsures(spec, graph);
52
+ const omissions = findOmissionHints(spec, graph);
53
+ const known = new Set([...omissions.map((h) => h.id), ...ensures.filter((e) => e.verdict === "unguarded").map(unguardedId)]);
54
+ const unmatched = Object.keys(spec.reviewed)
55
+ .filter((id) => !known.has(id))
56
+ .map((id) => ({ kind: "reviewed-unmatched", id }));
57
+ return { spec, graph: { ...graph, ensures, omissions, findings: [...graph.findings, ...unmatched] } };
58
+ };
59
+ export const generateProject = async (paths, format, title) => {
60
+ const objects = resolveLinks(await Promise.all(paths.map((p) => loadObject(p))));
61
+ const names = objects.map((o) => o.spec.name);
62
+ const duplicated = names.find((n, i) => names.indexOf(n) !== i);
63
+ if (duplicated !== undefined)
64
+ throw new Error(`ドメインオブジェクトの名前が重複しています: ${duplicated}(spec のファイル名を変えてください)`);
65
+ const projectTitle = title ?? (objects.length === 1 ? objects[0].spec.name : projectNameOf(paths[0]));
66
+ if (format === "html")
67
+ return { kind: "text", content: await renderProjectHtml(objects, { title: projectTitle }) };
68
+ if (format === "json") {
69
+ const models = objects.map((o) => normalize(o.spec, o.graph));
70
+ return { kind: "text", content: JSON.stringify(models.length === 1 ? models[0] : { objects: models }, null, 2) };
71
+ }
72
+ if (objects.length === 1)
73
+ return { kind: "text", content: renderMarkdown(objects[0].spec, objects[0].graph) };
74
+ return {
75
+ kind: "files",
76
+ files: {
77
+ "README.md": renderIndexMarkdown(objects, projectTitle),
78
+ ...Object.fromEntries(objects.map((o) => [`${o.spec.name}.md`, renderMarkdown(o.spec, o.graph, objects)])),
79
+ },
80
+ };
81
+ };
82
+ // つながりの名前の誤りをプロジェクトを読み込んだ時点で調べる理由: 相手のドメインオブジェクトは別の spec にあり、
83
+ // 1 つの spec を探索するだけでは確かめられないため。spec が 1 つのときは相手がいないので調べない。
84
+ const resolveLinks = (objects) => objects.map((o) => {
85
+ if (objects.length < 2)
86
+ return o;
87
+ const unresolved = o.graph.links.filter((l) => {
88
+ const target = objects.find((t) => t.spec.name === l.to);
89
+ return target === undefined || (l.action !== null && !target.spec.actions.some(([n]) => n === l.action));
90
+ });
91
+ if (unresolved.length === 0)
92
+ return o;
93
+ return {
94
+ spec: o.spec,
95
+ graph: { ...o.graph, findings: [...o.graph.findings, ...unresolved.map((l) => ({ kind: "link-unresolved", to: l.to, action: l.action }))] },
96
+ };
97
+ });
98
+ // プロジェクトの名前を package.json から取る理由: spec を置くディレクトリは specs/ のような汎用の名前が多く、
99
+ // ディレクトリ名をタイトルにすると、どのプロジェクトの仕様書なのかが分からないため。
100
+ const projectNameOf = (specPath) => {
101
+ for (let dir = dirname(resolve(specPath));; dir = dirname(dir)) {
102
+ const pkg = join(dir, "package.json");
103
+ if (existsSync(pkg)) {
104
+ try {
105
+ const name = JSON.parse(readFileSync(pkg, "utf8")).name;
106
+ if (typeof name === "string" && name !== "")
107
+ return name;
108
+ }
109
+ catch {
110
+ // 壊れた package.json で生成全体を止めない。タイトルはディレクトリ名で十分に代わりになるため。
111
+ }
112
+ return basename(dir);
113
+ }
114
+ if (dirname(dir) === dir)
115
+ return basename(dirname(resolve(specPath)));
116
+ }
117
+ };
118
+ // 失敗したことを出力そのものに書く理由: Markdown や JSON を前回の内容のまま残すと、読む人が古い仕様を
119
+ // 最新だと取り違えるため(specs/watch-session.spec.ts の未決事項だったもの)。HTML はエラーページにする。
120
+ export const failureOutput = (format, paths, error) => {
121
+ const message = error instanceof Error ? error.message : String(error);
122
+ if (format === "html")
123
+ return { kind: "text", content: renderErrorHtml(paths.length === 1 ? specNameOf(paths[0]) : "仕様書", error) };
124
+ if (format === "json")
125
+ return { kind: "text", content: JSON.stringify({ error: message }, null, 2) };
126
+ const notice = [
127
+ "# 仕様書を生成できませんでした",
128
+ "",
129
+ "spec ファイルを直して保存すると、自動で生成し直します。",
130
+ "",
131
+ "```",
132
+ message,
133
+ "```",
134
+ "",
135
+ ];
136
+ if (paths.length === 1)
137
+ return { kind: "text", content: notice.join("\n") };
138
+ return {
139
+ kind: "files",
140
+ files: { "README.md": [...notice, "このディレクトリのほかのファイルは、前回の生成のままです。", ""].join("\n") },
141
+ };
142
+ };
143
+ export const generate = async (path, format) => {
144
+ const out = await generateProject([path], format);
145
+ if (out.kind !== "text")
146
+ throw new Error("1 つの spec からは 1 つのテキストが生成されるはず");
147
+ return out.content;
148
+ };
149
+ const withNewline = (content) => (content.endsWith("\n") ? content : content + "\n");
150
+ export const writeOutput = async (out, content) => {
151
+ await mkdir(dirname(out), { recursive: true });
152
+ await writeFile(out, withNewline(content));
153
+ };
154
+ export const writeProjectOutput = async (out, output) => {
155
+ if (output.kind === "text")
156
+ return writeOutput(out, output.content);
157
+ await mkdir(out, { recursive: true });
158
+ await Promise.all(Object.entries(output.files).map(([name, content]) => writeFile(join(out, name), withNewline(content))));
159
+ };
@@ -0,0 +1,2 @@
1
+ export { ensure, NotAllowed } from "./ensure.js";
2
+ export { api, cli, ui, type SurfaceNode } from "./surface.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { ensure, NotAllowed } from "./ensure.js";
2
+ export { api, cli, ui } from "./surface.js";
package/dist/load.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ import { type EnsureCall, type FieldValue } from "./static.js";
2
+ export type State = Readonly<Record<string, unknown>>;
3
+ export type ActionFn = (state: never, actor: never) => unknown;
4
+ export type InvariantFn = (state: never) => unknown;
5
+ export type SurfaceFn = (state: never, actor: never) => unknown;
6
+ export interface Question {
7
+ readonly ask: string;
8
+ readonly note?: string;
9
+ readonly about?: ActionFn | Readonly<Record<string, unknown>>;
10
+ }
11
+ export interface Link {
12
+ readonly from?: ActionFn;
13
+ readonly to: string;
14
+ readonly action?: string;
15
+ readonly label: string;
16
+ }
17
+ export interface Decision {
18
+ readonly decide: (input: never) => unknown;
19
+ readonly cases: ReadonlyArray<{
20
+ readonly input: unknown;
21
+ readonly expect?: unknown;
22
+ }>;
23
+ }
24
+ export interface ScenarioStep {
25
+ readonly do: ActionFn;
26
+ readonly by: string;
27
+ readonly input?: string;
28
+ readonly expect?: Readonly<Record<string, unknown>>;
29
+ /** この手順は断られるはず。文字列なら、その理由で断られるはず */
30
+ readonly denied?: string | true;
31
+ }
32
+ export interface Spec {
33
+ readonly name: string;
34
+ readonly initial: State;
35
+ readonly actors: ReadonlyArray<readonly [name: string, actor: unknown]>;
36
+ readonly actions: ReadonlyArray<readonly [name: string, fn: ActionFn]>;
37
+ readonly invariants: ReadonlyArray<readonly [name: string, fn: InvariantFn]>;
38
+ readonly inputs: Readonly<Record<string, ReadonlyArray<readonly [label: string, args: ReadonlyArray<unknown>]>>>;
39
+ readonly surface: SurfaceFn | null;
40
+ readonly scenarios: ReadonlyArray<readonly [name: string, steps: ReadonlyArray<ScenarioStep>]>;
41
+ readonly questions: ReadonlyArray<Question>;
42
+ readonly links: ReadonlyArray<Link>;
43
+ readonly decisions: ReadonlyArray<readonly [name: string, decision: Decision]>;
44
+ readonly docs: Readonly<Record<string, string>>;
45
+ readonly fieldDocs: Readonly<Record<string, string>>;
46
+ readonly evidence: Readonly<Record<string, ReadonlyArray<string>>>;
47
+ /** 操作ごとの ensure(静的解析で読んだもの。ソースがなければ空) */
48
+ readonly ensures: Readonly<Record<string, ReadonlyArray<EnsureCall>>>;
49
+ readonly glossary: Readonly<Record<string, string>>;
50
+ /** 確かめてほしい点のうち、人や AI が「意図どおり」と答えたもの(キーは候補の id、値はその理由) */
51
+ readonly reviewed: Readonly<Record<string, string>>;
52
+ readonly fields: Readonly<Record<string, ReadonlyArray<FieldValue>>>;
53
+ readonly stateDoc: string | null;
54
+ }
55
+ export interface LoadOptions {
56
+ readonly source?: string;
57
+ }
58
+ export declare const loadSpec: (name: string, mod: Readonly<Record<string, unknown>>, options?: LoadOptions) => Spec;
package/dist/load.js ADDED
@@ -0,0 +1,79 @@
1
+ import { analyze } from "./static.js";
2
+ const RESERVED = new Set([
3
+ "initial",
4
+ "actors",
5
+ "invariants",
6
+ "inputs",
7
+ "surface",
8
+ "scenarios",
9
+ "questions",
10
+ "links",
11
+ "glossary",
12
+ "decisions",
13
+ "reviewed",
14
+ ]);
15
+ const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
16
+ export const loadSpec = (name, mod, options = {}) => {
17
+ const { initial, actors } = mod;
18
+ if (!isRecord(initial))
19
+ throw new Error(`${name}: 初期状態を表す \`export const initial\` が必要です`);
20
+ if (!isRecord(actors))
21
+ throw new Error(`${name}: 登場人物を表す \`export const actors\` が必要です`);
22
+ const info = options.source === undefined ? undefined : analyze(options.source);
23
+ return {
24
+ name,
25
+ initial,
26
+ actors: Object.entries(actors),
27
+ actions: orderActions(Object.entries(mod).filter((e) => !RESERVED.has(e[0]) && typeof e[1] === "function"), info?.order),
28
+ invariants: isRecord(mod.invariants)
29
+ ? Object.entries(mod.invariants).filter((e) => typeof e[1] === "function")
30
+ : [],
31
+ inputs: inputsOf(mod.inputs),
32
+ surface: typeof mod.surface === "function" ? mod.surface : null,
33
+ questions: Array.isArray(mod.questions)
34
+ ? mod.questions.filter((q) => isRecord(q) && typeof q.ask === "string")
35
+ : [],
36
+ decisions: isRecord(mod.decisions)
37
+ ? Object.entries(mod.decisions).filter((e) => isRecord(e[1]) && typeof e[1].decide === "function" && Array.isArray(e[1].cases))
38
+ : [],
39
+ links: Array.isArray(mod.links)
40
+ ? mod.links.filter((l) => isRecord(l) && typeof l.to === "string" && typeof l.label === "string")
41
+ : [],
42
+ scenarios: isRecord(mod.scenarios)
43
+ ? Object.entries(mod.scenarios).filter((e) => Array.isArray(e[1]))
44
+ : [],
45
+ docs: info?.docs ?? {},
46
+ fieldDocs: info?.fieldDocs ?? {},
47
+ evidence: info?.evidence ?? {},
48
+ ensures: info?.ensures ?? {},
49
+ reviewed: isRecord(mod.reviewed)
50
+ ? Object.fromEntries(Object.entries(mod.reviewed).filter((e) => typeof e[1] === "string"))
51
+ : {},
52
+ glossary: isRecord(mod.glossary)
53
+ ? Object.fromEntries(Object.entries(mod.glossary).filter((e) => typeof e[1] === "string"))
54
+ : {},
55
+ fields: info?.fields ?? {},
56
+ stateDoc: info?.stateDoc ?? null,
57
+ };
58
+ };
59
+ // ソースの順で並べる理由: ES のモジュール名前空間オブジェクトはキーを名前順に並べるので、
60
+ // import した結果からは書かれた順が分からない。仕様書では業務の流れ(edit → submit → publish)の
61
+ // 順に操作を見せたいので、構文解析で得た export の順を使う。
62
+ // ソースがないときに名前順にするのは、実行環境(Node と Vitest など)によって順序が変わらないようにするため。
63
+ const inputsOf = (u) => {
64
+ if (!isRecord(u))
65
+ return {};
66
+ return Object.fromEntries(Object.entries(u).flatMap(([action, examples]) => isRecord(examples)
67
+ ? [[action, Object.entries(examples).filter((e) => Array.isArray(e[1]))]]
68
+ : []));
69
+ };
70
+ const orderActions = (actions, order) => {
71
+ const byName = actions.sort(([a], [b]) => a.localeCompare(b));
72
+ if (order === undefined)
73
+ return byName;
74
+ const position = (name) => {
75
+ const i = order.indexOf(name);
76
+ return i === -1 ? Number.POSITIVE_INFINITY : i;
77
+ };
78
+ return byName.sort(([a], [b]) => position(a) - position(b));
79
+ };