operbe 0.0.0-stage → 1.0.0-rc.2

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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +106 -2
  3. package/conformance/describe/edge/body.json +1 -0
  4. package/conformance/describe/edge/digest +1 -0
  5. package/conformance/describe/edge/project/acme/architecture.md +18 -0
  6. package/conformance/describe/edge/project/behaviors/B-7.md +15 -0
  7. package/conformance/describe/edge/project/behaviors/coverage/web.md +8 -0
  8. package/conformance/describe/edge/project/operations/broken-file.md +1 -0
  9. package/conformance/describe/edge/project/operations/read-note.md +4 -0
  10. package/conformance/describe/edge/project/operations/send-note.md +20 -0
  11. package/conformance/describe/edge/project/operbe.md +15 -0
  12. package/conformance/describe/example/body.json +1 -0
  13. package/conformance/describe/example/digest +1 -0
  14. package/conformance/describe/example/project/behaviors/B-0001.md +36 -0
  15. package/conformance/describe/example/project/behaviors/B-0002.md +21 -0
  16. package/conformance/describe/example/project/behaviors/B-0003.md +19 -0
  17. package/conformance/describe/example/project/behaviors/B-0004.md +18 -0
  18. package/conformance/describe/example/project/behaviors/B-0005.md +18 -0
  19. package/conformance/describe/example/project/behaviors/coverage/desktop.md +8 -0
  20. package/conformance/describe/example/project/behaviors/coverage/phone.md +12 -0
  21. package/conformance/describe/example/project/client-actions/archive-conversation.md +22 -0
  22. package/conformance/describe/example/project/client-actions/show-conversations.md +21 -0
  23. package/conformance/describe/example/project/client-actions/start-retitle.md +22 -0
  24. package/conformance/describe/example/project/client-actions/unarchive-conversation.md +21 -0
  25. package/conformance/describe/example/project/operations/archive-conversation.md +16 -0
  26. package/conformance/describe/example/project/operations/list-conversations.md +16 -0
  27. package/conformance/describe/example/project/operations/set-conversation-title.md +16 -0
  28. package/conformance/describe/example/project/operations/unarchive-conversation.md +16 -0
  29. package/conformance/describe/example/project/operbe.md +15 -0
  30. package/conformance/diff/core/a/behaviors/B-0001.md +36 -0
  31. package/conformance/diff/core/a/behaviors/B-0002.md +21 -0
  32. package/conformance/diff/core/a/behaviors/B-0003.md +19 -0
  33. package/conformance/diff/core/a/behaviors/B-0004.md +18 -0
  34. package/conformance/diff/core/a/behaviors/B-0005.md +18 -0
  35. package/conformance/diff/core/a/behaviors/coverage/desktop.md +8 -0
  36. package/conformance/diff/core/a/behaviors/coverage/phone.md +12 -0
  37. package/conformance/diff/core/a/client-actions/archive-conversation.md +22 -0
  38. package/conformance/diff/core/a/client-actions/show-conversations.md +21 -0
  39. package/conformance/diff/core/a/client-actions/start-retitle.md +22 -0
  40. package/conformance/diff/core/a/client-actions/unarchive-conversation.md +21 -0
  41. package/conformance/diff/core/a/operations/archive-conversation.md +16 -0
  42. package/conformance/diff/core/a/operations/list-conversations.md +16 -0
  43. package/conformance/diff/core/a/operations/set-conversation-title.md +16 -0
  44. package/conformance/diff/core/a/operations/unarchive-conversation.md +16 -0
  45. package/conformance/diff/core/a/operbe.md +15 -0
  46. package/conformance/diff/core/b/behaviors/B-0001.md +36 -0
  47. package/conformance/diff/core/b/behaviors/B-0002.md +22 -0
  48. package/conformance/diff/core/b/behaviors/B-0003.md +19 -0
  49. package/conformance/diff/core/b/behaviors/B-0004.md +18 -0
  50. package/conformance/diff/core/b/behaviors/B-0005.md +18 -0
  51. package/conformance/diff/core/b/behaviors/coverage/desktop.md +8 -0
  52. package/conformance/diff/core/b/behaviors/coverage/phone.md +12 -0
  53. package/conformance/diff/core/b/client-actions/archive-conversation.md +22 -0
  54. package/conformance/diff/core/b/client-actions/show-conversations.md +21 -0
  55. package/conformance/diff/core/b/client-actions/unarchive-conversation.md +21 -0
  56. package/conformance/diff/core/b/operations/archive-conversation.md +16 -0
  57. package/conformance/diff/core/b/operations/list-conversations.md +16 -0
  58. package/conformance/diff/core/b/operations/set-conversation-name.md +16 -0
  59. package/conformance/diff/core/b/operations/unarchive-conversation.md +16 -0
  60. package/conformance/diff/core/b/operbe.md +16 -0
  61. package/conformance/diff/core/changes.json +192 -0
  62. package/conformance/diff/declared/a/acme/architecture.md +18 -0
  63. package/conformance/diff/declared/a/behaviors/B-7.md +15 -0
  64. package/conformance/diff/declared/a/behaviors/coverage/web.md +8 -0
  65. package/conformance/diff/declared/a/operations/broken-file.md +1 -0
  66. package/conformance/diff/declared/a/operations/read-note.md +4 -0
  67. package/conformance/diff/declared/a/operations/send-note.md +20 -0
  68. package/conformance/diff/declared/a/operbe.md +15 -0
  69. package/conformance/diff/declared/b/acme/architecture.md +18 -0
  70. package/conformance/diff/declared/b/behaviors/B-7.md +15 -0
  71. package/conformance/diff/declared/b/behaviors/coverage/web.md +8 -0
  72. package/conformance/diff/declared/b/operations/broken-file.md +1 -0
  73. package/conformance/diff/declared/b/operations/read-note.md +5 -0
  74. package/conformance/diff/declared/b/operations/send-note.md +19 -0
  75. package/conformance/diff/declared/b/operbe.md +15 -0
  76. package/conformance/diff/declared/changes.json +73 -0
  77. package/conformance/diff/reworded/a/behaviors/B-0001.md +36 -0
  78. package/conformance/diff/reworded/a/behaviors/B-0002.md +21 -0
  79. package/conformance/diff/reworded/a/behaviors/B-0003.md +19 -0
  80. package/conformance/diff/reworded/a/behaviors/B-0004.md +18 -0
  81. package/conformance/diff/reworded/a/behaviors/B-0005.md +18 -0
  82. package/conformance/diff/reworded/a/behaviors/coverage/desktop.md +8 -0
  83. package/conformance/diff/reworded/a/behaviors/coverage/phone.md +12 -0
  84. package/conformance/diff/reworded/a/client-actions/archive-conversation.md +22 -0
  85. package/conformance/diff/reworded/a/client-actions/show-conversations.md +21 -0
  86. package/conformance/diff/reworded/a/client-actions/start-retitle.md +22 -0
  87. package/conformance/diff/reworded/a/client-actions/unarchive-conversation.md +21 -0
  88. package/conformance/diff/reworded/a/operations/archive-conversation.md +16 -0
  89. package/conformance/diff/reworded/a/operations/list-conversations.md +16 -0
  90. package/conformance/diff/reworded/a/operations/set-conversation-title.md +16 -0
  91. package/conformance/diff/reworded/a/operations/unarchive-conversation.md +16 -0
  92. package/conformance/diff/reworded/a/operbe.md +18 -0
  93. package/conformance/diff/reworded/b/behaviors/B-0001.md +36 -0
  94. package/conformance/diff/reworded/b/behaviors/B-0002.md +21 -0
  95. package/conformance/diff/reworded/b/behaviors/B-0003.md +19 -0
  96. package/conformance/diff/reworded/b/behaviors/B-0004.md +18 -0
  97. package/conformance/diff/reworded/b/behaviors/B-0005.md +18 -0
  98. package/conformance/diff/reworded/b/behaviors/coverage/desktop.md +8 -0
  99. package/conformance/diff/reworded/b/behaviors/coverage/phone.md +12 -0
  100. package/conformance/diff/reworded/b/client-actions/archive-conversation.md +22 -0
  101. package/conformance/diff/reworded/b/client-actions/show-conversations.md +21 -0
  102. package/conformance/diff/reworded/b/client-actions/start-retitle.md +22 -0
  103. package/conformance/diff/reworded/b/client-actions/unarchive-conversation.md +21 -0
  104. package/conformance/diff/reworded/b/operations/archive-conversation.md +16 -0
  105. package/conformance/diff/reworded/b/operations/list-conversations.md +16 -0
  106. package/conformance/diff/reworded/b/operations/set-conversation-title.md +16 -0
  107. package/conformance/diff/reworded/b/operations/unarchive-conversation.md +16 -0
  108. package/conformance/diff/reworded/b/operbe.md +18 -0
  109. package/conformance/diff/reworded/changes.json +43 -0
  110. package/dist/check.d.ts +21 -0
  111. package/dist/check.js +422 -0
  112. package/dist/cli.d.ts +2 -0
  113. package/dist/cli.js +272 -0
  114. package/dist/describe.d.ts +22 -0
  115. package/dist/describe.js +201 -0
  116. package/dist/diff.d.ts +13 -0
  117. package/dist/diff.js +249 -0
  118. package/dist/findings.d.ts +11 -0
  119. package/dist/findings.js +6 -0
  120. package/dist/index.d.ts +19 -0
  121. package/dist/index.js +11 -0
  122. package/dist/indexes.d.ts +2 -0
  123. package/dist/indexes.js +27 -0
  124. package/dist/jcs.d.ts +1 -0
  125. package/dist/jcs.js +16 -0
  126. package/dist/jj.d.ts +12 -0
  127. package/dist/jj.js +82 -0
  128. package/dist/read.d.ts +83 -0
  129. package/dist/read.js +249 -0
  130. package/dist/reconcile.d.ts +9 -0
  131. package/dist/reconcile.js +46 -0
  132. package/dist/source.d.ts +5 -0
  133. package/dist/source.js +29 -0
  134. package/dist/version.d.ts +1 -0
  135. package/dist/version.js +2 -0
  136. package/package.json +40 -4
  137. package/schema/description.schema.json +481 -0
  138. package/skills/operbe/SKILL.md +69 -0
  139. package/skills/operbe/example/behaviors/B-0001.md +36 -0
  140. package/skills/operbe/example/behaviors/B-0002.md +21 -0
  141. package/skills/operbe/example/behaviors/B-0003.md +19 -0
  142. package/skills/operbe/example/behaviors/B-0004.md +18 -0
  143. package/skills/operbe/example/behaviors/B-0005.md +18 -0
  144. package/skills/operbe/example/behaviors/coverage/desktop.md +8 -0
  145. package/skills/operbe/example/behaviors/coverage/phone.md +12 -0
  146. package/skills/operbe/example/client-actions/archive-conversation.md +22 -0
  147. package/skills/operbe/example/client-actions/show-conversations.md +21 -0
  148. package/skills/operbe/example/client-actions/start-retitle.md +22 -0
  149. package/skills/operbe/example/client-actions/unarchive-conversation.md +21 -0
  150. package/skills/operbe/example/operations/archive-conversation.md +16 -0
  151. package/skills/operbe/example/operations/list-conversations.md +16 -0
  152. package/skills/operbe/example/operations/set-conversation-title.md +16 -0
  153. package/skills/operbe/example/operations/unarchive-conversation.md +16 -0
  154. package/skills/operbe/example/operbe.md +15 -0
  155. package/skills/operbe/references/adopting.md +48 -0
  156. package/skills/operbe/references/behaviors.md +168 -0
  157. package/skills/operbe/references/client-actions.md +211 -0
  158. package/skills/operbe/references/formats.md +408 -0
  159. package/skills/operbe/references/operations.md +146 -0
  160. package/skills/operbe/references/tandem.md +69 -0
  161. package/skills/operbe/templates/behavior.md +18 -0
  162. package/skills/operbe/templates/client-action.md +20 -0
  163. package/skills/operbe/templates/coverage.md +4 -0
  164. package/skills/operbe/templates/operation.md +14 -0
  165. package/skills/operbe/templates/operbe.md +10 -0
package/dist/cli.js ADDED
@@ -0,0 +1,272 @@
1
+ #!/usr/bin/env node
2
+ // The operbe command line. Its output and exit codes are API (formats.md, "The command line"):
3
+ // 0 no errors (gaps never fail)
4
+ // 1 the project has errors (check, reconcile), or a change at the --fail-on level (diff)
5
+ // 2 the command itself was wrong: an unknown command or option, a file that can't be read,
6
+ // jj missing or a revision that doesn't name exactly one commit (--at)
7
+ //
8
+ // Never process.exit() once output is written: it cuts off what a pipe hasn't taken yet (64 KB).
9
+ // Each command sets process.exitCode and returns.
10
+ import { readFileSync, statSync } from "node:fs";
11
+ import { check, counts, summary } from "./check.js";
12
+ import { bodyBytes, describe, parseDescription } from "./describe.js";
13
+ import { diff, diffSummary } from "./diff.js";
14
+ import { formatFinding, sortFindings } from "./findings.js";
15
+ import { renderIndex } from "./indexes.js";
16
+ import { jcs } from "./jcs.js";
17
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
18
+ import { dirname, join } from "node:path";
19
+ import { read } from "./read.js";
20
+ import { reconcile } from "./reconcile.js";
21
+ import { folderSource } from "./source.js";
22
+ const USAGE = `usage: operbe check [root] [--at <rev>] [--json]
23
+ operbe describe [root] [--at <rev>] [--body | --pretty]
24
+ operbe diff <side> <side> [--root <root>] [--fail-on breaking|warning] [--json]
25
+ a side is a description file, a project folder, or --at <rev> (the project at --root, default .)
26
+ operbe reconcile [root] --kind operation|client-action [--ui <ui>] [--via <field>] --names <file|-> [--json]
27
+ operbe index [root] [--at <rev>]
28
+ operbe new operation|client-action <name> [root]
29
+ operbe new behavior "<behavior name>" [root]
30
+ operbe schema
31
+ --at reads a jj revision without snapshotting the working copy: --at @ is the last snapshot,
32
+ not unsaved edits since (run any jj command first to snapshot them).`;
33
+ // Usage mistakes print the usage; trouble with a file, jj or a revision prints only what went wrong.
34
+ const fail = (msg, usage = true) => { console.error(usage ? `${msg}\n${USAGE}` : `operbe: ${msg}`); process.exit(2); };
35
+ // Options: --flag (on/off) or --key value. Which are allowed depends on the command.
36
+ const OPTIONS = {
37
+ check: { flags: ["--json"], values: ["--at"] },
38
+ describe: { flags: ["--body", "--pretty"], values: ["--at"] },
39
+ diff: { flags: ["--json"], values: ["--fail-on", "--root", "--at"] },
40
+ reconcile: { flags: ["--json"], values: ["--kind", "--ui", "--via", "--names"] },
41
+ schema: { flags: [], values: [] },
42
+ index: { flags: [], values: ["--at"] },
43
+ new: { flags: [], values: [] },
44
+ };
45
+ const [cmd, ...args] = process.argv.slice(2);
46
+ // --help or -h anywhere, on any command (or alone): the usage, on stdout, exit 0.
47
+ if ([cmd, ...args].some((a) => a === "--help" || a === "-h")) {
48
+ console.log(USAGE);
49
+ process.exit(0);
50
+ }
51
+ const allowed = OPTIONS[cmd ?? ""] ?? fail(cmd ? `unknown command '${cmd}'` : "no command");
52
+ const flags = new Set(), values = {}, positional = [];
53
+ // diff's sides, in the order written: a path, or a revision (--at). --at may come twice only for diff.
54
+ const sides = [];
55
+ for (let i = 0; i < args.length; i++) {
56
+ const a = args[i];
57
+ if (!a.startsWith("--")) {
58
+ positional.push(a);
59
+ sides.push({ path: a });
60
+ }
61
+ else if (allowed.flags.includes(a))
62
+ flags.add(a);
63
+ else if (allowed.values.includes(a)) {
64
+ const v = args[++i] ?? fail(`${a} needs a value`);
65
+ if (a === "--at") {
66
+ if (cmd !== "diff" && values[a])
67
+ fail("--at may be given once");
68
+ sides.push({ at: v });
69
+ }
70
+ values[a] = v;
71
+ }
72
+ else
73
+ fail(`unknown option '${a}'`);
74
+ }
75
+ const most = cmd === "new" ? 3 : 1;
76
+ if (cmd === "diff" ? sides.length !== 2 : positional.length > most)
77
+ fail(cmd === "diff" ? "diff takes two sides" : "one project root at most");
78
+ async function load(root, rev, empty = false) {
79
+ let l;
80
+ if (rev === undefined) {
81
+ if (!existsSync(root))
82
+ fail(`no such folder: ${root}`, false);
83
+ l = { model: read(folderSource(root)), findings: [] };
84
+ }
85
+ else {
86
+ const { jjSource, JjError } = await import("./jj.js");
87
+ try {
88
+ const j = jjSource(root, rev);
89
+ l = { model: read(j.source), findings: j.findings, at: { rev: j.rev, commit: j.commit, change: j.change } };
90
+ }
91
+ catch (e) {
92
+ if (e instanceof JjError)
93
+ fail(e.message, false);
94
+ throw e;
95
+ }
96
+ }
97
+ if (!l.model.profile && !empty)
98
+ fail(`${root} has no operbe.md${rev === undefined ? "" : ` at ${rev}`}; is it the project's root?`, false);
99
+ return l;
100
+ }
101
+ // The jj ids go beside the output (stderr), never into it: describe --at prints exactly what
102
+ // describe prints for a plain checkout of that commit.
103
+ const tellAt = (l) => { if (l.at)
104
+ console.error(`operbe: --at ${l.at.rev} is commit ${l.at.commit}, change ${l.at.change}`); };
105
+ const findingsOf = (l) => [...l.findings, ...check(l.model)];
106
+ if (cmd === "schema")
107
+ process.stdout.write(readFileSync(new URL("../schema/description.schema.json", import.meta.url), "utf8"));
108
+ // index: the behavior index, the coverage table and the client action index, printed (never committed).
109
+ else if (cmd === "index") {
110
+ const l = await load(positional[0] ?? ".", values["--at"]);
111
+ tellAt(l);
112
+ process.stdout.write(renderIndex(l.model));
113
+ }
114
+ // new: a record from the template, in the folder the profile names. A behavior gets the next free
115
+ // B- number in this working copy; if a parallel change took the same number, the merge conflicts
116
+ // and the one not yet merged is renumbered.
117
+ else if (cmd === "new") {
118
+ const [kind, name, root = "."] = positional;
119
+ if (kind !== "operation" && kind !== "behavior" && kind !== "client-action")
120
+ fail("new makes an operation, a behavior or a client-action");
121
+ if (!name)
122
+ fail(`new ${kind} needs a name`);
123
+ if (kind !== "behavior" && !/^[a-z0-9]+(-[a-z0-9]+)+$/.test(name))
124
+ fail(`'${name}': a name is lowercase words joined by hyphens, a verb then the thing`, false);
125
+ const m = read(folderSource(root));
126
+ if (!m.profile)
127
+ fail(`${root} has no operbe.md`, false);
128
+ const folder = kind === "operation" ? m.folders.operations : kind === "behavior" ? m.folders.behaviors : m.folders.clientActions;
129
+ if (!folder)
130
+ fail("this project keeps no client actions (operbe.md has no client-actions line)", false);
131
+ let template = readFileSync(new URL(`../skills/operbe/templates/${kind}.md`, import.meta.url), "utf8");
132
+ let stem = name;
133
+ if (kind === "behavior") {
134
+ if (m.behaviors.some((r) => r.fields.name?.value === name))
135
+ fail(`a behavior is already named '${name}'`, false);
136
+ // The next number, at least four digits like the ones already there.
137
+ const nums = m.behaviors.map((r) => r.stem.match(/^B-(\d+)$/)?.[1]).filter((x) => !!x);
138
+ const next = String(Math.max(0, ...nums.map(Number)) + 1).padStart(Math.max(4, ...nums.map((x) => x.length)), "0");
139
+ stem = `B-${next}`;
140
+ template = template.replace(/^id:.*$/m, `id: ${stem}`).replace(/^name:.*$/m, `name: ${name}`);
141
+ }
142
+ else
143
+ template = template.replace(/^name:.*$/m, `name: ${name}`);
144
+ const file = join(root, folder, `${stem}.md`);
145
+ if (existsSync(file))
146
+ fail(`${file} already exists`, false);
147
+ mkdirSync(dirname(file), { recursive: true });
148
+ writeFileSync(file, template);
149
+ console.log(file);
150
+ }
151
+ // describe: prints the description and exits 0 even when it holds errors; check is what fails.
152
+ // default the description as JCS (one line, canonical)
153
+ // --body exactly the bytes the digest is over, no newline: `operbe describe --body | shasum -a 256`
154
+ // --pretty indented, for people
155
+ else if (cmd === "describe") {
156
+ if (flags.has("--body") && flags.has("--pretty"))
157
+ fail("--body and --pretty don't go together");
158
+ const l = await load(positional[0] ?? ".", values["--at"]);
159
+ tellAt(l);
160
+ const d = describe(l.model, findingsOf(l));
161
+ process.stdout.write(flags.has("--body") ? bodyBytes(d.body) : flags.has("--pretty") ? JSON.stringify(d, null, 2) + "\n" : jcs(d) + "\n");
162
+ }
163
+ // diff: exit 1 only when --fail-on is given and a change reaches that level.
164
+ else if (cmd === "diff") {
165
+ const failOn = values["--fail-on"];
166
+ if (failOn !== undefined && failOn !== "breaking" && failOn !== "warning")
167
+ fail("--fail-on must be breaking or warning");
168
+ // A side is a description file (what describe printed), a project folder, or a revision.
169
+ const side = async (s) => {
170
+ if ("at" in s) {
171
+ const l = await load(values["--root"] ?? ".", s.at, true);
172
+ return { d: describe(l.model, findingsOf(l)), at: l.at };
173
+ }
174
+ let isDir = false;
175
+ try {
176
+ isDir = statSync(s.path).isDirectory();
177
+ }
178
+ catch {
179
+ fail(`no such file or folder: ${s.path}`, false);
180
+ }
181
+ if (isDir) {
182
+ const l = await load(s.path);
183
+ return { d: describe(l.model, findingsOf(l)) };
184
+ }
185
+ let text = "";
186
+ try {
187
+ text = readFileSync(s.path, "utf8");
188
+ }
189
+ catch (e) {
190
+ fail(`can't read ${s.path}: ${e.message}`, false);
191
+ }
192
+ try {
193
+ return { d: parseDescription(text) };
194
+ }
195
+ catch (e) {
196
+ return fail(`${s.path} is not a description operbe can trust (${e.message})`, false);
197
+ }
198
+ };
199
+ const a = await side(sides[0]), b = await side(sides[1]);
200
+ let changes = [];
201
+ try {
202
+ changes = diff(a.d, b.d);
203
+ }
204
+ catch (e) {
205
+ fail(e.message);
206
+ }
207
+ if (flags.has("--json")) {
208
+ // jj ids, when a side came from a revision, sit beside the digests.
209
+ const at = { ...(a.at ? { from: a.at } : {}), ...(b.at ? { to: b.at } : {}) };
210
+ console.log(JSON.stringify({ from: a.d.digest, to: b.d.digest, ...(a.at || b.at ? { at } : {}), changes }, null, 2));
211
+ }
212
+ else {
213
+ for (const x of [a.at, b.at])
214
+ if (x)
215
+ console.error(`operbe: --at ${x.rev} is commit ${x.commit}, change ${x.change}`);
216
+ for (const c of changes)
217
+ console.log(`${c.level} ${c.kind} ${c.record}${c.field ? ` ${c.field}` : ""}: ${c.message}`);
218
+ console.log(diffSummary(changes));
219
+ }
220
+ const worst = failOn === "warning" ? ["breaking", "warning"] : failOn === "breaking" ? ["breaking"] : [];
221
+ process.exitCode = changes.some((c) => worst.includes(c.level)) ? 1 : 0;
222
+ }
223
+ // check and reconcile: findings, printed one per line or as JSON; exit 1 on errors.
224
+ else {
225
+ const l = await load(positional[0] ?? ".", values["--at"]);
226
+ tellAt(l);
227
+ const m = l.model;
228
+ let findings;
229
+ if (cmd === "check")
230
+ findings = findingsOf(l);
231
+ else {
232
+ const kind = values["--kind"];
233
+ if (kind !== "operation" && kind !== "client-action")
234
+ fail("--kind must be operation or client-action");
235
+ if (kind === "client-action" && !values["--ui"])
236
+ fail("--ui is needed for client actions");
237
+ const from = values["--names"] ?? fail("--names <file|-> is needed");
238
+ let text = "";
239
+ try {
240
+ text = readFileSync(from === "-" ? 0 : from, "utf8");
241
+ }
242
+ catch (e) {
243
+ fail(`can't read names from ${from}: ${e.message}`, false);
244
+ }
245
+ // Names: a JSON array of strings, or one name per line.
246
+ let names = [];
247
+ if (text.trim().startsWith("[")) {
248
+ try {
249
+ names = JSON.parse(text);
250
+ }
251
+ catch {
252
+ fail(`names in ${from} start with '[' but aren't a JSON array`);
253
+ }
254
+ if (!Array.isArray(names) || names.some((n) => typeof n !== "string"))
255
+ fail(`names in ${from} must be a JSON array of strings`);
256
+ }
257
+ else
258
+ names = text.split(/\r?\n/).map((x) => x.trim()).filter(Boolean);
259
+ findings = reconcile(m, { kind: kind, ui: values["--ui"], via: values["--via"], names });
260
+ }
261
+ findings = sortFindings(findings);
262
+ // reconcile reports only its own findings, so its summary has no status counts.
263
+ const c = cmd === "check" ? counts(m, findings) : { ...counts(m, findings), behaviors: null, clientActions: null };
264
+ if (flags.has("--json"))
265
+ console.log(JSON.stringify({ findings, counts: c }, null, 2));
266
+ else {
267
+ for (const f of findings)
268
+ console.log(formatFinding(f));
269
+ console.log(summary(c));
270
+ }
271
+ process.exitCode = c.errors ? 1 : 0;
272
+ }
@@ -0,0 +1,22 @@
1
+ import { type Finding } from "./findings.ts";
2
+ import { type Model } from "./read.ts";
3
+ export declare const FORMAT = "operbe.description/1";
4
+ type Json = string | number | boolean | Json[] | {
5
+ [k: string]: Json;
6
+ };
7
+ type Obj = {
8
+ [k: string]: Json;
9
+ };
10
+ export interface Description {
11
+ format: string;
12
+ body: Obj;
13
+ digest: string;
14
+ derived: Obj;
15
+ findings: Finding[];
16
+ }
17
+ export declare function body(m: Model): Obj;
18
+ export declare const bodyBytes: (b: Obj) => string;
19
+ export declare const digestOf: (b: Obj) => string;
20
+ export declare function describe(m: Model, findings: Finding[]): Description;
21
+ export declare function parseDescription(text: string): Description;
22
+ export {};
@@ -0,0 +1,201 @@
1
+ // describe: the model in, the description out (formats.md, "The description"). Other languages
2
+ // read this JSON and never parse the markdown.
3
+ //
4
+ // { format, body, digest, derived, findings }
5
+ //
6
+ // `body` is what the files say, normalized, and nothing else. Its bytes are RFC 8785 JSON (JCS)
7
+ // and `digest` is the SHA-256 of them, so the same files give the same digest on any machine and
8
+ // with any build that writes this format. Every rule below that shapes the body is part of the
9
+ // format: changing one, even adding an optional field, means a new `format`.
10
+ //
11
+ // `derived` (tallies, rollups, the tool's version) and `findings` sit outside the hash: they may
12
+ // change with the tool.
13
+ import { createHash } from "node:crypto";
14
+ import { KNOWN, whole } from "./check.js";
15
+ import { sortFindings } from "./findings.js";
16
+ import { jcs } from "./jcs.js";
17
+ import { dict, str } from "./read.js";
18
+ import { VERSION } from "./version.js";
19
+ export const FORMAT = "operbe.description/1";
20
+ // A query reads, a change changes, a signal passes: pinned by format/1.
21
+ const EFFECT = { query: "reads", change: "changes", signal: "passes" };
22
+ // Risk from lowest to highest, for a client action's rollup.
23
+ const RISK_ORDER = ["reads", "changes", "changes-rights", "destroys"];
24
+ // One record's header and sections, normalized:
25
+ // - operbe's own fields as written; `form` as an integer when it is one;
26
+ // - an empty value is the same as no field, so it is left out;
27
+ // - unknown unprefixed fields are left out (check reports them);
28
+ // - `arch.field` goes to ext.arch.field, as written;
29
+ // - sections in written order, each { title, text } (text LF-normalized and trimmed by read).
30
+ function record(r) {
31
+ // Every map keyed by something a file says has no prototype (dict): see read.ts.
32
+ const out = dict(), ext = dict();
33
+ for (const [k, { value }] of Object.entries(r.fields)) {
34
+ if (value === "")
35
+ continue;
36
+ const dot = k.indexOf(".");
37
+ if (dot >= 0)
38
+ (ext[k.slice(0, dot)] ??= dict())[k.slice(dot + 1)] = value;
39
+ else if (KNOWN[r.kind].includes(k))
40
+ out[k] = k === "form" && whole(value) ? Number(value) : value;
41
+ }
42
+ out.sections = r.sections.map((s) => ({ title: s.title, text: s.text }));
43
+ if (Object.keys(ext).length)
44
+ out.ext = ext;
45
+ return out;
46
+ }
47
+ // Records keyed by name (id for behaviors). If two files give the same key, the first (by path) is kept.
48
+ function keyed(rs, key, extra = () => { }) {
49
+ const out = dict();
50
+ for (const r of rs) {
51
+ if (!r.readable)
52
+ continue;
53
+ const k = str(r, key) || r.stem;
54
+ if (Object.hasOwn(out, k))
55
+ continue;
56
+ const o = record(r);
57
+ delete o[key]; // the key is the record's name already
58
+ extra(r, o);
59
+ out[k] = o;
60
+ }
61
+ return out;
62
+ }
63
+ export function body(m) {
64
+ if (!m.profile)
65
+ return {};
66
+ const profile = record(m.profile);
67
+ for (const k of ["operations", "behaviors", "client-actions"])
68
+ delete profile[k]; // folders: where, not what
69
+ const behaviorIds = new Set(m.behaviors.map((b) => str(b, "id")));
70
+ const actionNames = new Set(m.clientActions.map((a) => str(a, "name")));
71
+ // Coverage: per UI with a file, per row that names a behavior or client action. First row wins.
72
+ const coverage = dict();
73
+ for (const ui of m.uis) {
74
+ const lines = m.coverage[ui]?.lines;
75
+ if (!lines)
76
+ continue;
77
+ const rows = dict();
78
+ for (const { cells: [id, value, form, note] } of lines) {
79
+ if (note === undefined || Object.hasOwn(rows, id) || !(behaviorIds.has(id) || actionNames.has(id)))
80
+ continue;
81
+ rows[id] = { value, ...(form ? { form: whole(form) ? Number(form) : form } : {}), ...(note ? { note } : {}) };
82
+ }
83
+ coverage[ui] = rows;
84
+ }
85
+ // Declarations: fields sorted by (field, on), diff rules by (field, change); their order means nothing.
86
+ const architectures = dict();
87
+ for (const a of m.architectures)
88
+ architectures[a.name] = {
89
+ fields: [...a.fields].sort((x, y) => cmp(x.field, y.field) || cmp(x.on, y.on))
90
+ .map((f) => ({ field: f.field, on: f.on, required: f.required, ...(f.values ? { values: f.values } : {}) })),
91
+ "diff-rules": [...a.diffRules].sort((x, y) => cmp(x.field, y.field) || cmp(x.change, y.change))
92
+ .map((r) => ({ field: r.field, change: r.change, level: r.level })),
93
+ };
94
+ return {
95
+ profile,
96
+ operations: keyed(m.operations, "name", (_r, o) => { const e = EFFECT[o.class]; if (e)
97
+ o.effect = e; }),
98
+ behaviors: keyed(m.behaviors, "id"),
99
+ ...(m.folders.clientActions !== null ? { "client-actions": keyed(m.clientActions, "name") } : {}),
100
+ coverage,
101
+ architectures,
102
+ };
103
+ }
104
+ const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
105
+ // What follows from the body, for readers who'd otherwise compute it themselves. Not hashed.
106
+ function derived(b) {
107
+ const ops = (b.operations ?? {});
108
+ const behs = (b.behaviors ?? {});
109
+ const acts = (b["client-actions"] ?? {});
110
+ const uis = (b.profile?.uis ?? []);
111
+ const names = (v) => (Array.isArray(v) ? v : []);
112
+ const sorted = (xs) => [...xs].sort(cmp);
113
+ // used-by: which behaviors and client actions name each operation.
114
+ const usedBy = dict();
115
+ for (const op of Object.keys(ops))
116
+ usedBy[op] = {
117
+ behaviors: sorted(Object.keys(behs).filter((id) => names(behs[id].operations).includes(op))),
118
+ "client-actions": sorted(Object.keys(acts).filter((n) => names(acts[n].operations).includes(op))),
119
+ };
120
+ // Status counts per kind.
121
+ const statuses = (rs) => {
122
+ const t = { firm: 0, rough: 0, retired: 0 };
123
+ for (const r of Object.values(rs))
124
+ if (Object.hasOwn(t, r.status))
125
+ t[r.status]++;
126
+ return t;
127
+ };
128
+ // Coverage tallies per UI: each value, and `unbuilt` for applying behaviors with no row.
129
+ const tallies = dict();
130
+ for (const ui of uis) {
131
+ const rows = (b.coverage[ui] ?? {});
132
+ const t = { honours: 0, differs: 0, limited: 0, "not-here": 0, unbuilt: 0 };
133
+ for (const [id, r] of Object.entries(behs)) {
134
+ const applies = r["applies-to"] === "all" || names(r["applies-to"]).includes(ui);
135
+ if (!applies || r.status === "retired")
136
+ continue;
137
+ const v = rows[id]?.value;
138
+ if (v && Object.hasOwn(t, v))
139
+ t[v]++;
140
+ else if (!v)
141
+ t.unbuilt++;
142
+ }
143
+ tallies[ui] = t;
144
+ }
145
+ // Per client action: its class, the highest risk among its operations, and whether any of them
146
+ // can't be taken back (a change or signal with taken-back-by: nothing).
147
+ const rollup = dict();
148
+ for (const [n, a] of Object.entries(acts)) {
149
+ const its = names(a.operations).map((o) => ops[o]).filter(Boolean);
150
+ const risk = its.map((o) => RISK_ORDER.indexOf(o.risk)).reduce((x, y) => Math.max(x, y), -1);
151
+ rollup[n] = {
152
+ class: a.class ?? "",
153
+ ...(risk >= 0 ? { risk: RISK_ORDER[risk] } : {}),
154
+ irreversible: its.some((o) => o.effect !== "reads" && o["taken-back-by"] === "nothing"),
155
+ };
156
+ }
157
+ return {
158
+ tool: `operbe ${VERSION}`,
159
+ "used-by": usedBy,
160
+ statuses: { behaviors: statuses(behs), ...(b["client-actions"] ? { "client-actions": statuses(acts) } : {}) },
161
+ coverage: tallies,
162
+ "client-actions": rollup,
163
+ };
164
+ }
165
+ // The exact bytes the digest is taken over.
166
+ export const bodyBytes = (b) => jcs(b);
167
+ export const digestOf = (b) => `sha256:${createHash("sha256").update(bodyBytes(b), "utf8").digest("hex")}`;
168
+ export function describe(m, findings) {
169
+ const b = body(m);
170
+ return { format: FORMAT, body: b, digest: digestOf(b), derived: derived(b), findings: sortFindings(findings) };
171
+ }
172
+ // A description read back from text (a file, another tool's output). It is trusted only as far as
173
+ // it checks out: this format, a body whose digest is recomputed here and matches, and a findings
174
+ // list. Anything else throws a TypeError saying what is wrong.
175
+ export function parseDescription(text) {
176
+ let d;
177
+ try {
178
+ d = JSON.parse(text);
179
+ }
180
+ catch {
181
+ throw new TypeError("not JSON");
182
+ }
183
+ if (typeof d?.format !== "string")
184
+ throw new TypeError("no format; not a description");
185
+ if (d.format !== FORMAT)
186
+ throw new TypeError(`format ${d.format}; this build reads ${FORMAT}`);
187
+ if (!d.body || typeof d.body !== "object" || Array.isArray(d.body))
188
+ throw new TypeError("no body");
189
+ if (!Array.isArray(d.findings))
190
+ throw new TypeError("no findings list");
191
+ let digest;
192
+ try {
193
+ digest = digestOf(d.body);
194
+ }
195
+ catch (e) {
196
+ throw new TypeError(`its body can't be hashed: ${e.message}`);
197
+ }
198
+ if (d.digest !== digest)
199
+ throw new TypeError(`its digest is ${d.digest}, but its body hashes to ${digest}: the body was changed after it was described`);
200
+ return d;
201
+ }
package/dist/diff.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { Description } from "./describe.ts";
2
+ export type Level = "breaking" | "warning" | "info";
3
+ export interface Change {
4
+ kind: string;
5
+ record: string;
6
+ field?: string;
7
+ before?: unknown;
8
+ after?: unknown;
9
+ level: Level;
10
+ message: string;
11
+ }
12
+ export declare function diff(a: Description, b: Description): Change[];
13
+ export declare const diffSummary: (cs: Change[]) => string;