@ontology-kit/reader 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alan B Smith
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # @ontology-kit/reader
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read the file format of [Ontology Kit](https://ontology-kit.dev): an ontology folder of `okb.json`, `nodes.jsonl` and `edges.jsonl`. It gives another tool the typed nodes and edges, loading (with conversion of older formats), the edge types the format reserves and the relationship values, without the `okb` command line, the meta-KB or the skills.
4
+
5
+ Needs **Node.js 24+**. It has no runtime dependencies.
6
+
7
+ ```bash
8
+ npm install @ontology-kit/reader
9
+ ```
10
+
11
+ ```ts
12
+ import { Ontology, isRelationship, isStructuralEdgeType } from "@ontology-kit/reader";
13
+
14
+ const ont = Ontology.load("./my-ontology");
15
+
16
+ // Every relationship value of every instance, whichever end the edge is stored on.
17
+ for (const slot of ont.ofType("Slot").filter(isRelationship)) {
18
+ for (const instance of ont.ofType("Instance")) {
19
+ for (const target of ont.rel.values(instance.id, slot.id)) {
20
+ console.log(`${instance.name} ${slot.name} ${ont.label(target)}`);
21
+ }
22
+ }
23
+ }
24
+
25
+ // An edge whose type okb doesn't reserve is a relationship value.
26
+ const links = ont.edges.filter((e) => !isStructuralEdgeType(e.type));
27
+ console.log(`${links.length} relationship edges`);
28
+ ```
29
+
30
+ This package reads. To change an ontology, use the [`okb`](https://www.npmjs.com/package/@ontology-kit/okb) command: it keeps ids, provenance and locking consistent, and the write methods on `Ontology` are internal and may change in any release. The exports follow semver, and `docs/FORMAT.md` lists them and says what counts as a breaking change. Before 1.0 any release may break them.
31
+
32
+ **Docs: [the format reference](https://ontology-kit.dev/reference/format/)**. The source is at [github.com/alanbsmith/ontology-kit](https://github.com/alanbsmith/ontology-kit).
33
+
34
+ ## License
35
+
36
+ [MIT](LICENSE)
@@ -0,0 +1,18 @@
1
+ /** Every node type the format defines, in the order of the registry. */
2
+ export declare const NODE_TYPES: readonly string[];
3
+ /**
4
+ * Every edge type okb reserves for its own structure: IS_A, INSTANCE_OF, HAS_SLOT, RANGE, INVERSE_OF,
5
+ * DISJOINT_WITH, NEEDS, BECAME, ABOUT, CITES, PART_OF, GOVERNS, REFINES, FULFILLS. An edge whose type is
6
+ * not in this list is a relationship value, stored under a relationship slot's `relType`. Built from
7
+ * the format registry, so a new structural edge type shows up here without a code change.
8
+ */
9
+ export declare const STRUCTURAL_EDGE_TYPES: readonly string[];
10
+ /**
11
+ * The structural edge types of the provenance and rule layer: CITES, PART_OF, GOVERNS, REFINES, FULFILLS.
12
+ * A subset of STRUCTURAL_EDGE_TYPES.
13
+ */
14
+ export declare const PROVENANCE_EDGE_TYPES: readonly string[];
15
+ /** Whether an edge type is one okb reserves (as opposed to a relationship slot's `relType`). */
16
+ export declare const isStructuralEdgeType: (type: string) => boolean;
17
+ /** Whether an edge type belongs to the provenance and rule layer. */
18
+ export declare const isProvenanceEdgeType: (type: string) => boolean;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The node and edge types the format reserves, built from the registry data (registry.ts, which the
3
+ * okb meta-KB build generates from format.yaml). Kept apart from the public entry so the model can
4
+ * use it without importing the entry.
5
+ */
6
+ import { EDGE_TYPE_NAMES, NODE_TYPE_NAMES, PROVENANCE_EDGE_TYPE_NAMES } from "./registry.js";
7
+ /** Every node type the format defines, in the order of the registry. */
8
+ export const NODE_TYPES = NODE_TYPE_NAMES;
9
+ /**
10
+ * Every edge type okb reserves for its own structure: IS_A, INSTANCE_OF, HAS_SLOT, RANGE, INVERSE_OF,
11
+ * DISJOINT_WITH, NEEDS, BECAME, ABOUT, CITES, PART_OF, GOVERNS, REFINES, FULFILLS. An edge whose type is
12
+ * not in this list is a relationship value, stored under a relationship slot's `relType`. Built from
13
+ * the format registry, so a new structural edge type shows up here without a code change.
14
+ */
15
+ export const STRUCTURAL_EDGE_TYPES = EDGE_TYPE_NAMES;
16
+ /**
17
+ * The structural edge types of the provenance and rule layer: CITES, PART_OF, GOVERNS, REFINES, FULFILLS.
18
+ * A subset of STRUCTURAL_EDGE_TYPES.
19
+ */
20
+ export const PROVENANCE_EDGE_TYPES = PROVENANCE_EDGE_TYPE_NAMES;
21
+ const structural = new Set(STRUCTURAL_EDGE_TYPES);
22
+ const provenance = new Set(PROVENANCE_EDGE_TYPES);
23
+ /** Whether an edge type is one okb reserves (as opposed to a relationship slot's `relType`). */
24
+ export const isStructuralEdgeType = (type) => structural.has(type);
25
+ /** Whether an edge type belongs to the provenance and rule layer. */
26
+ export const isProvenanceEdgeType = (type) => provenance.has(type);
@@ -0,0 +1,3 @@
1
+ /** A user-facing problem (bad name, missing node...). The CLI prints it without a stack trace. */
2
+ export declare class OkbError extends Error {
3
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,3 @@
1
+ /** A user-facing problem (bad name, missing node...). The CLI prints it without a stack trace. */
2
+ export class OkbError extends Error {
3
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @ontology-kit/reader: the okb file format, as a library.
3
+ *
4
+ * Everything another tool needs to read an okb ontology folder: the typed nodes, loading with
5
+ * migrations of older formats, the edge types okb reserves, reading relationship values, and the
6
+ * few name helpers the format's identities are built from. It's an explicit allowlist: nothing else
7
+ * in the package is public, and the write side, which @ontology-kit/okb uses, is tagged internal in the
8
+ * source and left out of the shipped type declarations. docs/FORMAT.md lists the
9
+ * API and says what counts as a breaking change.
10
+ */
11
+ export { Ontology, FORMAT, MANIFEST, findRoot, nodeLabel, nameOrText, literalValue, literalValues } from "./model.js";
12
+ export { OkbError } from "./errors.js";
13
+ export { Relationships, isRelationship, edgeProps } from "./relationships.js";
14
+ export type { LinkSpec } from "./relationships.js";
15
+ export { NODE_TYPES, STRUCTURAL_EDGE_TYPES, PROVENANCE_EDGE_TYPES, isStructuralEdgeType, isProvenanceEdgeType } from "./edge-types.js";
16
+ export { fold, key, rawTokens, relType, slug, stripAccents, tokens } from "./naming.js";
17
+ export { CARDINALITIES, DISPOSITIONS, MODALITIES, VALUE_TYPES, VERIFICATION_STATUSES, } from "./types.js";
18
+ export type { Cardinality, ClassNode, CompetencyQuestionNode, Conventions, DesignDecisionNode, Disposition, EdgePropertyDecl, ExtractedFields, Facets, FacetOverride, GraphEdge, GraphNode, InstanceNode, Literal, LiteralType, Manifest, Modality, NodeOf, NodeType, OkbNode, OntologyNode, RelationshipSlot, ReusedOntologyNode, RuleNode, SlotNode, SourceLocationNode, SourceBlock, SourceNode, StoredValue, TermNode, ValueType, Verification, VerificationStatus, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @ontology-kit/reader: the okb file format, as a library.
3
+ *
4
+ * Everything another tool needs to read an okb ontology folder: the typed nodes, loading with
5
+ * migrations of older formats, the edge types okb reserves, reading relationship values, and the
6
+ * few name helpers the format's identities are built from. It's an explicit allowlist: nothing else
7
+ * in the package is public, and the write side, which @ontology-kit/okb uses, is tagged internal in the
8
+ * source and left out of the shipped type declarations. docs/FORMAT.md lists the
9
+ * API and says what counts as a breaking change.
10
+ */
11
+ export { Ontology, FORMAT, MANIFEST, findRoot, nodeLabel, nameOrText, literalValue, literalValues } from "./model.js";
12
+ export { OkbError } from "./errors.js";
13
+ export { Relationships, isRelationship, edgeProps } from "./relationships.js";
14
+ export { NODE_TYPES, STRUCTURAL_EDGE_TYPES, PROVENANCE_EDGE_TYPES, isStructuralEdgeType, isProvenanceEdgeType } from "./edge-types.js";
15
+ export { fold, key, rawTokens, relType, slug, stripAccents, tokens } from "./naming.js";
16
+ export { CARDINALITIES, DISPOSITIONS, MODALITIES, VALUE_TYPES, VERIFICATION_STATUSES, } from "./types.js";
@@ -0,0 +1,18 @@
1
+ import type { GraphEdge, OkbNode } from "./types.js";
2
+ export declare const NODES_FILE = "nodes.jsonl";
3
+ export declare const EDGES_FILE = "edges.jsonl";
4
+ /** Compare ids so `cq.2` sorts before `cq.10` and the order is the same on every machine. */
5
+ export declare function compareNatural(a: string, b: string): number;
6
+ export declare function nodeLine(n: OkbNode): string;
7
+ export declare function edgeLine(e: GraphEdge): string;
8
+ /** The lines of nodes.jsonl: by id (a duplicated id keeps both, so validate can report it). */
9
+ export declare function nodeLines(nodes: readonly OkbNode[]): string[];
10
+ /** The lines of edges.jsonl: by from, type, to, then the rest of the line. */
11
+ export declare function edgeLines(edges: readonly GraphEdge[]): string[];
12
+ /** Read nodes and edges from either layout. Throws if a folder has both (a half-finished merge or migration). */
13
+ export declare function readGraph(root: string): {
14
+ nodes: OkbNode[];
15
+ edges: GraphEdge[];
16
+ };
17
+ /** Write the three files (each atomically, all temp files first) and remove the old-layout files. */
18
+ export declare function writeGraph(root: string, manifest: unknown, nodes: readonly OkbNode[], edges: readonly GraphEdge[]): void;
package/dist/layout.js ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The on-disk layout of an ontology folder (okb-lpg/3): `okb.json` plus `nodes.jsonl` and `edges.jsonl`,
3
+ * one node or edge per line, sorted, with a fixed key order, so two branches that edit different nodes
4
+ * touch different lines and `git merge` has nothing to conflict on. Older folders (`nodes.json` and
5
+ * `edges.json`, each one JSON array) still load. Part of @ontology-kit/reader.
6
+ */
7
+ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { OkbError } from "./errors.js";
10
+ export const NODES_FILE = "nodes.jsonl";
11
+ export const EDGES_FILE = "edges.jsonl";
12
+ const LEGACY_NODES = "nodes.json";
13
+ const LEGACY_EDGES = "edges.json";
14
+ /** Compare ids so `cq.2` sorts before `cq.10` and the order is the same on every machine. */
15
+ export function compareNatural(a, b) {
16
+ const pa = a.split(/(\d+)/);
17
+ const pb = b.split(/(\d+)/);
18
+ for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
19
+ if (pa[i] === pb[i])
20
+ continue;
21
+ if (i % 2 === 1) {
22
+ const d = Number(pa[i]) - Number(pb[i]);
23
+ if (d !== 0)
24
+ return d;
25
+ }
26
+ return pa[i] < pb[i] ? -1 : 1;
27
+ }
28
+ return pa.length - pb.length;
29
+ }
30
+ /** JSON with every object's keys in a fixed order: `first` (those present), then the rest alphabetically. Arrays keep their order. */
31
+ function canonical(value, first = []) {
32
+ if (Array.isArray(value))
33
+ return value.map((v) => canonical(v));
34
+ if (value === null || typeof value !== "object")
35
+ return value;
36
+ const rec = value;
37
+ const keys = Object.keys(rec).filter((k) => rec[k] !== undefined);
38
+ const head = first.filter((k) => keys.includes(k));
39
+ const tail = keys.filter((k) => !head.includes(k)).sort();
40
+ return Object.fromEntries([...head, ...tail].map((k) => [k, canonical(rec[k])]));
41
+ }
42
+ export function nodeLine(n) {
43
+ return JSON.stringify(canonical(n, ["id", "type"]));
44
+ }
45
+ export function edgeLine(e) {
46
+ return JSON.stringify(canonical(e, ["from", "type", "to"]));
47
+ }
48
+ /** The lines of nodes.jsonl: by id (a duplicated id keeps both, so validate can report it). */
49
+ export function nodeLines(nodes) {
50
+ return nodes.map((n) => [n.id ?? "", nodeLine(n)])
51
+ .sort((a, b) => compareNatural(a[0], b[0]) || (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)).map((x) => x[1]);
52
+ }
53
+ /** The lines of edges.jsonl: by from, type, to, then the rest of the line. */
54
+ export function edgeLines(edges) {
55
+ return edges.map((e) => [e, edgeLine(e)]).sort((a, b) => compareNatural(a[0].from, b[0].from) || compareNatural(a[0].type, b[0].type) || compareNatural(a[0].to, b[0].to) ||
56
+ (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)).map((x) => x[1]);
57
+ }
58
+ function parseLines(text, file) {
59
+ const out = [];
60
+ text.split("\n").forEach((line, i) => {
61
+ if (!line.trim())
62
+ return;
63
+ if (/^(<{7}|={7}|>{7})( |$)/.test(line)) {
64
+ throw new OkbError(`${file} line ${i + 1} is a git merge conflict marker. Resolve the conflict (keep the lines you want from both sides, delete the markers), then run okb validate.`);
65
+ }
66
+ try {
67
+ out.push(JSON.parse(line));
68
+ }
69
+ catch {
70
+ throw new OkbError(`${file} line ${i + 1} isn't valid JSON (each line holds one ${file.startsWith("nodes") ? "node" : "edge"}). If a merge left it like this, fix the line by hand.`);
71
+ }
72
+ });
73
+ return out;
74
+ }
75
+ function readArray(path, name) {
76
+ try {
77
+ return JSON.parse(readFileSync(path, "utf8"));
78
+ }
79
+ catch (e) {
80
+ if (e instanceof SyntaxError)
81
+ throw new OkbError(`${name} isn't valid JSON: ${e.message}`);
82
+ throw e;
83
+ }
84
+ }
85
+ /** Read nodes and edges from either layout. Throws if a folder has both (a half-finished merge or migration). */
86
+ export function readGraph(root) {
87
+ const side = (jsonl, legacy) => {
88
+ const a = join(root, jsonl);
89
+ const b = join(root, legacy);
90
+ if (existsSync(a) && existsSync(b)) {
91
+ throw new OkbError(`Both ${jsonl} and ${legacy} exist. ${jsonl} is the current layout; if ${legacy} is left over from a merge, check it has nothing you need, then delete it.`);
92
+ }
93
+ if (existsSync(a))
94
+ return parseLines(readFileSync(a, "utf8"), jsonl);
95
+ if (existsSync(b))
96
+ return readArray(b, legacy);
97
+ return [];
98
+ };
99
+ return { nodes: side(NODES_FILE, LEGACY_NODES), edges: side(EDGES_FILE, LEGACY_EDGES) };
100
+ }
101
+ /** Write the three files (each atomically, all temp files first) and remove the old-layout files. */
102
+ export function writeGraph(root, manifest, nodes, edges) {
103
+ const lines = (ls) => (ls.length ? ls.join("\n") + "\n" : "");
104
+ const files = [
105
+ ["okb.json", JSON.stringify(manifest, null, 2) + "\n"],
106
+ [NODES_FILE, lines(nodeLines(nodes))],
107
+ [EDGES_FILE, lines(edgeLines(edges))],
108
+ ];
109
+ for (const [name, text] of files)
110
+ writeFileSync(join(root, name + ".tmp"), text, "utf8");
111
+ for (const [name] of files)
112
+ renameSync(join(root, name + ".tmp"), join(root, name));
113
+ for (const old of [LEGACY_NODES, LEGACY_EDGES])
114
+ if (existsSync(join(root, old)))
115
+ unlinkSync(join(root, old));
116
+ }
package/dist/lock.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export declare const LOCK_FILE = ".okb.lock";
2
+ /** Whether a command holds the lock right now. */
3
+ export declare function isLocked(root: string): boolean;
4
+ /** Wait (up to a few seconds) until no command holds the lock. Used by readers, who don't take it. */
5
+ export declare function waitUnlocked(root: string, ms?: number): void;
6
+ /** Take the folder's lock, waiting briefly if another command has it. Returns the function that releases it. */
7
+ export declare function acquireLock(root: string, waitMs?: number): () => void;
package/dist/lock.js ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * A lock for one ontology folder, so two okb commands running at once can't lose a write (each
3
+ * command loads the whole folder and saves it back). The lock is the file `.okb.lock`, created
4
+ * exclusively and holding the owner's process id. Part of @ontology-kit/reader.
5
+ */
6
+ import { randomBytes } from "node:crypto";
7
+ import { existsSync, linkSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
8
+ import { hostname } from "node:os";
9
+ import { join } from "node:path";
10
+ import { OkbError } from "./errors.js";
11
+ export const LOCK_FILE = ".okb.lock";
12
+ const WAIT_MS = 10_000;
13
+ /** A lock this old is stale whatever its owner (another machine on a shared folder, a reused process id). */
14
+ const MAX_AGE_MS = 10 * 60_000;
15
+ function sleep(ms) {
16
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
17
+ }
18
+ /** What the lock file says. `unreadable` is a read that failed for a reason other than the file being gone (EACCES, EIO). */
19
+ function readOwner(path) {
20
+ try {
21
+ const raw = readFileSync(path, "utf8");
22
+ try {
23
+ return { raw, owner: JSON.parse(raw) };
24
+ }
25
+ catch {
26
+ return { raw };
27
+ }
28
+ }
29
+ catch (e) {
30
+ return e.code === "ENOENT" ? { raw: "" } : { raw: "", unreadable: true };
31
+ }
32
+ }
33
+ function alive(pid) {
34
+ try {
35
+ process.kill(pid, 0);
36
+ return true;
37
+ }
38
+ catch (e) {
39
+ return e.code === "EPERM";
40
+ }
41
+ }
42
+ /**
43
+ * The lock's owner is gone: a crashed command (same machine, process not running), or, when the owner can't be
44
+ * checked (another machine on a shared folder, a lock no one can read), a lock older than ten minutes.
45
+ * A command still running on this machine keeps its lock however long it takes.
46
+ */
47
+ function isStale(path) {
48
+ const { owner, unreadable } = readOwner(path);
49
+ if (unreadable)
50
+ return false; // not knowing who holds it is no proof that nobody does
51
+ const mine = Boolean(owner && owner.host === hostname() && Number.isInteger(owner.pid));
52
+ if (mine)
53
+ return !alive(owner.pid);
54
+ try {
55
+ return Date.now() - statSync(path).mtimeMs > MAX_AGE_MS;
56
+ }
57
+ catch {
58
+ return false; // released while we looked
59
+ }
60
+ }
61
+ /** Whether a command holds the lock right now. */
62
+ export function isLocked(root) {
63
+ const path = join(root, LOCK_FILE);
64
+ return existsSync(path) && !isStale(path);
65
+ }
66
+ /**
67
+ * Remove the lock at `path` if it is still `seen`, the stale one that was judged. The lock is first moved aside with a
68
+ * rename, which takes exactly one file and can't be undone by another command's create; only then is it read and, if it
69
+ * is the stale one, deleted. If it turns out to be a newer lock, it is put back. (A command that creates a lock in the
70
+ * instant between the move and the put-back leaves a rare, short overlap; the lock is advisory for commands that run
71
+ * seconds apart, not a security boundary.)
72
+ */
73
+ function removeStale(path, seen, token) {
74
+ const aside = `${path}.stale-${token}`;
75
+ try {
76
+ renameSync(path, aside);
77
+ }
78
+ catch (e) {
79
+ if (e.code === "ENOENT")
80
+ return; // someone else took it away first
81
+ throw new OkbError(`Can't remove the stale lock ${path}: ${e.message}. If no okb command is running, delete it yourself.`);
82
+ }
83
+ const moved = readOwner(aside);
84
+ try {
85
+ if (moved.unreadable || moved.raw !== seen) {
86
+ // Not the lock we judged: a command made a fresh one in between. Put it back, unless yet another took the spot.
87
+ try {
88
+ linkSync(aside, path);
89
+ }
90
+ catch { /* the spot is taken again; the moved lock is already released or superseded */ }
91
+ }
92
+ }
93
+ finally {
94
+ try {
95
+ unlinkSync(aside);
96
+ }
97
+ catch { /* gone */ }
98
+ }
99
+ }
100
+ /** Wait (up to a few seconds) until no command holds the lock. Used by readers, who don't take it. */
101
+ export function waitUnlocked(root, ms = 2000) {
102
+ const path = join(root, LOCK_FILE);
103
+ const end = Date.now() + ms;
104
+ while (existsSync(path) && !isStale(path) && Date.now() < end)
105
+ sleep(25);
106
+ }
107
+ /** Take the folder's lock, waiting briefly if another command has it. Returns the function that releases it. */
108
+ export function acquireLock(root, waitMs = Number(process.env.OKB_LOCK_WAIT_MS) || WAIT_MS) {
109
+ const path = join(root, LOCK_FILE);
110
+ const token = randomBytes(8).toString("hex");
111
+ const mine = { pid: process.pid, host: hostname(), token };
112
+ const end = Date.now() + waitMs;
113
+ for (;;) {
114
+ try {
115
+ writeFileSync(path, JSON.stringify(mine), { flag: "wx" });
116
+ return () => {
117
+ // Remove it only if it is still ours (it could have been judged stale and taken over).
118
+ if (readOwner(path).owner?.token === token) {
119
+ try {
120
+ unlinkSync(path);
121
+ }
122
+ catch { /* already gone */ }
123
+ }
124
+ };
125
+ }
126
+ catch (e) {
127
+ if (e.code !== "EEXIST")
128
+ throw e;
129
+ }
130
+ // Read the lock before judging it, so the takeover can tell it from a fresh one that took its place.
131
+ const seen = readOwner(path).raw;
132
+ if (isStale(path)) {
133
+ removeStale(path, seen, token);
134
+ if (Date.now() < end)
135
+ continue;
136
+ }
137
+ if (Date.now() >= end) {
138
+ const { owner } = readOwner(path);
139
+ throw new OkbError(`Another okb command${owner?.pid ? ` (process ${owner.pid})` : ""} has been writing in ${root} for more than ${Math.max(1, Math.round(waitMs / 1000))} second(s). ` +
140
+ `Try again in a moment. If no okb command is running, delete ${path}.`);
141
+ }
142
+ sleep(25 + Math.floor(Math.random() * 50));
143
+ }
144
+ }
@@ -0,0 +1,104 @@
1
+ import { OkbError } from "./errors.js";
2
+ import { Relationships, edgeProps, isRelationship } from "./relationships.js";
3
+ import { DISPOSITIONS, VALUE_TYPES, type ClassNode, type Conventions, type Facets, type GraphEdge, type InstanceNode, type Manifest, type NodeOf, type NodeType, type OkbNode, type OntologyNode, type RuleNode, type StoredValue } from "./types.js";
4
+ export { DISPOSITIONS, VALUE_TYPES };
5
+ export declare const FORMAT: string;
6
+ export declare const MANIFEST = "okb.json";
7
+ export { OkbError };
8
+ /** What a node is called: its name, or a question's/term's text, or a decision's title. */
9
+ export declare function nodeLabel(n: OkbNode): string;
10
+ export { isRelationship };
11
+ export declare function findRoot(start: string): string | null;
12
+ export declare class Ontology {
13
+ root: string;
14
+ manifest: Manifest;
15
+ private _nodes;
16
+ private _edges;
17
+ private byId;
18
+ /** Relationship values and the edges that store them (see relationships.ts). */
19
+ readonly rel: Relationships;
20
+ private outIdx;
21
+ private incIdx;
22
+ constructor(root: string, manifest: Manifest, nodes: readonly OkbNode[], edges: readonly GraphEdge[]);
23
+ get nodes(): readonly OkbNode[];
24
+ get edges(): readonly GraphEdge[];
25
+ static load(start: string): Ontology;
26
+ private static rootOf;
27
+ private static read;
28
+ static fromData(nodes: readonly OkbNode[], edges: readonly GraphEdge[], manifest?: Partial<Manifest>): Ontology;
29
+ private indexEdge;
30
+ /** The Ontology node (scope, conventions). A stand-in if the file lacks one; struct-well-formed reports that. */
31
+ get meta(): OntologyNode;
32
+ get conventions(): Conventions | undefined;
33
+ get step(): number;
34
+ get(id: string): OkbNode | undefined;
35
+ /**
36
+ * The node with this id, which the caller knows exists (an edge end, a stored
37
+ * slot id). Throws a readable OkbError rather than crashing on a hand-edited
38
+ * file where it doesn't.
39
+ */
40
+ require(id: string): OkbNode;
41
+ require<T extends NodeType>(id: string, type: T): NodeOf<T>;
42
+ ofType<T extends NodeType>(type: T): NodeOf<T>[];
43
+ outEdges(id: string, type: string): GraphEdge[];
44
+ inEdges(id: string, type: string): GraphEdge[];
45
+ targets(id: string, type: string): string[];
46
+ sources(id: string, type: string): string[];
47
+ edgesOf(type: string): GraphEdge[];
48
+ label(id: string): string;
49
+ /** Find a node by id, or by name/text (case- and delimiter-insensitive) among `types`. */
50
+ find<T extends NodeType>(ref: string, types: T | readonly T[]): NodeOf<T>;
51
+ find(ref: string, types?: NodeType | readonly NodeType[]): OkbNode;
52
+ find<T extends NodeType>(ref: string, types: T | readonly T[] | undefined, required: false): NodeOf<T> | undefined;
53
+ private opTime;
54
+ parents(id: string): string[];
55
+ children(id: string): string[];
56
+ /** All classes above id (not including id). Cycle-safe. */
57
+ ancestors(id: string): Set<string>;
58
+ descendants(id: string): Set<string>;
59
+ /**
60
+ * Everything reachable with `next`, nearest first (a parent before its own parents), and among classes
61
+ * the same distance away in id order, so the order is the same in memory and after a save and reload.
62
+ * Cycle-safe.
63
+ */
64
+ private walk;
65
+ /** id plus all its ancestors. */
66
+ up(id: string): Set<string>;
67
+ /** a is b, or a (transitively) IS_A b. */
68
+ isSub(a: string, b: string): boolean;
69
+ /** a and b can never share members: a declared DISJOINT_WITH pair covers them (directly or via ancestors). */
70
+ disjointImplied(a: string, b: string): boolean;
71
+ roots(): string[];
72
+ /** Every class an instance belongs to, including inherited ones. */
73
+ instanceClasses(id: string): Set<string>;
74
+ /** Classes a node belongs to for slot purposes: an instance's classes, or a class and its ancestors. */
75
+ classContext(id: string): string[];
76
+ /** Whether following `type` edges from `from` ever reaches `to`. */
77
+ reaches(from: string, to: string, type: string): boolean;
78
+ ownSlots(id: string): string[];
79
+ slotsOfClasses(classes: Iterable<string>): string[];
80
+ /** Own + inherited slots of a class, all slots of an instance, or the slots declared to apply to Rules. */
81
+ applicableSlots(id: string): string[];
82
+ domain(slotId: string): string[];
83
+ /** Whether a slot belongs to anything: a class, or every Rule. */
84
+ isAttached(slotId: string): boolean;
85
+ range(slotId: string): string[];
86
+ inverses(slotId: string): string[];
87
+ /** Slot facets with overrides from any of `classes` applied (most restrictive wins). */
88
+ effectiveFacets(slotId: string, classes: Iterable<string>): Facets;
89
+ /** Values a node states for a slot: literals (values / fixedValues) plus relationship targets. */
90
+ statedValues(id: string, slotId: string): unknown[];
91
+ /** The fixed (class-level) values for a slot inherited from any of `classes`, with the class that set them. */
92
+ inheritedFixed(slotId: string, classes: Iterable<string>, exclude?: string): {
93
+ cls: string;
94
+ values: unknown[];
95
+ } | null;
96
+ }
97
+ /** A node's own literal value for a slot: an instance's value, or a class's fixed value. */
98
+ export declare function literalValue(n: OkbNode, slotId: string): StoredValue | undefined;
99
+ /** Where a node keeps its own literal values: instances and rules in `values`, classes in `fixedValues`. */
100
+ export declare function literalValues(n: InstanceNode | ClassNode | RuleNode): Record<string, StoredValue>;
101
+ /** A node's name, or a question's/term's text (undefined for anything else). */
102
+ export declare function nameOrText(n: OkbNode): string | undefined;
103
+ export { edgeProps };
104
+ export declare function editDistance(a: string, b: string): number;