@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
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Expected answers for competency questions (`okb cq answer`, `okb cq check`).
3
+ *
4
+ * A question stores a declarative query and the names it should return. The query is one of three
5
+ * shapes, each a JSON object with one key, modeled on the read tools an agent uses:
6
+ *
7
+ * {"find": {"class": "Wine", "where": {"color": "red"}}} instances of a class (and its subclasses) whose slot values match
8
+ * {"traverse": {"from": "Chateau Morgon", "slot": "produces"}} what a slot gives for one class or instance
9
+ * {"slots": {"of": "RedWine"}} the slots a class or instance has
10
+ *
11
+ * Evaluation is the reader's query layer (`query` and `resultNames`, see docs/FORMAT.md); this file only
12
+ * stores answers and compares names. It reads the ontology and never writes it.
13
+ */
14
+ import { type CompetencyQuestionNode, type Ontology } from "@ontology-kit/reader";
15
+ export type MatchMode = "exact" | "includes";
16
+ export type AnswerQuery = Record<string, unknown>;
17
+ export interface Answer {
18
+ query: AnswerQuery;
19
+ expect: string[];
20
+ match?: MatchMode;
21
+ }
22
+ export type CqStatus = "pass" | "fail" | "none";
23
+ export interface CqResult {
24
+ number: number;
25
+ id: string;
26
+ text: string;
27
+ status: CqStatus;
28
+ /** Expected names the query didn't return. */
29
+ missing: string[];
30
+ /** Names the query returned that weren't expected (a failure only for `exact`). */
31
+ extra: string[];
32
+ /** What the query returned. */
33
+ actual: string[];
34
+ /** Why the query couldn't run, for example a name that no longer exists. */
35
+ error?: string;
36
+ /** Set when the query has a `*` in `where`, which the reader reads as "has any value". */
37
+ note?: string;
38
+ match?: MatchMode;
39
+ }
40
+ /** Parse a stored query's JSON and check its shape with the reader, or throw an `OkbError` saying what is wrong. Names aren't resolved here. */
41
+ export declare function parseQuery(text: string): AnswerQuery;
42
+ /** Run a query through the reader. Throws an `OkbError` when a name in it doesn't exist. Names come back sorted. */
43
+ export declare const evaluate: (ont: Ontology, q: AnswerQuery) => string[];
44
+ /** Compare what a query returned with what was expected, ignoring case. */
45
+ export declare function compare(actual: string[], answer: Answer): Pick<CqResult, "status" | "missing" | "extra" | "actual" | "match">;
46
+ /** Evaluate one question's stored answer. */
47
+ export declare function checkQuestion(ont: Ontology, q: CompetencyQuestionNode): CqResult;
48
+ /** Evaluate every question, in number order. */
49
+ export declare function checkQuestions(ont: Ontology): CqResult[];
50
+ /** One line per result, for the terminal and for `okb check`'s problem list. */
51
+ export declare function describeResult(r: CqResult): string;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Expected answers for competency questions (`okb cq answer`, `okb cq check`).
3
+ *
4
+ * A question stores a declarative query and the names it should return. The query is one of three
5
+ * shapes, each a JSON object with one key, modeled on the read tools an agent uses:
6
+ *
7
+ * {"find": {"class": "Wine", "where": {"color": "red"}}} instances of a class (and its subclasses) whose slot values match
8
+ * {"traverse": {"from": "Chateau Morgon", "slot": "produces"}} what a slot gives for one class or instance
9
+ * {"slots": {"of": "RedWine"}} the slots a class or instance has
10
+ *
11
+ * Evaluation is the reader's query layer (`query` and `resultNames`, see docs/FORMAT.md); this file only
12
+ * stores answers and compares names. It reads the ontology and never writes it.
13
+ */
14
+ import { OkbError, checkQuery, query, resultNames } from "@ontology-kit/reader";
15
+ const STAR_NOTE = `"*" in where means "has any value", not the text "*". If this question meant the literal text, it no longer matches it.`;
16
+ const norm = (s) => s.trim().toLowerCase();
17
+ /** Parse a stored query's JSON and check its shape with the reader, or throw an `OkbError` saying what is wrong. Names aren't resolved here. */
18
+ export function parseQuery(text) {
19
+ let q;
20
+ try {
21
+ q = JSON.parse(text);
22
+ }
23
+ catch {
24
+ throw new OkbError(`--query isn't valid JSON. Example: --query '{"find":{"class":"Wine","where":{"color":"red"}}}'`);
25
+ }
26
+ return checkQuery(q);
27
+ }
28
+ /** Run a query through the reader. Throws an `OkbError` when a name in it doesn't exist. Names come back sorted. */
29
+ export const evaluate = (ont, q) => resultNames(query(ont, q));
30
+ /** A `find.where` value of `*` means "has any value" in the reader; older files may have meant the literal text. */
31
+ function usesStar(q) {
32
+ const where = q.find?.where ?? {};
33
+ return Object.values(where).some((v) => (Array.isArray(v) ? v : [v]).some((x) => x === "*"));
34
+ }
35
+ /** Compare what a query returned with what was expected, ignoring case. */
36
+ export function compare(actual, answer) {
37
+ const match = answer.match ?? "exact";
38
+ const have = new Set(actual.map(norm));
39
+ const want = new Set(answer.expect.map(norm));
40
+ const missing = answer.expect.filter((n) => !have.has(norm(n)));
41
+ const extra = actual.filter((n) => !want.has(norm(n)));
42
+ const ok = !missing.length && (match === "includes" || !extra.length);
43
+ return { status: ok ? "pass" : "fail", missing, extra, actual, match };
44
+ }
45
+ /** Evaluate one question's stored answer. */
46
+ export function checkQuestion(ont, q) {
47
+ const base = { number: ont.displayNumber(q), id: q.id, text: q.text, missing: [], extra: [], actual: [] };
48
+ if (!q.answer)
49
+ return { ...base, status: "none" };
50
+ try {
51
+ const r = { ...base, ...compare(evaluate(ont, q.answer.query), q.answer) };
52
+ return usesStar(q.answer.query) ? { ...r, note: STAR_NOTE } : r;
53
+ }
54
+ catch (e) {
55
+ if (!(e instanceof OkbError))
56
+ throw e;
57
+ return { ...base, status: "fail", missing: q.answer.expect, match: q.answer.match ?? "exact", error: e.message };
58
+ }
59
+ }
60
+ /** Evaluate every question, in number order. */
61
+ export function checkQuestions(ont) {
62
+ return ont.numbered("CompetencyQuestion").map((q) => checkQuestion(ont, q));
63
+ }
64
+ /** One line per result, for the terminal and for `okb check`'s problem list. */
65
+ export function describeResult(r) {
66
+ const head = `${r.number}. ${r.text}`;
67
+ if (r.status === "none")
68
+ return `${head}: no answer stored (okb cq answer ${r.number} --query '...' --expect ...)`;
69
+ const note = r.note ? ` Note: ${r.note}` : "";
70
+ if (r.status === "pass")
71
+ return `${head}: pass (${r.actual.length ? r.actual.join(", ") : "no names"})${note}`;
72
+ if (r.error)
73
+ return `${head}: can't run the query: ${r.error}`;
74
+ const parts = [r.missing.length ? `missing ${r.missing.join(", ")}` : "", r.extra.length && r.match !== "includes" ? `extra ${r.extra.join(", ")}` : ""].filter(Boolean);
75
+ return `${head}: fail, ${parts.join("; ")}${note}`;
76
+ }
package/dist/diff.d.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `okb diff`: what changed in the knowledge between two versions of an ontology, not in the JSON.
3
+ * `diffOntologies` is a pure function over two loaded `Ontology` objects (no git, no files);
4
+ * `diffMarkdown` writes it for a PR comment. Nodes are matched by id, so a rename keeps its
5
+ * identity and shows as a rename. `createdAt`/`updatedAt` are ignored: a node whose only change is
6
+ * a stamp isn't a change in the knowledge (it's counted in `summary.stampOnly`).
7
+ */
8
+ import { type OkbNode, type Ontology } from "@ontology-kit/reader";
9
+ /** One changed field. `path` is the raw key path; `field` is how it reads (slot ids become slot names). */
10
+ export interface FieldChange {
11
+ path: string[];
12
+ field: string;
13
+ before?: unknown;
14
+ after?: unknown;
15
+ }
16
+ export interface NodeRef {
17
+ id: string;
18
+ type: string;
19
+ name: string;
20
+ }
21
+ export interface NodeChange extends NodeRef {
22
+ /** The old name, when it differs from `name`. */
23
+ renamedFrom?: string;
24
+ /** Other names it has had (from `formerNames`, oldest first): earlier ones, or ones it passed through on the way here. */
25
+ otherFormerNames?: string[];
26
+ fields: FieldChange[];
27
+ /** For a quote: how it changed in words ("moved", "text changed"). */
28
+ note?: string;
29
+ }
30
+ export interface TypeDiff {
31
+ added: NodeRef[];
32
+ removed: NodeRef[];
33
+ changed: NodeChange[];
34
+ }
35
+ export interface EdgeRef {
36
+ from: string;
37
+ type: string;
38
+ to: string;
39
+ /** The link in words: `Merlot is a Red`, `Wine has slot body`, `Wine —maker→ Winery`. */
40
+ text: string;
41
+ props?: Record<string, unknown>;
42
+ }
43
+ export interface EdgeChange extends EdgeRef {
44
+ before: Record<string, unknown>;
45
+ after: Record<string, unknown>;
46
+ }
47
+ export interface TypeRename {
48
+ slot: string;
49
+ from: string;
50
+ to: string;
51
+ /** How many edges carry the type. */
52
+ edges: number;
53
+ /** Other edge types the slot has used (from `formerRelTypes`, oldest first), when there are any. */
54
+ otherFormerTypes?: string[];
55
+ }
56
+ export interface OntologyDiff {
57
+ old: string;
58
+ new: string;
59
+ summary: {
60
+ nodesAdded: number;
61
+ nodesRemoved: number;
62
+ nodesChanged: number;
63
+ edgesAdded: number;
64
+ edgesRemoved: number;
65
+ edgesChanged: number;
66
+ /** Nodes whose only difference is createdAt/updatedAt. */
67
+ stampOnly: number;
68
+ };
69
+ /** Only types with changes, in the format's order. */
70
+ types: Record<string, TypeDiff>;
71
+ /** Relationship slots whose edge type changed (a slot rename); their edges are not listed as changes. */
72
+ relationshipTypeRenames: TypeRename[];
73
+ edges: {
74
+ added: EdgeRef[];
75
+ removed: EdgeRef[];
76
+ changed: EdgeChange[];
77
+ };
78
+ }
79
+ /** What a node is called, for a reader. */
80
+ export declare function label(n: OkbNode, ont: Ontology): string;
81
+ /** Compare two ontologies. `oldName`/`newName` only label the result. */
82
+ export declare function diffOntologies(a: Ontology, b: Ontology, oldName?: string, newName?: string): OntologyDiff;
83
+ export declare function isEmpty(d: OntologyDiff): boolean;
84
+ /** The diff as Markdown, written for a PR comment. */
85
+ export declare function diffMarkdown(d: OntologyDiff): string;
package/dist/diff.js ADDED
@@ -0,0 +1,323 @@
1
+ /**
2
+ * `okb diff`: what changed in the knowledge between two versions of an ontology, not in the JSON.
3
+ * `diffOntologies` is a pure function over two loaded `Ontology` objects (no git, no files);
4
+ * `diffMarkdown` writes it for a PR comment. Nodes are matched by id, so a rename keeps its
5
+ * identity and shows as a rename. `createdAt`/`updatedAt` are ignored: a node whose only change is
6
+ * a stamp isn't a change in the knowledge (it's counted in `summary.stampOnly`).
7
+ */
8
+ import { NODE_TYPES, edgeProps, nodeLabel } from "@ontology-kit/reader";
9
+ const STAMPS = new Set(["createdAt", "updatedAt"]);
10
+ /** Bookkeeping that `okb rename` keeps; the rename itself is what a reader needs, so these aren't listed as field changes. */
11
+ const RENAME_TRAIL = new Set(["formerNames", "formerRelTypes"]);
12
+ const isPlain = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
13
+ /** What a node is called, for a reader. */
14
+ export function label(n, ont) {
15
+ if (n.type === "SourceLocation") {
16
+ const q = String(n.quote ?? "");
17
+ const text = q.length > 60 ? q.slice(0, 57) + "..." : q;
18
+ const src = ont.targets(n.id, "PART_OF").map((id) => ont.get(id)).find((s) => s?.type === "Source");
19
+ return `"${text}"` + (src && src.type === "Source" ? ` (${src.title})` : "");
20
+ }
21
+ return nodeLabel(n);
22
+ }
23
+ function leaves(node) {
24
+ const out = new Map();
25
+ const walk = (value, path) => {
26
+ if (isPlain(value)) {
27
+ for (const [k, v] of Object.entries(value))
28
+ if (v !== undefined)
29
+ walk(v, [...path, k]);
30
+ }
31
+ else
32
+ out.set(JSON.stringify(path), { path, value });
33
+ };
34
+ for (const [k, v] of Object.entries(node))
35
+ if (v !== undefined && !STAMPS.has(k) && k !== "id" && k !== "type")
36
+ walk(v, [k]);
37
+ return out;
38
+ }
39
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
40
+ function fieldChanges(a, b, name) {
41
+ const la = leaves(a);
42
+ const lb = leaves(b);
43
+ const out = [];
44
+ const keys = new Set([...la.keys(), ...lb.keys()]);
45
+ for (const k of keys) {
46
+ const x = la.get(k);
47
+ const y = lb.get(k);
48
+ if (x && y && same(x.value, y.value))
49
+ continue;
50
+ const path = (x ?? y).path;
51
+ const field = path.map((seg, i) => (i === 0 ? seg : name(seg))).join(".");
52
+ const change = { path, field };
53
+ if (x)
54
+ change.before = x.value;
55
+ if (y)
56
+ change.after = y.value;
57
+ out.push(change);
58
+ }
59
+ return out.sort((p, q) => (p.field < q.field ? -1 : p.field > q.field ? 1 : 0));
60
+ }
61
+ const LOCATION_FIELDS = new Set(["locator", "headingPath", "startLine", "endLine", "lines", "blockKind", "sourceLink", "pageLink", "page"]);
62
+ const PHRASE = {
63
+ IS_A: (a, b) => `${a} is a ${b}`,
64
+ INSTANCE_OF: (a, b) => `${a} is an instance of ${b}`,
65
+ HAS_SLOT: (a, b) => `${a} has slot ${b}`,
66
+ RANGE: (a, b) => `${a} has range ${b}`,
67
+ INVERSE_OF: (a, b) => `${a} is the inverse of ${b}`,
68
+ DISJOINT_WITH: (a, b) => `${a} is disjoint with ${b}`,
69
+ NEEDS: (a, b) => `${a} needs ${b}`,
70
+ BECAME: (a, b) => `${a} became ${b}`,
71
+ ABOUT: (a, b) => `${a} is about ${b}`,
72
+ CITES: (a, b) => `${a} cites ${b}`,
73
+ PART_OF: (a, b) => `${a} is part of ${b}`,
74
+ GOVERNS: (a, b) => `${a} governs ${b}`,
75
+ REFINES: (a, b) => `${a} refines ${b}`,
76
+ FULFILLS: (a, b) => `${a} fulfills ${b}`,
77
+ };
78
+ const edgeKey = (from, type, to) => `${from}\u0000${type}\u0000${to}`;
79
+ /** Compare two ontologies. `oldName`/`newName` only label the result. */
80
+ export function diffOntologies(a, b, oldName = "old", newName = "new") {
81
+ const byIdA = new Map();
82
+ for (const n of a.nodes)
83
+ if (!byIdA.has(n.id))
84
+ byIdA.set(n.id, n);
85
+ const byIdB = new Map();
86
+ for (const n of b.nodes)
87
+ if (!byIdB.has(n.id))
88
+ byIdB.set(n.id, n);
89
+ // How a stored id reads: its name in the new version, else the old one, else the id itself.
90
+ const nameOf = (id) => {
91
+ const n = byIdB.get(id) ?? byIdA.get(id);
92
+ return n ? label(n, byIdB.has(id) ? b : a) : id;
93
+ };
94
+ const types = {};
95
+ const bucket = (t) => (types[t] ??= { added: [], removed: [], changed: [] });
96
+ const ref = (n, o) => ({ id: n.id, type: n.type, name: label(n, o) });
97
+ let stampOnly = 0;
98
+ for (const [id, nb] of byIdB) {
99
+ const na = byIdA.get(id);
100
+ if (!na) {
101
+ bucket(nb.type).added.push(ref(nb, b));
102
+ continue;
103
+ }
104
+ if (na.type !== nb.type) {
105
+ bucket(na.type).removed.push(ref(na, a));
106
+ bucket(nb.type).added.push(ref(nb, b));
107
+ continue;
108
+ }
109
+ const fields = fieldChanges(na, nb, nameOf).filter((f) => !RENAME_TRAIL.has(f.path[0]));
110
+ if (!fields.length) {
111
+ if (!same(na, nb))
112
+ stampOnly++;
113
+ continue;
114
+ }
115
+ const change = { ...ref(nb, b), fields };
116
+ const was = label(na, a);
117
+ if (was !== change.name) {
118
+ change.renamedFrom = was;
119
+ const earlier = "formerNames" in nb && Array.isArray(nb.formerNames) ? nb.formerNames.filter((x) => x !== was && x !== change.name) : undefined;
120
+ if (earlier?.length)
121
+ change.otherFormerNames = earlier;
122
+ }
123
+ if (nb.type === "SourceLocation") {
124
+ const parts = [];
125
+ if (fields.some((f) => LOCATION_FIELDS.has(f.path[0])))
126
+ parts.push("moved");
127
+ if (fields.some((f) => f.path[0] === "quote"))
128
+ parts.push("text changed");
129
+ if (parts.length)
130
+ change.note = parts.join(", ");
131
+ }
132
+ bucket(nb.type).changed.push(change);
133
+ }
134
+ for (const [id, na] of byIdA)
135
+ if (!byIdB.has(id))
136
+ bucket(na.type).removed.push(ref(na, a));
137
+ const byName = (x, y) => (x.name < y.name ? -1 : x.name > y.name ? 1 : x.id < y.id ? -1 : x.id > y.id ? 1 : 0);
138
+ const ordered = {};
139
+ const order = [...NODE_TYPES, ...Object.keys(types).filter((t) => !NODE_TYPES.includes(t))];
140
+ for (const t of order) {
141
+ const d = types[t];
142
+ if (!d)
143
+ continue;
144
+ d.added.sort(byName);
145
+ d.removed.sort(byName);
146
+ d.changed.sort(byName);
147
+ ordered[t] = d;
148
+ }
149
+ // A slot rename changes its edge type, and with it every edge of that type; say so once instead of listing them.
150
+ const renames = [];
151
+ const retype = new Map();
152
+ const slotTypesA = a.rel.edgeTypes();
153
+ const slotTypesB = b.rel.edgeTypes();
154
+ const countA = new Map();
155
+ for (const e of a.edges)
156
+ countA.set(e.type, (countA.get(e.type) ?? 0) + 1);
157
+ for (const [oldType, slotId] of slotTypesA) {
158
+ const nb = byIdB.get(slotId);
159
+ if (nb?.type !== "Slot" || !nb.relType || nb.relType === oldType)
160
+ continue;
161
+ // Skip if the old type is still some slot's type in the new version (types swapped or reused).
162
+ if (slotTypesB.has(oldType))
163
+ continue;
164
+ retype.set(oldType, nb.relType);
165
+ const rename = { slot: label(nb, b), from: oldType, to: nb.relType, edges: countA.get(oldType) ?? 0 };
166
+ const earlier = nb.formerRelTypes?.filter((x) => x !== oldType && x !== nb.relType);
167
+ if (Array.isArray(earlier) && earlier.length)
168
+ rename.otherFormerTypes = earlier;
169
+ renames.push(rename);
170
+ }
171
+ renames.sort((x, y) => (x.from < y.from ? -1 : 1));
172
+ const edgesA = new Map();
173
+ for (const e of a.edges)
174
+ edgesA.set(edgeKey(e.from, retype.get(e.type) ?? e.type, e.to), e);
175
+ const edgesB = new Map();
176
+ for (const e of b.edges)
177
+ edgesB.set(edgeKey(e.from, e.type, e.to), e);
178
+ const slotOfType = (t) => {
179
+ const id = slotTypesB.get(t) ?? slotTypesA.get(t);
180
+ const s = id ? (byIdB.get(id) ?? byIdA.get(id)) : undefined;
181
+ return s ? label(s, byIdB.has(s.id) ? b : a) : undefined;
182
+ };
183
+ const describe = (e) => {
184
+ const from = nameOf(e.from);
185
+ const to = nameOf(e.to);
186
+ const phrase = Object.hasOwn(PHRASE, e.type) ? PHRASE[e.type] : undefined;
187
+ const slot = phrase ? undefined : slotOfType(e.type);
188
+ const text = phrase ? phrase(from, to) : `${from} —${slot ?? e.type}→ ${to}`;
189
+ const props = edgeProps(e);
190
+ const r = { from: e.from, type: e.type, to: e.to, text };
191
+ if (Object.keys(props).length)
192
+ r.props = props;
193
+ return r;
194
+ };
195
+ const added = [];
196
+ const removed = [];
197
+ const changed = [];
198
+ for (const [k, eb] of edgesB) {
199
+ const ea = edgesA.get(k);
200
+ if (!ea)
201
+ added.push(describe(eb));
202
+ else if (!same(sortKeys(edgeProps(ea)), sortKeys(edgeProps(eb)))) {
203
+ changed.push({ ...describe(eb), before: edgeProps(ea), after: edgeProps(eb) });
204
+ }
205
+ }
206
+ for (const [k, ea] of edgesA)
207
+ if (!edgesB.has(k))
208
+ removed.push(describe({ ...ea, type: retype.get(ea.type) ?? ea.type }));
209
+ const byText = (x, y) => (x.text < y.text ? -1 : x.text > y.text ? 1 : 0);
210
+ added.sort(byText);
211
+ removed.sort(byText);
212
+ changed.sort(byText);
213
+ let nodesAdded = 0, nodesRemoved = 0, nodesChanged = 0;
214
+ for (const d of Object.values(ordered)) {
215
+ nodesAdded += d.added.length;
216
+ nodesRemoved += d.removed.length;
217
+ nodesChanged += d.changed.length;
218
+ }
219
+ return {
220
+ old: oldName,
221
+ new: newName,
222
+ summary: { nodesAdded, nodesRemoved, nodesChanged, edgesAdded: added.length, edgesRemoved: removed.length, edgesChanged: changed.length, stampOnly },
223
+ types: ordered,
224
+ relationshipTypeRenames: renames,
225
+ edges: { added, removed, changed },
226
+ };
227
+ }
228
+ function sortKeys(o) {
229
+ return Object.fromEntries(Object.keys(o).sort().map((k) => [k, o[k]]));
230
+ }
231
+ export function isEmpty(d) {
232
+ const s = d.summary;
233
+ return s.nodesAdded + s.nodesRemoved + s.nodesChanged + s.edgesAdded + s.edgesRemoved + s.edgesChanged + d.relationshipTypeRenames.length === 0;
234
+ }
235
+ const TYPE_TITLES = {
236
+ Ontology: "Ontology", CompetencyQuestion: "Competency questions", Term: "Terms", ReusedOntology: "Reused ontologies", Class: "Classes",
237
+ Slot: "Slots", Instance: "Instances", DesignDecision: "Design decisions", Source: "Sources", SourceLocation: "Quotes", Rule: "Rules",
238
+ };
239
+ /** A value on one line, for a table cell or a sentence. */
240
+ function show(v) {
241
+ if (v === undefined)
242
+ return "(none)";
243
+ if (typeof v === "string")
244
+ return JSON.stringify(v);
245
+ if (Array.isArray(v))
246
+ return v.length ? v.map((x) => (typeof x === "string" ? x : JSON.stringify(x))).join(", ") : "(empty)";
247
+ return JSON.stringify(v);
248
+ }
249
+ const cell = (s) => s.replace(/\|/g, "\\|").replace(/\r?\n/g, " ");
250
+ const code = (s) => "`" + s.replace(/`/g, "'") + "`";
251
+ /** A changed rule: statement, modality and verification status side by side, then any other field that changed. */
252
+ function ruleTable(c) {
253
+ const find = (p) => c.fields.find((f) => f.field === p);
254
+ const row = (name, f, unchanged) => f ? ` | ${name} | ${cell(show(f.before))} | ${cell(show(f.after))} |` : ` | ${name} | ${unchanged} | (same) |`;
255
+ const main = ["statement", "modality", "verification.status"];
256
+ return [
257
+ " | | Before | After |",
258
+ " |---|---|---|",
259
+ row("statement", find("statement"), "unchanged"),
260
+ row("modality", find("modality"), "unchanged"),
261
+ row("verification", find("verification.status"), "unchanged"),
262
+ ...c.fields.filter((f) => ![...main, "name"].includes(f.field)).map((f) => ` | ${cell(f.field)} | ${cell(show(f.before))} | ${cell(show(f.after))} |`),
263
+ ];
264
+ }
265
+ /** The diff as Markdown, written for a PR comment. */
266
+ export function diffMarkdown(d) {
267
+ const out = [`# Ontology changes: ${d.old} → ${d.new}`, ""];
268
+ if (isEmpty(d)) {
269
+ out.push("No changes to the knowledge." + (d.summary.stampOnly ? ` (${d.summary.stampOnly} node(s) differ only in createdAt/updatedAt.)` : ""));
270
+ return out.join("\n") + "\n";
271
+ }
272
+ const s = d.summary;
273
+ out.push(`${s.nodesAdded} added, ${s.nodesRemoved} removed and ${s.nodesChanged} changed node(s); ${s.edgesAdded} link(s) added, ${s.edgesRemoved} removed, ${s.edgesChanged} changed.`, "");
274
+ for (const [type, t] of Object.entries(d.types)) {
275
+ out.push(`## ${TYPE_TITLES[type] ?? type + "s"}`, "");
276
+ for (const n of t.added)
277
+ out.push(`- **Added** ${code(n.name)}`);
278
+ for (const n of t.removed)
279
+ out.push(`- **Removed** ${code(n.name)}${type === "SourceLocation" ? " (the quote disappeared)" : ""}`);
280
+ for (const c of t.changed) {
281
+ const head = c.renamedFrom !== undefined ? `**Renamed** ${code(c.renamedFrom)} → ${code(c.name)}` : `**Changed** ${code(c.name)}`;
282
+ const others = c.otherFormerNames ? ` (also named ${c.otherFormerNames.map(code).join(", ")})` : "";
283
+ out.push(`- ${head}${c.note ? ` (${c.note})` : ""}${others}`);
284
+ if (type === "Rule") {
285
+ out.push("", ...ruleTable(c), "");
286
+ continue;
287
+ }
288
+ for (const f of c.fields) {
289
+ if (f.field === "name" && c.renamedFrom !== undefined)
290
+ continue;
291
+ out.push(` - ${f.field}: ${show(f.before)} → ${show(f.after)}`);
292
+ }
293
+ }
294
+ out.push("");
295
+ }
296
+ if (d.relationshipTypeRenames.length) {
297
+ out.push("## Relationship edge types renamed", "");
298
+ for (const r of d.relationshipTypeRenames)
299
+ out.push(`- ${code(":" + r.from)} → ${code(":" + r.to)} (slot ${code(r.slot)}, ${r.edges} edge(s) keep their meaning${r.otherFormerTypes ? `; also used ${r.otherFormerTypes.map((t) => code(":" + t)).join(", ")}` : ""})`);
300
+ out.push("");
301
+ }
302
+ const links = (title, list, mark) => {
303
+ if (!list.length)
304
+ return;
305
+ out.push(`## ${title}`, "");
306
+ for (const e of list)
307
+ out.push(`- ${mark} ${e.text}${e.props ? ` (${Object.entries(e.props).map(([k, v]) => `${k}=${show(v)}`).join(", ")})` : ""}`);
308
+ out.push("");
309
+ };
310
+ links("Links added", d.edges.added, "+");
311
+ links("Links removed", d.edges.removed, "−");
312
+ if (d.edges.changed.length) {
313
+ out.push("## Link properties changed", "");
314
+ for (const e of d.edges.changed) {
315
+ const keys = new Set([...Object.keys(e.before), ...Object.keys(e.after)]);
316
+ out.push(`- ${e.text}: ${[...keys].sort().filter((k) => !same(e.before[k], e.after[k])).map((k) => `${k} ${show(e.before[k])} → ${show(e.after[k])}`).join("; ")}`);
317
+ }
318
+ out.push("");
319
+ }
320
+ if (s.stampOnly)
321
+ out.push(`${s.stampOnly} other node(s) differ only in createdAt/updatedAt and are not listed.`, "");
322
+ return out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
323
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `okb export --format cypher --since <release|git ref>`: an openCypher script that moves a database
3
+ * loaded from the older release to the current one, without clearing it.
4
+ *
5
+ * It compares the two EXPORT graphs (what `okb export` writes for each side, with the same options),
6
+ * not the okb files: the export is a projection (labels from ancestors, inherited values, rules held
7
+ * back until verified), so only a comparison of the projections says exactly what a database holds.
8
+ * Nodes match by `okbId` and relationships by (from, type, to), the same keys the full script's MERGE uses,
9
+ * so loading release A and then this script gives the graph a full load of release B gives.
10
+ *
11
+ * The script's order, which is also why it is safe to stop and run again:
12
+ * 1. guard: fails, before anything changes, unless the (:OkbRelease) node holds the starting version
13
+ * 2. delete removed relationships, 3. DETACH DELETE removed nodes
14
+ * 4. REMOVE the properties and labels a changed node no longer has
15
+ * 5. MERGE added and changed nodes (SET +=, so what other systems added to a node stays)
16
+ * 6. MERGE added and changed relationships
17
+ * 7. move the (:OkbRelease) version forward: last, so a script that stopped half-way still passes the guard
18
+ * Every statement but the last is idempotent.
19
+ */
20
+ import { type ExportGraph, type ReleaseStamp } from "./export.js";
21
+ export interface ChangeSetOptions {
22
+ /** The release the database must be at, and the one the script moves it to. */
23
+ from: ReleaseStamp;
24
+ to: ReleaseStamp;
25
+ /** The export flags both graphs were made with, so a reader sees what to repeat. */
26
+ flags?: string;
27
+ }
28
+ export interface ChangeSetSummary {
29
+ nodesAdded: number;
30
+ nodesChanged: number;
31
+ nodesRemoved: number;
32
+ relationshipsAdded: number;
33
+ relationshipsChanged: number;
34
+ relationshipsRemoved: number;
35
+ }
36
+ export interface ChangeSet {
37
+ text: string;
38
+ summary: ChangeSetSummary;
39
+ }
40
+ export declare function changeSetCypher(oldG: ExportGraph, newG: ExportGraph, o: ChangeSetOptions): ChangeSet;