@ontology-kit/okb 0.1.0 → 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 (74) hide show
  1. package/README.md +1 -1
  2. package/dist/check.d.ts +43 -0
  3. package/dist/check.js +83 -0
  4. package/dist/checks.d.ts +1 -1
  5. package/dist/checks.js +4 -4
  6. package/dist/cli.js +159 -45
  7. package/dist/clock.js +1 -1
  8. package/dist/commands.js +96 -2
  9. package/dist/diff.d.ts +85 -0
  10. package/dist/diff.js +323 -0
  11. package/dist/export.d.ts +1 -1
  12. package/dist/export.js +1 -1
  13. package/dist/families.d.ts +1 -1
  14. package/dist/families.js +1 -1
  15. package/dist/help.d.ts +1 -1
  16. package/dist/help.js +9 -2
  17. package/dist/kbdocs.d.ts +18 -0
  18. package/dist/kbdocs.js +393 -0
  19. package/dist/metakb.d.ts +1 -1
  20. package/dist/metakb.js +1 -1
  21. package/dist/naming.d.ts +2 -2
  22. package/dist/naming.js +2 -2
  23. package/dist/ontology-ref.d.ts +20 -0
  24. package/dist/ontology-ref.js +108 -0
  25. package/dist/ops/admin.d.ts +1 -1
  26. package/dist/ops/admin.js +24 -7
  27. package/dist/ops/classes.d.ts +1 -1
  28. package/dist/ops/classes.js +13 -5
  29. package/dist/ops/instances.d.ts +2 -1
  30. package/dist/ops/instances.js +7 -1
  31. package/dist/ops/links.d.ts +1 -1
  32. package/dist/ops/links.js +1 -1
  33. package/dist/ops/naming.d.ts +1 -1
  34. package/dist/ops/naming.js +3 -1
  35. package/dist/ops/scope.d.ts +5 -1
  36. package/dist/ops/scope.js +19 -1
  37. package/dist/ops/slots.d.ts +1 -1
  38. package/dist/ops/slots.js +15 -2
  39. package/dist/ops/values.d.ts +1 -1
  40. package/dist/ops/values.js +5 -1
  41. package/dist/provenance.d.ts +4 -2
  42. package/dist/provenance.js +58 -17
  43. package/dist/release.d.ts +48 -0
  44. package/dist/release.js +318 -0
  45. package/dist/render.d.ts +4 -1
  46. package/dist/render.js +21 -2
  47. package/dist/resync.d.ts +98 -0
  48. package/dist/resync.js +234 -0
  49. package/dist/review.d.ts +1 -1
  50. package/dist/review.js +1 -1
  51. package/dist/reviewdocs.d.ts +42 -0
  52. package/dist/reviewdocs.js +263 -0
  53. package/dist/skills.js +1 -1
  54. package/dist/status.d.ts +1 -1
  55. package/dist/status.js +1 -1
  56. package/dist/types.d.ts +1 -1
  57. package/dist/types.js +1 -1
  58. package/dist/verifynote.d.ts +18 -0
  59. package/dist/verifynote.js +92 -0
  60. package/meta-kb/data/manifest.json +2 -2
  61. package/meta-kb/data/nodes.json +8 -8
  62. package/package.json +7 -3
  63. package/schema/edge.schema.json +68 -0
  64. package/schema/edges.schema.json +9 -0
  65. package/schema/node.schema.json +893 -0
  66. package/schema/nodes.schema.json +9 -0
  67. package/schema/okb.schema.json +41 -0
  68. package/skills/build-domain-kb-from-docs/SKILL.md +20 -2
  69. package/skills/ontology-coach/SKILL.md +6 -2
  70. package/skills/ontology-maintainer/SKILL.md +152 -0
  71. package/skills/ontology-review/SKILL.md +3 -1
  72. package/skills/ontology-signoff/SKILL.md +182 -0
  73. package/templates/okb-check.yml +132 -0
  74. package/templates/pull_request_template.md +16 -0
package/README.md CHANGED
@@ -4,7 +4,7 @@ The `okb` command-line tool from [Ontology Kit](https://ontology-kit.dev), a too
4
4
 
5
5
  It's for a team that keeps a knowledge base and wants every fact to point back to its source. It's also for someone building their first: the Ontology 101 method (Noy & McGuinness, 2001), the Learn course and the tutorials walk you through it step by step.
6
6
 
7
- The package ships the `okb` command, the meta-KB (a knowledge base about building knowledge bases, which holds the method and its rules), and skills that let Claude coach you, review your work, and extract a knowledge base from documents. Other tools can read the file format with the small [`@ontology-kit/format`](https://www.npmjs.com/package/@ontology-kit/format) package, which okb itself builds on.
7
+ The package ships the `okb` command, the meta-KB (a knowledge base about building knowledge bases, which holds the method and its rules), and skills that let Claude coach you, review your work, and extract a knowledge base from documents. Other tools can read the file format with the small [`@ontology-kit/reader`](https://www.npmjs.com/package/@ontology-kit/reader) package, which okb itself builds on.
8
8
 
9
9
  ## Install
10
10
 
@@ -0,0 +1,43 @@
1
+ /**
2
+ * `okb check`: the one answer to "is this KB safe to merge?". It reads the folder and never writes it
3
+ * or takes the lock. Each check is one entry in CHECK_STEPS; to add a check (the ledger check, `okb cq check`),
4
+ * add an entry and, if it handles a rule that `validate` also reports, list the rule in its `rules`.
5
+ */
6
+ import type { Ontology } from "@ontology-kit/reader";
7
+ import type { Finding } from "./types.js";
8
+ export type StepStatus = "pass" | "warn" | "fail";
9
+ export interface StepResult {
10
+ id: string;
11
+ title: string;
12
+ status: StepStatus;
13
+ /** One line saying what was found, for the summary. */
14
+ summary: string;
15
+ /** What a reviewer should look at, one entry per problem. */
16
+ problems: string[];
17
+ }
18
+ export interface CheckInput {
19
+ ont: Ontology;
20
+ /** The report of `validate --all` (nothing hidden). */
21
+ findings: Finding[];
22
+ /** The okb version running this check. */
23
+ installed: string;
24
+ }
25
+ export interface CheckStep {
26
+ id: string;
27
+ title: string;
28
+ /** Rules this step reports. `validation` leaves them out so a problem shows once. */
29
+ rules?: string[];
30
+ run(input: CheckInput): Omit<StepResult, "id" | "title">;
31
+ }
32
+ /** Compare `a.b.c[-pre]` versions (a leading `v` and `+build` are ignored): negative when `a` is older than `b`. Null for text that isn't a version. */
33
+ export declare function compareVersions(a: string, b: string): number | null;
34
+ /** The checks, in the order they're reported. */
35
+ export declare const CHECK_STEPS: CheckStep[];
36
+ export interface CheckReport {
37
+ ok: boolean;
38
+ installed: string;
39
+ pinned: string | null;
40
+ steps: StepResult[];
41
+ }
42
+ /** Run every check. Reads the folder and its source files; writes nothing. */
43
+ export declare function runCheck(ont: Ontology, installed: string): Promise<CheckReport>;
package/dist/check.js ADDED
@@ -0,0 +1,83 @@
1
+ import { loadSourcePages, runChecks } from "./checks.js";
2
+ import { compareVersions as compareSemver } from "./release.js";
3
+ const open = (fs) => fs.filter((f) => !f.explainedBy);
4
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
5
+ /** Compare `a.b.c[-pre]` versions (a leading `v` and `+build` are ignored): negative when `a` is older than `b`. Null for text that isn't a version. */
6
+ export function compareVersions(a, b) {
7
+ const core = (v) => /^v?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?:\+.*)?$/.exec(v.trim())?.[1];
8
+ const x = core(a), y = core(b);
9
+ return x && y ? compareSemver(x, y) : null;
10
+ }
11
+ const QUOTE_RULES = ["prov-quote-current"];
12
+ const VERIFY_RULES = ["prov-verified", "prov-cites-quote"];
13
+ /** The checks, in the order they're reported. */
14
+ export const CHECK_STEPS = [
15
+ {
16
+ id: "validate",
17
+ title: "Validation (okb validate --all)",
18
+ run({ findings }) {
19
+ const claimed = new Set(CHECK_STEPS.flatMap((s) => s.rules ?? []));
20
+ const mine = open(findings).filter((f) => !claimed.has(f.rule));
21
+ const errors = mine.filter((f) => f.severity === "error");
22
+ const warnings = mine.filter((f) => f.severity === "warning").length;
23
+ const tail = warnings ? ` (${plural(warnings, "warning")} ${warnings === 1 ? "doesn't" : "don't"} block a merge; okb validate --all lists them)` : "";
24
+ return errors.length
25
+ ? { status: "fail", summary: `${plural(errors.length, "error")}${tail}`, problems: errors.map((f) => `${f.rule}: ${f.message}`) }
26
+ : { status: "pass", summary: `no errors${tail}`, problems: [] };
27
+ },
28
+ },
29
+ {
30
+ id: "quotes",
31
+ title: "Quotes are still in their sources",
32
+ rules: QUOTE_RULES,
33
+ run({ ont, findings }) {
34
+ // A quote that can't be checked fails too: in CI a missing source file means the check proved nothing.
35
+ // A quote that only moved is still in its source (the validator reports it at info level), so it doesn't fail.
36
+ const found = open(findings).filter((f) => QUOTE_RULES.includes(f.rule));
37
+ const bad = found.filter((f) => f.severity !== "info");
38
+ const moved = found.length - bad.length;
39
+ const unchecked = ont.ofType("Source").filter((s) => !s.localPath && ont.sources(s.id, "PART_OF").some((i) => ont.get(i)?.type === "SourceLocation")).length;
40
+ const notes = [
41
+ unchecked ? `${plural(unchecked, "source")} with quotes has no localPath, so its quotes weren't checked` : "",
42
+ moved ? `${plural(moved, "quote")} moved; okb source refresh --all updates them` : "",
43
+ ].filter(Boolean);
44
+ const note = notes.length ? ` (${notes.join("; ")})` : "";
45
+ return bad.length
46
+ ? { status: "fail", summary: `${plural(bad.length, "quote")} can't be matched${note}`, problems: bad.map((f) => f.message) }
47
+ : { status: unchecked ? "warn" : "pass", summary: `every checked quote is still in its source${note}`, problems: [] };
48
+ },
49
+ },
50
+ {
51
+ id: "verification",
52
+ title: "Rules and extracted facts are verified",
53
+ rules: VERIFY_RULES,
54
+ run({ findings }) {
55
+ const bad = open(findings).filter((f) => VERIFY_RULES.includes(f.rule));
56
+ return bad.length
57
+ ? { status: "fail", summary: `${plural(bad.length, "problem")}: something unverified, not supported by its quote, or without a quote`, problems: bad.map((f) => f.message) }
58
+ : { status: "pass", summary: "nothing is unverified, unsupported or waiting for approval", problems: [] };
59
+ },
60
+ },
61
+ {
62
+ id: "okb-version",
63
+ title: "okb version",
64
+ run({ ont, installed }) {
65
+ const pinned = ont.manifest.okbVersion;
66
+ if (!pinned)
67
+ return { status: "pass", summary: `installed ${installed}; the KB pins no version (okbVersion in okb.json)`, problems: [] };
68
+ const cmp = compareVersions(installed, pinned);
69
+ if (cmp === null)
70
+ return { status: "warn", summary: `okbVersion '${pinned}' in okb.json isn't a version like 1.2.3`, problems: [] };
71
+ return cmp < 0
72
+ ? { status: "warn", summary: `installed ${installed} is older than the ${pinned} this KB pins; install ${pinned} or newer (npm i -g @ontology-kit/okb@${pinned})`, problems: [] }
73
+ : { status: "pass", summary: `installed ${installed}, pinned ${pinned}`, problems: [] };
74
+ },
75
+ },
76
+ ];
77
+ /** Run every check. Reads the folder and its source files; writes nothing. */
78
+ export async function runCheck(ont, installed) {
79
+ const ctx = { pages: await loadSourcePages(ont) };
80
+ const { findings } = runChecks(ont, { all: true }, ctx);
81
+ const steps = CHECK_STEPS.map((s) => ({ id: s.id, title: s.title, ...s.run({ ont, findings, installed }) }));
82
+ return { ok: steps.every((s) => s.status !== "fail"), installed, pinned: ont.manifest.okbVersion ?? null, steps };
83
+ }
package/dist/checks.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Ontology } from "@ontology-kit/format";
1
+ import { Ontology } from "@ontology-kit/reader";
2
2
  import { type Finding, type Severity } from "./types.js";
3
3
  import { type MdDoc } from "./markdown.js";
4
4
  export interface Hit {
package/dist/checks.js CHANGED
@@ -10,7 +10,7 @@
10
10
  import { existsSync } from "node:fs";
11
11
  import { isAbsolute, join } from "node:path";
12
12
  import { MetaKB } from "./metakb.js";
13
- import { Ontology, VALUE_TYPES, DISPOSITIONS } from "@ontology-kit/format";
13
+ import { Ontology, VALUE_TYPES, DISPOSITIONS } from "@ontology-kit/reader";
14
14
  import { isOneOf } from "./types.js";
15
15
  import * as naming from "./naming.js";
16
16
  import { findQuote, loadPages, normalize } from "./quotes.js";
@@ -80,7 +80,7 @@ export const CHECKS = {
80
80
  continue;
81
81
  }
82
82
  if (seen.has(n.id))
83
- hits.push({ message: `Two nodes share the id '${n.id}'.`, nodes: [n.id] });
83
+ hits.push({ message: `Two nodes share the id '${n.id}'. A git merge that kept both sides' version of a node is the likely cause; keep one and delete the other.`, nodes: [n.id] });
84
84
  seen.add(n.id);
85
85
  const nt = nodeTypes.get(n.type);
86
86
  if (!nt) {
@@ -113,7 +113,7 @@ export const CHECKS = {
113
113
  const a = ont.get(e.from);
114
114
  const b = ont.get(e.to);
115
115
  if (!a || !b)
116
- hits.push({ message: `Edge ${tag} points at a node that doesn't exist (${!a ? e.from : e.to}).`, nodes: [a ? e.from : e.to] });
116
+ hits.push({ message: `Edge ${tag} points at a node that doesn't exist (${!a ? e.from : e.to}). A git merge where one branch deleted the node and another added this edge is the likely cause; remove the edge or restore the node.`, nodes: [a ? e.from : e.to] });
117
117
  else if (!["Instance", "Class"].includes(a.type) || !["Instance", "Class"].includes(b.type) || (a.type === "Instance" && b.type === "Class")) {
118
118
  hits.push({ message: `Relationship ${tag} connects ${a.type} → ${b.type}; relationships link instances (or state a fixed value on a class).`, nodes: [e.from, e.to] });
119
119
  }
@@ -125,7 +125,7 @@ export const CHECKS = {
125
125
  const a = ont.get(e.from);
126
126
  const b = ont.get(e.to);
127
127
  if (!a || !b) {
128
- hits.push({ message: `Edge ${tag} points at a node that doesn't exist (${!a ? e.from : e.to}).`, nodes: [a ? e.from : e.to] });
128
+ hits.push({ message: `Edge ${tag} points at a node that doesn't exist (${!a ? e.from : e.to}). A git merge where one branch deleted the node and another added this edge is the likely cause; remove the edge or restore the node.`, nodes: [a ? e.from : e.to] });
129
129
  continue;
130
130
  }
131
131
  // Instance misuse in the hierarchy gets its own friendlier rule (inst-are-leaves).
package/dist/cli.js CHANGED
@@ -5,15 +5,22 @@ import { writeFileSync } from "node:fs";
5
5
  import { resolve } from "node:path";
6
6
  import { duplicateQuotes, loadSourcePages, runChecks } from "./checks.js";
7
7
  import { MetaKB, explainName } from "./metakb.js";
8
- import { OkbError, Ontology } from "@ontology-kit/format";
8
+ import { OkbError, Ontology } from "@ontology-kit/reader";
9
9
  import * as ops from "./ops.js";
10
- import { c, explain, formatFindings, listExplainable, mermaid, show, stepGuide, SYMBOL, tree } from "./render.js";
10
+ import { c, explain, formatCheck, formatFindings, listExplainable, mermaid, show, stepGuide, SYMBOL, tree } from "./render.js";
11
11
  import { exportGraph, toCypher } from "./export.js";
12
+ import { kbDocs, writeChangedPages, writeKbDocs, writePages } from "./kbdocs.js";
13
+ import { changedPageSet, changesPage, contextPage } from "./reviewdocs.js";
12
14
  import { buildReview } from "./review.js";
13
15
  import * as prov from "./provenance.js";
14
16
  import { computeStatus } from "./status.js";
15
17
  import { HELP } from "./help.js";
16
18
  import { PACKAGE_VERSION } from "./version.js";
19
+ import { runCheck } from "./check.js";
20
+ import { renderResync, resync } from "./resync.js";
21
+ import { diffMarkdown, diffOntologies } from "./diff.js";
22
+ import { loadSide } from "./ontology-ref.js";
23
+ import { cutRelease, verifyRelease } from "./release.js";
17
24
  import { installSkills, skillsStatus } from "./skills.js";
18
25
  const str = { type: "string" };
19
26
  const strs = { type: "string", multiple: true };
@@ -48,11 +55,13 @@ function output(v, data, human) {
48
55
  function load(v) {
49
56
  return Ontology.load(v.C ?? ".");
50
57
  }
58
+ /** Load the folder, change it, save it and print the notes, all with the folder's lock held. */
51
59
  function mutate(v, fn) {
52
- const ont = load(v);
53
- const notes = fn(ont);
54
- ont.save();
55
- say(notes);
60
+ Ontology.edit(v.C ?? ".", (ont) => {
61
+ const notes = ont.tick(() => fn(ont));
62
+ ont.save();
63
+ say(notes);
64
+ });
56
65
  }
57
66
  async function main(argvIn) {
58
67
  // Accept -C <folder> anywhere, including before the command.
@@ -106,11 +115,13 @@ async function main(argvIn) {
106
115
  case "scope": {
107
116
  const { v } = parse(rest, { name: str, domain: str, purpose: str, users: strs, maintainers: strs, "out-of-scope": strs, kind: str });
108
117
  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
- }
118
+ const ont = touched
119
+ ? Ontology.edit(v.C ?? ".", (o) => {
120
+ ops.setScope(o, { name: v.name, domain: v.domain, purpose: v.purpose, users: v.users, maintainers: v.maintainers, outOfScope: v["out-of-scope"], kind: v.kind });
121
+ o.save();
122
+ return o;
123
+ })
124
+ : load(v);
114
125
  const m = ont.meta;
115
126
  const row = (k, val) => console.log(` ${c.dim(k.padEnd(13))} ${Array.isArray(val) ? val.join(", ") || c.yellow("—") : val || c.yellow("—")}`);
116
127
  return output(v, () => m, () => {
@@ -147,17 +158,7 @@ async function main(argvIn) {
147
158
  }
148
159
  if (sub === "set") {
149
160
  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
+ return mutate(v, (ont) => ops.setCQ(ont, p[0], { text: v.text, status: v.status }));
161
162
  }
162
163
  if (sub === "remove") {
163
164
  const { v, p } = parse(rest.slice(1));
@@ -165,14 +166,15 @@ async function main(argvIn) {
165
166
  }
166
167
  const { v } = parse(sub === "list" ? rest.slice(1) : rest);
167
168
  const ont = load(v);
168
- const qs = ont.ofType("CompetencyQuestion");
169
+ const qs = ont.numbered("CompetencyQuestion");
169
170
  return output(v, () => qs.map((q) => ({ ...q, needs: ont.targets(q.id, "NEEDS") })), () => {
170
171
  if (!qs.length)
171
172
  return void console.log(c.dim('No competency questions yet. okb cq add "..."'));
172
173
  for (const q of qs) {
173
174
  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>...)"}`));
175
+ const num = ont.displayNumber(q);
176
+ console.log(`${c.bold(String(num).padEnd(3))} ${q.text} ${c.dim(`[${q.status ?? "draft"}]`)}`);
177
+ console.log(c.dim(` needs: ${needs.length ? needs.join(", ") : "(not linked yet: okb cq link " + num + " <Class|slot>...)"}`));
176
178
  }
177
179
  });
178
180
  }
@@ -309,8 +311,7 @@ async function main(argvIn) {
309
311
  ...(p.length > 1 ? ops.assign(ont, ont.find(p[0], "Instance").id, p.slice(1)) : []),
310
312
  ];
311
313
  if (v.desc !== undefined) {
312
- ont.find(p[0], "Instance").description = v.desc;
313
- notes.push("Updated description.");
314
+ notes.push(...ops.setInstanceDescription(ont, p[0], v.desc));
314
315
  }
315
316
  return notes;
316
317
  });
@@ -326,10 +327,10 @@ async function main(argvIn) {
326
327
  }
327
328
  const { v } = parse(sub === "list" ? rest.slice(1) : rest);
328
329
  const ont = load(v);
329
- const ds = ont.ofType("DesignDecision");
330
+ const ds = ont.numbered("DesignDecision");
330
331
  return output(v, () => ds, () => {
331
332
  for (const d of ds) {
332
- console.log(`${c.bold(d.id)} ${d.title}`);
333
+ console.log(`${c.bold(String(ont.displayNumber(d)).padEnd(3))} ${d.title}`);
333
334
  console.log(` ${d.decision}${d.rationale ? c.dim(" · why: " + d.rationale) : ""}`);
334
335
  const about = ont.targets(d.id, "ABOUT").map((x) => ont.label(x));
335
336
  if (about.length || d.metaRules)
@@ -422,14 +423,16 @@ async function main(argvIn) {
422
423
  const { v, p } = parse(rest);
423
424
  const meta = MetaKB.get();
424
425
  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();
426
+ const { target, leaving } = Ontology.edit(v.C ?? ".", (ont) => {
427
+ const target = p[0] === "next" ? ont.step + 1 : p[0] === "prev" ? ont.step - 1 : Number(p[0]);
428
+ if (!meta.step(target))
429
+ throw new OkbError(`There is no step ${p[0]}. Steps are 1–${meta.steps.length}.`);
430
+ const st = computeStatus(ont);
431
+ const leaving = st.steps.find((s) => s.order === ont.step);
432
+ ont.manifest.currentStep = target;
433
+ ont.save();
434
+ return { target, leaving };
435
+ });
433
436
  if (target > leaving.order && !leaving.complete) {
434
437
  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
438
  }
@@ -543,8 +546,28 @@ async function main(argvIn) {
543
546
  return mutate(v, (ont) => prov.addSource(ont, p[0], { title: v.title, url: v.url, repoUrl: v["repo-url"], id: v.id }));
544
547
  }
545
548
  if (sub === "refresh") {
546
- const { v, p } = parse(rest2);
547
- return mutate(v, (ont) => prov.refreshSource(ont, p[0]));
549
+ const { v, p } = parse(rest2, { all: bool, record: bool, "dry-run": bool, strict: bool });
550
+ if (!v.all)
551
+ return mutate(v, (ont) => prov.refreshSource(ont, p[0]));
552
+ if (p.length)
553
+ throw new OkbError("--all re-checks every source; leave out the source name (or drop --all).");
554
+ const ont = load(v);
555
+ const pages = await loadSourcePages(ont);
556
+ const o = { write: !v["dry-run"], record: !!v.record && !v["dry-run"] };
557
+ let report = resync(ont, pages, { write: false, record: false });
558
+ // Take the lock only when something has to be written.
559
+ if (o.write && (report.moved.length || o.record)) {
560
+ report = Ontology.edit(v.C ?? ".", (locked) => {
561
+ const r = locked.tick(() => resync(locked, pages, o));
562
+ locked.save();
563
+ return r;
564
+ });
565
+ }
566
+ output(v, () => report, () => say(renderResync(report, { dryRun: !o.write })));
567
+ // 1 when the KB no longer matches its documents (a quote is gone or a source can't be read); --strict also when blocks need work.
568
+ if (!report.ok || (v.strict && report.worklist.length))
569
+ process.exitCode = 1;
570
+ return;
548
571
  }
549
572
  if (sub === "outline") {
550
573
  const { v, p } = parse(rest2, { quotable: bool, problems: bool });
@@ -605,9 +628,11 @@ async function main(argvIn) {
605
628
  const { v, p } = parse(rest.slice(1), { cites: strs, line: str, "allow-code": bool });
606
629
  if (p.length < 2)
607
630
  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();
631
+ const notes = await Ontology.edit(v.C ?? ".", async (ont) => {
632
+ const notes = await prov.addQuote(ont, p[0], p.slice(1).join(" "), { cites: v.cites, line: num(v.line, "--line"), allowCode: v["allow-code"] });
633
+ ont.save();
634
+ return notes;
635
+ });
611
636
  return void say(notes);
612
637
  }
613
638
  const { v, p } = parse(sub === "list" ? rest.slice(1) : rest);
@@ -654,10 +679,10 @@ async function main(argvIn) {
654
679
  return mutate(v, (ont) => prov.fulfill(ont, p[0], p[1], { remove: v.remove }));
655
680
  }
656
681
  case "verify": {
657
- const { v, p } = parse(rest, { status: str, corrected: str, confidence: str, note: str, approve: bool });
682
+ const { v, p } = parse(rest, { status: str, corrected: str, confidence: str, note: str, ref: str, approve: bool });
658
683
  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 }));
684
+ throw new OkbError('Usage: okb verify <node> --status SUPPORTED|OVERREACH|UNSUPPORTED [--corrected "..."] [--confidence verbatim|paraphrased] [--note "..."] [--ref <url>] · okb verify <node> --approve');
685
+ return mutate(v, (ont) => prov.verify(ont, p[0], { status: v.status, corrected: v.corrected, confidence: v.confidence, note: v.note, ref: v.ref, approve: v.approve }));
661
686
  }
662
687
  case "drift": {
663
688
  const { v, p } = parse(rest);
@@ -671,6 +696,95 @@ async function main(argvIn) {
671
696
  console.log(`${SYMBOL.info} ${h.message}`);
672
697
  });
673
698
  }
699
+ case "release": {
700
+ if (sub === "verify") {
701
+ const { v, p } = parse(rest.slice(1));
702
+ if (p.length)
703
+ throw new OkbError("Usage: okb release verify (checks the folder against its manifest.json; read-only)");
704
+ const r = verifyRelease(resolve(v.C ?? "."));
705
+ output(v, () => r, () => {
706
+ if (r.ok)
707
+ return void console.log(`${SYMBOL.ok} ${r.id} ${r.version} matches its manifest (${r.checked} files).`);
708
+ console.log(`${SYMBOL.error} ${r.id} ${r.version} doesn't match its manifest:`);
709
+ for (const pr of r.problems)
710
+ console.log(` - ${pr}`);
711
+ console.log(c.dim(" If the changes are intended, cut a new release: okb release <version>. If not, restore the files (git checkout)."));
712
+ });
713
+ process.exitCode = r.ok ? 0 : 1;
714
+ return;
715
+ }
716
+ const { v, p } = parse(rest);
717
+ if (p.length !== 1)
718
+ throw new OkbError("Usage: okb release <version> · okb release verify (version is semver, like 1.0.0)");
719
+ const dir = v.C ?? ".";
720
+ const result = await Ontology.edit(dir, async (ont) => {
721
+ const findings = runChecks(ont, { all: false }, { pages: await loadSourcePages(ont) }).findings;
722
+ return cutRelease(ont, p[0], findings);
723
+ });
724
+ output(v, () => ({ version: result.version, previous: result.previous ?? null, manifest: result.manifest }), () => say(result.notes));
725
+ return;
726
+ }
727
+ case "pin": {
728
+ const { v, p } = parse(rest);
729
+ if (p.length)
730
+ throw new OkbError("Usage: okb pin (records the installed okb version in okb.json)");
731
+ Ontology.edit(v.C ?? ".", (ont) => {
732
+ ont.manifest.okbVersion = PACKAGE_VERSION;
733
+ ont.save();
734
+ });
735
+ console.log(`${SYMBOL.ok} Pinned okb ${PACKAGE_VERSION} in okb.json. okb check warns anyone with an older okb, and the CI workflow installs this version.`);
736
+ return;
737
+ }
738
+ case "check": {
739
+ const { v, p } = parse(rest);
740
+ if (p.length)
741
+ throw new OkbError("Usage: okb check [--json] (checks the current folder; use -C <folder> for another)");
742
+ const ont = load(v);
743
+ const report = await runCheck(ont, PACKAGE_VERSION);
744
+ output(v, () => report, () => console.log(formatCheck(report, ont.meta.name)));
745
+ process.exitCode = report.ok ? 0 : 1;
746
+ return;
747
+ }
748
+ case "diff": {
749
+ const { v, p } = parse(rest);
750
+ if (p.length < 1 || p.length > 2)
751
+ throw new OkbError("Usage: okb diff <old> [<new>] (each a folder or a git ref; with one, <new> is the current folder)");
752
+ const here = v.C ?? ".";
753
+ const a = loadSide(p[0], here);
754
+ const b = p[1] ? loadSide(p[1], here) : { ont: Ontology.load(here), name: "working folder" };
755
+ const d = diffOntologies(a.ont, b.ont, a.name, b.name);
756
+ return output(v, () => d, () => process.stdout.write(diffMarkdown(d)));
757
+ }
758
+ case "docs": {
759
+ const DOCS_USAGE = "Usage: okb docs --out <folder> · okb docs --out <folder> --changed <ref> [--hops N] · okb docs --out <folder> --context";
760
+ const { v, p } = parse(rest, { out: str, changed: str, hops: str, context: bool });
761
+ if (p.length || !v.out)
762
+ throw new OkbError(DOCS_USAGE);
763
+ const out = resolve(v.out);
764
+ const done = (files, what, hint, extra = {}) => output(v, () => ({ out: v.out, files, ...extra }), () => console.log(`${SYMBOL.ok} Wrote ${what} to ${v.out}${hint}.`));
765
+ if (v.context && (v.changed !== undefined || v.hops !== undefined))
766
+ throw new OkbError("--context is its own view of every rule; it doesn't combine with --changed or --hops.");
767
+ if (v.hops !== undefined && v.changed === undefined)
768
+ throw new OkbError("--hops adds neighbors to a --changed view; give --changed <ref> too.");
769
+ if (v.context) {
770
+ const ont = load(v);
771
+ return done(writePages(out, { "rules-in-context.md": contextPage(ont, await loadSourcePages(ont)) }), "rules-in-context.md", "");
772
+ }
773
+ if (v.changed !== undefined) {
774
+ const hops = num(v.hops, "--hops") ?? 0;
775
+ const ont = load(v);
776
+ const old = loadSide(v.changed, v.C ?? ".");
777
+ const { pages, changes } = changedPageSet(kbDocs(old.ont), kbDocs(ont), hops);
778
+ const after = kbDocs(ont);
779
+ const report = resync(ont, await loadSourcePages(ont), { write: false, record: false });
780
+ const files = Object.fromEntries(pages.map((n) => [n, after[n]]));
781
+ files["changes.md"] = changesPage({ against: v.changed, name: ont.meta.name, changes, hops, resync: report });
782
+ const stale = report.gone.length + report.moved.length + report.worklist.length;
783
+ return done(writeChangedPages(out, files), `${pages.length} changed ${pages.length === 1 ? "page" : "pages"} and changes.md (${stale} source ${stale === 1 ? "change" : "changes"} not yet in the KB)`, " (start at changes.md)", changes);
784
+ }
785
+ const files = writeKbDocs(load(v), out);
786
+ return done(files, `${files.length} pages`, " (start at index.md)");
787
+ }
674
788
  case "skills": {
675
789
  const SKILLS_USAGE = "Usage: okb skills install [--copy] [--dir <folder>] [--force] · okb skills status [--dir <folder>]";
676
790
  if (sub !== "install" && sub !== "status")
package/dist/clock.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * convention) pins it, so generated output like examples/wine is the same on any
5
5
  * day and in any time zone.
6
6
  */
7
- import { OkbError } from "@ontology-kit/format";
7
+ import { OkbError } from "@ontology-kit/reader";
8
8
  /** YYYY-MM-DD, in UTC. */
9
9
  export function today() {
10
10
  const epoch = process.env.SOURCE_DATE_EPOCH;
package/dist/commands.js CHANGED
@@ -429,6 +429,37 @@ export const COMMANDS = [
429
429
  ],
430
430
  }],
431
431
  },
432
+ {
433
+ name: "docs",
434
+ group: "Reviewing and sharing",
435
+ description: "Writes Markdown reference pages for the ontology, so people can read its structure and rules without okb: an index, one page per class, a rules page and a sources page.",
436
+ forms: [
437
+ {
438
+ description: "Writes `index.md` (scope, competency questions, class tree, decisions), `classes/<id>.md` (slots with allowed values, inherited and own rules with their quotes, instances, decisions), `rules.md` and `sources.md`. Every rule links to its quote on the sources page. Items have stable anchors made from their ids (`rule.breve` becomes `#rule-breve`), links are relative, and the output has no dates, so you can commit it and check it for drift. It replaces pages an earlier run wrote and leaves other files alone. It never changes the ontology.",
439
+ examples: ["okb docs --out docs/kb"],
440
+ args: [["--out", "folder", "Where to write the pages. Required; it is created if it doesn't exist."]],
441
+ },
442
+ {
443
+ sub: "--changed",
444
+ description: "A review view of a change: only the pages whose text differs from `<ref>` (a git ref or a folder, the same as `okb diff`). A rule changed on a class changes the page of every subclass that inherits it, so those pages come with it. It also writes `changes.md`, which lists the changed pages and the stale-quote worklist from `okb source refresh --all --dry-run` (quotes that are gone or moved, and blocks that are new or changed, each with the nodes that cite them), because a source edit that hasn't been re-synced yet changes no page. Pages are the same text as the full render, so links to pages that aren't in the folder point into the full output. It only adds and overwrites files, so write it to a scratch folder, not to the committed pages. It never changes the ontology.",
445
+ examples: ["okb docs --out review --changed main", "okb docs --out review --changed v1.0.0 --hops 1"],
446
+ args: [
447
+ ["--out", "folder", "Where to write the pages. Required."],
448
+ ["--changed", "ref", "The git ref (or folder) to compare the working folder with."],
449
+ ["--hops", "number", "Also write the class pages that link to or from a changed class page, this many links away. Default 0. It doesn't go through the index, rules or sources pages, which link to everything."],
450
+ ],
451
+ },
452
+ {
453
+ sub: "--context",
454
+ description: "A review view of every rule beside the source text around its quote: the statement, modality, verification status, the verifier's note (when `okb verify --note` stored one), the original draft of a corrected rule, the quote, and the lines around it with the quoted lines marked. Rules that need a person come first (UNSUPPORTED, OVERREACH not yet approved, not verified, no quote, quote no longer in the source), then the rest by name. It reads the source files, so it needs them on disk. A source that isn't Markdown shows the quote alone. It writes `rules-in-context.md` and never changes the ontology.",
455
+ examples: ["okb docs --out review --context"],
456
+ args: [
457
+ ["--out", "folder", "Where to write `rules-in-context.md`. Required."],
458
+ ["--context", "flag", "Write the rules-in-context page instead of the reference pages. It doesn't combine with `--changed`."],
459
+ ],
460
+ },
461
+ ],
462
+ },
432
463
  {
433
464
  name: "source",
434
465
  group: "Working from documents",
@@ -452,7 +483,18 @@ export const COMMANDS = [
452
483
  examples: ["okb source outline button --quotable"],
453
484
  args: [["<source>", "name", "The source."], ["--quotable", "flag", "Show only blocks you can quote."], ["--problems", "flag", "Show only problems in the document."]],
454
485
  },
455
- { sub: "refresh", description: "Checks quotes again after the document changes.", examples: ["okb source refresh button"], args: [["<source>", "name", "The source."]] },
486
+ {
487
+ sub: "refresh",
488
+ description: "Checks quotes again after the document changes. With `--all` it checks every source, reports quotes that are gone (with the rules and facts that cite them) or moved, and lists the new, changed and removed blocks as a worklist. With `--all` it exits with code 1 when a quote is gone or a source can't be read (a single source only reports).",
489
+ examples: ["okb source refresh button", "okb source refresh --all", "okb source refresh --all --json --dry-run"],
490
+ args: [
491
+ ["[<source>]", "name", "The source to check (leave it out with --all)."],
492
+ ["--all", "flag", "Check every source and list the worklist of new, changed and removed blocks."],
493
+ ["--dry-run", "flag", "With --all: write nothing, not even moved quotes."],
494
+ ["--record", "flag", "With --all: store the current blocks as the baseline once the worklist is dealt with."],
495
+ ["--strict", "flag", "With --all: also exit with code 1 when the worklist isn't empty."],
496
+ ],
497
+ },
456
498
  { sub: "list", description: "Lists the sources. Bare `okb source` does the same.", examples: ["okb source list"], args: [] },
457
499
  ],
458
500
  },
@@ -530,7 +572,8 @@ export const COMMANDS = [
530
572
  ["--status", "SUPPORTED, OVERREACH or UNSUPPORTED", "What the check found."],
531
573
  ["--corrected", "text", "A corrected wording, for OVERREACH."],
532
574
  ["--confidence", "verbatim or paraphrased", "How closely the node follows the quote."],
533
- ["--note", "text", "A note about the check."],
575
+ ["--note", "text", "One sentence on why: the word or number you changed, or the part of the statement the quote doesn't support. OVERREACH prints a suggestion."],
576
+ ["--ref", "url", "An http or https link to the PR comment, issue or review thread where the reasoning happened."],
534
577
  ["--approve", "flag", "Approve it after review."],
535
578
  ],
536
579
  }],
@@ -576,6 +619,57 @@ export const COMMANDS = [
576
619
  description: "Compares quotes with the documents they came from and reports quotes that no longer match.",
577
620
  forms: [{ description: "Checks one or more ontology folders. With none it checks the current folder.", examples: ["okb drift .", "okb drift ../wine ../food"], args: [["[folder]...", "paths", "The ontology folders to check."]] }],
578
621
  },
622
+ {
623
+ name: "check",
624
+ group: "Housekeeping",
625
+ description: "Says whether a knowledge base is safe to merge: no validation errors, every quote still in its source, and nothing unverified, unsupported or waiting for approval. Exits non-zero when a check fails, so a CI job can gate on it.",
626
+ forms: [{
627
+ description: "Checks the current folder. It reads the folder and its source files and never changes them or takes the write lock. Warnings from `okb validate` don't block a merge. It also warns when the installed okb is older than the `okbVersion` the KB pins in okb.json.",
628
+ examples: ["okb check", "okb check --json", "okb check -C ../wine"],
629
+ args: [["--json", "flag", "Print the result as JSON: `ok`, the installed and pinned versions, and each check with its status, summary and problems."]],
630
+ }],
631
+ },
632
+ {
633
+ name: "pin",
634
+ group: "Housekeeping",
635
+ description: "Records the installed okb version in okb.json as `okbVersion`, so `okb check` warns anyone with an older okb and the CI workflow installs that version. Run it again after you upgrade okb.",
636
+ forms: [{ description: "Pins the installed version.", examples: ["okb pin"], args: [] }],
637
+ },
638
+ {
639
+ name: "diff",
640
+ group: "Housekeeping",
641
+ description: "Shows what changed in the knowledge between two versions of an ontology: added, removed, renamed and changed things, rules side by side, moved quotes and changed links, in words rather than JSON lines.",
642
+ forms: [{
643
+ description: "Each side is an ontology folder or a git ref. With one argument, the other side is the current folder, so `okb diff main` shows what this branch changes. It never modifies the folder or checks anything out. The output is Markdown, ready for a PR comment; createdAt and updatedAt changes are not reported.",
644
+ examples: ["okb diff main", "okb diff v1.0 v1.1", "okb diff ../wine-old .", "okb diff main --json"],
645
+ args: [
646
+ ["<old>", "folder or git ref", "The earlier version. An existing folder is read as it is; anything else is a branch, tag or commit in the repository around the current folder. A name that is both is an error that shows both spellings (`./name` for the folder, `refs/heads/name` for the branch)."],
647
+ ["[new]", "folder or git ref", "The later version. Defaults to the current folder."],
648
+ ["--json", "flag", "Print the changes as JSON for other tools."],
649
+ ],
650
+ }],
651
+ },
652
+ {
653
+ name: "release",
654
+ group: "Housekeeping",
655
+ description: "Cuts a numbered release of the knowledge base that other tools can pin: a manifest with the SHA-256 of every file and source, and a change log of what changed since the last release.",
656
+ forms: [
657
+ {
658
+ description: "Writes `manifest.json` (the pin), `RELEASES.md` (every release's change log, newest first) and `releases/<version>/` (the files as released, plus `CHANGES.md` and `changes.json`), and records the version in `okb.json`. The change log is `okb diff` against the previous release's snapshot, so it lists renames with old and new names and renamed edge types. It stops, and writes nothing, if `okb validate` reports an error, if the version isn't newer than the last release, if a registered source file is missing or if nothing changed. Commit the files it writes.",
659
+ examples: ["okb release 1.0.0", "okb release 1.1.0 --json"],
660
+ args: [
661
+ ["<version>", "semver", "The new version: `1.0.0`, `1.2.3` or `2.0.0-rc.1`. It must be higher than the version in `manifest.json`."],
662
+ ["--json", "flag", "Print the version and the manifest as JSON."],
663
+ ],
664
+ },
665
+ {
666
+ sub: "verify",
667
+ description: "Checks the files against `manifest.json`: every pinned file must exist and match its SHA-256, and `okb.json` must carry the manifest's version. It changes nothing. It exits 1 when something differs, so it can run in CI or before a server starts.",
668
+ examples: ["okb release verify", "okb release verify -C ../wine --json"],
669
+ args: [["--json", "flag", "Print the result as JSON."]],
670
+ },
671
+ ],
672
+ },
579
673
  {
580
674
  name: "help",
581
675
  group: "Housekeeping",