@ontology-kit/okb 0.1.0 → 0.3.0-alpha.133

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 (109) hide show
  1. package/README.md +1 -1
  2. package/dist/check.d.ts +43 -0
  3. package/dist/check.js +102 -0
  4. package/dist/checks.d.ts +1 -1
  5. package/dist/checks.js +27 -4
  6. package/dist/cli.js +11 -705
  7. package/dist/clidocs.d.ts +0 -2
  8. package/dist/clidocs.js +5 -27
  9. package/dist/clock.js +1 -1
  10. package/dist/command-table.d.ts +144 -0
  11. package/dist/command-table.js +85 -0
  12. package/dist/commands/documents.d.ts +3 -0
  13. package/dist/commands/documents.js +250 -0
  14. package/dist/commands/getting-started.d.ts +3 -0
  15. package/dist/commands/getting-started.js +135 -0
  16. package/dist/commands/housekeeping.d.ts +3 -0
  17. package/dist/commands/housekeeping.js +203 -0
  18. package/dist/commands/modeling.d.ts +3 -0
  19. package/dist/commands/modeling.js +467 -0
  20. package/dist/commands/planning.d.ts +3 -0
  21. package/dist/commands/planning.js +251 -0
  22. package/dist/commands/reviewing.d.ts +3 -0
  23. package/dist/commands/reviewing.js +234 -0
  24. package/dist/commands/skills.d.ts +3 -0
  25. package/dist/commands/skills.js +53 -0
  26. package/dist/commands.d.ts +10 -22
  27. package/dist/commands.js +15 -622
  28. package/dist/cqanswer.d.ts +51 -0
  29. package/dist/cqanswer.js +76 -0
  30. package/dist/diff.d.ts +85 -0
  31. package/dist/diff.js +323 -0
  32. package/dist/export-changes.d.ts +40 -0
  33. package/dist/export-changes.js +115 -0
  34. package/dist/export-csv.d.ts +17 -0
  35. package/dist/export-csv.js +188 -0
  36. package/dist/export-eval-cases.d.ts +38 -0
  37. package/dist/export-eval-cases.js +40 -0
  38. package/dist/export.d.ts +34 -3
  39. package/dist/export.js +70 -12
  40. package/dist/families.d.ts +1 -1
  41. package/dist/families.js +1 -1
  42. package/dist/help.d.ts +11 -2
  43. package/dist/help.js +51 -57
  44. package/dist/kbdocs.d.ts +18 -0
  45. package/dist/kbdocs.js +393 -0
  46. package/dist/metakb.d.ts +1 -1
  47. package/dist/metakb.js +1 -1
  48. package/dist/naming.d.ts +2 -2
  49. package/dist/naming.js +2 -2
  50. package/dist/ontology-ref.d.ts +20 -0
  51. package/dist/ontology-ref.js +108 -0
  52. package/dist/ops/admin.d.ts +2 -2
  53. package/dist/ops/admin.js +26 -8
  54. package/dist/ops/classes.d.ts +1 -1
  55. package/dist/ops/classes.js +15 -7
  56. package/dist/ops/common.d.ts +12 -2
  57. package/dist/ops/common.js +3 -0
  58. package/dist/ops/instances.d.ts +2 -1
  59. package/dist/ops/instances.js +9 -3
  60. package/dist/ops/links.d.ts +2 -2
  61. package/dist/ops/links.js +3 -2
  62. package/dist/ops/naming.d.ts +1 -1
  63. package/dist/ops/naming.js +3 -1
  64. package/dist/ops/scope.d.ts +14 -3
  65. package/dist/ops/scope.js +38 -4
  66. package/dist/ops/slots.d.ts +1 -1
  67. package/dist/ops/slots.js +21 -8
  68. package/dist/ops/values.d.ts +1 -1
  69. package/dist/ops/values.js +5 -1
  70. package/dist/provenance.d.ts +5 -3
  71. package/dist/provenance.js +61 -19
  72. package/dist/release.d.ts +52 -0
  73. package/dist/release.js +337 -0
  74. package/dist/render.d.ts +88 -1
  75. package/dist/render.js +265 -3
  76. package/dist/resync.d.ts +98 -0
  77. package/dist/resync.js +234 -0
  78. package/dist/review.d.ts +1 -1
  79. package/dist/review.js +1 -1
  80. package/dist/reviewdocs.d.ts +42 -0
  81. package/dist/reviewdocs.js +263 -0
  82. package/dist/runner.d.ts +3 -0
  83. package/dist/runner.js +84 -0
  84. package/dist/skills.d.ts +19 -3
  85. package/dist/skills.js +130 -14
  86. package/dist/status.d.ts +1 -1
  87. package/dist/status.js +1 -1
  88. package/dist/types.d.ts +1 -1
  89. package/dist/types.js +1 -1
  90. package/dist/verifynote.d.ts +19 -0
  91. package/dist/verifynote.js +93 -0
  92. package/dist/workflows.d.ts +283 -0
  93. package/dist/workflows.js +270 -0
  94. package/meta-kb/data/edges.json +25 -0
  95. package/meta-kb/data/manifest.json +5 -5
  96. package/meta-kb/data/nodes.json +46 -9
  97. package/package.json +9 -4
  98. package/schema/edge.schema.json +68 -0
  99. package/schema/edges.schema.json +9 -0
  100. package/schema/node.schema.json +914 -0
  101. package/schema/nodes.schema.json +9 -0
  102. package/schema/okb.schema.json +41 -0
  103. package/skills/build-domain-kb-from-docs/SKILL.md +21 -3
  104. package/skills/ontology-coach/SKILL.md +8 -4
  105. package/skills/ontology-maintainer/SKILL.md +152 -0
  106. package/skills/ontology-review/SKILL.md +4 -2
  107. package/skills/ontology-signoff/SKILL.md +182 -0
  108. package/templates/okb-check.yml +148 -0
  109. package/templates/pull_request_template.md +16 -0
package/dist/cli.js CHANGED
@@ -1,715 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  /** okb: command-line interface. Run `okb help` for usage. */
3
- import { parseArgs } from "node:util";
4
- import { writeFileSync } from "node:fs";
5
- import { resolve } from "node:path";
6
- import { duplicateQuotes, loadSourcePages, runChecks } from "./checks.js";
7
- import { MetaKB, explainName } from "./metakb.js";
8
- import { OkbError, Ontology } from "@ontology-kit/format";
9
- import * as ops from "./ops.js";
10
- import { c, explain, formatFindings, listExplainable, mermaid, show, stepGuide, SYMBOL, tree } from "./render.js";
11
- import { exportGraph, toCypher } from "./export.js";
12
- import { buildReview } from "./review.js";
13
- import * as prov from "./provenance.js";
14
- import { computeStatus } from "./status.js";
15
- import { HELP } from "./help.js";
16
- import { PACKAGE_VERSION } from "./version.js";
17
- import { installSkills, skillsStatus } from "./skills.js";
18
- const str = { type: "string" };
19
- const strs = { type: "string", multiple: true };
20
- const bool = { type: "boolean" };
21
- const GLOBAL = { C: { type: "string", short: "C" }, json: bool };
22
- function parse(argv, options = {}) {
23
- const { values, positionals } = parseArgs({ args: argv, options: { ...GLOBAL, ...options }, allowPositionals: true, strict: true });
24
- return { v: values, p: positionals };
25
- }
26
- const num = (x, flag) => {
27
- if (x === undefined)
28
- return undefined;
29
- if (!/^\d+$/.test(x))
30
- throw new OkbError(`${flag} needs a whole number (0 or more).`);
31
- return Number(x);
32
- };
33
- const tri = (x) => (x === undefined ? undefined : ["true", "yes", "1"].includes(x.toLowerCase()));
34
- /** `okb review` lists this many prompts per rule in the terminal; --json has them all. */
35
- const REVIEW_PROMPTS_SHOWN = 12;
36
- const TIP = /^(Tip|Add a|Attach|Decide|Say which|List the)/;
37
- function say(notes) {
38
- for (const n of notes)
39
- console.log(TIP.test(n) ? c.dim(" " + n) : n);
40
- }
41
- /** Under --json print what `data` builds; otherwise run the human-readable printer. */
42
- function output(v, data, human) {
43
- if (v.json)
44
- console.log(JSON.stringify(data(), null, 2));
45
- else
46
- human();
47
- }
48
- function load(v) {
49
- return Ontology.load(v.C ?? ".");
50
- }
51
- function mutate(v, fn) {
52
- const ont = load(v);
53
- const notes = fn(ont);
54
- ont.save();
55
- say(notes);
56
- }
57
- async function main(argvIn) {
58
- // Accept -C <folder> anywhere, including before the command.
59
- const argv = [...argvIn];
60
- if (argv[0] === "-C" && argv.length > 2)
61
- argv.push(...argv.splice(0, 2));
62
- if (argv.includes("--help") || argv.includes("-h")) {
63
- console.log(HELP);
64
- return;
65
- }
66
- // "property" and "relationship" are everyday names for Ontology 101's two kinds of slot.
67
- if (argv[0] === "property")
68
- argv[0] = "slot";
69
- if (argv[0] === "relationship") {
70
- argv[0] = "slot";
71
- if (argv[1] === "add")
72
- argv.push("--type", "Instance");
73
- if (argv[1] === "property")
74
- argv[0] = "edgeprop";
75
- for (let i = 2; i < argv.length; i++) {
76
- if (argv[i] === "--from")
77
- argv[i] = "--on";
78
- else if (argv[i] === "--to")
79
- argv[i] = "--range";
80
- }
81
- }
82
- const [cmd, ...rest] = argv;
83
- const sub = rest[0];
84
- switch (cmd) {
85
- case undefined:
86
- case "help":
87
- console.log(HELP);
88
- return;
89
- case "version":
90
- case "--version":
91
- console.log(`okb ${PACKAGE_VERSION} · meta-KB ${MetaKB.get().version}`);
92
- return;
93
- case "init": {
94
- const { v, p } = parse(rest, { name: str });
95
- if (!p[0])
96
- throw new OkbError('Usage: okb init <folder> --name "My Ontology"');
97
- const name = v.name ?? p[0];
98
- const ont = ops.createOntology(p[0], name);
99
- ont.manifest.metaKbVersion = MetaKB.get().version;
100
- ont.save();
101
- console.log(`${SYMBOL.ok} Created ontology '${name}' in ${ont.root}\n`);
102
- console.log(stepGuide(MetaKB.get().step(1)));
103
- console.log(c.dim(`\nNext: cd ${p[0]} && okb scope --domain "..." --purpose "..." --users "..."`));
104
- return;
105
- }
106
- case "scope": {
107
- const { v } = parse(rest, { name: str, domain: str, purpose: str, users: strs, maintainers: strs, "out-of-scope": strs, kind: str });
108
- const touched = ["name", "domain", "purpose", "users", "maintainers", "out-of-scope", "kind"].some((k) => v[k] !== undefined);
109
- const ont = load(v);
110
- if (touched) {
111
- ops.setScope(ont, { name: v.name, domain: v.domain, purpose: v.purpose, users: v.users, maintainers: v.maintainers, outOfScope: v["out-of-scope"], kind: v.kind });
112
- ont.save();
113
- }
114
- const m = ont.meta;
115
- const row = (k, val) => console.log(` ${c.dim(k.padEnd(13))} ${Array.isArray(val) ? val.join(", ") || c.yellow("—") : val || c.yellow("—")}`);
116
- return output(v, () => m, () => {
117
- console.log(c.bold(m.name));
118
- row("domain", m.domain);
119
- row("purpose", m.purpose);
120
- row("users", m.users);
121
- row("maintainers", m.maintainers);
122
- row("out of scope", m.outOfScope);
123
- row("kind", m.kind);
124
- });
125
- }
126
- case "convention": {
127
- const { v } = parse(rest, { "class-case": str, "slot-case": str, "instance-case": str, number: str, "slot-affix": str });
128
- mutate(v, (ont) => {
129
- const notes = ops.setConventions(ont, { classCase: v["class-case"], slotCase: v["slot-case"], instanceCase: v["instance-case"], classNumber: v.number, slotAffix: v["slot-affix"] });
130
- const cv = ont.conventions;
131
- return [`Naming convention: classes ${cv.classCase} (${cv.classNumber}) · slots ${cv.slotCase}${cv.slotAffix !== "none" ? ` (${cv.slotAffix})` : ""} · instances ${cv.instanceCase ?? "free text"}`, ...notes];
132
- });
133
- return;
134
- }
135
- case "cq": {
136
- if (sub === "add") {
137
- const { v, p } = parse(rest.slice(1));
138
- if (!p.length)
139
- throw new OkbError('Usage: okb cq add "Your question?"');
140
- return mutate(v, (ont) => p.flatMap((t) => ops.addCQ(ont, t)));
141
- }
142
- if (sub === "link" || sub === "unlink") {
143
- const { v, p } = parse(rest.slice(1));
144
- if (p.length < 2)
145
- throw new OkbError(`Usage: okb cq ${sub} <question number> <Class|slot|instance>...`);
146
- return mutate(v, (ont) => ops.linkCQ(ont, p[0], p.slice(1), sub === "unlink"));
147
- }
148
- if (sub === "set") {
149
- const { v, p } = parse(rest.slice(1), { text: str, status: str });
150
- return mutate(v, (ont) => {
151
- const q = ont.find(p[0], "CompetencyQuestion");
152
- if (v.text)
153
- q.text = v.text;
154
- if (v.status) {
155
- if (!["draft", "answerable"].includes(v.status))
156
- throw new OkbError("--status must be draft or answerable.");
157
- q.status = v.status;
158
- }
159
- return v.status === "answerable" ? [`Updated ${q.id}.`, ops.familyTip(ont, q.id)] : [`Updated ${q.id}.`];
160
- });
161
- }
162
- if (sub === "remove") {
163
- const { v, p } = parse(rest.slice(1));
164
- return mutate(v, (ont) => ops.remove(ont, p[0], ["CompetencyQuestion"]));
165
- }
166
- const { v } = parse(sub === "list" ? rest.slice(1) : rest);
167
- const ont = load(v);
168
- const qs = ont.ofType("CompetencyQuestion");
169
- return output(v, () => qs.map((q) => ({ ...q, needs: ont.targets(q.id, "NEEDS") })), () => {
170
- if (!qs.length)
171
- return void console.log(c.dim('No competency questions yet. okb cq add "..."'));
172
- for (const q of qs) {
173
- const needs = ont.targets(q.id, "NEEDS").map((n) => ont.label(n));
174
- console.log(`${c.bold(q.id.padEnd(6))} ${q.text} ${c.dim(`[${q.status ?? "draft"}]`)}`);
175
- console.log(c.dim(` needs: ${needs.length ? needs.join(", ") : "(not linked yet: okb cq link " + q.id.split(".")[1] + " <Class|slot>...)"}`));
176
- }
177
- });
178
- }
179
- case "term": {
180
- if (sub === "add") {
181
- const { v, p } = parse(rest.slice(1), { note: str });
182
- if (!p.length)
183
- throw new OkbError("Usage: okb term add <term> [<term>...] (quote multi-word terms)");
184
- return mutate(v, (ont) => ops.addTerms(ont, p, v.note));
185
- }
186
- if (sub === "set") {
187
- const { v, p } = parse(rest.slice(1), { as: str, node: str, note: str });
188
- if (!p[0] || !v.as)
189
- throw new OkbError("Usage: okb term set <term> --as class|slot|instance|value|synonym|out-of-scope [--node Name]");
190
- return mutate(v, (ont) => ops.setTerm(ont, p[0], v.as, v.node, v.note));
191
- }
192
- const { v } = parse(sub === "list" ? rest.slice(1) : rest);
193
- const ont = load(v);
194
- const ts = ont.ofType("Term");
195
- return output(v, () => ts, () => {
196
- const groups = new Map();
197
- for (const t of ts) {
198
- const d = t.disposition ?? "undecided";
199
- const became = ont.targets(t.id, "BECAME").map((x) => ont.label(x));
200
- groups.set(d, [...(groups.get(d) ?? []), t.text + (became.length ? c.dim(` → ${became.join(", ")}`) : "")]);
201
- }
202
- for (const [d, items] of groups)
203
- console.log(`${c.bold(d.padEnd(13))} ${items.join(" · ")}`);
204
- if (!ts.length)
205
- console.log(c.dim("No terms yet. okb term add wine grape winery ..."));
206
- });
207
- }
208
- case "reuse": {
209
- if (sub === "add") {
210
- const { v } = parse(rest.slice(1), { name: str, url: str, decision: str, notes: str });
211
- if (!v.name || !v.decision)
212
- throw new OkbError("Usage: okb reuse add --name ... --decision reuse|adapt|reference|rejected [--url ...] [--notes ...]");
213
- return mutate(v, (ont) => ops.addReuse(ont, { name: v.name, url: v.url, decision: v.decision, notes: v.notes }));
214
- }
215
- if (sub === "none") {
216
- const { v } = parse(rest.slice(1), { why: str });
217
- if (!v.why)
218
- throw new OkbError('Usage: okb reuse none --why "what you looked at and why nothing fit"');
219
- return mutate(v, (ont) => ops.reuseNone(ont, v.why));
220
- }
221
- const { v } = parse(sub === "list" ? rest.slice(1) : rest);
222
- const ont = load(v);
223
- for (const r of ont.ofType("ReusedOntology"))
224
- console.log(`${c.bold(r.name)} ${c.dim(`[${r.decision}]`)} ${r.url ?? ""} ${r.notes ? "\n " + r.notes : ""}`);
225
- if (!ont.ofType("ReusedOntology").length)
226
- console.log(c.dim(ont.meta.reuseReviewed ? "Reviewed: nothing reused." : "Not reviewed yet."));
227
- return;
228
- }
229
- case "class": {
230
- const rest2 = rest.slice(1);
231
- if (sub === "add") {
232
- const { v, p } = parse(rest2, { parent: strs, desc: str, synonym: strs, abstract: bool, terminological: bool, force: bool });
233
- if (!p[0])
234
- throw new OkbError("Usage: okb class add <Name> [--parent P] [--desc ...]");
235
- return mutate(v, (ont) => ops.addClass(ont, p[0], { parents: v.parent, description: v.desc, synonyms: v.synonym, abstract: v.abstract, terminological: v.terminological, force: v.force }));
236
- }
237
- if (sub === "set") {
238
- const { v, p } = parse(rest2, { desc: str, "add-parent": strs, "remove-parent": strs, synonym: strs, abstract: str, terminological: str });
239
- if (!p[0])
240
- throw new OkbError("Usage: okb class set <Class> [--desc ...] [--add-parent P] [--remove-parent P] [--synonym S] [--abstract true|false]");
241
- return mutate(v, (ont) => ops.setClass(ont, p[0], { description: v.desc, addParents: v["add-parent"], removeParents: v["remove-parent"], synonyms: v.synonym, abstract: tri(v.abstract), terminological: tri(v.terminological) }));
242
- }
243
- if (sub === "disjoint") {
244
- const { v, p } = parse(rest2);
245
- return mutate(v, (ont) => ops.disjoint(ont, p));
246
- }
247
- if (sub === "fix") {
248
- const { v, p } = parse(rest2);
249
- if (p.length < 2)
250
- throw new OkbError("Usage: okb class fix <Class> slot=value ...");
251
- return mutate(v, (ont) => ops.assign(ont, ont.find(p[0], "Class").id, p.slice(1), "fixed"));
252
- }
253
- if (sub === "default") {
254
- const { v, p } = parse(rest2);
255
- if (p.length < 2)
256
- throw new OkbError("Usage: okb class default <Class> slot=value ...");
257
- return mutate(v, (ont) => ops.classDefault(ont, p[0], p.slice(1)));
258
- }
259
- if (sub === "restrict") {
260
- const { v, p } = parse(rest2, { values: strs, min: str, max: str, range: strs, clear: bool });
261
- if (p.length < 2)
262
- throw new OkbError("Usage: okb class restrict <Class> <slot> [--values a,b] [--min N] [--max N] [--range C] [--clear]");
263
- return mutate(v, (ont) => ops.restrict(ont, p[0], p[1], { values: v.values, min: num(v.min, "--min"), max: num(v.max, "--max"), range: v.range, clear: v.clear }));
264
- }
265
- throw new OkbError("Usage: okb class add|set|disjoint|fix|default|restrict ... (okb help)");
266
- }
267
- case "slot": {
268
- const rest2 = rest.slice(1);
269
- const slotOpts = { on: strs, off: strs, type: str, values: strs, range: strs, "add-range": strs, "remove-range": strs, card: str, min: str, max: str, default: str, desc: str, force: bool, "on-rules": bool, "off-rules": bool };
270
- const toOpts = (v) => ({
271
- on: v.on, off: v.off, type: v.type, values: v.values, range: v.range, addRange: v["add-range"], removeRange: v["remove-range"],
272
- card: v.card, min: num(v.min, "--min"), max: num(v.max, "--max"), default: v.default, description: v.desc, force: v.force, onRules: v["on-rules"], offRules: v["off-rules"],
273
- });
274
- if (sub === "add") {
275
- const { v, p } = parse(rest2, slotOpts);
276
- if (!p[0])
277
- throw new OkbError("Usage: okb slot add <name> --on <Class> --type <Type> [--card single|multiple] ...");
278
- return mutate(v, (ont) => ops.addSlot(ont, p[0], toOpts(v)));
279
- }
280
- if (sub === "set") {
281
- const { v, p } = parse(rest2, slotOpts);
282
- if (!p[0])
283
- throw new OkbError("Usage: okb slot set <slot> [--on C] [--type T] [--values a,b] [--range C] [--card single|multiple] ...");
284
- return mutate(v, (ont) => ops.updateSlot(ont, p[0], toOpts(v)));
285
- }
286
- if (sub === "inverse") {
287
- const { v, p } = parse(rest2);
288
- if (p.length !== 2)
289
- throw new OkbError("Usage: okb slot inverse <slotA> <slotB>");
290
- return mutate(v, (ont) => ops.inverse(ont, p[0], p[1]));
291
- }
292
- throw new OkbError("Usage: okb slot add|set|inverse ... (okb help)");
293
- }
294
- case "instance": {
295
- const rest2 = rest.slice(1);
296
- if (sub === "add") {
297
- const { v, p } = parse(rest2, { of: strs, desc: str });
298
- if (!p[0])
299
- throw new OkbError('Usage: okb instance add "Name" --of <Class> [slot=value ...]');
300
- return mutate(v, (ont) => ops.addInstance(ont, p[0], { of: v.of, description: v.desc, assignments: p.slice(1) }));
301
- }
302
- if (sub === "set") {
303
- const { v, p } = parse(rest2, { of: strs, desc: str });
304
- if (!p[0])
305
- throw new OkbError('Usage: okb instance set "Name" slot=value ... [--of <Class>]');
306
- return mutate(v, (ont) => {
307
- const notes = [
308
- ...(v.of?.length ? ops.setInstanceClasses(ont, p[0], v.of) : []),
309
- ...(p.length > 1 ? ops.assign(ont, ont.find(p[0], "Instance").id, p.slice(1)) : []),
310
- ];
311
- if (v.desc !== undefined) {
312
- ont.find(p[0], "Instance").description = v.desc;
313
- notes.push("Updated description.");
314
- }
315
- return notes;
316
- });
317
- }
318
- throw new OkbError("Usage: okb instance add|set ... (okb help)");
319
- }
320
- case "decision": {
321
- if (sub === "add") {
322
- const { v } = parse(rest.slice(1), { title: str, decision: str, question: str, why: str, alt: strs, about: strs, waives: strs });
323
- if (!v.title || !v.decision)
324
- throw new OkbError('Usage: okb decision add --title "..." --decision "..." --why "..." [--about X] [--waives rule-id]');
325
- return mutate(v, (ont) => ops.addDecision(ont, { title: v.title, decision: v.decision, question: v.question, rationale: v.why, alternatives: v.alt, about: v.about, waives: v.waives }));
326
- }
327
- const { v } = parse(sub === "list" ? rest.slice(1) : rest);
328
- const ont = load(v);
329
- const ds = ont.ofType("DesignDecision");
330
- return output(v, () => ds, () => {
331
- for (const d of ds) {
332
- console.log(`${c.bold(d.id)} ${d.title}`);
333
- console.log(` ${d.decision}${d.rationale ? c.dim(" · why: " + d.rationale) : ""}`);
334
- const about = ont.targets(d.id, "ABOUT").map((x) => ont.label(x));
335
- if (about.length || d.metaRules)
336
- console.log(c.dim(` about: ${about.join(", ") || "—"}${d.metaRules ? " · explains: " + d.metaRules.join(", ") : ""}`));
337
- }
338
- if (!ds.length)
339
- console.log(c.dim("No design decisions recorded yet."));
340
- });
341
- }
342
- case "rename": {
343
- const { v, p } = parse(rest, { force: bool });
344
- if (p.length !== 2)
345
- throw new OkbError("Usage: okb rename <old name> <new name>");
346
- return mutate(v, (ont) => ops.rename(ont, p[0], p[1], v.force));
347
- }
348
- case "remove": {
349
- const { v, p } = parse(rest, { type: str });
350
- if (!p[0])
351
- throw new OkbError("Usage: okb remove <name> [--type Class|Slot|Instance|Term|...]");
352
- return mutate(v, (ont) => ops.remove(ont, p[0], v.type ? [v.type] : undefined));
353
- }
354
- case "show": {
355
- const { v, p } = parse(rest);
356
- const ont = load(v);
357
- const n = ont.find(p[0] ?? "ontology");
358
- return output(v, () => ({ node: n, out: ont.edges.filter((e) => e.from === n.id), in: ont.edges.filter((e) => e.to === n.id) }), () => console.log(show(ont, n)));
359
- }
360
- case "tree": {
361
- const { v } = parse(rest, { instances: bool });
362
- console.log(tree(load(v), v.instances));
363
- return;
364
- }
365
- case "diagram": {
366
- const { v } = parse(rest, { out: str });
367
- const md = mermaid(load(v));
368
- if (v.out) {
369
- writeFileSync(resolve(v.out), md + "\n");
370
- console.log(`Wrote ${v.out}. Open it in GitHub, VS Code (Markdown preview), or mermaid.live.`);
371
- }
372
- else
373
- console.log(md);
374
- return;
375
- }
376
- case "validate": {
377
- const { v } = parse(rest, { all: bool, why: bool, rule: strs, strict: bool });
378
- const ont = load(v);
379
- const { findings, hiddenLater } = runChecks(ont, { all: v.all, only: v.rule }, { pages: await loadSourcePages(ont) });
380
- output(v, () => ({ step: ont.step, metaKbVersion: MetaKB.get().version, hiddenLater, findings }), () => {
381
- console.log(formatFindings(findings, ont, { all: v.all, verbose: v.why }));
382
- if (hiddenLater)
383
- console.log(c.dim(`(${hiddenLater} warning(s)/hint(s) from later steps are hidden until you get there; okb validate --all shows them. Errors are never hidden.)`));
384
- });
385
- const open = findings.filter((f) => !f.explainedBy);
386
- const fail = open.some((f) => f.severity === "error") || (v.strict && open.some((f) => f.severity === "warning"));
387
- process.exitCode = fail ? 1 : 0;
388
- return;
389
- }
390
- case "status": {
391
- const { v } = parse(rest);
392
- const ont = load(v);
393
- const { findings } = runChecks(ont, { all: true }, { pages: await loadSourcePages(ont) });
394
- const st = computeStatus(ont, findings);
395
- return output(v, () => ({ currentStep: ont.step, ...st }), () => {
396
- const meta = MetaKB.get();
397
- const shown = findings.filter((f) => !f.explainedBy && (f.severity === "error" || (meta.rule(f.rule).fromStep ?? 1) <= ont.step));
398
- const count = (sev) => shown.filter((f) => f.severity === sev).length;
399
- console.log(c.bold(ont.meta.name) + c.dim(` · ${ont.ofType("Class").length} classes · ${ont.ofType("Slot").length} slots · ${ont.ofType("Instance").length} instances · ${ont.ofType("CompetencyQuestion").length} questions`));
400
- console.log("");
401
- for (const s of st.steps) {
402
- const here = s.order === ont.step ? c.cyan(" ◀ you are here") : "";
403
- const mark = s.complete ? SYMBOL.ok : s.order === ont.step ? c.cyan("▶") : SYMBOL.todo;
404
- console.log(`${mark} ${c.bold(`${s.order}. ${s.name}`)}${here}`);
405
- if (s.order === ont.step || (!s.complete && s.order < ont.step)) {
406
- for (const it of s.items)
407
- console.log(` ${it.done === null ? SYMBOL.ask : it.done ? SYMBOL.ok : SYMBOL.todo} ${it.text}`);
408
- }
409
- }
410
- console.log("");
411
- console.log(`Validator (steps 1–${ont.step}): ${SYMBOL.error} ${count("error")} ${SYMBOL.warning} ${count("warning")} ${SYMBOL.info} ${count("info")} ${c.dim("okb validate for details")}`);
412
- const cur = st.steps.find((s) => s.order === ont.step);
413
- if (cur.complete && ont.step < st.steps.length)
414
- console.log(c.green(`\nStep ${ont.step} looks done. When you're happy with it: okb step next`));
415
- else if (st.suggested < ont.step)
416
- console.log(c.yellow(`\nStep ${st.suggested} still has open items. It's fine to go back: okb step ${st.suggested}`));
417
- else
418
- console.log(c.dim(`\nSee the guide for this step: okb step`));
419
- });
420
- }
421
- case "step": {
422
- const { v, p } = parse(rest);
423
- const meta = MetaKB.get();
424
- if (p[0]) {
425
- const ont = load(v);
426
- const target = p[0] === "next" ? ont.step + 1 : p[0] === "prev" ? ont.step - 1 : Number(p[0]);
427
- if (!meta.step(target))
428
- throw new OkbError(`There is no step ${p[0]}. Steps are 1–${meta.steps.length}.`);
429
- const st = computeStatus(ont);
430
- const leaving = st.steps.find((s) => s.order === ont.step);
431
- ont.manifest.currentStep = target;
432
- ont.save();
433
- if (target > leaving.order && !leaving.complete) {
434
- console.log(c.yellow(`Moving on with step ${leaving.order} unfinished (${leaving.items.filter((i) => i.done === false).map((i) => i.text).join("; ")}). That's allowed; the method is iterative.`));
435
- }
436
- console.log(c.cyan(`Now on step ${target}.`) + c.dim(` (To read a step's guide without moving: okb explain ${target})`) + "\n");
437
- console.log(stepGuide(meta.step(target)));
438
- return;
439
- }
440
- let order = 1;
441
- try {
442
- order = load(v).step;
443
- }
444
- catch {
445
- /* no ontology here: show step 1 */
446
- }
447
- console.log(stepGuide(meta.step(order)));
448
- return;
449
- }
450
- case "explain": {
451
- const { v, p } = parse(rest, { search: str });
452
- const meta = MetaKB.get();
453
- if (v.search) {
454
- const hits = meta.search(v.search.replace(/[-_]/g, " "));
455
- if (!hits.length)
456
- return void console.log(`Nothing mentions '${v.search}'.`);
457
- for (const h of hits)
458
- console.log(`${(h.type === "Rule" ? h.key : h.id).padEnd(40)} ${c.dim(h.type)} ${h.type === "Rule" ? h.statement.slice(0, 60) : h.name}`);
459
- return;
460
- }
461
- if (!p.length)
462
- return void console.log(listExplainable());
463
- const q = p.join(" ");
464
- const hits = meta.resolve(q);
465
- return output(v, () => hits.map((h) => ({ ...h, citations: meta.citations(h.id), rationale: h.type === "Rule" ? meta.rationale(h) : undefined })), () => {
466
- if (!hits.length)
467
- return void console.log(`Nothing called '${q}'. Try: okb explain --search ${q}`);
468
- console.log(explain(hits[0]));
469
- if (hits.length > 1)
470
- console.log(c.dim(`\nAlso matches: ${hits.slice(1, 6).map(explainName).join(", ")}`));
471
- });
472
- }
473
- case "review": {
474
- // The judgment rules a script can't check, turned into concrete questions about
475
- // this ontology. Used by the ontology-review skill.
476
- const { v } = parse(rest, { all: bool });
477
- const ont = load(v);
478
- const items = buildReview(ont, v.all);
479
- const classes = () => ont.ofType("Class").map((cl) => ({
480
- id: cl.id, name: cl.name, description: cl.description, parents: ont.parents(cl.id).map((x) => ont.label(x)),
481
- children: ont.children(cl.id).map((x) => ont.label(x)), ownSlots: ont.ownSlots(cl.id).map((s) => ont.label(s)),
482
- abstract: cl.abstract, terminological: cl.terminological, instances: ont.sources(cl.id, "INSTANCE_OF").length,
483
- }));
484
- return output(v, () => ({ step: ont.step, scope: ont.meta, judgmentRules: items, classes: classes(), decisions: ont.ofType("DesignDecision") }), () => {
485
- console.log(c.bold(v.all ? "Review: what only a person can judge (all rules)" : `Review: what only a person can judge (step ${ont.step} and anything already visible)`) + "\n");
486
- for (const it of items) {
487
- console.log(`${SYMBOL.ask} ${c.bold(it.rule)} ${c.dim(`(${it.modality.replace("_", " ")})`)} ${it.question}`);
488
- for (const f of it.flags)
489
- console.log(` ${SYMBOL.warning} ${f}`);
490
- for (const x of it.prompts.slice(0, REVIEW_PROMPTS_SHOWN))
491
- console.log(` · ${x}`);
492
- if (it.prompts.length > REVIEW_PROMPTS_SHOWN)
493
- console.log(c.dim(` · ...and ${it.prompts.length - REVIEW_PROMPTS_SHOWN} more (okb review --json)`));
494
- if (it.source)
495
- console.log(c.dim(` ${it.source}`));
496
- console.log("");
497
- }
498
- console.log(c.dim("Record answers that needed thought (or that someone might question later): okb decision add ..."));
499
- });
500
- }
501
- case "edgeprop": {
502
- const { v, p } = parse(rest.slice(1), { type: str, values: strs, required: bool, desc: str, remove: bool });
503
- if (p.length !== 2)
504
- throw new OkbError("Usage: okb relationship property <relationship> <name> --type String|Integer|Float|Boolean|Enumerated [--values a,b] [--required] [--desc ...] [--remove]");
505
- return mutate(v, (ont) => ops.declareEdgeProperty(ont, p[0], p[1], { type: v.type, values: v.values, required: v.required, description: v.desc, remove: v.remove }));
506
- }
507
- case "link": {
508
- const { v, p } = parse(rest, { rule: str, clear: strs });
509
- if (p.length < 3)
510
- throw new OkbError('Usage: okb link <from> <relationship> <to> [name=value ...] [--rule <rule id>] [--clear name]');
511
- return mutate(v, (ont) => ops.link(ont, p[0], p[1], p[2], { props: p.slice(3), rule: v.rule, clear: v.clear }));
512
- }
513
- case "unlink": {
514
- const { v, p } = parse(rest);
515
- if (p.length !== 3)
516
- throw new OkbError("Usage: okb unlink <from> <relationship> <to>");
517
- return mutate(v, (ont) => ops.unlink(ont, p[0], p[1], p[2]));
518
- }
519
- case "export": {
520
- const { v } = parse(rest, { format: str, out: str, "with-schema": bool, "no-inherited": bool, "no-rules": bool, "include-unverified": bool });
521
- const ont = load(v);
522
- const fmt = v.format ?? (v.out?.endsWith(".cypher") || v.out?.endsWith(".cql") ? "cypher" : "json");
523
- if (!["json", "cypher"].includes(fmt))
524
- throw new OkbError("--format must be json or cypher.");
525
- const g = exportGraph(ont, { inherited: !v["no-inherited"], schema: v["with-schema"], rules: !v["no-rules"], unverified: v["include-unverified"] });
526
- const text = fmt === "cypher" ? toCypher(g) : JSON.stringify(g, null, 2) + "\n";
527
- if (v.out) {
528
- writeFileSync(resolve(v.out), text);
529
- console.log(`Wrote ${v.out}: ${g.nodes.length} nodes, ${g.relationships.length} relationships (${fmt}).`);
530
- for (const n of g.notes)
531
- console.log(c.dim(" " + n));
532
- }
533
- else
534
- process.stdout.write(text);
535
- return;
536
- }
537
- case "source": {
538
- const rest2 = rest.slice(1);
539
- if (sub === "add") {
540
- const { v, p } = parse(rest2, { title: str, url: str, "repo-url": str, id: str });
541
- if (!p[0])
542
- throw new OkbError("Usage: okb source add <file.md|file.pdf> [--title ...] [--repo-url <GitHub file URL>] [--url <rendered page URL>]");
543
- return mutate(v, (ont) => prov.addSource(ont, p[0], { title: v.title, url: v.url, repoUrl: v["repo-url"], id: v.id }));
544
- }
545
- if (sub === "refresh") {
546
- const { v, p } = parse(rest2);
547
- return mutate(v, (ont) => prov.refreshSource(ont, p[0]));
548
- }
549
- if (sub === "outline") {
550
- const { v, p } = parse(rest2, { quotable: bool, problems: bool });
551
- const ont = load(v);
552
- const src = ont.find(p[0], "Source");
553
- if (src.format !== "markdown")
554
- throw new OkbError("outline works on markdown sources.");
555
- const doc = prov.readMarkdownSource(ont, src);
556
- const quoted = new Map();
557
- for (const id of ont.sources(src.id, "PART_OF")) {
558
- const l = ont.get(id);
559
- if (l?.type !== "SourceLocation" || l.startLine === undefined)
560
- continue;
561
- const { startLine, endLine } = l;
562
- for (let n = startLine; n <= (endLine ?? startLine); n++)
563
- quoted.set(n, [...(quoted.get(n) ?? []), id]);
564
- }
565
- const blocks = doc.blocks.filter((b) => !v.quotable || b.quotable);
566
- const outline = () => ({
567
- source: src.id, title: doc.title, frontmatter: doc.frontmatter, problems: doc.problems,
568
- blocks: blocks.map((b) => ({ index: b.index, kind: b.kind, headingPath: b.headingPath, lines: [b.startLine, b.endLine], quotable: b.quotable, note: b.note, calloutType: b.calloutType, row: b.row, text: b.kind === "code" ? undefined : b.text, alreadyQuoted: [...new Set(Array.from({ length: b.endLine - b.startLine + 1 }, (_, k) => quoted.get(b.startLine + k) ?? []).flat())] })),
569
- });
570
- return output(v, outline, () => {
571
- console.log(c.bold(`${doc.title ?? src.id}`) + c.dim(` ${src.localPath} · ${doc.blocks.length} blocks, ${doc.blocks.filter((b) => b.quotable).length} quotable`));
572
- if (doc.problems.length) {
573
- console.log(c.yellow(`\n${doc.problems.length} problem(s) in the document:`));
574
- for (const pr of doc.problems)
575
- console.log(c.yellow(` line ${pr.line}: ${pr.message}`));
576
- }
577
- if (v.problems)
578
- return;
579
- let lastPath = "";
580
- for (const b of blocks) {
581
- const pth = b.headingPath.join(" > ");
582
- if (pth !== lastPath) {
583
- console.log("\n" + c.bold(pth || "(top)"));
584
- lastPath = pth;
585
- }
586
- const mark = !b.quotable ? c.dim("·") : quoted.has(b.startLine) ? SYMBOL.ok : SYMBOL.todo;
587
- const where = `L${b.startLine}${b.endLine > b.startLine ? `-${b.endLine}` : ""}`.padEnd(9);
588
- const label = b.kind === "code" ? c.dim(`code (${b.lang || "text"}), not quotable`) : b.kind === "comment" ? c.dim("comment") : b.kind === "frontmatter" ? c.dim("frontmatter") : (b.calloutType ? c.cyan(`[${b.calloutType}] `) : "") + b.text.slice(0, 110) + (b.text.length > 110 ? "…" : "");
589
- console.log(` ${mark} ${c.dim(where)} ${c.dim(b.kind.padEnd(10))} ${label}${b.note?.startsWith("malformed") ? c.yellow(" ⚠ " + b.note) : ""}`);
590
- }
591
- console.log(c.dim(`\n${SYMBOL.ok} quoted ${SYMBOL.todo} not quoted yet · not quotable · okb quote add ${src.id} "..."`));
592
- });
593
- }
594
- const { v } = parse(sub === "list" ? rest2 : rest);
595
- const ont = load(v);
596
- for (const s of ont.ofType("Source")) {
597
- console.log(`${c.bold(s.id)} ${s.title} ${c.dim(`(${s.format ?? "?"}, ${ont.sources(s.id, "PART_OF").length} quotes)`)} ${c.dim(s.localPath ?? s.url ?? "")}`);
598
- }
599
- if (!ont.ofType("Source").length)
600
- console.log(c.dim("No sources yet. okb source add <file>"));
601
- return;
602
- }
603
- case "quote": {
604
- if (sub === "add") {
605
- const { v, p } = parse(rest.slice(1), { cites: strs, line: str, "allow-code": bool });
606
- if (p.length < 2)
607
- throw new OkbError('Usage: okb quote add <source> "verbatim text" [--cites <node>] [--line N]');
608
- const ont = load(v);
609
- const notes = await prov.addQuote(ont, p[0], p.slice(1).join(" "), { cites: v.cites, line: num(v.line, "--line"), allowCode: v["allow-code"] });
610
- ont.save();
611
- return void say(notes);
612
- }
613
- const { v, p } = parse(sub === "list" ? rest.slice(1) : rest);
614
- const ont = load(v);
615
- const locs = ont.ofType("SourceLocation").filter((l) => !p[0] || ont.targets(l.id, "PART_OF").includes(ont.find(p[0], "Source").id));
616
- return output(v, () => locs.map((l) => ({ ...l, citedBy: ont.sources(l.id, "CITES") })), () => {
617
- for (const l of locs) {
618
- const by = ont.sources(l.id, "CITES").map((x) => ont.label(x));
619
- console.log(`${c.bold(l.id)} ${c.dim(`${l.locator}${l.lines ? `, line ${l.lines}` : ""}`)}\n "${l.quote}"${by.length ? c.dim(`\n cited by: ${by.join(", ")}`) : ""}`);
620
- }
621
- });
622
- }
623
- case "rule": {
624
- if (sub === "add") {
625
- const { v } = parse(rest.slice(1), { statement: str, modality: str, governs: strs, cites: strs, name: str, authored: bool, value: strs, refines: strs, adds: str });
626
- if (!v.statement || !v.modality)
627
- throw new OkbError('Usage: okb rule add --statement "..." --modality MUST|SHOULD|MAY|MUST_NOT|SHOULD_NOT --cites <quote id> [--governs <Class|slot>] [--authored] [--value slot=value ...] [--refines <rule> [--adds "..."]]');
628
- return mutate(v, (ont) => prov.addRule(ont, { statement: v.statement, modality: v.modality, governs: v.governs, cites: v.cites, name: v.name, authored: v.authored, values: v.value, refines: v.refines, adds: v.adds }));
629
- }
630
- if (sub === "refines") {
631
- const { v, p } = parse(rest.slice(1), { adds: str, remove: bool });
632
- if (p.length !== 2)
633
- throw new OkbError('Usage: okb rule refines <rule> <broader rule> [--adds "..."] [--remove]');
634
- return mutate(v, (ont) => prov.refine(ont, p[0], p[1], { adds: v.adds, remove: v.remove }));
635
- }
636
- const { v } = parse(sub === "list" ? rest.slice(1) : rest);
637
- const ont = load(v);
638
- for (const r of ont.ofType("Rule")) {
639
- const st = r.verification?.status ?? "unverified";
640
- console.log(`${c.bold(r.id)} ${c.dim(`[${r.modality} · ${r.authored ? "authored · " : ""}${st}${r.extractionConfidence ? " · " + r.extractionConfidence : ""}]`)}\n ${r.statement}${c.dim(`\n governs: ${ont.targets(r.id, "GOVERNS").map((x) => ont.label(x)).join(", ") || "—"} · cites: ${ont.targets(r.id, "CITES").join(", ")}`)}`);
641
- }
642
- return;
643
- }
644
- case "cite": {
645
- const { v, p } = parse(rest);
646
- if (p.length !== 2)
647
- throw new OkbError("Usage: okb cite <node> <quote id> (attach an existing quote; see okb quote list)");
648
- return mutate(v, (ont) => prov.cite(ont, p[0], p[1]));
649
- }
650
- case "fulfills": {
651
- const { v, p } = parse(rest, { remove: bool });
652
- if (p.length !== 2)
653
- throw new OkbError("Usage: okb fulfills <instance> <rule> [--remove]");
654
- return mutate(v, (ont) => prov.fulfill(ont, p[0], p[1], { remove: v.remove }));
655
- }
656
- case "verify": {
657
- const { v, p } = parse(rest, { status: str, corrected: str, confidence: str, note: str, approve: bool });
658
- if (!p[0])
659
- throw new OkbError('Usage: okb verify <node> --status SUPPORTED|OVERREACH|UNSUPPORTED [--corrected "..."] [--confidence verbatim|paraphrased] · okb verify <node> --approve');
660
- return mutate(v, (ont) => prov.verify(ont, p[0], { status: v.status, corrected: v.corrected, confidence: v.confidence, note: v.note, approve: v.approve }));
661
- }
662
- case "drift": {
663
- const { v, p } = parse(rest);
664
- const onts = (p.length ? p : ["."]).map((d) => Ontology.load(d));
665
- const merged = Ontology.fromData(onts.flatMap((o) => o.nodes.filter((n) => n.type !== "Ontology")), onts.flatMap((o) => o.edges));
666
- const hits = duplicateQuotes(merged);
667
- return output(v, () => hits, () => {
668
- if (!hits.length)
669
- return void console.log(`${SYMBOL.ok} No near-duplicate quotes across different sources.`);
670
- for (const h of hits)
671
- console.log(`${SYMBOL.info} ${h.message}`);
672
- });
673
- }
674
- case "skills": {
675
- const SKILLS_USAGE = "Usage: okb skills install [--copy] [--dir <folder>] [--force] · okb skills status [--dir <folder>]";
676
- if (sub !== "install" && sub !== "status")
677
- throw new OkbError(SKILLS_USAGE);
678
- const { v, p } = parse(rest.slice(1), sub === "install" ? { copy: bool, dir: str, force: bool } : { dir: str });
679
- if (p.length)
680
- throw new OkbError(SKILLS_USAGE);
681
- const opts = { dir: v.dir, metaVersion: MetaKB.get().version };
682
- if (sub === "install") {
683
- const { dir, lines } = installSkills({ ...opts, copy: v.copy, force: v.force });
684
- if (v.json)
685
- return void console.log(JSON.stringify({ dir, lines }, null, 2));
686
- console.log(`${SYMBOL.ok} Skills in ${dir}`);
687
- for (const l of lines)
688
- console.log(` ${l}`);
689
- console.log(c.dim("\n Start a new Claude Code or Cursor session to load them."));
690
- return;
691
- }
692
- const { dir, skills } = skillsStatus(opts);
693
- const good = (s) => s === "current";
694
- if (!skills.every((s) => good(s.state)))
695
- process.exitCode = 1;
696
- return output(v, () => ({ dir, metaKbVersion: opts.metaVersion, skills }), () => {
697
- console.log(c.bold(`Skills in ${dir}`) + c.dim(` (okb meta-KB ${opts.metaVersion})`));
698
- for (const s of skills)
699
- console.log(` ${good(s.state) ? SYMBOL.ok : s.state === "missing" ? SYMBOL.todo : SYMBOL.warning} ${s.name.padEnd(26)} ${s.detail}`);
700
- if (!skills.every((s) => good(s.state)))
701
- console.log(c.dim("\n Fix it with: okb skills install"));
702
- });
703
- }
704
- default:
705
- throw new OkbError(`Unknown command '${cmd}'. Run okb help.`);
706
- }
3
+ import { OkbError } from "@ontology-kit/reader";
4
+ import { COMMANDS } from "./commands.js";
5
+ import { asksForHelp, isParseError, leadingGlobals } from "./command-table.js";
6
+ import { runCommand } from "./runner.js";
7
+ import { SYMBOL } from "./render.js";
8
+ async function main(argv) {
9
+ // Global options (-C, --json) may come before the command; they also work after it.
10
+ const { globals, rest } = leadingGlobals(argv);
11
+ const words = asksForHelp(rest) ? ["help"] : rest;
12
+ await runCommand(COMMANDS, words, globals);
707
13
  }
708
14
  try {
709
15
  await main(process.argv.slice(2));
710
16
  }
711
17
  catch (e) {
712
- if (e instanceof OkbError || String(e?.code ?? "").startsWith("ERR_PARSE_ARGS")) {
18
+ if (e instanceof OkbError || isParseError(e)) {
713
19
  console.error(`${SYMBOL.error} ${e.message}`);
714
20
  process.exitCode = 2;
715
21
  }