@ontology-kit/okb 0.0.0-stage → 0.1.0-bootstrap.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.
- package/LICENSE +9 -0
- package/README.md +26 -2
- package/bin/okb.js +8 -0
- package/dist/checks.d.ts +33 -0
- package/dist/checks.js +966 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +718 -0
- package/dist/clidocs.d.ts +6 -0
- package/dist/clidocs.js +90 -0
- package/dist/clock.d.ts +2 -0
- package/dist/clock.js +16 -0
- package/dist/commands.d.ts +28 -0
- package/dist/commands.js +622 -0
- package/dist/export.d.ts +54 -0
- package/dist/export.js +290 -0
- package/dist/families.d.ts +20 -0
- package/dist/families.js +51 -0
- package/dist/help.d.ts +2 -0
- package/dist/help.js +57 -0
- package/dist/markdown.d.ts +60 -0
- package/dist/markdown.js +310 -0
- package/dist/metakb.d.ts +164 -0
- package/dist/metakb.js +130 -0
- package/dist/naming.d.ts +20 -0
- package/dist/naming.js +140 -0
- package/dist/ops/admin.d.ts +16 -0
- package/dist/ops/admin.js +119 -0
- package/dist/ops/classes.d.ts +21 -0
- package/dist/ops/classes.js +105 -0
- package/dist/ops/common.d.ts +6 -0
- package/dist/ops/common.js +4 -0
- package/dist/ops/instances.d.ts +8 -0
- package/dist/ops/instances.js +70 -0
- package/dist/ops/links.d.ts +9 -0
- package/dist/ops/links.js +85 -0
- package/dist/ops/naming.d.ts +4 -0
- package/dist/ops/naming.js +70 -0
- package/dist/ops/scope.d.ts +29 -0
- package/dist/ops/scope.js +124 -0
- package/dist/ops/slots.d.ts +31 -0
- package/dist/ops/slots.js +186 -0
- package/dist/ops/values.d.ts +20 -0
- package/dist/ops/values.js +151 -0
- package/dist/ops.d.ts +14 -0
- package/dist/ops.js +14 -0
- package/dist/provenance.d.ts +53 -0
- package/dist/provenance.js +296 -0
- package/dist/quotes.d.ts +14 -0
- package/dist/quotes.js +104 -0
- package/dist/render.d.ts +30 -0
- package/dist/render.js +413 -0
- package/dist/review.d.ts +10 -0
- package/dist/review.js +145 -0
- package/dist/site.d.ts +6 -0
- package/dist/site.js +6 -0
- package/dist/skills.d.ts +52 -0
- package/dist/skills.js +120 -0
- package/dist/status.d.ts +18 -0
- package/dist/status.js +59 -0
- package/dist/types.d.ts +12 -0
- package/dist/types.js +5 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +7 -0
- package/meta-kb/data/edges.json +3172 -0
- package/meta-kb/data/manifest.json +19 -0
- package/meta-kb/data/nodes.json +3546 -0
- package/package.json +71 -3
- package/skills/build-domain-kb-from-docs/SKILL.md +87 -0
- package/skills/ontology-coach/SKILL.md +100 -0
- package/skills/ontology-review/SKILL.md +66 -0
package/dist/naming.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/** Name styles, conversion, and singular/plural guessing. */
|
|
2
|
+
import { rawTokens, stripAccents, tokens } from "@ontology-kit/format";
|
|
3
|
+
export { fold, key, rawTokens, relType, slug, stripAccents, tokens } from "@ontology-kit/format";
|
|
4
|
+
export const CLASS_STYLES = ["PascalCase", "Title Case", "snake_case", "kebab-case", "Sentence case"];
|
|
5
|
+
export const SLOT_STYLES = ["camelCase", "snake_case", "kebab-case", "lower case"];
|
|
6
|
+
export const DEFAULT_CONVENTIONS = {
|
|
7
|
+
classCase: "PascalCase",
|
|
8
|
+
slotCase: "camelCase",
|
|
9
|
+
instanceCase: null, // instances are proper names; free text by default
|
|
10
|
+
classNumber: "singular",
|
|
11
|
+
slotAffix: "none",
|
|
12
|
+
};
|
|
13
|
+
/** "a Winery" / "an Author" */
|
|
14
|
+
export const an = (w) => (/^[aeiou]/i.test(w) ? "an " : "a ") + w;
|
|
15
|
+
const cap = (w) => w.charAt(0).toUpperCase() + w.slice(1);
|
|
16
|
+
export function convert(name, style) {
|
|
17
|
+
const ws = tokens(name);
|
|
18
|
+
if (ws.length === 0)
|
|
19
|
+
return name;
|
|
20
|
+
switch (style) {
|
|
21
|
+
case "PascalCase":
|
|
22
|
+
return ws.map(cap).join("");
|
|
23
|
+
case "camelCase":
|
|
24
|
+
return ws[0] + ws.slice(1).map(cap).join("");
|
|
25
|
+
case "Title Case":
|
|
26
|
+
return ws.map(cap).join(" ");
|
|
27
|
+
case "Sentence case":
|
|
28
|
+
return cap(ws.join(" "));
|
|
29
|
+
case "snake_case":
|
|
30
|
+
return ws.join("_");
|
|
31
|
+
case "kebab-case":
|
|
32
|
+
return ws.join("-");
|
|
33
|
+
case "lower case":
|
|
34
|
+
return ws.join(" ");
|
|
35
|
+
default:
|
|
36
|
+
return name;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const PATTERNS = {
|
|
40
|
+
PascalCase: /^[A-Z][A-Za-z0-9]*$/,
|
|
41
|
+
camelCase: /^[a-z][A-Za-z0-9]*$/,
|
|
42
|
+
"Title Case": /^[A-Z0-9][A-Za-z0-9'’]*( [A-Z0-9][A-Za-z0-9'’]*)*$/,
|
|
43
|
+
"Sentence case": /^[A-Z0-9][a-z0-9'’]*( [a-z0-9][a-z0-9'’]*)*$/,
|
|
44
|
+
snake_case: /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/,
|
|
45
|
+
"kebab-case": /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/,
|
|
46
|
+
"lower case": /^[a-z][a-z0-9]*( [a-z0-9]+)*$/,
|
|
47
|
+
};
|
|
48
|
+
export function matches(name, style) {
|
|
49
|
+
if (!style)
|
|
50
|
+
return true;
|
|
51
|
+
const re = PATTERNS[style];
|
|
52
|
+
return re ? re.test(name) : true;
|
|
53
|
+
}
|
|
54
|
+
const INVARIANT = new Set([
|
|
55
|
+
"series", "species", "sheep", "fish", "deer", "news", "means", "glass", "class", "status", "analysis",
|
|
56
|
+
"basis", "axis", "gas", "bus", "chaos", "canvas", "lens", "corps", "cross", "business", "process",
|
|
57
|
+
"address", "access", "boss", "rose", "bordeaux", "physics", "mathematics", "economics", "data", "media",
|
|
58
|
+
"metadata", "software", "hardware", "information", "equipment", "cheese", "vs", "cotes", "alsace",
|
|
59
|
+
]);
|
|
60
|
+
const IRREGULAR_PL = {
|
|
61
|
+
people: "person", children: "child", men: "man", women: "woman", mice: "mouse", geese: "goose",
|
|
62
|
+
feet: "foot", teeth: "tooth", criteria: "criterion", phenomena: "phenomenon", indices: "index",
|
|
63
|
+
matrices: "matrix", vertices: "vertex",
|
|
64
|
+
};
|
|
65
|
+
const IRREGULAR_SG = Object.fromEntries(Object.entries(IRREGULAR_PL).map(([p, s]) => [s, p]));
|
|
66
|
+
const plain = (w) => stripAccents(w).toLowerCase();
|
|
67
|
+
export function isPlural(word) {
|
|
68
|
+
const w = plain(word);
|
|
69
|
+
if (w in IRREGULAR_PL)
|
|
70
|
+
return true;
|
|
71
|
+
if (INVARIANT.has(w) || w in IRREGULAR_SG || w.length <= 3)
|
|
72
|
+
return false;
|
|
73
|
+
if (/(ss|us|is|ous|ics|ness|sis|xis)$/.test(w))
|
|
74
|
+
return false;
|
|
75
|
+
return w.endsWith("s");
|
|
76
|
+
}
|
|
77
|
+
function matchCase(original, next) {
|
|
78
|
+
return /^[A-Z]/.test(original) ? cap(next) : next;
|
|
79
|
+
}
|
|
80
|
+
export function singularize(word) {
|
|
81
|
+
const w = word.toLowerCase();
|
|
82
|
+
let out;
|
|
83
|
+
if (w in IRREGULAR_PL)
|
|
84
|
+
out = IRREGULAR_PL[w];
|
|
85
|
+
else if (!isPlural(word))
|
|
86
|
+
return word;
|
|
87
|
+
else if (w.endsWith("ies") && w.length > 4)
|
|
88
|
+
out = w.slice(0, -3) + "y";
|
|
89
|
+
else if (/(ches|shes|xes|zes|sses)$/.test(w))
|
|
90
|
+
out = w.slice(0, -2);
|
|
91
|
+
else
|
|
92
|
+
out = w.slice(0, -1);
|
|
93
|
+
return matchCase(word, out);
|
|
94
|
+
}
|
|
95
|
+
export function pluralize(word) {
|
|
96
|
+
const w = word.toLowerCase();
|
|
97
|
+
let out;
|
|
98
|
+
if (w in IRREGULAR_SG)
|
|
99
|
+
out = IRREGULAR_SG[w];
|
|
100
|
+
else if (isPlural(word) || INVARIANT.has(plain(word)))
|
|
101
|
+
return word;
|
|
102
|
+
else if (/[^aeiou]y$/.test(w))
|
|
103
|
+
out = w.slice(0, -1) + "ies";
|
|
104
|
+
else if (/(ch|sh|x|z|s)$/.test(w))
|
|
105
|
+
out = w + "es";
|
|
106
|
+
else
|
|
107
|
+
out = w + "s";
|
|
108
|
+
return matchCase(word, out);
|
|
109
|
+
}
|
|
110
|
+
export function headWord(name) {
|
|
111
|
+
const ts = tokens(name);
|
|
112
|
+
return ts.length ? ts[ts.length - 1] : name;
|
|
113
|
+
}
|
|
114
|
+
/** Apply fn to the last word of name, preserving the rest of the name's layout. */
|
|
115
|
+
export function withHead(name, fn) {
|
|
116
|
+
const raw = rawTokens(name).map((t) => t.replace(/\.$/, ""));
|
|
117
|
+
if (raw.length === 0)
|
|
118
|
+
return name;
|
|
119
|
+
const last = raw[raw.length - 1];
|
|
120
|
+
const idx = name.lastIndexOf(last);
|
|
121
|
+
return name.slice(0, idx) + fn(last) + name.slice(idx + last.length);
|
|
122
|
+
}
|
|
123
|
+
/** Apply the slot affix convention to a proposed slot name. */
|
|
124
|
+
export function applySlotAffix(name, conv) {
|
|
125
|
+
const style = conv.slotCase;
|
|
126
|
+
const ws = tokens(name);
|
|
127
|
+
if (conv.slotAffix === "has-prefix" && ws[0] !== "has")
|
|
128
|
+
return convert(["has", ...ws].join(" "), style);
|
|
129
|
+
if (conv.slotAffix === "of-suffix" && ws[ws.length - 1] !== "of")
|
|
130
|
+
return convert([...ws, "of"].join(" "), style);
|
|
131
|
+
return convert(name, style);
|
|
132
|
+
}
|
|
133
|
+
/** The name a class/slot should have under the conventions (for "did you mean" hints). */
|
|
134
|
+
export function conventionalName(name, kind, conv) {
|
|
135
|
+
if (kind === "Slot")
|
|
136
|
+
return applySlotAffix(name, conv);
|
|
137
|
+
let n = convert(name, conv.classCase);
|
|
138
|
+
n = withHead(n, conv.classNumber === "plural" ? pluralize : singularize);
|
|
139
|
+
return n;
|
|
140
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Ontology, type NodeType } from "@ontology-kit/format";
|
|
2
|
+
import type { Notes } from "./common.js";
|
|
3
|
+
/** Start an empty ontology folder: the manifest, the one Ontology node, no edges. Saved before it returns. */
|
|
4
|
+
export declare function createOntology(root: string, name: string): Ontology;
|
|
5
|
+
export declare function addDecision(ont: Ontology, o: {
|
|
6
|
+
title: string;
|
|
7
|
+
decision: string;
|
|
8
|
+
question?: string;
|
|
9
|
+
rationale?: string;
|
|
10
|
+
alternatives?: string[];
|
|
11
|
+
about?: string[];
|
|
12
|
+
waives?: string[];
|
|
13
|
+
}): Notes;
|
|
14
|
+
export declare function rename(ont: Ontology, ref: string, next: string, force?: boolean): Notes;
|
|
15
|
+
export declare function remove(ont: Ontology, ref: string, types?: NodeType[]): Notes;
|
|
16
|
+
/** Change which class(es) an instance belongs to, keeping its values. */
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** Creating an ontology, design decisions, renaming and removing. */
|
|
2
|
+
import { existsSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import * as naming from "../naming.js";
|
|
5
|
+
import { runChecks } from "../checks.js";
|
|
6
|
+
import { today } from "../clock.js";
|
|
7
|
+
import { MetaKB } from "../metakb.js";
|
|
8
|
+
import { FORMAT, MANIFEST, OkbError, Ontology, nameOrText } from "@ontology-kit/format";
|
|
9
|
+
import { checkName } from "./naming.js";
|
|
10
|
+
/** Start an empty ontology folder: the manifest, the one Ontology node, no edges. Saved before it returns. */
|
|
11
|
+
export function createOntology(root, name) {
|
|
12
|
+
mkdirSync(root, { recursive: true });
|
|
13
|
+
if (existsSync(join(root, MANIFEST)))
|
|
14
|
+
throw new OkbError(`${root} already contains an ontology (${MANIFEST}).`);
|
|
15
|
+
const manifest = { format: FORMAT, name, currentStep: 1, created: today() };
|
|
16
|
+
const nodes = [{
|
|
17
|
+
type: "Ontology", id: "ontology", name, domain: "", purpose: "", users: [], maintainers: [],
|
|
18
|
+
outOfScope: [], kind: "application", reuseReviewed: false,
|
|
19
|
+
}];
|
|
20
|
+
const ont = new Ontology(resolve(root), manifest, nodes, []);
|
|
21
|
+
ont.save();
|
|
22
|
+
return ont;
|
|
23
|
+
}
|
|
24
|
+
export function addDecision(ont, o) {
|
|
25
|
+
const meta = MetaKB.get();
|
|
26
|
+
for (const r of o.waives ?? []) {
|
|
27
|
+
const rule = meta.rules.get(r);
|
|
28
|
+
if (!rule)
|
|
29
|
+
throw new OkbError(`Unknown rule '${r}'. See okb explain for the list.`);
|
|
30
|
+
if (rule.severity === "error")
|
|
31
|
+
throw new OkbError(`'${r}' is a MUST rule; a design decision can explain warnings and hints but can't waive an error. Fix it instead.`);
|
|
32
|
+
}
|
|
33
|
+
const id = ont.newId("DesignDecision");
|
|
34
|
+
ont.addNode({
|
|
35
|
+
type: "DesignDecision", id, title: o.title, decision: o.decision, question: o.question, rationale: o.rationale,
|
|
36
|
+
alternatives: o.alternatives?.length ? o.alternatives : undefined, metaRules: o.waives?.length ? o.waives : undefined,
|
|
37
|
+
date: today(),
|
|
38
|
+
});
|
|
39
|
+
for (const a of o.about ?? [])
|
|
40
|
+
ont.addEdge(id, "ABOUT", a === "ontology" ? "ontology" : ont.find(a).id);
|
|
41
|
+
const notes = [`Recorded design decision ${id}: ${o.title}.`];
|
|
42
|
+
if (o.waives?.length) {
|
|
43
|
+
const explained = runChecks(ont, { all: true, only: o.waives }).findings.filter((f) => f.explainedBy === id).length;
|
|
44
|
+
notes.push(explained
|
|
45
|
+
? `It explains ${explained} current finding(s) from ${o.waives.join(", ")} (they'll show as 'explained' in okb validate).`
|
|
46
|
+
: `Note: it doesn't match any current finding from ${o.waives.join(", ")}. Check the --about target (a decision about a class also covers its subclasses).`);
|
|
47
|
+
}
|
|
48
|
+
if (!o.rationale)
|
|
49
|
+
notes.push("Tip: add --why so future readers know the reason, not just the choice.");
|
|
50
|
+
return notes;
|
|
51
|
+
}
|
|
52
|
+
export function rename(ont, ref, next, force = false) {
|
|
53
|
+
const n = ont.find(ref, ["Class", "Slot", "Instance", "ReusedOntology"]);
|
|
54
|
+
const notes = [];
|
|
55
|
+
if (n.type === "Class" || n.type === "Slot") {
|
|
56
|
+
checkName(ont, next, n.type, force, notes, n.id);
|
|
57
|
+
}
|
|
58
|
+
else if (ont.ofType(n.type).some((x) => x.id !== n.id && naming.key(x.name) === naming.key(next))) {
|
|
59
|
+
throw new OkbError(`There is already a ${n.type} called '${next}'.`);
|
|
60
|
+
}
|
|
61
|
+
const old = n.name;
|
|
62
|
+
if (n.type === "Slot" && n.valueType === "Instance") {
|
|
63
|
+
const retyped = ont.rel.rename(n, next);
|
|
64
|
+
if (retyped)
|
|
65
|
+
notes.push(`Its links are now stored as ${retyped.to} (were ${retyped.from}).`);
|
|
66
|
+
}
|
|
67
|
+
n.name = next;
|
|
68
|
+
notes.unshift(`Renamed ${n.type} '${old}' → '${next}' (id ${n.id} unchanged).`);
|
|
69
|
+
return notes;
|
|
70
|
+
}
|
|
71
|
+
export function remove(ont, ref, types) {
|
|
72
|
+
const n = ont.find(ref, types);
|
|
73
|
+
if (n.id === "ontology")
|
|
74
|
+
throw new OkbError("You can't remove the Ontology node.");
|
|
75
|
+
const notes = [];
|
|
76
|
+
const slotsBefore = new Map(ont.ofType("Slot").map((s) => [s.id, { domain: ont.domain(s.id).length, range: ont.range(s.id).length }]));
|
|
77
|
+
if (n.type === "Class") {
|
|
78
|
+
const kids = ont.children(n.id);
|
|
79
|
+
const parents = ont.parents(n.id);
|
|
80
|
+
for (const k of kids)
|
|
81
|
+
for (const p of parents)
|
|
82
|
+
ont.addEdge(k, "IS_A", p);
|
|
83
|
+
if (kids.length)
|
|
84
|
+
notes.push(`Its subclasses (${kids.map((k) => ont.label(k)).join(", ")}) moved up to ${parents.length ? parents.map((p) => ont.label(p)).join(", ") : "the top level"}.`);
|
|
85
|
+
const inst = ont.sources(n.id, "INSTANCE_OF");
|
|
86
|
+
if (inst.length && parents.length) {
|
|
87
|
+
for (const i of inst)
|
|
88
|
+
for (const p of parents)
|
|
89
|
+
ont.addEdge(i, "INSTANCE_OF", p);
|
|
90
|
+
notes.push(`Its instances (${inst.map((i) => ont.label(i)).join(", ")}) now belong to ${parents.map((p) => ont.label(p)).join(", ")}.`);
|
|
91
|
+
}
|
|
92
|
+
else if (inst.length) {
|
|
93
|
+
throw new OkbError(`${n.name} has instances (${inst.map((i) => ont.label(i)).join(", ")}) and no parent to move them to. Move them first: okb instance set "<name>" --of <OtherClass>`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (n.type === "Slot") {
|
|
97
|
+
const kept = ont.rel.drop(n);
|
|
98
|
+
if (kept)
|
|
99
|
+
notes.push(`Its ${kept.links} link(s) are kept, now stored from the other end as ${kept.type} (${kept.name}).`);
|
|
100
|
+
}
|
|
101
|
+
for (const t of ont.ofType("Term")) {
|
|
102
|
+
if (ont.targets(t.id, "BECAME").includes(n.id)) {
|
|
103
|
+
t.disposition = "undecided";
|
|
104
|
+
notes.push(`Term '${t.text}' is undecided again.`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
ont.removeNode(n.id);
|
|
108
|
+
for (const [sid, before] of slotsBefore) {
|
|
109
|
+
if (sid === n.id)
|
|
110
|
+
continue;
|
|
111
|
+
if (before.domain > 0 && !ont.isAttached(sid))
|
|
112
|
+
notes.push(`Warning: slot ${ont.label(sid)} is no longer attached to any class. Attach it (okb slot set ${ont.label(sid)} --on <Class>) or remove it.`);
|
|
113
|
+
if (before.range > 0 && ont.range(sid).length < before.range)
|
|
114
|
+
notes.push(`Warning: slot ${ont.label(sid)}'s range lost ${nameOrText(n)}${ont.range(sid).length ? "" : ", and is now empty"}.`);
|
|
115
|
+
}
|
|
116
|
+
notes.unshift(`Removed ${n.type} '${nameOrText(n) ?? n.id}'.`);
|
|
117
|
+
return notes;
|
|
118
|
+
}
|
|
119
|
+
/** Change which class(es) an instance belongs to, keeping its values. */
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type Ontology } from "@ontology-kit/format";
|
|
2
|
+
import { type Notes } from "./common.js";
|
|
3
|
+
export declare function addClass(ont: Ontology, name: string, o?: {
|
|
4
|
+
parents?: string[];
|
|
5
|
+
description?: string;
|
|
6
|
+
synonyms?: string[];
|
|
7
|
+
abstract?: boolean;
|
|
8
|
+
terminological?: boolean;
|
|
9
|
+
force?: boolean;
|
|
10
|
+
}): Notes;
|
|
11
|
+
/** Refuse parents that are disjoint; warn about redundant ones. */
|
|
12
|
+
export declare function checkParents(ont: Ontology, parents: string[], name: string, notes?: Notes): void;
|
|
13
|
+
export declare function setClass(ont: Ontology, ref: string, o: {
|
|
14
|
+
description?: string;
|
|
15
|
+
addParents?: string[];
|
|
16
|
+
removeParents?: string[];
|
|
17
|
+
synonyms?: string[];
|
|
18
|
+
abstract?: boolean;
|
|
19
|
+
terminological?: boolean;
|
|
20
|
+
}): Notes;
|
|
21
|
+
export declare function disjoint(ont: Ontology, refs: string[]): Notes;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** The class hierarchy: adding and changing classes, parents and disjointness. */
|
|
2
|
+
import * as naming from "../naming.js";
|
|
3
|
+
import { OkbError } from "@ontology-kit/format";
|
|
4
|
+
import { an, splitList as list } from "./common.js";
|
|
5
|
+
import { checkName } from "./naming.js";
|
|
6
|
+
import { linkTermIfAny } from "./scope.js";
|
|
7
|
+
export function addClass(ont, name, o = {}) {
|
|
8
|
+
const notes = [];
|
|
9
|
+
checkName(ont, name, "Class", o.force, notes);
|
|
10
|
+
const parents = (o.parents ?? []).map((p) => ont.find(p, "Class"));
|
|
11
|
+
const sg = (x) => naming.key(naming.withHead(x, naming.singularize));
|
|
12
|
+
const pairParent = parents.find((p) => sg(p.name) === sg(name));
|
|
13
|
+
if (pairParent) {
|
|
14
|
+
throw new OkbError(`'${name}' can't be a subclass of '${pairParent.name}': they're the singular and plural of the same concept, so neither is a kind of the other (Ontology 101 §4.1: "a single Wine is not a kind of Wines"). Use one class.`);
|
|
15
|
+
}
|
|
16
|
+
checkParents(ont, parents.map((p) => p.id), name);
|
|
17
|
+
const id = ont.newId("Class", name);
|
|
18
|
+
const node = { type: "Class", id, name };
|
|
19
|
+
if (o.description)
|
|
20
|
+
node.description = o.description;
|
|
21
|
+
if (o.synonyms?.length)
|
|
22
|
+
node.synonyms = list(o.synonyms);
|
|
23
|
+
if (o.abstract)
|
|
24
|
+
node.abstract = true;
|
|
25
|
+
if (o.terminological)
|
|
26
|
+
node.terminological = true;
|
|
27
|
+
ont.addNode(node);
|
|
28
|
+
for (const p of parents)
|
|
29
|
+
ont.addEdge(id, "IS_A", p.id);
|
|
30
|
+
notes.unshift(`Added class ${name}${parents.length ? ` (a kind of ${parents.map((p) => p.name).join(" and ")})` : " at the top level"}.`);
|
|
31
|
+
if (parents.length > 1)
|
|
32
|
+
notes.push("Multiple parents are fine when it's truly a kind of each. Consider recording why with `okb decision add`.");
|
|
33
|
+
for (const p of parents) {
|
|
34
|
+
const sibs = ont.children(p.id).filter((k) => k !== id);
|
|
35
|
+
if (sibs.length === 1 && !ont.disjointImplied(id, sibs[0])) {
|
|
36
|
+
notes.push(`Can anything be both ${an(name)} and ${an(ont.label(sibs[0]))}? If not, say so: okb class disjoint "${name}" "${ont.label(sibs[0])}"`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const asValue = ont.ofType("Slot").find((s) => (s.allowedValues ?? []).some((v) => naming.key(v) === naming.key(name)));
|
|
40
|
+
if (asValue)
|
|
41
|
+
notes.push(`Careful: '${name}' is also an allowed value of the slot ${asValue.name}. Model it as a class OR a value, not both (okb explain decision.class-or-value).`);
|
|
42
|
+
if (!o.description)
|
|
43
|
+
notes.push(`Add a one-line description: okb class set "${name}" --desc "..."`);
|
|
44
|
+
linkTermIfAny(ont, name, id, "class");
|
|
45
|
+
return notes;
|
|
46
|
+
}
|
|
47
|
+
/** Refuse parents that are disjoint; warn about redundant ones. */
|
|
48
|
+
export function checkParents(ont, parents, name, notes) {
|
|
49
|
+
for (let i = 0; i < parents.length; i++) {
|
|
50
|
+
for (let j = i + 1; j < parents.length; j++) {
|
|
51
|
+
if (ont.disjointImplied(parents[i], parents[j])) {
|
|
52
|
+
throw new OkbError(`${name} can't be under both ${ont.label(parents[i])} and ${ont.label(parents[j])}: they're declared disjoint, so nothing can be both (rule disjoint-no-shared-members).`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const p of parents) {
|
|
57
|
+
const via = parents.find((q) => q !== p && ont.ancestors(q).has(p));
|
|
58
|
+
if (via)
|
|
59
|
+
notes?.push(`Note: ${name} is already under ${ont.label(p)} through ${ont.label(via)}, so the direct link to ${ont.label(p)} is redundant (rule hier-no-redundant-isa).`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
export function setClass(ont, ref, o) {
|
|
63
|
+
const cl = ont.find(ref, "Class");
|
|
64
|
+
const notes = [];
|
|
65
|
+
if (o.description !== undefined)
|
|
66
|
+
cl.description = o.description;
|
|
67
|
+
for (const p of o.addParents ?? []) {
|
|
68
|
+
const pn = ont.find(p, "Class");
|
|
69
|
+
if (pn.id === cl.id || ont.ancestors(pn.id).has(cl.id))
|
|
70
|
+
throw new OkbError(`${pn.name} is ${pn.id === cl.id ? "the same class" : `already below ${cl.name}`}; that would create a cycle (a class can't be its own ancestor).`);
|
|
71
|
+
checkParents(ont, [...ont.parents(cl.id), pn.id], cl.name, notes);
|
|
72
|
+
ont.addEdge(cl.id, "IS_A", pn.id);
|
|
73
|
+
notes.push(`${cl.name} is now also a kind of ${pn.name}.`);
|
|
74
|
+
}
|
|
75
|
+
for (const p of o.removeParents ?? []) {
|
|
76
|
+
const pn = ont.find(p, "Class");
|
|
77
|
+
ont.removeEdges((e) => e.from === cl.id && e.type === "IS_A" && e.to === pn.id);
|
|
78
|
+
notes.push(`${cl.name} is no longer under ${pn.name}.`);
|
|
79
|
+
}
|
|
80
|
+
if (o.synonyms?.length)
|
|
81
|
+
cl.synonyms = [...new Set([...(cl.synonyms ?? []), ...list(o.synonyms)])];
|
|
82
|
+
if (o.abstract !== undefined)
|
|
83
|
+
cl.abstract = o.abstract || undefined;
|
|
84
|
+
if (o.terminological !== undefined)
|
|
85
|
+
cl.terminological = o.terminological || undefined;
|
|
86
|
+
return notes.length ? notes : [`Updated ${cl.name}.`];
|
|
87
|
+
}
|
|
88
|
+
export function disjoint(ont, refs) {
|
|
89
|
+
if (refs.length < 2)
|
|
90
|
+
throw new OkbError("Name at least two classes.");
|
|
91
|
+
const cs = refs.map((r) => ont.find(r, "Class"));
|
|
92
|
+
const notes = [];
|
|
93
|
+
for (let i = 0; i < cs.length; i++) {
|
|
94
|
+
for (let j = i + 1; j < cs.length; j++) {
|
|
95
|
+
const [a, b] = [cs[i], cs[j]];
|
|
96
|
+
if (ont.isSub(a.id, b.id) || ont.isSub(b.id, a.id))
|
|
97
|
+
throw new OkbError(`${a.name} and ${b.name} are in the same line of the hierarchy; one can't be disjoint with its own ancestor.`);
|
|
98
|
+
const exists = ont.edgesOf("DISJOINT_WITH").some((e) => (e.from === a.id && e.to === b.id) || (e.from === b.id && e.to === a.id));
|
|
99
|
+
if (!exists)
|
|
100
|
+
ont.addEdge(a.id, "DISJOINT_WITH", b.id);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
notes.push(`Declared disjoint: ${cs.map((x) => x.name).join(", ")}. Nothing can be more than one of these now.`);
|
|
104
|
+
return notes;
|
|
105
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Shared by the ops modules. */
|
|
2
|
+
/** Human-readable notes about what an operation did, including gentle warnings, so beginners learn as they go. */
|
|
3
|
+
export type Notes = string[];
|
|
4
|
+
export { an } from "../naming.js";
|
|
5
|
+
/** Command-line list values: repeated flags and/or comma-separated ("a,b" "c" -> [a, b, c]). */
|
|
6
|
+
export declare const splitList: (s: string | string[] | undefined) => string[];
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Shared by the ops modules. */
|
|
2
|
+
export { an } from "../naming.js";
|
|
3
|
+
/** Command-line list values: repeated flags and/or comma-separated ("a,b" "c" -> [a, b, c]). */
|
|
4
|
+
export const splitList = (s) => (Array.isArray(s) ? s : s ? [s] : []).flatMap((x) => x.split(",")).map((x) => x.trim()).filter(Boolean);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type Ontology } from "@ontology-kit/format";
|
|
2
|
+
import { type Notes } from "./common.js";
|
|
3
|
+
export declare function addInstance(ont: Ontology, name: string, o: {
|
|
4
|
+
of: string[];
|
|
5
|
+
description?: string;
|
|
6
|
+
assignments?: string[];
|
|
7
|
+
}): Notes;
|
|
8
|
+
export declare function setInstanceClasses(ont: Ontology, ref: string, classes: string[]): Notes;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/** Instances and the classes they belong to. */
|
|
2
|
+
import * as naming from "../naming.js";
|
|
3
|
+
import { OkbError, literalValues } from "@ontology-kit/format";
|
|
4
|
+
import { an } from "./common.js";
|
|
5
|
+
import { assign } from "./values.js";
|
|
6
|
+
import { checkParents } from "./classes.js";
|
|
7
|
+
export function addInstance(ont, name, o) {
|
|
8
|
+
if (!o.of?.length)
|
|
9
|
+
throw new OkbError("Say which class it belongs to with --of <Class>.");
|
|
10
|
+
const classes = o.of.map((c) => ont.find(c, "Class"));
|
|
11
|
+
const clash = ont.ofType("Instance").find((i) => naming.key(i.name) === naming.key(name));
|
|
12
|
+
if (clash)
|
|
13
|
+
throw new OkbError(`There is already an instance called '${clash.name}'.`);
|
|
14
|
+
const notes = [];
|
|
15
|
+
for (const cl of classes) {
|
|
16
|
+
if (cl.abstract)
|
|
17
|
+
throw new OkbError(`${cl.name} is abstract, so it can't have direct instances. Pick one of its subclasses: ${ont.children(cl.id).map((k) => ont.label(k)).join(", ")}.`);
|
|
18
|
+
if (ont.children(cl.id).length)
|
|
19
|
+
notes.push(`Tip: ${cl.name} has subclasses (${ont.children(cl.id).map((k) => ont.label(k)).join(", ")}). Use the most specific class that fits.`);
|
|
20
|
+
}
|
|
21
|
+
const id = ont.newId("Instance", name);
|
|
22
|
+
const inst = ont.addNode({ type: "Instance", id, name, ...(o.description ? { description: o.description } : {}), values: {} });
|
|
23
|
+
for (const cl of classes)
|
|
24
|
+
ont.addEdge(id, "INSTANCE_OF", cl.id);
|
|
25
|
+
notes.unshift(`Added ${name} (${classes.map((x) => an(x.name)).join(" and ")}).`);
|
|
26
|
+
if (o.assignments?.length)
|
|
27
|
+
notes.push(...assign(ont, id, o.assignments));
|
|
28
|
+
// Fill in defaults (most specific class first, then the slot's own default).
|
|
29
|
+
const ctx = [...classes.map((x) => x.id), ...classes.flatMap((x) => [...ont.ancestors(x.id)])];
|
|
30
|
+
for (const sid of ont.applicableSlots(id)) {
|
|
31
|
+
if (ont.statedValues(id, sid).length || ont.inheritedFixed(sid, ctx))
|
|
32
|
+
continue;
|
|
33
|
+
const s = ont.get(sid);
|
|
34
|
+
if (s?.type !== "Slot")
|
|
35
|
+
continue; // a HAS_SLOT to a non-slot: struct-well-formed reports it
|
|
36
|
+
const fromClass = ctx.map((c) => ont.get(c)).map((c) => (c?.type === "Class" ? c.defaults?.[sid] : undefined)).find((v) => v !== undefined);
|
|
37
|
+
const dv = fromClass ?? s.default;
|
|
38
|
+
if (dv === undefined)
|
|
39
|
+
continue;
|
|
40
|
+
if (s.valueType === "Instance")
|
|
41
|
+
ont.rel.link(id, sid, String(dv));
|
|
42
|
+
// A multiple slot stores a list; a default that's already a list becomes that list, not a list inside a list.
|
|
43
|
+
else
|
|
44
|
+
literalValues(inst)[sid] = s.cardinality === "multiple" ? [dv].flat() : dv;
|
|
45
|
+
notes.push(`Filled in default ${s.name} = ${JSON.stringify(dv)}.`);
|
|
46
|
+
}
|
|
47
|
+
const missing = ont.applicableSlots(id).filter((sid) => {
|
|
48
|
+
const f = ont.effectiveFacets(sid, ont.instanceClasses(id));
|
|
49
|
+
return f.min > 0 && ont.statedValues(id, sid).length < f.min && !ont.inheritedFixed(sid, ont.instanceClasses(id));
|
|
50
|
+
});
|
|
51
|
+
if (missing.length)
|
|
52
|
+
notes.push(`Still required: ${missing.map((m) => ont.label(m)).join(", ")}. okb instance set "${name}" ${ont.label(missing[0])}=...`);
|
|
53
|
+
return notes;
|
|
54
|
+
}
|
|
55
|
+
export function setInstanceClasses(ont, ref, classes) {
|
|
56
|
+
const inst = ont.find(ref, "Instance");
|
|
57
|
+
const cs = classes.map((c) => ont.find(c, "Class"));
|
|
58
|
+
for (const c of cs)
|
|
59
|
+
if (c.abstract)
|
|
60
|
+
throw new OkbError(`${c.name} is abstract, so it can't have direct instances.`);
|
|
61
|
+
checkParents(ont, cs.map((c) => c.id), inst.name);
|
|
62
|
+
ont.removeEdges((e) => e.from === inst.id && e.type === "INSTANCE_OF");
|
|
63
|
+
for (const c of cs)
|
|
64
|
+
ont.addEdge(inst.id, "INSTANCE_OF", c.id);
|
|
65
|
+
const lost = [...Object.keys(inst.values ?? {}), ...ont.rel.slotsWithValues(inst.id)].filter((s) => !ont.applicableSlots(inst.id).includes(s));
|
|
66
|
+
const notes = [`${inst.name} is now ${cs.map((c) => an(c.name)).join(" and ")}.`];
|
|
67
|
+
if (lost.length)
|
|
68
|
+
notes.push(`Warning: its values for ${[...new Set(lost)].map((s) => ont.label(s)).join(", ")} don't apply to the new class. Remove them (okb instance set "${inst.name}" <slot>=) or pick another class.`);
|
|
69
|
+
return notes;
|
|
70
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type Ontology } from "@ontology-kit/format";
|
|
2
|
+
import type { Notes } from "./common.js";
|
|
3
|
+
/** Create (or update) one relationship value, with edge properties. */
|
|
4
|
+
export declare function link(ont: Ontology, fromRef: string, relRef: string, toRef: string, o?: {
|
|
5
|
+
props?: string[];
|
|
6
|
+
rule?: string;
|
|
7
|
+
clear?: string[];
|
|
8
|
+
}): Notes;
|
|
9
|
+
export declare function unlink(ont: Ontology, fromRef: string, relRef: string, toRef: string): Notes;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** One relationship value at a time, with edge properties (okb link / unlink). */
|
|
2
|
+
import * as naming from "../naming.js";
|
|
3
|
+
import { OkbError, edgeProps } from "@ontology-kit/format";
|
|
4
|
+
import { assign, findSlotFor, parseAssignments } from "./values.js";
|
|
5
|
+
function coerceEdgeValue(decl, raw, relName) {
|
|
6
|
+
switch (decl.valueType) {
|
|
7
|
+
case "Integer":
|
|
8
|
+
if (!/^-?\d+$/.test(raw))
|
|
9
|
+
throw new OkbError(`${relName}.${decl.name} needs a whole number; got '${raw}'.`);
|
|
10
|
+
return Number(raw);
|
|
11
|
+
case "Float":
|
|
12
|
+
case "Number": {
|
|
13
|
+
const n = Number(raw);
|
|
14
|
+
if (raw === "" || Number.isNaN(n))
|
|
15
|
+
throw new OkbError(`${relName}.${decl.name} needs a number; got '${raw}'.`);
|
|
16
|
+
return n;
|
|
17
|
+
}
|
|
18
|
+
case "Boolean":
|
|
19
|
+
if (/^(true|yes|1)$/i.test(raw))
|
|
20
|
+
return true;
|
|
21
|
+
if (/^(false|no|0)$/i.test(raw))
|
|
22
|
+
return false;
|
|
23
|
+
throw new OkbError(`${relName}.${decl.name} needs true or false; got '${raw}'.`);
|
|
24
|
+
case "Enumerated": {
|
|
25
|
+
const hit = (decl.allowedValues ?? []).find((v) => naming.key(v) === naming.key(raw));
|
|
26
|
+
if (!hit)
|
|
27
|
+
throw new OkbError(`${relName}.${decl.name} must be one of ${(decl.allowedValues ?? []).join(", ")}; got '${raw}'.`);
|
|
28
|
+
return hit;
|
|
29
|
+
}
|
|
30
|
+
default:
|
|
31
|
+
return raw;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Create (or update) one relationship value, with edge properties. */
|
|
35
|
+
export function link(ont, fromRef, relRef, toRef, o = {}) {
|
|
36
|
+
const owner = ont.find(fromRef, ["Instance", "Class"]);
|
|
37
|
+
const slot = findSlotFor(ont, owner.id, relRef);
|
|
38
|
+
if (slot.valueType !== "Instance")
|
|
39
|
+
throw new OkbError(`${slot.name} is a property, not a relationship. Use okb instance set / class fix for values.`);
|
|
40
|
+
const target = ont.find(toRef, owner.type === "Class" ? ["Class", "Instance"] : ["Instance"]);
|
|
41
|
+
const primary = ont.require(ont.rel.primary(slot.id), "Slot");
|
|
42
|
+
const decls = primary.edgeProperties ?? [];
|
|
43
|
+
const props = {};
|
|
44
|
+
for (const a of parseAssignments(o.props ?? [])) {
|
|
45
|
+
const decl = decls.find((d) => naming.key(d.name) === naming.key(a.slot));
|
|
46
|
+
if (!decl)
|
|
47
|
+
throw new OkbError(`${primary.name} has no edge property '${a.slot}'. Declare it first: okb relationship property ${primary.name} ${a.slot} --type String${decls.length ? ` (declared: ${decls.map((d) => d.name).join(", ")})` : ""}`);
|
|
48
|
+
props[decl.name] = coerceEdgeValue(decl, a.raw, primary.name);
|
|
49
|
+
}
|
|
50
|
+
if (o.rule) {
|
|
51
|
+
const r = ont.find(o.rule, "Rule");
|
|
52
|
+
props.rule = r.id;
|
|
53
|
+
}
|
|
54
|
+
const existing = ont.rel.edge(owner.id, slot.id, target.id);
|
|
55
|
+
if (!existing) {
|
|
56
|
+
// New value: same range/cardinality rules as okb instance set.
|
|
57
|
+
const current = ont.rel.values(owner.id, slot.id);
|
|
58
|
+
const f = ont.effectiveFacets(slot.id, ont.classContext(owner.id));
|
|
59
|
+
if (f.max !== null && current.length + 1 > f.max) {
|
|
60
|
+
throw new OkbError(`${owner.name}.${slot.name} allows at most ${f.max} value(s) and already has ${current.map((x) => ont.label(x)).join(", ")}. Remove one first (okb unlink ...).`);
|
|
61
|
+
}
|
|
62
|
+
assign(ont, owner.id, [`${slot.name}+=${target.name}`], owner.type === "Class" ? "fixed" : "value");
|
|
63
|
+
}
|
|
64
|
+
const edge = ont.rel.edge(owner.id, slot.id, target.id);
|
|
65
|
+
Object.assign(edge, props);
|
|
66
|
+
for (const k of o.clear ?? [])
|
|
67
|
+
delete edge[k];
|
|
68
|
+
const missing = decls.filter((d) => d.required && edge[d.name] === undefined).map((d) => d.name);
|
|
69
|
+
const shown = Object.entries(edgeProps(edge)).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join(", ");
|
|
70
|
+
const notes = [`${existing ? "Updated" : "Linked"} (${ont.label(edge.from)})-[:${edge.type}${shown ? ` {${shown}}` : ""}]->(${ont.label(edge.to)})`];
|
|
71
|
+
if (missing.length)
|
|
72
|
+
notes.push(`Still required on this edge: ${missing.join(", ")}.`);
|
|
73
|
+
if (!props.rule && !edge.rule && ont.ofType("Rule").length)
|
|
74
|
+
notes.push(`Tip: if a documented rule justifies this link, add --rule <rule id> so the edge shares its quote and verification.`);
|
|
75
|
+
return notes;
|
|
76
|
+
}
|
|
77
|
+
export function unlink(ont, fromRef, relRef, toRef) {
|
|
78
|
+
const owner = ont.find(fromRef, ["Instance", "Class"]);
|
|
79
|
+
const slot = findSlotFor(ont, owner.id, relRef);
|
|
80
|
+
const target = ont.find(toRef, ["Instance", "Class"]);
|
|
81
|
+
if (!ont.rel.edge(owner.id, slot.id, target.id))
|
|
82
|
+
throw new OkbError(`${owner.name} isn't linked to ${target.name} by ${slot.name}.`);
|
|
83
|
+
ont.rel.unlink(owner.id, slot.id, target.id);
|
|
84
|
+
return [`Removed ${owner.name} ${slot.name} ${target.name} (and its edge properties).`];
|
|
85
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type Ontology, type Conventions } from "@ontology-kit/format";
|
|
2
|
+
import type { Notes } from "./common.js";
|
|
3
|
+
export declare function setConventions(ont: Ontology, o: Partial<Conventions>): Notes;
|
|
4
|
+
export declare function checkName(ont: Ontology, name: string, kind: "Class" | "Slot", force: boolean | undefined, notes: Notes, exclude?: string): void;
|