@ontology-kit/okb 0.2.0 → 0.3.0-alpha.135

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 (71) hide show
  1. package/dist/check.js +21 -2
  2. package/dist/checks.js +23 -0
  3. package/dist/cli.js +11 -819
  4. package/dist/clidocs.d.ts +0 -2
  5. package/dist/clidocs.js +5 -27
  6. package/dist/command-table.d.ts +144 -0
  7. package/dist/command-table.js +85 -0
  8. package/dist/commands/documents.d.ts +3 -0
  9. package/dist/commands/documents.js +250 -0
  10. package/dist/commands/getting-started.d.ts +3 -0
  11. package/dist/commands/getting-started.js +135 -0
  12. package/dist/commands/housekeeping.d.ts +3 -0
  13. package/dist/commands/housekeeping.js +203 -0
  14. package/dist/commands/modeling.d.ts +3 -0
  15. package/dist/commands/modeling.js +467 -0
  16. package/dist/commands/planning.d.ts +3 -0
  17. package/dist/commands/planning.js +251 -0
  18. package/dist/commands/reviewing.d.ts +3 -0
  19. package/dist/commands/reviewing.js +234 -0
  20. package/dist/commands/skills.d.ts +3 -0
  21. package/dist/commands/skills.js +53 -0
  22. package/dist/commands.d.ts +10 -22
  23. package/dist/commands.js +15 -716
  24. package/dist/cqanswer.d.ts +51 -0
  25. package/dist/cqanswer.js +76 -0
  26. package/dist/export-changes.d.ts +40 -0
  27. package/dist/export-changes.js +115 -0
  28. package/dist/export-csv.d.ts +17 -0
  29. package/dist/export-csv.js +188 -0
  30. package/dist/export-eval-cases.d.ts +38 -0
  31. package/dist/export-eval-cases.js +40 -0
  32. package/dist/export.d.ts +33 -2
  33. package/dist/export.js +69 -11
  34. package/dist/help.d.ts +11 -2
  35. package/dist/help.js +51 -64
  36. package/dist/ops/admin.d.ts +1 -1
  37. package/dist/ops/admin.js +2 -1
  38. package/dist/ops/classes.js +2 -2
  39. package/dist/ops/common.d.ts +12 -2
  40. package/dist/ops/common.js +3 -0
  41. package/dist/ops/instances.js +2 -2
  42. package/dist/ops/links.d.ts +1 -1
  43. package/dist/ops/links.js +2 -1
  44. package/dist/ops/scope.d.ts +9 -2
  45. package/dist/ops/scope.js +19 -3
  46. package/dist/ops/slots.js +6 -6
  47. package/dist/provenance.d.ts +1 -1
  48. package/dist/provenance.js +3 -2
  49. package/dist/release.d.ts +4 -0
  50. package/dist/release.js +22 -3
  51. package/dist/render.d.ts +85 -1
  52. package/dist/render.js +244 -1
  53. package/dist/runner.d.ts +3 -0
  54. package/dist/runner.js +84 -0
  55. package/dist/skills.d.ts +19 -3
  56. package/dist/skills.js +129 -13
  57. package/dist/verifynote.d.ts +4 -3
  58. package/dist/verifynote.js +3 -2
  59. package/dist/workflows.d.ts +283 -0
  60. package/dist/workflows.js +270 -0
  61. package/meta-kb/data/edges.json +25 -0
  62. package/meta-kb/data/manifest.json +4 -4
  63. package/meta-kb/data/nodes.json +39 -2
  64. package/package.json +4 -3
  65. package/schema/node.schema.json +22 -1
  66. package/skills/build-domain-kb-from-docs/SKILL.md +2 -2
  67. package/skills/ontology-coach/SKILL.md +3 -3
  68. package/skills/ontology-maintainer/SKILL.md +2 -2
  69. package/skills/ontology-review/SKILL.md +2 -2
  70. package/skills/ontology-signoff/SKILL.md +2 -2
  71. package/templates/okb-check.yml +17 -1
@@ -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
+ }
@@ -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;
@@ -0,0 +1,115 @@
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 { CYPHER_NODE_LABEL, RELEASE_LABEL, chunks, comment, groupBy, ident, literal, mapLiteral } from "./export.js";
21
+ const stable = (v) => JSON.stringify(v, (_k, x) => (x && typeof x === "object" && !Array.isArray(x) ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, x[k]])) : x));
22
+ const labelSet = (n) => [...new Set(n.labels)].sort();
23
+ const relKey = (r) => `${r.from}\0${r.type}\0${r.to}`;
24
+ /** The properties of `a` that `b` doesn't have, in order. */
25
+ const droppedKeys = (a, b) => Object.keys(a).filter((k) => !(k in b)).sort();
26
+ export function changeSetCypher(oldG, newG, o) {
27
+ const oldNodes = new Map(oldG.nodes.map((n) => [n.id, n]));
28
+ const newNodes = new Map(newG.nodes.map((n) => [n.id, n]));
29
+ const oldRels = new Map(oldG.relationships.map((r) => [relKey(r), r]));
30
+ const newRels = new Map(newG.relationships.map((r) => [relKey(r), r]));
31
+ const addedNodes = [];
32
+ const changedNodes = [];
33
+ for (const [id, after] of newNodes) {
34
+ const before = oldNodes.get(id);
35
+ if (!before)
36
+ addedNodes.push(after);
37
+ else if (stable(before.properties) !== stable(after.properties) || stable(labelSet(before)) !== stable(labelSet(after)))
38
+ changedNodes.push({ before, after });
39
+ }
40
+ const removedNodes = [...oldNodes.keys()].filter((id) => !newNodes.has(id));
41
+ // A relationship that touches a removed node goes with it (DETACH DELETE), so it isn't listed on its own.
42
+ const gone = new Set(removedNodes);
43
+ const removedRels = [...oldRels].filter(([k, r]) => !newRels.has(k) && !gone.has(r.from) && !gone.has(r.to)).map(([, r]) => r);
44
+ const addedRels = [];
45
+ const changedRels = [];
46
+ for (const [k, after] of newRels) {
47
+ const before = oldRels.get(k);
48
+ if (!before)
49
+ addedRels.push(after);
50
+ else if (stable(before.properties) !== stable(after.properties))
51
+ changedRels.push({ before, after });
52
+ }
53
+ const summary = {
54
+ nodesAdded: addedNodes.length, nodesChanged: changedNodes.length, nodesRemoved: removedNodes.length,
55
+ relationshipsAdded: addedRels.length, relationshipsChanged: changedRels.length, relationshipsRemoved: removedRels.length,
56
+ };
57
+ const out = [
58
+ comment(`${o.to.ontology}: change set from ${o.from.version} to ${o.to.version}, written by okb (meta-KB ${newG.metaKbVersion})`),
59
+ comment(`Run it against a database loaded at version ${o.from.version} (a full export of ${o.from.version}, or the change sets before this one). It stops before changing anything at any other version.`),
60
+ comment(`${summary.nodesAdded} node(s) added, ${summary.nodesChanged} changed, ${summary.nodesRemoved} removed; ${summary.relationshipsAdded} relationship(s) added, ${summary.relationshipsChanged} changed, ${summary.relationshipsRemoved} removed.`),
61
+ ...(o.flags ? [comment(`Made with ${o.flags}. Use the same flags for the full export this builds on.`)] : []),
62
+ comment("Run it with cypher-shell --fail-fast (its default) so the first error stops the run."),
63
+ "",
64
+ comment(`1. Guard. 1 / 0 is the error that stops the run: the database isn't at version ${o.from.version}.`),
65
+ `OPTIONAL MATCH (r:${RELEASE_LABEL} {ontology: ${literal(o.from.ontology)}})`,
66
+ `WITH r, CASE WHEN r.version = ${literal(o.from.version)} THEN 1 ELSE 0 END AS atStartingVersion`,
67
+ "RETURN 1 / atStartingVersion AS atStartingVersion;",
68
+ "",
69
+ ];
70
+ const section = (title, empty) => {
71
+ if (!empty)
72
+ out.push(comment(title));
73
+ };
74
+ section("2. Delete removed relationships.", !removedRels.length);
75
+ for (const [type, group] of groupBy(removedRels, (r) => r.type)) {
76
+ for (const rows of chunks(group)) {
77
+ out.push("UNWIND [", rows.map((r) => ` {from: ${literal(r.from)}, to: ${literal(r.to)}}`).join(",\n"), `] AS row MATCH (a:${CYPHER_NODE_LABEL} {okbId: row.from})-[r:${ident(type)}]->(b:${CYPHER_NODE_LABEL} {okbId: row.to}) DELETE r;`, "");
78
+ }
79
+ }
80
+ section("3. Delete removed nodes, with whatever is attached to them.", !removedNodes.length);
81
+ for (const ids of chunks(removedNodes)) {
82
+ out.push("UNWIND [", ids.map((id) => " " + literal(id)).join(",\n"), `] AS id MATCH (n:${CYPHER_NODE_LABEL} {okbId: id}) DETACH DELETE n;`, "");
83
+ }
84
+ const removals = [];
85
+ for (const { before, after } of changedNodes) {
86
+ const labels = labelSet(before).filter((l) => !labelSet(after).includes(l));
87
+ const props = droppedKeys(before.properties, after.properties);
88
+ if (labels.length || props.length)
89
+ removals.push(`MATCH (n:${CYPHER_NODE_LABEL} {okbId: ${literal(after.id)}}) REMOVE ${[...labels.map((l) => "n:" + ident(l)), ...props.map((p) => "n." + ident(p))].join(", ")};`);
90
+ }
91
+ for (const { before, after } of changedRels) {
92
+ const props = droppedKeys(before.properties, after.properties);
93
+ if (props.length)
94
+ removals.push(`MATCH (:${CYPHER_NODE_LABEL} {okbId: ${literal(after.from)}})-[r:${ident(after.type)}]->(:${CYPHER_NODE_LABEL} {okbId: ${literal(after.to)}}) REMOVE ${props.map((p) => "r." + ident(p)).join(", ")};`);
95
+ }
96
+ section("4. Remove the properties and labels that are gone.", !removals.length);
97
+ if (removals.length)
98
+ out.push(...removals, "");
99
+ section("5. Add and update nodes. SET += leaves properties other systems added.", !addedNodes.length && !changedNodes.length);
100
+ const upserts = [...addedNodes, ...changedNodes.map((c) => c.after)];
101
+ for (const group of groupBy(upserts, (n) => n.labels.join("\0")).values()) {
102
+ const labels = group[0].labels.length ? ", n:" + group[0].labels.map(ident).join(":") : "";
103
+ for (const rows of chunks(group)) {
104
+ out.push("UNWIND [", rows.map((n) => " " + mapLiteral(n.properties)).join(",\n"), `] AS row MERGE (n:${CYPHER_NODE_LABEL} {okbId: row.okbId}) SET n += row${labels};`, "");
105
+ }
106
+ }
107
+ section("6. Add and update relationships.", !addedRels.length && !changedRels.length);
108
+ for (const [type, group] of groupBy([...addedRels, ...changedRels.map((c) => c.after)], (r) => r.type)) {
109
+ for (const rows of chunks(group)) {
110
+ out.push("UNWIND [", rows.map((r) => ` {from: ${literal(r.from)}, to: ${literal(r.to)}, props: ${mapLiteral(r.properties)}}`).join(",\n"), `] AS row MATCH (a:${CYPHER_NODE_LABEL} {okbId: row.from}) MATCH (b:${CYPHER_NODE_LABEL} {okbId: row.to}) MERGE (a)-[r:${ident(type)}]->(b) SET r += row.props;`, "");
111
+ }
112
+ }
113
+ out.push(comment(`7. Move the database to version ${o.to.version}. Last, so a run that stopped earlier can be run again.`), `MATCH (r:${RELEASE_LABEL} {ontology: ${literal(o.from.ontology)}}) SET r.version = ${literal(o.to.version)}, r.ontology = ${literal(o.to.ontology)};`, "");
114
+ return { text: out.join("\n"), summary };
115
+ }
@@ -0,0 +1,17 @@
1
+ import { type ExportGraph } from "./export.js";
2
+ export type CsvFormat = "neo4j-csv" | "neptune-csv";
3
+ export declare const CSV_FORMATS: readonly CsvFormat[];
4
+ /** A file name (relative to `--out`) and its text. */
5
+ export type CsvFiles = Record<string, string>;
6
+ /** One CSV field: quoted when it holds a comma, quote, CR or LF (RFC 4180, which both loaders read). */
7
+ export declare function csvField(s: string): string;
8
+ export interface Neo4jCsv {
9
+ files: CsvFiles;
10
+ /** The `neo4j-admin database import full` command, with the file names this export wrote. */
11
+ command: string;
12
+ }
13
+ export declare function toNeo4jCsv(g: ExportGraph): Neo4jCsv;
14
+ export declare function toNeptuneCsv(g: ExportGraph): {
15
+ files: CsvFiles;
16
+ notes: string[];
17
+ };
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Bulk-loader CSV exports: files for `neo4j-admin database import` and for Amazon
3
+ * Neptune's openCypher bulk loader. okb writes files; the team runs the loader.
4
+ *
5
+ * Both writers take the same ExportGraph as the Cypher export, so labels, ids and
6
+ * property names agree across formats: every node has the `OkbNode` label plus its class
7
+ * labels and an `okbId` property, and relationships are matched on `okbId`.
8
+ *
9
+ * Properties differ from node to node, so each file's header is the union of the
10
+ * properties its rows use. A row that lacks a property leaves the field empty, which
11
+ * both loaders read as "no value". An empty string and an empty list are therefore the
12
+ * same as a missing value in CSV (the Cypher export has the same effect for empty lists).
13
+ */
14
+ import { OkbError } from "@ontology-kit/reader";
15
+ import { CYPHER_NODE_LABEL } from "./export.js";
16
+ export const CSV_FORMATS = ["neo4j-csv", "neptune-csv"];
17
+ /** One CSV field: quoted when it holds a comma, quote, CR or LF (RFC 4180, which both loaders read). */
18
+ export function csvField(s) {
19
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
20
+ }
21
+ const csvLine = (fields) => fields.map(csvField).join(",") + "\n";
22
+ function kindOf(v) {
23
+ if (typeof v === "boolean")
24
+ return "boolean";
25
+ // A whole number past 2^53 has already lost digits in JSON, and one past 2^63 would overflow a long: write it as a double.
26
+ if (typeof v === "number")
27
+ return Number.isSafeInteger(v) ? "long" : "double";
28
+ return "string";
29
+ }
30
+ /** The narrowest kind that holds every value: long and double widen to double, anything else mixed falls back to string. */
31
+ function widen(kinds) {
32
+ const set = new Set(kinds);
33
+ if (set.size === 1)
34
+ return [...set][0];
35
+ if (set.size === 2 && set.has("long") && set.has("double"))
36
+ return "double";
37
+ return "string";
38
+ }
39
+ /** The union of properties across rows, in first-seen order, with one inferred type each. */
40
+ function columns(rows) {
41
+ const seen = new Map();
42
+ for (const r of rows) {
43
+ for (const [k, v] of Object.entries(r)) {
44
+ if (v === undefined || v === null)
45
+ continue;
46
+ const entry = seen.get(k) ?? { kinds: [], list: false };
47
+ for (const x of Array.isArray(v) ? v : [v])
48
+ entry.kinds.push(kindOf(x));
49
+ if (Array.isArray(v))
50
+ entry.list = true;
51
+ seen.set(k, entry);
52
+ }
53
+ }
54
+ return [...seen].filter(([, e]) => e.kinds.length).map(([name, e]) => ({ name, kind: widen(e.kinds), list: e.list }));
55
+ }
56
+ /** A value as text in its column's kind. Objects (which okb doesn't store today) become JSON. */
57
+ function scalarText(v, kind) {
58
+ if (kind === "string")
59
+ return typeof v === "string" ? v : typeof v === "object" ? JSON.stringify(v) : String(v);
60
+ return String(v);
61
+ }
62
+ const withoutId = ({ okbId: _id, ...rest }) => rest;
63
+ function guardNames(cols, where) {
64
+ const bad = cols.find((c) => /[:,\r\n\s]/.test(c.name));
65
+ if (bad)
66
+ throw new OkbError(`Property name ${JSON.stringify(bad.name)} on ${where} has a colon, comma, space or newline in it, which the CSV headers can't carry. Rename the slot.`);
67
+ }
68
+ // Neo4j
69
+ const NEO4J_DELIMITERS = [";", "|", "\u001f"];
70
+ /** Neo4j's array delimiter is one character shared by `:LABEL` and every `[]` column, so pick one no label or list item contains. */
71
+ function arrayDelimiter(g) {
72
+ const texts = [];
73
+ for (const n of g.nodes) {
74
+ texts.push(...n.labels);
75
+ for (const v of Object.values(n.properties))
76
+ if (Array.isArray(v))
77
+ texts.push(...v.map((x) => scalarText(x, "string")));
78
+ }
79
+ for (const r of g.relationships)
80
+ for (const v of Object.values(r.properties))
81
+ if (Array.isArray(v))
82
+ texts.push(...v.map((x) => scalarText(x, "string")));
83
+ const d = NEO4J_DELIMITERS.find((c) => !texts.some((t) => t.includes(c)));
84
+ if (!d)
85
+ throw new OkbError("Every array delimiter okb can use appears in a label or a list value, so the files can't be split safely. Change the values.");
86
+ return d;
87
+ }
88
+ function neo4jHeader(c) {
89
+ return `${c.name}:${c.kind}${c.list ? "[]" : ""}`;
90
+ }
91
+ function neo4jCell(v, c, delimiter) {
92
+ if (v === undefined || v === null)
93
+ return "";
94
+ if (!c.list)
95
+ return scalarText(v, c.kind);
96
+ return (Array.isArray(v) ? v : [v]).map((x) => scalarText(x, c.kind)).join(delimiter);
97
+ }
98
+ export function toNeo4jCsv(g) {
99
+ const delimiter = arrayDelimiter(g);
100
+ const nodeCols = columns(g.nodes.map((n) => withoutId(n.properties)));
101
+ guardNames(nodeCols, "a node");
102
+ const nodes = [csvLine(["okbId:ID", ":LABEL", ...nodeCols.map(neo4jHeader)])];
103
+ g.nodes.forEach((n) => {
104
+ nodes.push(csvLine([n.id, [CYPHER_NODE_LABEL, ...n.labels].join(delimiter), ...nodeCols.map((c) => neo4jCell(n.properties[c.name], c, delimiter))]));
105
+ });
106
+ const rels = uniqueRels(g);
107
+ const relCols = columns(rels.map((r) => r.properties));
108
+ guardNames(relCols, "a relationship");
109
+ const relLines = [csvLine([":START_ID", ":END_ID", ":TYPE", ...relCols.map(neo4jHeader)])];
110
+ for (const r of rels)
111
+ relLines.push(csvLine([r.from, r.to, r.type, ...relCols.map((c) => neo4jCell(r.properties[c.name], c, delimiter))]));
112
+ const files = { "nodes.csv": nodes.join("") };
113
+ if (rels.length)
114
+ files["relationships.csv"] = relLines.join("");
115
+ const quotedDelim = delimiter === ";" ? "';'" : delimiter === "|" ? "'|'" : "$'\\x1f'";
116
+ const command = [
117
+ "neo4j-admin database import full okb",
118
+ ' --nodes="$PWD/nodes.csv"',
119
+ ...(rels.length ? [' --relationships="$PWD/relationships.csv"'] : []),
120
+ ` --array-delimiter=${quotedDelim}`,
121
+ " --multiline-fields=true",
122
+ ].join(" \\\n");
123
+ files["import.sh"] = `#!/bin/sh\n# Written by okb. Run it from this folder (neo4j-admin wants absolute paths, so the command uses $PWD). It loads into a new database named "okb" and refuses to overwrite one (add --overwrite-destination to replace it).\n${command}\n`;
124
+ return { files, command };
125
+ }
126
+ // Neptune
127
+ const NEPTUNE_TYPES = { string: "String", long: "Long", double: "Double", boolean: "Bool" };
128
+ /** Neptune's openCypher format has no list columns, so a column that holds any list becomes a String column of JSON arrays. */
129
+ function neptuneColumn(c) {
130
+ return c.list ? { ...c, kind: "string" } : c;
131
+ }
132
+ function neptuneCell(v, c) {
133
+ if (v === undefined || v === null)
134
+ return "";
135
+ if (c.list)
136
+ return JSON.stringify(v);
137
+ return scalarText(v, c.kind);
138
+ }
139
+ export function toNeptuneCsv(g) {
140
+ const notes = [];
141
+ const header = (c) => `${c.name}:${NEPTUNE_TYPES[c.kind]}`;
142
+ const listCols = new Set();
143
+ const nodeCols = columns(g.nodes.map((n) => withoutId(n.properties))).map((c) => {
144
+ if (c.list)
145
+ listCols.add(c.name);
146
+ return neptuneColumn(c);
147
+ });
148
+ guardNames(nodeCols, "a node");
149
+ // `okbId` is the node's :ID and also a String property, so queries match on it the same way in every format.
150
+ const nodes = [csvLine([":ID", ":LABEL", "okbId:String", ...nodeCols.map(header)])];
151
+ const badLabel = g.nodes.flatMap((n) => n.labels).find((l) => l.includes(";"));
152
+ if (badLabel !== undefined)
153
+ throw new OkbError(`Class name ${JSON.stringify(badLabel)} has a semicolon in it, which separates the labels of a node in Neptune's CSV format. Rename the class.`);
154
+ g.nodes.forEach((n) => {
155
+ nodes.push(csvLine([n.id, [CYPHER_NODE_LABEL, ...n.labels].join(";"), n.id, ...nodeCols.map((c) => neptuneCell(n.properties[c.name], { ...c, list: listCols.has(c.name) }))]));
156
+ });
157
+ const rels = uniqueRels(g);
158
+ const relCols = columns(rels.map((r) => r.properties)).map((c) => {
159
+ if (c.list)
160
+ listCols.add(c.name);
161
+ return neptuneColumn(c);
162
+ });
163
+ guardNames(relCols, "a relationship");
164
+ const relLines = [csvLine([":ID", ":START_ID", ":END_ID", ":TYPE", ...relCols.map(header)])];
165
+ for (const r of rels) {
166
+ relLines.push(csvLine([relId(r), r.from, r.to, r.type, ...relCols.map((c) => neptuneCell(r.properties[c.name], { ...c, list: false }))]));
167
+ }
168
+ if (listCols.size)
169
+ notes.push(`Neptune's CSV format has no list columns, so list values in ${[...listCols].join(", ")} are written as JSON text (a String).`);
170
+ const files = { "nodes.csv": nodes.join("") };
171
+ if (rels.length)
172
+ files["relationships.csv"] = relLines.join("");
173
+ return { files, notes };
174
+ }
175
+ // Shared
176
+ /**
177
+ * Neptune needs an edge id, and the Cypher export merges on (from, type, to), so that triple is the id and a repeat collapses.
178
+ * The parts are joined with `:`, and a `:` or `\` inside a part is escaped with `\`, so two different triples never share an
179
+ * id. An id without either character comes out as `type:from:to`.
180
+ */
181
+ const relId = (r) => [r.type, r.from, r.to].map((p) => p.replace(/[\\:]/g, "\\$&")).join(":");
182
+ /** One row per (type, from, to), last one wins, which is what MERGE in the Cypher export leaves. */
183
+ function uniqueRels(g) {
184
+ const m = new Map();
185
+ for (const r of g.relationships)
186
+ m.set(relId(r), r);
187
+ return [...m.values()];
188
+ }
@@ -0,0 +1,38 @@
1
+ import { type Ontology } from "@ontology-kit/reader";
2
+ export declare const EVAL_CASES_FORMAT = "okb-eval-cases/1";
3
+ export interface EvalNeed {
4
+ id: string;
5
+ type: string;
6
+ name: string;
7
+ }
8
+ export interface EvalCase {
9
+ id: string;
10
+ number: number;
11
+ question: string;
12
+ /** The stored query (see "Expected answers" in docs/FORMAT.md). */
13
+ query: Record<string, unknown>;
14
+ /** The names a correct answer holds. */
15
+ expect: string[];
16
+ match: "exact" | "includes";
17
+ /** The classes, slots and instances the question needs: what a correct answer should retrieve. */
18
+ needs: EvalNeed[];
19
+ }
20
+ export interface EvalCases {
21
+ format: typeof EVAL_CASES_FORMAT;
22
+ kb: {
23
+ name: string;
24
+ /** The release's id (from manifest.json), or null before the first release. */
25
+ id: string | null;
26
+ /** The released version these cases were exported from, or null before the first release. */
27
+ version: string | null;
28
+ };
29
+ cases: EvalCase[];
30
+ skipped: {
31
+ id: string;
32
+ number: number;
33
+ question: string;
34
+ reason: string;
35
+ }[];
36
+ notes: string[];
37
+ }
38
+ export declare function exportEvalCases(ont: Ontology): EvalCases;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `okb export --format eval-cases`: the competency questions as cases an evaluation runner can load
3
+ * (decision 0036). A case is a question, the names a correct answer holds, the nodes the question needs
4
+ * (the facts a correct answer should retrieve) and the stored query that produces the names. A question
5
+ * with no stored answer isn't a case: it is listed under `skipped`, so a runner never scores a question
6
+ * that has no answer to compare with. The file names the KB and its released version, so a runner can
7
+ * serve that release and check it served the right one. It reads the ontology and never writes it.
8
+ */
9
+ import { join } from "node:path";
10
+ import { OkbError } from "@ontology-kit/reader";
11
+ import { MANIFEST_FILE, readReleaseManifest, verifyRelease } from "./release.js";
12
+ export const EVAL_CASES_FORMAT = "okb-eval-cases/1";
13
+ export function exportEvalCases(ont) {
14
+ const version = ont.manifest.version ?? null;
15
+ const manifestFile = join(ont.root, MANIFEST_FILE);
16
+ let id = null;
17
+ if (version) {
18
+ // A KB that names a version must have the release's manifest: verifyRelease throws when it is missing.
19
+ const v = verifyRelease(ont.root);
20
+ if (!v.ok)
21
+ throw new OkbError(`The folder has changed since release ${version} (${v.problems[0]}), so cases exported now would name a version the files don't match. Cut a release first (okb release <version>), then export.`);
22
+ id = readReleaseManifest(manifestFile).id;
23
+ }
24
+ const notes = version ? [] : ["This KB has no release yet, so the cases name no version. Cut one with `okb release <version>` so a runner can pin what it queries."];
25
+ const cases = [];
26
+ const skipped = [];
27
+ for (const q of ont.numbered("CompetencyQuestion")) {
28
+ const number = ont.displayNumber(q);
29
+ if (!q.answer) {
30
+ skipped.push({ id: q.id, number, question: q.text, reason: "no stored answer (okb cq answer)" });
31
+ continue;
32
+ }
33
+ const needs = ont.targets(q.id, "NEEDS").map((t) => {
34
+ const n = ont.require(t);
35
+ return { id: n.id, type: n.type, name: ont.label(t) };
36
+ });
37
+ cases.push({ id: q.id, number, question: q.text, query: q.answer.query, expect: q.answer.expect, match: q.answer.match ?? "exact", needs });
38
+ }
39
+ return { format: EVAL_CASES_FORMAT, kb: { name: ont.meta.name || ont.manifest.name || "", id, version }, cases, skipped, notes };
40
+ }
package/dist/export.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  /**
2
2
  * `okb export`: writes the ontology's DATA the way a graph database expects it.
3
3
  *
4
+ * It reads the ontology directly, not through the reader's query layer (query.ts, decision 0034): the export needs
5
+ * raw typed values, edge properties and inheritance details (which class a value came from) that the layer's
6
+ * name-based results don't carry.
7
+ *
4
8
  * In the okb file, classes are nodes (so the schema itself can be queried and
5
9
  * validated). In a graph database you usually want the opposite: each instance is a
6
10
  * node labeled with its class and every ancestor class (labels are flat, so
@@ -50,5 +54,32 @@ export interface ExportOptions {
50
54
  unverified?: boolean;
51
55
  }
52
56
  export declare function exportGraph(ont: Ontology, opts?: ExportOptions): ExportGraph;
53
- /** openCypher script (Neo4j, Memgraph, Amazon Neptune). Run against an empty database, or delete the previous import first. */
54
- export declare function toCypher(g: ExportGraph): string;
57
+ export declare const ident: (s: string) => string;
58
+ export declare function literal(v: unknown): string;
59
+ export declare function mapLiteral(props: Record<string, unknown>): string;
60
+ /** The label every node gets in the default style, so one uniqueness constraint covers the `okbId` lookups. */
61
+ export declare const CYPHER_NODE_LABEL = "OkbNode";
62
+ /** The label of the one node per ontology that holds the release a database was loaded at. */
63
+ export declare const RELEASE_LABEL = "OkbRelease";
64
+ /** The release a full export loads: the guard a later change set (`--since`) checks. */
65
+ export interface ReleaseStamp {
66
+ ontology: string;
67
+ version: string;
68
+ }
69
+ export interface CypherOptions {
70
+ /** When the knowledge base has a release version, the script also records it in an (:OkbRelease) node, so `okb export --since` can guard on it. */
71
+ release?: ReleaseStamp;
72
+ /** `batched` (default): constraint plus UNWIND/MERGE, safe to run again. `simple`: one CREATE per node and edge, readable, for an empty database. */
73
+ style?: "batched" | "simple";
74
+ }
75
+ /** openCypher script (Neo4j, Memgraph, Amazon Neptune). The default style is idempotent for what it writes: loading it again gives the same graph with the new values. It sets every property of the nodes and relationships it writes (`SET n = row`), and deletes nothing. */
76
+ export declare function toCypher(g: ExportGraph, opts?: CypherOptions): string;
77
+ /** Records the loaded release. MERGE keeps one node per ontology, so loading a newer full export moves it forward. */
78
+ export declare function releaseStatement(r: ReleaseStamp): string;
79
+ /**
80
+ * One `//` comment line. Names, notes and versions come from user data, and a line break in one would end the
81
+ * comment and run the rest as Cypher, so every control character and Unicode line break becomes a space.
82
+ */
83
+ export declare const comment: (text: string) => string;
84
+ export declare function groupBy<T>(items: T[], key: (t: T) => string): Map<string, T[]>;
85
+ export declare function chunks<T>(items: T[]): Generator<T[]>;