@ontology-kit/reader 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.
package/dist/index.d.ts CHANGED
@@ -8,10 +8,12 @@
8
8
  * source and left out of the shipped type declarations. docs/FORMAT.md lists the
9
9
  * API and says what counts as a breaking change.
10
10
  */
11
- export { Ontology, FORMAT, MANIFEST, findRoot, nodeLabel, nameOrText, literalValue, literalValues } from "./model.js";
11
+ export { Ontology, FORMAT, MANIFEST, findRoot, nodeLabel, nameOrText, literalValues } from "./model.js";
12
12
  export { OkbError } from "./errors.js";
13
13
  export { Relationships, isRelationship, edgeProps } from "./relationships.js";
14
14
  export type { LinkSpec } from "./relationships.js";
15
+ export { checkQuery, query, queryFind, queryGet, querySlots, queryTraverse, resultNames } from "./query.js";
16
+ export type { FindQuery, GetResult, NodeHit, Query, QueryResult, QueryValue, SlotHit, SlotsQuery, TraverseHit, TraverseQuery, } from "./query.js";
15
17
  export { NODE_TYPES, STRUCTURAL_EDGE_TYPES, PROVENANCE_EDGE_TYPES, isStructuralEdgeType, isProvenanceEdgeType } from "./edge-types.js";
16
18
  export { fold, key, rawTokens, relType, slug, stripAccents, tokens } from "./naming.js";
17
19
  export { CARDINALITIES, DISPOSITIONS, MODALITIES, VALUE_TYPES, VERIFICATION_STATUSES, } from "./types.js";
package/dist/index.js CHANGED
@@ -8,9 +8,10 @@
8
8
  * source and left out of the shipped type declarations. docs/FORMAT.md lists the
9
9
  * API and says what counts as a breaking change.
10
10
  */
11
- export { Ontology, FORMAT, MANIFEST, findRoot, nodeLabel, nameOrText, literalValue, literalValues } from "./model.js";
11
+ export { Ontology, FORMAT, MANIFEST, findRoot, nodeLabel, nameOrText, literalValues } from "./model.js";
12
12
  export { OkbError } from "./errors.js";
13
13
  export { Relationships, isRelationship, edgeProps } from "./relationships.js";
14
+ export { checkQuery, query, queryFind, queryGet, querySlots, queryTraverse, resultNames } from "./query.js";
14
15
  export { NODE_TYPES, STRUCTURAL_EDGE_TYPES, PROVENANCE_EDGE_TYPES, isStructuralEdgeType, isProvenanceEdgeType } from "./edge-types.js";
15
16
  export { fold, key, rawTokens, relType, slug, stripAccents, tokens } from "./naming.js";
16
17
  export { CARDINALITIES, DISPOSITIONS, MODALITIES, VALUE_TYPES, VERIFICATION_STATUSES, } from "./types.js";
package/dist/layout.d.ts CHANGED
@@ -1,6 +1,19 @@
1
1
  import type { GraphEdge, OkbNode } from "./types.js";
2
2
  export declare const NODES_FILE = "nodes.jsonl";
3
3
  export declare const EDGES_FILE = "edges.jsonl";
4
+ /**
5
+ * The marker of a save in progress (decision 0033). It is written once all three temp files are complete and removed once
6
+ * the last rename is done, so a marker on disk means "finish this save": `finishSave` renames what is left.
7
+ * `*.tmp` is git-ignored by `okb init`, so the marker is too.
8
+ */
9
+ export declare const SAVING_MARKER = ".okb.saving.tmp";
10
+ /**
11
+ * Test seam (internal: not exported from the package index). `at` is called after each step of a save or a roll-forward
12
+ * (`temps`, `marker`, `renamed:<file>`, `legacy`, `unmarked`); a test throws from it to stop where a crash would.
13
+ */
14
+ export declare const saveSeam: {
15
+ at: (_step: string) => void;
16
+ };
4
17
  /** Compare ids so `cq.2` sorts before `cq.10` and the order is the same on every machine. */
5
18
  export declare function compareNatural(a: string, b: string): number;
6
19
  export declare function nodeLine(n: OkbNode): string;
@@ -14,5 +27,18 @@ export declare function readGraph(root: string): {
14
27
  nodes: OkbNode[];
15
28
  edges: GraphEdge[];
16
29
  };
17
- /** Write the three files (each atomically, all temp files first) and remove the old-layout files. */
30
+ /**
31
+ * Write the three files so that a crash at any point leaves either the old files or a save the next load finishes:
32
+ * all temp files first (flushed), then the marker, then the renames with `okb.json` last, then the old-layout files
33
+ * and the marker are removed. The caller holds the folder's lock (a new folder has no other writer).
34
+ */
18
35
  export declare function writeGraph(root: string, manifest: unknown, nodes: readonly OkbNode[], edges: readonly GraphEdge[]): void;
36
+ /** Whether a save was interrupted after its marker was written (a save in flight looks the same; check the lock). */
37
+ export declare function saveInterrupted(root: string): boolean;
38
+ /**
39
+ * Finish an interrupted save: a marker means all three temp files were complete, so renaming the ones that are left gives
40
+ * exactly the folder the save would have made. Safe to run again after a crash of its own. The caller holds the lock.
41
+ * The renames go in a fixed order, so the temp files that remain must be a tail of it; anything else (a temp file
42
+ * deleted by hand, say) is not a state a crash makes, and it stops with an error instead of guessing.
43
+ */
44
+ export declare function finishSave(root: string): void;
package/dist/layout.js CHANGED
@@ -4,13 +4,27 @@
4
4
  * touch different lines and `git merge` has nothing to conflict on. Older folders (`nodes.json` and
5
5
  * `edges.json`, each one JSON array) still load. Part of @ontology-kit/reader.
6
6
  */
7
- import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { OkbError } from "./errors.js";
10
10
  export const NODES_FILE = "nodes.jsonl";
11
11
  export const EDGES_FILE = "edges.jsonl";
12
12
  const LEGACY_NODES = "nodes.json";
13
13
  const LEGACY_EDGES = "edges.json";
14
+ const MANIFEST_FILE = "okb.json";
15
+ /**
16
+ * The marker of a save in progress (decision 0033). It is written once all three temp files are complete and removed once
17
+ * the last rename is done, so a marker on disk means "finish this save": `finishSave` renames what is left.
18
+ * `*.tmp` is git-ignored by `okb init`, so the marker is too.
19
+ */
20
+ export const SAVING_MARKER = ".okb.saving.tmp";
21
+ /** The rename order. `okb.json` is last: a crash then leaves an old `format` over new data, which loads fine. */
22
+ const SAVE_ORDER = [NODES_FILE, EDGES_FILE, MANIFEST_FILE];
23
+ /**
24
+ * Test seam (internal: not exported from the package index). `at` is called after each step of a save or a roll-forward
25
+ * (`temps`, `marker`, `renamed:<file>`, `legacy`, `unmarked`); a test throws from it to stop where a crash would.
26
+ */
27
+ export const saveSeam = { at: (_step) => { } };
14
28
  /** Compare ids so `cq.2` sorts before `cq.10` and the order is the same on every machine. */
15
29
  export function compareNatural(a, b) {
16
30
  const pa = a.split(/(\d+)/);
@@ -88,7 +102,10 @@ export function readGraph(root) {
88
102
  const a = join(root, jsonl);
89
103
  const b = join(root, legacy);
90
104
  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.`);
105
+ throw new OkbError(`Both ${jsonl} and ${legacy} exist. ${jsonl} is the current layout, but don't just delete ${legacy}: an interrupted save or migration ` +
106
+ `(by an okb older than 0.3.0) can leave some files new and some old, and deleting the old file then keeps new nodes with old edges. ` +
107
+ `Restore the folder from git or a backup, or, if nodes.jsonl.tmp, edges.jsonl.tmp or okb.json.tmp are there, rename each over ` +
108
+ `the file it names (drop the .tmp) and then delete ${LEGACY_NODES} and ${LEGACY_EDGES}. If ${legacy} is only left over from a merge, check it has nothing you need, then delete it.`);
92
109
  }
93
110
  if (existsSync(a))
94
111
  return parseLines(readFileSync(a, "utf8"), jsonl);
@@ -98,19 +115,97 @@ export function readGraph(root) {
98
115
  };
99
116
  return { nodes: side(NODES_FILE, LEGACY_NODES), edges: side(EDGES_FILE, LEGACY_EDGES) };
100
117
  }
101
- /** Write the three files (each atomically, all temp files first) and remove the old-layout files. */
118
+ /** Flush a file's data to disk. A directory can't be opened for this on Windows; there the call does nothing. */
119
+ function flush(path) {
120
+ let fd;
121
+ try {
122
+ fd = openSync(path, "r");
123
+ }
124
+ catch (e) {
125
+ if (process.platform === "win32")
126
+ return;
127
+ throw e;
128
+ }
129
+ try {
130
+ fsyncSync(fd);
131
+ }
132
+ catch (e) {
133
+ const code = e.code;
134
+ if (code !== "EINVAL" && code !== "EPERM" && code !== "ENOTSUP")
135
+ throw e; // a file system without fsync
136
+ }
137
+ finally {
138
+ closeSync(fd);
139
+ }
140
+ }
141
+ const has = (root, name) => existsSync(join(root, name));
142
+ /**
143
+ * Write the three files so that a crash at any point leaves either the old files or a save the next load finishes:
144
+ * all temp files first (flushed), then the marker, then the renames with `okb.json` last, then the old-layout files
145
+ * and the marker are removed. The caller holds the folder's lock (a new folder has no other writer).
146
+ */
102
147
  export function writeGraph(root, manifest, nodes, edges) {
103
148
  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)
149
+ const text = {
150
+ [MANIFEST_FILE]: JSON.stringify(manifest, null, 2) + "\n",
151
+ [NODES_FILE]: lines(nodeLines(nodes)),
152
+ [EDGES_FILE]: lines(edgeLines(edges)),
153
+ };
154
+ // A marker left by an interrupted save of an older okb, or one nobody finished, would make the roll-forward below
155
+ // rename these new temp files over a save it doesn't know about. Finish that one first.
156
+ finishSave(root);
157
+ for (const name of SAVE_ORDER) {
158
+ const tmp = join(root, name + ".tmp");
159
+ writeFileSync(tmp, text[name], "utf8");
160
+ flush(tmp);
161
+ }
162
+ saveSeam.at("temps");
163
+ writeFileSync(join(root, SAVING_MARKER), SAVE_ORDER.join("\n") + "\n", "utf8");
164
+ flush(join(root, SAVING_MARKER));
165
+ flush(root);
166
+ saveSeam.at("marker");
167
+ completeSave(root);
168
+ }
169
+ /** Rename the temp files that are left (in order), drop the old-layout files, then remove the marker. Resumable at every step. */
170
+ function completeSave(root) {
171
+ for (const name of SAVE_ORDER) {
172
+ if (!has(root, name + ".tmp"))
173
+ continue;
112
174
  renameSync(join(root, name + ".tmp"), join(root, name));
175
+ saveSeam.at(`renamed:${name}`);
176
+ }
177
+ flush(root);
113
178
  for (const old of [LEGACY_NODES, LEGACY_EDGES])
114
- if (existsSync(join(root, old)))
179
+ if (has(root, old))
115
180
  unlinkSync(join(root, old));
181
+ saveSeam.at("legacy");
182
+ unlinkSync(join(root, SAVING_MARKER));
183
+ saveSeam.at("unmarked");
184
+ }
185
+ /** Whether a save was interrupted after its marker was written (a save in flight looks the same; check the lock). */
186
+ export function saveInterrupted(root) {
187
+ return has(root, SAVING_MARKER);
188
+ }
189
+ /**
190
+ * Finish an interrupted save: a marker means all three temp files were complete, so renaming the ones that are left gives
191
+ * exactly the folder the save would have made. Safe to run again after a crash of its own. The caller holds the lock.
192
+ * The renames go in a fixed order, so the temp files that remain must be a tail of it; anything else (a temp file
193
+ * deleted by hand, say) is not a state a crash makes, and it stops with an error instead of guessing.
194
+ */
195
+ export function finishSave(root) {
196
+ if (!has(root, SAVING_MARKER))
197
+ return;
198
+ const left = SAVE_ORDER.map((name) => has(root, name + ".tmp"));
199
+ const first = left.indexOf(true);
200
+ const missing = first < 0 ? [] : SAVE_ORDER.filter((_, i) => i > first && !left[i]);
201
+ const missingFinal = SAVE_ORDER.filter((name, i) => !left[i] && !has(root, name));
202
+ if (missing.length || missingFinal.length) {
203
+ const tmps = SAVE_ORDER.filter((_, i) => left[i]).map((n) => n + ".tmp");
204
+ throw new OkbError(`The last save of ${root} was interrupted (${SAVING_MARKER} is there), and the files aren't in a state okb can finish: ` +
205
+ `${tmps.length ? `${tmps.join(", ")} left over` : "no temp files left"}, ` +
206
+ `${missing.length ? `${missing.map((n) => n + ".tmp").join(", ")} missing` : ""}${missing.length && missingFinal.length ? ", " : ""}` +
207
+ `${missingFinal.length ? `${missingFinal.join(", ")} missing` : ""}. ` +
208
+ "Nothing was changed. Restore the folder from git or a backup, or fix those files by hand and delete " + SAVING_MARKER + ".");
209
+ }
210
+ completeSave(root);
116
211
  }
package/dist/lock.d.ts CHANGED
@@ -1,4 +1,13 @@
1
1
  export declare const LOCK_FILE = ".okb.lock";
2
+ /**
3
+ * Test seam (internal: not exported from the package index). `at` is called at the named steps of a takeover so a test
4
+ * can run other contenders in between; `now` and `sleep` let it run without real waiting.
5
+ */
6
+ export declare const testSeam: {
7
+ at: (_step: string) => void;
8
+ now: () => number;
9
+ sleep: (ms: number) => void;
10
+ };
2
11
  /** Whether a command holds the lock right now. */
3
12
  export declare function isLocked(root: string): boolean;
4
13
  /** Wait (up to a few seconds) until no command holds the lock. Used by readers, who don't take it. */
package/dist/lock.js CHANGED
@@ -3,17 +3,34 @@
3
3
  * command loads the whole folder and saves it back). The lock is the file `.okb.lock`, created
4
4
  * exclusively and holding the owner's process id. Part of @ontology-kit/reader.
5
5
  */
6
- import { randomBytes } from "node:crypto";
7
- import { existsSync, linkSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { createHash, randomBytes } from "node:crypto";
7
+ import { existsSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
8
8
  import { hostname } from "node:os";
9
- import { join } from "node:path";
9
+ import { basename, join } from "node:path";
10
10
  import { OkbError } from "./errors.js";
11
11
  export const LOCK_FILE = ".okb.lock";
12
12
  const WAIT_MS = 10_000;
13
13
  /** A lock this old is stale whatever its owner (another machine on a shared folder, a reused process id). */
14
14
  const MAX_AGE_MS = 10 * 60_000;
15
+ /**
16
+ * A claim is held for milliseconds (one read, one check, one delete), so one this old is abandoned whoever owns it: the
17
+ * empty file a crash leaves between its creation and its write, one that can't be parsed, or one from another machine.
18
+ * Only a claim whose owner is a live process on this machine is never old enough.
19
+ */
20
+ const CLAIM_MAX_AGE_MS = 30_000;
21
+ /** How many abandoned claims on one stale lock a contender steps over before it gives up and waits. */
22
+ const MAX_CLAIMS = 20;
23
+ /**
24
+ * Test seam (internal: not exported from the package index). `at` is called at the named steps of a takeover so a test
25
+ * can run other contenders in between; `now` and `sleep` let it run without real waiting.
26
+ */
27
+ export const testSeam = {
28
+ at: (_step) => { },
29
+ now: () => Date.now(),
30
+ sleep: (ms) => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); },
31
+ };
15
32
  function sleep(ms) {
16
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
33
+ testSeam.sleep(ms);
17
34
  }
18
35
  /** What the lock file says. `unreadable` is a read that failed for a reason other than the file being gone (EACCES, EIO). */
19
36
  function readOwner(path) {
@@ -42,9 +59,10 @@ function alive(pid) {
42
59
  /**
43
60
  * The lock's owner is gone: a crashed command (same machine, process not running), or, when the owner can't be
44
61
  * 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.
62
+ * A command still running on this machine keeps its lock however long it takes. `maxAgeMs` is the age that counts as
63
+ * stale when the owner can't be checked (ten minutes for a lock, a few seconds' worth of work for a claim).
46
64
  */
47
- function isStale(path) {
65
+ function isStale(path, maxAgeMs = MAX_AGE_MS) {
48
66
  const { owner, unreadable } = readOwner(path);
49
67
  if (unreadable)
50
68
  return false; // not knowing who holds it is no proof that nobody does
@@ -52,7 +70,7 @@ function isStale(path) {
52
70
  if (mine)
53
71
  return !alive(owner.pid);
54
72
  try {
55
- return Date.now() - statSync(path).mtimeMs > MAX_AGE_MS;
73
+ return testSeam.now() - statSync(path).mtimeMs > maxAgeMs;
56
74
  }
57
75
  catch {
58
76
  return false; // released while we looked
@@ -64,35 +82,90 @@ export function isLocked(root) {
64
82
  return existsSync(path) && !isStale(path);
65
83
  }
66
84
  /**
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.)
85
+ * Take over the stale lock at `path`, whose contents were `seen`. Returns whether the stale lock is gone.
86
+ *
87
+ * A file can't be deleted "only if it is still this one": `unlink` and `rename` take whatever is at the path now. So
88
+ * the takeover is made exclusive instead. The contender first creates, with `wx`, a claim file named after the stale
89
+ * lock's contents (`.okb.lock.claim-<hash of seen>-<n>`). Only one contender can hold the claim for a given stale
90
+ * lock. The holder reads the lock again and deletes it only if it still holds exactly `seen` and is still stale.
91
+ * Nothing else can replace a stale lock in that window: a create (`wx`) fails while the file exists, a dead
92
+ * owner can't release it, and every other contender is shut out by the claim. So the delete can never hit another
93
+ * command's fresh lock, and no moment exists with the spot empty and a lock being put back. The holder never creates
94
+ * the real lock here; the caller does, with the same `wx` as everyone else, so exactly one contender wins it.
95
+ *
96
+ * A claim can be abandoned by a crash. It is judged like a lock (owner gone on this machine; a live local owner is never
97
+ * stale; one that can't be read is never stale), except that when the owner can't be checked (an empty or garbled
98
+ * claim, another machine) it counts as abandoned after 30 seconds instead of ten minutes, since a claim is only held for
99
+ * milliseconds. A claim is never deleted by someone else, since that would be the same race again. A contender that
100
+ * finds an abandoned claim moves on to the next number (`-1`, `-2`, ...), which only one contender can create. The
101
+ * winner removes its own claim and the ones it superseded once the stale lock is gone, and a lock token never comes
102
+ * back, so a claim for it can't matter again. Every early exit below happens while the stale lock still exists, so the
103
+ * superseded claims stay: deleting one would free its number for a new contender who could then claim the same stale
104
+ * lock beside the live claim holder. If all `MAX_CLAIMS` numbers are abandoned, the takeover stops with an error that
105
+ * names the files, so the user can delete them.
106
+ *
107
+ * What remains: a lock judged stale by age alone (another machine on a shared folder, or an owner no one can check) has
108
+ * an owner that may still be running. If that owner releases its lock in the instant between the check and the delete,
109
+ * and a third command creates a new lock in that instant, the delete removes the new lock. The same goes for two
110
+ * contenders who both judge a claim abandoned by age (30 seconds) while its holder, on another machine or with a
111
+ * garbled record, is merely very slow: both then claim the next number. That needs a holder stalled for over 30
112
+ * seconds in a millisecond step, or an owner on another machine silent for ten minutes that then acts within
113
+ * microseconds of the takeover; a plain filesystem has no compare-and-delete to close that. For a command on this
114
+ * machine, the owner's process id decides, and the race is closed.
72
115
  */
73
- function removeStale(path, seen, token) {
74
- const aside = `${path}.stale-${token}`;
75
- try {
76
- renameSync(path, aside);
116
+ function takeOver(path, seen, me) {
117
+ const id = createHash("sha1").update(seen).digest("hex").slice(0, 16);
118
+ const superseded = [];
119
+ let claim;
120
+ for (let n = 0; n < MAX_CLAIMS && !claim; n++) {
121
+ const candidate = `${path}.claim-${id}-${n}`;
122
+ try {
123
+ writeFileSync(candidate, JSON.stringify(me), { flag: "wx" });
124
+ claim = candidate;
125
+ }
126
+ catch (e) {
127
+ if (e.code !== "EEXIST")
128
+ throw e;
129
+ if (!isStale(candidate, CLAIM_MAX_AGE_MS))
130
+ return false; // another contender is taking this lock over right now
131
+ superseded.push(candidate);
132
+ }
77
133
  }
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.`);
134
+ if (!claim) {
135
+ throw new OkbError(`Can't take over the stale lock ${path}: ${superseded.length} leftover claim files block it (${superseded.map((f) => basename(f)).join(", ")}). ` +
136
+ "If no okb command is running, delete them.");
82
137
  }
83
- const moved = readOwner(aside);
84
138
  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.
139
+ testSeam.at("claimed");
140
+ const now = readOwner(path);
141
+ if (now.unreadable)
142
+ return false;
143
+ if (now.raw === seen && isStale(path)) {
144
+ testSeam.at("verified");
87
145
  try {
88
- linkSync(aside, path);
146
+ unlinkSync(path);
147
+ }
148
+ catch (e) {
149
+ if (e.code !== "ENOENT") {
150
+ throw new OkbError(`Can't remove the stale lock ${path}: ${e.message}. If no okb command is running, delete it yourself.`);
151
+ }
89
152
  }
90
- catch { /* the spot is taken again; the moved lock is already released or superseded */ }
153
+ testSeam.at("unlinked");
91
154
  }
155
+ else if (existsSync(path) && now.raw === seen) {
156
+ return false; // not stale after all
157
+ }
158
+ // The stale lock is gone (by us, or replaced by a newer one). Claims named after it are done.
159
+ for (const old of superseded)
160
+ try {
161
+ unlinkSync(old);
162
+ }
163
+ catch { /* gone */ }
164
+ return true;
92
165
  }
93
166
  finally {
94
167
  try {
95
- unlinkSync(aside);
168
+ unlinkSync(claim);
96
169
  }
97
170
  catch { /* gone */ }
98
171
  }
@@ -100,8 +173,8 @@ function removeStale(path, seen, token) {
100
173
  /** Wait (up to a few seconds) until no command holds the lock. Used by readers, who don't take it. */
101
174
  export function waitUnlocked(root, ms = 2000) {
102
175
  const path = join(root, LOCK_FILE);
103
- const end = Date.now() + ms;
104
- while (existsSync(path) && !isStale(path) && Date.now() < end)
176
+ const end = testSeam.now() + ms;
177
+ while (existsSync(path) && !isStale(path) && testSeam.now() < end)
105
178
  sleep(25);
106
179
  }
107
180
  /** Take the folder's lock, waiting briefly if another command has it. Returns the function that releases it. */
@@ -109,8 +182,9 @@ export function acquireLock(root, waitMs = Number(process.env.OKB_LOCK_WAIT_MS)
109
182
  const path = join(root, LOCK_FILE);
110
183
  const token = randomBytes(8).toString("hex");
111
184
  const mine = { pid: process.pid, host: hostname(), token };
112
- const end = Date.now() + waitMs;
185
+ const end = testSeam.now() + waitMs;
113
186
  for (;;) {
187
+ testSeam.at("create");
114
188
  try {
115
189
  writeFileSync(path, JSON.stringify(mine), { flag: "wx" });
116
190
  return () => {
@@ -130,11 +204,11 @@ export function acquireLock(root, waitMs = Number(process.env.OKB_LOCK_WAIT_MS)
130
204
  // Read the lock before judging it, so the takeover can tell it from a fresh one that took its place.
131
205
  const seen = readOwner(path).raw;
132
206
  if (isStale(path)) {
133
- removeStale(path, seen, token);
134
- if (Date.now() < end)
207
+ testSeam.at("judged");
208
+ if (takeOver(path, seen, mine) && testSeam.now() < end)
135
209
  continue;
136
210
  }
137
- if (Date.now() >= end) {
211
+ if (testSeam.now() >= end) {
138
212
  const { owner } = readOwner(path);
139
213
  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
214
  `Try again in a moment. If no okb command is running, delete ${path}.`);
package/dist/model.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { OkbError } from "./errors.js";
2
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";
3
+ import { DISPOSITIONS, VALUE_TYPES, type ClassNode, type Facets, type GraphEdge, type InstanceNode, type Manifest, type NodeOf, type NodeType, type OkbNode, type OntologyNode, type RuleNode, type StoredValue } from "./types.js";
4
4
  export { DISPOSITIONS, VALUE_TYPES };
5
5
  export declare const FORMAT: string;
6
6
  export declare const MANIFEST = "okb.json";
@@ -10,7 +10,6 @@ export declare function nodeLabel(n: OkbNode): string;
10
10
  export { isRelationship };
11
11
  export declare function findRoot(start: string): string | null;
12
12
  export declare class Ontology {
13
- root: string;
14
13
  manifest: Manifest;
15
14
  private _nodes;
16
15
  private _edges;
@@ -19,18 +18,32 @@ export declare class Ontology {
19
18
  readonly rel: Relationships;
20
19
  private outIdx;
21
20
  private incIdx;
21
+ /**
22
+ * Name index: `naming.key()` of each name-like field (see lookupNames) -> the nodes with that key, in node order.
23
+ * `find()` reads it instead of scanning every node. Kept current by reindex (load, removal), addNode and touch
24
+ * (every op that changes a node's name calls touch, see `rename`).
25
+ */
26
+ private nameIdx;
27
+ /** The keys each node is indexed under, and its position in node order (buckets are kept sorted by it). */
28
+ private nameKeys;
29
+ private nextSeq;
22
30
  constructor(root: string, manifest: Manifest, nodes: readonly OkbNode[], edges: readonly GraphEdge[]);
23
31
  get nodes(): readonly OkbNode[];
24
32
  get edges(): readonly GraphEdge[];
25
33
  static load(start: string): Ontology;
34
+ private static recover;
26
35
  private static rootOf;
27
36
  private static read;
28
37
  static fromData(nodes: readonly OkbNode[], edges: readonly GraphEdge[], manifest?: Partial<Manifest>): Ontology;
38
+ /** Index a node under the keys of its current names, as the last in node order. */
39
+ private indexName;
40
+ /** A node's name changed in place: move it to the keys of its new names, keeping buckets in node order. */
41
+ private reindexName;
42
+ /** The nodes (in node order) any of whose names has this key. */
43
+ private byKey;
29
44
  private indexEdge;
30
45
  /** The Ontology node (scope, conventions). A stand-in if the file lacks one; struct-well-formed reports that. */
31
46
  get meta(): OntologyNode;
32
- get conventions(): Conventions | undefined;
33
- get step(): number;
34
47
  get(id: string): OkbNode | undefined;
35
48
  /**
36
49
  * The node with this id, which the caller knows exists (an edge end, a stored
@@ -57,45 +70,27 @@ export declare class Ontology {
57
70
  ancestors(id: string): Set<string>;
58
71
  descendants(id: string): Set<string>;
59
72
  /**
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.
73
+ * Everything reachable with `next`, breadth-first, so nearer classes come before farther ones. Each
74
+ * class's own parents (or children) are visited in id order. The order is deterministic, so it is the same
75
+ * in memory and after a save and reload, but it is not sorted by id across all the classes at one distance:
76
+ * for a class whose parents are `b` and `c`, where `b` has the parent `z` and `c` has the parent `a`,
77
+ * the walk gives `b, c, z, a`. Cycle-safe.
63
78
  */
64
79
  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
80
  roots(): string[];
72
81
  /** Every class an instance belongs to, including inherited ones. */
73
82
  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
83
  ownSlots(id: string): string[];
79
- slotsOfClasses(classes: Iterable<string>): string[];
80
84
  /** Own + inherited slots of a class, all slots of an instance, or the slots declared to apply to Rules. */
81
85
  applicableSlots(id: string): string[];
82
86
  domain(slotId: string): string[];
83
- /** Whether a slot belongs to anything: a class, or every Rule. */
84
- isAttached(slotId: string): boolean;
85
87
  range(slotId: string): string[];
86
88
  inverses(slotId: string): string[];
87
89
  /** Slot facets with overrides from any of `classes` applied (most restrictive wins). */
88
90
  effectiveFacets(slotId: string, classes: Iterable<string>): Facets;
89
91
  /** Values a node states for a slot: literals (values / fixedValues) plus relationship targets. */
90
92
  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
93
  }
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
94
  /** Where a node keeps its own literal values: instances and rules in `values`, classes in `fixedValues`. */
100
95
  export declare function literalValues(n: InstanceNode | ClassNode | RuleNode): Record<string, StoredValue>;
101
96
  /** A node's name, or a question's/term's text (undefined for anything else). */
package/dist/model.js CHANGED
@@ -3,7 +3,7 @@ import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { OkbError } from "./errors.js";
6
- import { compareNatural, readGraph, writeGraph } from "./layout.js";
6
+ import { compareNatural, finishSave, readGraph, saveInterrupted, writeGraph } from "./layout.js";
7
7
  import { acquireLock, isLocked, waitUnlocked } from "./lock.js";
8
8
  import { FORMAT_VERSION } from "./registry.js";
9
9
  import * as naming from "./naming.js";
@@ -59,7 +59,12 @@ export function nodeLabel(n) {
59
59
  }
60
60
  /** Every name-like field a node can be looked up by (a quote's text counts: its id has a random tag). */
61
61
  function lookupNames(n) {
62
- return [("name" in n && n.name) || "", ("text" in n && n.text) || "", ("title" in n && n.title) || "", ("quote" in n && typeof n.quote === "string" && n.quote) || ""];
62
+ // A hand-edited file can hold a number or object here; those can't be looked up by name, and must not reach key().
63
+ // Positions are fixed (name, text, title, quote): callers slice the first two, so a missing field stays as "".
64
+ return ["name", "text", "title", "quote"].map((f) => {
65
+ const v = n[f];
66
+ return typeof v === "string" ? v : "";
67
+ });
63
68
  }
64
69
  export { isRelationship };
65
70
  export function findRoot(start) {
@@ -77,6 +82,7 @@ function readJson(path, fallback) {
77
82
  return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : fallback;
78
83
  }
79
84
  export class Ontology {
85
+ /** @internal */
80
86
  root;
81
87
  manifest;
82
88
  // Changed only through addNode/addEdge/remove*, which keep the indexes current.
@@ -87,6 +93,15 @@ export class Ontology {
87
93
  rel = new Relationships(this);
88
94
  outIdx = new Map();
89
95
  incIdx = new Map();
96
+ /**
97
+ * Name index: `naming.key()` of each name-like field (see lookupNames) -> the nodes with that key, in node order.
98
+ * `find()` reads it instead of scanning every node. Kept current by reindex (load, removal), addNode and touch
99
+ * (every op that changes a node's name calls touch, see `rename`).
100
+ */
101
+ nameIdx = new Map();
102
+ /** The keys each node is indexed under, and its position in node order (buckets are kept sorted by it). */
103
+ nameKeys = new Map();
104
+ nextSeq = 0;
90
105
  constructor(root, manifest, nodes, edges) {
91
106
  this.root = root;
92
107
  this.manifest = manifest;
@@ -106,11 +121,36 @@ export class Ontology {
106
121
  // this was reading, the files may be a mix of old and new, so read again.
107
122
  for (let attempt = 0;; attempt++) {
108
123
  waitUnlocked(root);
124
+ // A marker means a save started and may not have finished. Taking the lock waits out a save still running (it
125
+ // removes the marker before it lets go) and, if the saver is gone, finishes the save under the lock.
126
+ if (saveInterrupted(root)) {
127
+ Ontology.recover(root);
128
+ continue;
129
+ }
109
130
  const ont = Ontology.read(root);
131
+ if (saveInterrupted(root))
132
+ continue; // a save began while we read
110
133
  if (attempt >= 3 || !isLocked(root))
111
134
  return ont;
112
135
  }
113
136
  }
137
+ static recover(root) {
138
+ let release;
139
+ try {
140
+ release = acquireLock(root);
141
+ }
142
+ catch (e) {
143
+ if (e instanceof OkbError)
144
+ throw e;
145
+ throw new OkbError(`The last save of ${root} was interrupted and okb can't finish it: ${e.message}. Run any okb command that changes this folder where you can write to it.`);
146
+ }
147
+ try {
148
+ finishSave(root);
149
+ }
150
+ finally {
151
+ release();
152
+ }
153
+ }
114
154
  /**
115
155
  * Load, change and save one folder with its lock held, so a second command running at the same time
116
156
  * waits instead of overwriting this one's work. `fn` may be async; it should call `save()` itself.
@@ -121,6 +161,7 @@ export class Ontology {
121
161
  const release = acquireLock(root);
122
162
  let result;
123
163
  try {
164
+ finishSave(root); // the lock is ours, so a marker is a save that was interrupted
124
165
  result = fn(Ontology.read(root));
125
166
  }
126
167
  catch (e) {
@@ -186,6 +227,56 @@ export class Ontology {
186
227
  this.incIdx = new Map();
187
228
  for (const e of this.edges)
188
229
  this.indexEdge(e);
230
+ this.nameIdx = new Map();
231
+ this.nameKeys = new Map();
232
+ this.nextSeq = 0;
233
+ for (const n of this.nodes)
234
+ this.indexName(n);
235
+ }
236
+ /** Index a node under the keys of its current names, as the last in node order. */
237
+ indexName(n) {
238
+ const keys = [...new Set(lookupNames(n).map(naming.key).filter(Boolean))];
239
+ this.nameKeys.set(n, { keys, seq: this.nextSeq++ });
240
+ for (const k of keys) {
241
+ const bucket = this.nameIdx.get(k);
242
+ if (bucket)
243
+ bucket.push(n);
244
+ else
245
+ this.nameIdx.set(k, [n]);
246
+ }
247
+ }
248
+ /** A node's name changed in place: move it to the keys of its new names, keeping buckets in node order. */
249
+ reindexName(n) {
250
+ const entry = this.nameKeys.get(n);
251
+ if (!entry)
252
+ return; // not (or no longer) one of this ontology's nodes
253
+ const keys = [...new Set(lookupNames(n).map(naming.key).filter(Boolean))];
254
+ for (const k of entry.keys) {
255
+ if (keys.includes(k))
256
+ continue;
257
+ const bucket = this.nameIdx.get(k);
258
+ const at = bucket?.indexOf(n) ?? -1;
259
+ if (bucket && at >= 0)
260
+ bucket.splice(at, 1);
261
+ if (bucket && !bucket.length)
262
+ this.nameIdx.delete(k);
263
+ }
264
+ for (const k of keys) {
265
+ if (entry.keys.includes(k))
266
+ continue;
267
+ const bucket = this.nameIdx.get(k);
268
+ if (!bucket)
269
+ this.nameIdx.set(k, [n]);
270
+ else {
271
+ bucket.push(n);
272
+ bucket.sort((a, b) => (this.nameKeys.get(a)?.seq ?? 0) - (this.nameKeys.get(b)?.seq ?? 0));
273
+ }
274
+ }
275
+ entry.keys = keys;
276
+ }
277
+ /** The nodes (in node order) any of whose names has this key. */
278
+ byKey(k) {
279
+ return k ? this.nameIdx.get(k) ?? [] : [];
189
280
  }
190
281
  indexEdge(e) {
191
282
  const ko = `${e.from}\u0000${e.type}`;
@@ -206,9 +297,11 @@ export class Ontology {
206
297
  ? n
207
298
  : { type: "Ontology", id: "ontology", name: "", domain: "", purpose: "", users: [], maintainers: [], outOfScope: [], kind: "application", reuseReviewed: false };
208
299
  }
300
+ /** @internal */
209
301
  get conventions() {
210
302
  return this.meta.conventions;
211
303
  }
304
+ /** @internal */
212
305
  get step() {
213
306
  return Number(this.manifest.currentStep ?? 1);
214
307
  }
@@ -257,7 +350,7 @@ export class Ontology {
257
350
  if (direct && ok(direct))
258
351
  return direct;
259
352
  const k = naming.key(ref);
260
- let hits = this.nodes.filter((n) => ok(n) && k && lookupNames(n).some((x) => naming.key(x) === k));
353
+ let hits = this.byKey(k).filter(ok);
261
354
  if (hits.length === 0 && /^\d+$/.test(ref) && ts) {
262
355
  // A bare number is a position in `okb cq list` / `okb decision list` (display order; ids carry no number),
263
356
  // or, for ids made before okb-lpg/3, the number inside `cq.3` / `d.3`.
@@ -290,7 +383,7 @@ export class Ontology {
290
383
  const what = ts ? ts.join(" or ") : "node";
291
384
  if (ts) {
292
385
  const wanted = ts;
293
- const other = this.nodes.find((n) => !wanted.includes(n.type) && k && lookupNames(n).slice(0, 2).some((x) => naming.key(x) === k));
386
+ const other = this.byKey(k).find((n) => !wanted.includes(n.type) && lookupNames(n).slice(0, 2).some((x) => naming.key(x) === k));
294
387
  if (other) {
295
388
  const extra = other.type === "Instance" && ts.includes("Class")
296
389
  ? " Instances can't have subclasses or be used as a class (rule inst-are-leaves); if you need that, make it a class."
@@ -356,18 +449,25 @@ export class Ontology {
356
449
  * the same value, so a command that creates a node and edits it afterwards leaves the two
357
450
  * equal. The CLI wraps each command in this; nesting reuses the outer read. A library caller
358
451
  * that calls ops directly without it still gets a fresh read per addNode/touch, which is fine.
452
+ * An async `fn` keeps the read until its promise settles.
359
453
  * @internal
360
454
  */
361
455
  tick(fn) {
362
456
  if (this.opTime !== null)
363
457
  return fn();
364
458
  this.opTime = timestamp();
459
+ let result;
365
460
  try {
366
- return fn();
461
+ result = fn();
367
462
  }
368
- finally {
463
+ catch (e) {
369
464
  this.opTime = null;
465
+ throw e;
370
466
  }
467
+ if (result instanceof Promise)
468
+ return result.finally(() => (this.opTime = null));
469
+ this.opTime = null;
470
+ return result;
371
471
  }
372
472
  /**
373
473
  * Record that something stored ON the node changed (its own fields, property values or
@@ -379,6 +479,7 @@ export class Ontology {
379
479
  // Never before createdAt: a question or decision added in the same second as another was stamped a second later.
380
480
  const now = this.opTime ?? timestamp();
381
481
  node.updatedAt = node.createdAt && node.createdAt > now ? node.createdAt : now;
482
+ this.reindexName(node);
382
483
  }
383
484
  /** @internal */
384
485
  addNode(node) {
@@ -396,6 +497,7 @@ export class Ontology {
396
497
  node.updatedAt = now;
397
498
  this._nodes.push(node);
398
499
  this.byId.set(node.id, node);
500
+ this.indexName(node);
399
501
  return node;
400
502
  }
401
503
  /** @internal */
@@ -460,9 +562,11 @@ export class Ontology {
460
562
  return this.walk(id, (x) => this.children(x));
461
563
  }
462
564
  /**
463
- * Everything reachable with `next`, nearest first (a parent before its own parents), and among classes
464
- * the same distance away in id order, so the order is the same in memory and after a save and reload.
465
- * Cycle-safe.
565
+ * Everything reachable with `next`, breadth-first, so nearer classes come before farther ones. Each
566
+ * class's own parents (or children) are visited in id order. The order is deterministic, so it is the same
567
+ * in memory and after a save and reload, but it is not sorted by id across all the classes at one distance:
568
+ * for a class whose parents are `b` and `c`, where `b` has the parent `z` and `c` has the parent `a`,
569
+ * the walk gives `b, c, z, a`. Cycle-safe.
466
570
  */
467
571
  walk(id, next) {
468
572
  const seen = new Set();
@@ -477,15 +581,24 @@ export class Ontology {
477
581
  }
478
582
  return seen;
479
583
  }
480
- /** id plus all its ancestors. */
584
+ /**
585
+ * id plus all its ancestors.
586
+ * @internal
587
+ */
481
588
  up(id) {
482
589
  return new Set([id, ...this.ancestors(id)]);
483
590
  }
484
- /** a is b, or a (transitively) IS_A b. */
591
+ /**
592
+ * a is b, or a (transitively) IS_A b.
593
+ * @internal
594
+ */
485
595
  isSub(a, b) {
486
596
  return a === b || this.ancestors(a).has(b);
487
597
  }
488
- /** a and b can never share members: a declared DISJOINT_WITH pair covers them (directly or via ancestors). */
598
+ /**
599
+ * a and b can never share members: a declared DISJOINT_WITH pair covers them (directly or via ancestors).
600
+ * @internal
601
+ */
489
602
  disjointImplied(a, b) {
490
603
  const ua = this.up(a);
491
604
  const ub = this.up(b);
@@ -502,14 +615,20 @@ export class Ontology {
502
615
  out.add(x);
503
616
  return out;
504
617
  }
505
- /** Classes a node belongs to for slot purposes: an instance's classes, or a class and its ancestors. */
618
+ /**
619
+ * Classes a node belongs to for slot purposes: an instance's classes, or a class and its ancestors.
620
+ * @internal
621
+ */
506
622
  classContext(id) {
507
623
  const n = this.byId.get(id);
508
624
  if (n?.type === "Rule")
509
625
  return [];
510
626
  return [...(n?.type === "Instance" ? this.instanceClasses(id) : this.up(id))];
511
627
  }
512
- /** Whether following `type` edges from `from` ever reaches `to`. */
628
+ /**
629
+ * Whether following `type` edges from `from` ever reaches `to`.
630
+ * @internal
631
+ */
513
632
  reaches(from, to, type) {
514
633
  const seen = new Set();
515
634
  const stack = [from];
@@ -526,6 +645,7 @@ export class Ontology {
526
645
  ownSlots(id) {
527
646
  return this.targets(id, "HAS_SLOT");
528
647
  }
648
+ /** @internal */
529
649
  slotsOfClasses(classes) {
530
650
  const out = [];
531
651
  for (const c of classes)
@@ -546,7 +666,10 @@ export class Ontology {
546
666
  domain(slotId) {
547
667
  return this.sources(slotId, "HAS_SLOT");
548
668
  }
549
- /** Whether a slot belongs to anything: a class, or every Rule. */
669
+ /**
670
+ * Whether a slot belongs to anything: a class, or every Rule.
671
+ * @internal
672
+ */
550
673
  isAttached(slotId) {
551
674
  const s = this.byId.get(slotId);
552
675
  return this.domain(slotId).length > 0 || (s?.type === "Slot" && s.appliesToRules === true);
@@ -606,7 +729,10 @@ export class Ontology {
606
729
  out.push(...this.rel.values(id, slotId));
607
730
  return out;
608
731
  }
609
- /** The fixed (class-level) values for a slot inherited from any of `classes`, with the class that set them. */
732
+ /**
733
+ * The fixed (class-level) values for a slot inherited from any of `classes`, with the class that set them.
734
+ * @internal
735
+ */
610
736
  inheritedFixed(slotId, classes, exclude) {
611
737
  for (const c of classes) {
612
738
  if (c === exclude)
@@ -619,7 +745,7 @@ export class Ontology {
619
745
  }
620
746
  }
621
747
  /** A node's own literal value for a slot: an instance's value, or a class's fixed value. */
622
- export function literalValue(n, slotId) {
748
+ function literalValue(n, slotId) {
623
749
  if (n.type === "Instance" || n.type === "Rule")
624
750
  return n.values?.[slotId];
625
751
  if (n.type === "Class")
@@ -0,0 +1,88 @@
1
+ import type { Ontology } from "./model.js";
2
+ import type { GraphEdge, NodeType, OkbNode, StoredValue } from "./types.js";
3
+ /** What one operation takes. Only the keys listed here are allowed. */
4
+ export interface FindQuery {
5
+ class: string;
6
+ where?: Record<string, QueryValue | QueryValue[]>;
7
+ }
8
+ export interface TraverseQuery {
9
+ from: string | string[];
10
+ slot: string;
11
+ direction?: "out" | "in";
12
+ depth?: number;
13
+ }
14
+ export interface SlotsQuery {
15
+ of: string;
16
+ }
17
+ export type QueryValue = string | number | boolean;
18
+ /** A query: an object with exactly one of these keys. */
19
+ export type Query = {
20
+ find: FindQuery;
21
+ } | {
22
+ traverse: TraverseQuery;
23
+ } | {
24
+ slots: SlotsQuery;
25
+ };
26
+ /** A node a query returns. */
27
+ export interface NodeHit {
28
+ id: string;
29
+ type: NodeType;
30
+ name: string;
31
+ }
32
+ /** A slot a query returns. */
33
+ export interface SlotHit {
34
+ id: string;
35
+ name: string;
36
+ valueType: string | undefined;
37
+ relationship: boolean;
38
+ }
39
+ /**
40
+ * One value a traversal reaches. `id` and `type` are set when the value is a node (a relationship
41
+ * target); a property value has neither. `from` is the node it was read from and `depth` the hop (1 is
42
+ * direct). `edge` holds the edge properties of a relationship link. `inheritedFrom` is the class whose
43
+ * fixed value this is, when the node states none of its own.
44
+ */
45
+ export interface TraverseHit {
46
+ name: string;
47
+ value: StoredValue;
48
+ id?: string;
49
+ type?: NodeType;
50
+ from: string;
51
+ depth: number;
52
+ edge?: Record<string, unknown>;
53
+ inheritedFrom?: string;
54
+ }
55
+ /** `queryGet`: a node and the edges on both sides of it, as `okb show --json` prints them. */
56
+ export interface GetResult {
57
+ node: OkbNode;
58
+ out: GraphEdge[];
59
+ in: GraphEdge[];
60
+ }
61
+ export type QueryResult = {
62
+ kind: "find";
63
+ hits: NodeHit[];
64
+ } | {
65
+ kind: "traverse";
66
+ hits: TraverseHit[];
67
+ } | {
68
+ kind: "slots";
69
+ hits: SlotHit[];
70
+ };
71
+ /** Check a query's shape and return it typed, or throw an `OkbError` saying what is wrong. Names aren't looked up here. */
72
+ export declare function checkQuery(q: unknown): Query;
73
+ /** Run a query. Throws an `OkbError` when its shape is wrong or a name in it doesn't exist. */
74
+ export declare function query(ont: Ontology, q: unknown): QueryResult;
75
+ /** The distinct names in a result, sorted: the list `okb cq answer` compares with `expect`. */
76
+ export declare function resultNames(r: QueryResult): string[];
77
+ /** Instances of a class (and its subclasses) whose slot values match. Every `where` slot must match, and a list means all of its values. */
78
+ export declare function queryFind(ont: Ontology, q: FindQuery): NodeHit[];
79
+ /**
80
+ * What a slot gives from one or more classes or instances. A relationship slot follows its own direction
81
+ * (an inverse slot reads the same edges backwards); `direction: "in"` reads it the other way. `depth` follows
82
+ * the same slot again from each node it reaches, up to 3 hops, never revisiting a node.
83
+ */
84
+ export declare function queryTraverse(ont: Ontology, q: TraverseQuery): TraverseHit[];
85
+ /** The slots a class (own and inherited) or an instance has. */
86
+ export declare function querySlots(ont: Ontology, q: SlotsQuery): SlotHit[];
87
+ /** One node (by id, name or `class:Foo`) with the edges leaving and entering it: the data `okb show --json` prints. */
88
+ export declare function queryGet(ont: Ontology, ref: string): GetResult;
package/dist/query.js ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The read-only query layer: pure functions above `Ontology` that return typed data, not text.
3
+ *
4
+ * A query is a JSON object with one key, the shapes `okb cq answer` stores (docs/FORMAT.md, "Expected
5
+ * answers"): `find`, `traverse` and `slots`. `queryGet` is the fourth operation, the data `okb show --json`
6
+ * prints. Everything reads through the `Ontology` primitives (`statedValues`, `inheritedFixed`,
7
+ * `applicableSlots`, `rel`), so relationship storage stays in one place. Nothing here writes.
8
+ *
9
+ * Match rules, the choices behind them and what was left out are written down in decision 0034 and in
10
+ * FORMAT.md. Results are sorted by name, and a thing appears once.
11
+ */
12
+ import { OkbError } from "./errors.js";
13
+ import { edgeProps } from "./relationships.js";
14
+ const SHAPES = new Map([
15
+ ["find", ["class", "where"]],
16
+ ["traverse", ["from", "slot", "direction", "depth"]],
17
+ ["slots", ["of"]],
18
+ ]);
19
+ /** The most hops a traversal takes. */
20
+ const MAX_DEPTH = 3;
21
+ const isObj = (x) => !!x && typeof x === "object" && !Array.isArray(x);
22
+ // okb's cq compare (packages/okb/src/cqanswer.ts) normalizes names the same way; keep the two definitions equal.
23
+ const norm = (s) => s.trim().toLowerCase();
24
+ /** One collation for every result, so `--json` order and cq names don't change with the process's LANG. */
25
+ const collator = new Intl.Collator("en");
26
+ const byText = (a, b) => collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
27
+ /** By name, then id (a property value has none, so it sorts as ""). */
28
+ const byName = (a, b) => byText(a.name, b.name) || byText(a.id ?? "", b.id ?? "");
29
+ /** Check a query's shape and return it typed, or throw an `OkbError` saying what is wrong. Names aren't looked up here. */
30
+ export function checkQuery(q) {
31
+ const keys = isObj(q) ? Object.keys(q) : [];
32
+ if (!isObj(q) || keys.length !== 1 || !SHAPES.has(keys[0]))
33
+ throw new OkbError(`A query is an object with one key: ${[...SHAPES.keys()].join(", ")}. Example: {"traverse":{"from":"Chateau Morgon","slot":"produces"}}`);
34
+ const kind = keys[0];
35
+ const allowed = SHAPES.get(kind);
36
+ const body = q[kind];
37
+ if (!isObj(body))
38
+ throw new OkbError(`"${kind}" must be an object with ${allowed.join(", ")}.`);
39
+ const unknown = Object.keys(body).filter((k) => !allowed.includes(k));
40
+ if (unknown.length)
41
+ throw new OkbError(`"${kind}" doesn't take ${unknown.map((k) => `"${k}"`).join(", ")}. It takes ${allowed.join(", ")}.`);
42
+ const name = (k) => {
43
+ if (body[k] === undefined)
44
+ throw new OkbError(`"${kind}" needs "${k}".`);
45
+ if (typeof body[k] !== "string" || !body[k])
46
+ throw new OkbError(`"${kind}.${k}" must be a name (text).`);
47
+ };
48
+ if (kind === "find") {
49
+ name("class");
50
+ const w = body.where;
51
+ if (w !== undefined) {
52
+ if (!isObj(w))
53
+ throw new OkbError(`"find.where" must be an object of slot: value.`);
54
+ for (const [slot, v] of Object.entries(w)) {
55
+ const vals = Array.isArray(v) ? v : [v];
56
+ if (!vals.length || !vals.every((x) => ["string", "number", "boolean"].includes(typeof x)))
57
+ throw new OkbError(`"find.where.${slot}" must be a value or a list of values.`);
58
+ }
59
+ }
60
+ }
61
+ else if (kind === "traverse") {
62
+ name("slot");
63
+ const from = body.from;
64
+ if (from === undefined)
65
+ throw new OkbError(`"traverse" needs "from".`);
66
+ if (!(typeof from === "string" && from) && !(Array.isArray(from) && from.length && from.every((x) => typeof x === "string" && x)))
67
+ throw new OkbError(`"traverse.from" must be a name (text) or a list of names.`);
68
+ if (body.direction !== undefined && body.direction !== "out" && body.direction !== "in")
69
+ throw new OkbError(`"traverse.direction" must be "out" or "in".`);
70
+ const d = body.depth;
71
+ if (d !== undefined && (!Number.isInteger(d) || d < 1 || d > MAX_DEPTH))
72
+ throw new OkbError(`"traverse.depth" must be a whole number from 1 to ${MAX_DEPTH}.`);
73
+ }
74
+ else
75
+ name("of");
76
+ return q;
77
+ }
78
+ /** Run a query. Throws an `OkbError` when its shape is wrong or a name in it doesn't exist. */
79
+ export function query(ont, q) {
80
+ const checked = checkQuery(q);
81
+ if ("find" in checked)
82
+ return { kind: "find", hits: queryFind(ont, checked.find) };
83
+ if ("traverse" in checked)
84
+ return { kind: "traverse", hits: queryTraverse(ont, checked.traverse) };
85
+ return { kind: "slots", hits: querySlots(ont, checked.slots) };
86
+ }
87
+ /** The distinct names in a result, sorted: the list `okb cq answer` compares with `expect`. */
88
+ export function resultNames(r) {
89
+ return [...new Set(r.hits.map((h) => h.name))].sort(byText);
90
+ }
91
+ const hit = (ont, id) => {
92
+ const n = ont.require(id);
93
+ return { id, type: n.type, name: ont.label(id) };
94
+ };
95
+ /**
96
+ * A node's own values for a slot, else what a class fixes for it. Relationship values are node ids; the rest are literals.
97
+ * Only edges leaving a class are inherited, so reading in reverse never falls back to the class.
98
+ */
99
+ function read(ont, id, slotId, reverse) {
100
+ const stated = (n) => (reverse ? flipped(ont, n, slotId) : ont.statedValues(n, slotId));
101
+ const own = stated(id);
102
+ if (own.length || reverse)
103
+ return { values: own };
104
+ for (const c of ont.classContext(id)) {
105
+ if (c === id)
106
+ continue;
107
+ const vals = stated(c);
108
+ if (vals.length)
109
+ return { values: vals, inheritedFrom: c };
110
+ }
111
+ return { values: [] };
112
+ }
113
+ /** Literal values plus the relationship read the other way round than the slot says. */
114
+ function flipped(ont, id, slotId) {
115
+ const spec = ont.rel.spec(slotId);
116
+ if (!spec)
117
+ return ont.statedValues(id, slotId);
118
+ return spec.reverse ? ont.targets(id, spec.type) : ont.sources(id, spec.type);
119
+ }
120
+ /** Instances of a class (and its subclasses) whose slot values match. Every `where` slot must match, and a list means all of its values. */
121
+ export function queryFind(ont, q) {
122
+ const cls = ont.find(q.class, "Class");
123
+ const where = Object.entries(q.where ?? {}).map(([slot, v]) => ({
124
+ id: ont.find(slot, "Slot").id,
125
+ relationship: ont.rel.spec(ont.find(slot, "Slot").id) !== null,
126
+ want: (Array.isArray(v) ? v : [v]).map((x) => String(x)),
127
+ }));
128
+ const matches = (id, w) => {
129
+ const have = read(ont, id, w.id, false).values.map((v) => norm(valueName(ont, v, w.relationship)));
130
+ // "*" is "has any value".
131
+ return w.want.every((x) => (x === "*" ? have.length > 0 : have.includes(norm(x))));
132
+ };
133
+ const out = ont.ofType("Instance")
134
+ .filter((i) => ont.instanceClasses(i.id).has(cls.id))
135
+ .filter((i) => where.every((w) => matches(i.id, w)))
136
+ .map((i) => hit(ont, i.id));
137
+ return out.sort(byName);
138
+ }
139
+ /** What a stored value is called: the label of the node it points at when the slot is a relationship, else its text. */
140
+ const valueName = (ont, v, relationship) => (relationship && typeof v === "string" && ont.get(v) ? ont.label(v) : String(v));
141
+ /**
142
+ * What a slot gives from one or more classes or instances. A relationship slot follows its own direction
143
+ * (an inverse slot reads the same edges backwards); `direction: "in"` reads it the other way. `depth` follows
144
+ * the same slot again from each node it reaches, up to 3 hops, never revisiting a node.
145
+ */
146
+ export function queryTraverse(ont, q) {
147
+ const found = (Array.isArray(q.from) ? q.from : [q.from]).map((f) => ont.find(f, ["Class", "Instance"]));
148
+ const starts = found.filter((s, i) => found.findIndex((o) => o.id === s.id) === i);
149
+ const slot = ont.find(q.slot, "Slot");
150
+ const depth = q.depth ?? 1;
151
+ const spec = ont.rel.spec(slot.id);
152
+ const relationship = spec !== null;
153
+ if ((depth > 1 || q.direction) && !relationship)
154
+ throw new OkbError(`"${slot.name}" is a property, so it has no direction or hops. Only a relationship can be followed more than once.`);
155
+ const reverse = q.direction === "in";
156
+ const hits = [];
157
+ const seen = new Set(starts.map((s) => s.id));
158
+ let frontier = starts.map((s) => s.id);
159
+ for (let level = 1; level <= depth && frontier.length; level++) {
160
+ const next = [];
161
+ for (const id of frontier) {
162
+ const { values, inheritedFrom } = read(ont, id, slot.id, reverse);
163
+ for (const v of values) {
164
+ const node = relationship && typeof v === "string" ? ont.get(v) : undefined;
165
+ const h = { name: valueName(ont, v, relationship), value: v, from: id, depth: level };
166
+ if (node) {
167
+ h.id = node.id;
168
+ h.type = node.type;
169
+ const e = spec && edgeBetween(ont, inheritedFrom ?? id, node.id, spec.type, spec.reverse !== reverse);
170
+ if (e) {
171
+ const p = edgeProps(e);
172
+ if (Object.keys(p).length)
173
+ h.edge = p;
174
+ }
175
+ if (!seen.has(node.id)) {
176
+ seen.add(node.id);
177
+ next.push(node.id);
178
+ }
179
+ }
180
+ if (inheritedFrom)
181
+ h.inheritedFrom = inheritedFrom;
182
+ hits.push(h);
183
+ }
184
+ }
185
+ frontier = next;
186
+ }
187
+ return hits.sort((a, b) => a.depth - b.depth || byName(a, b));
188
+ }
189
+ function edgeBetween(ont, id, other, type, reverse) {
190
+ const [from, to] = reverse ? [other, id] : [id, other];
191
+ return ont.outEdges(from, type).find((e) => e.to === to);
192
+ }
193
+ /** The slots a class (own and inherited) or an instance has. */
194
+ export function querySlots(ont, q) {
195
+ const of = ont.find(q.of, ["Class", "Instance"]);
196
+ return ont.applicableSlots(of.id)
197
+ .map((id) => ont.require(id, "Slot"))
198
+ .map((s) => ({ id: s.id, name: ont.label(s.id), valueType: s.valueType, relationship: ont.rel.spec(s.id) !== null }))
199
+ .sort(byName);
200
+ }
201
+ /** One node (by id, name or `class:Foo`) with the edges leaving and entering it: the data `okb show --json` prints. */
202
+ export function queryGet(ont, ref) {
203
+ const node = ont.find(ref);
204
+ return { node, out: ont.edges.filter((e) => e.from === node.id), in: ont.edges.filter((e) => e.to === node.id) };
205
+ }
package/dist/types.d.ts CHANGED
@@ -94,6 +94,12 @@ export interface CompetencyQuestionNode extends Stamps {
94
94
  id: string;
95
95
  text: string;
96
96
  status?: "draft" | "answerable";
97
+ /** The stored expected answer (`okb cq answer`): a declarative query, the names it should return, and how strictly to compare. */
98
+ answer?: {
99
+ query: Record<string, unknown>;
100
+ expect: string[];
101
+ match?: "exact" | "includes";
102
+ };
97
103
  }
98
104
  export interface TermNode extends Stamps {
99
105
  type: "Term";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ontology-kit/reader",
3
- "version": "0.2.0",
3
+ "version": "0.3.0-alpha.135",
4
4
  "license": "MIT",
5
5
  "description": "Read the okb file format: an ontology folder's typed nodes and edges, loading with migrations, the reserved edge types and relationship values. No CLI, no meta-KB.",
6
6
  "homepage": "https://ontology-kit.dev",
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/node": "^26.6.6",
44
- "typescript": "^5.9.0"
44
+ "typescript": "^7.0.2"
45
45
  },
46
46
  "scripts": {
47
47
  "typecheck": "tsc",