@ontology-kit/okb 0.1.0-bootstrap.0 → 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.
Files changed (74) hide show
  1. package/README.md +1 -1
  2. package/dist/check.d.ts +43 -0
  3. package/dist/check.js +83 -0
  4. package/dist/checks.d.ts +1 -1
  5. package/dist/checks.js +4 -4
  6. package/dist/cli.js +159 -45
  7. package/dist/clock.js +1 -1
  8. package/dist/commands.js +96 -2
  9. package/dist/diff.d.ts +85 -0
  10. package/dist/diff.js +323 -0
  11. package/dist/export.d.ts +1 -1
  12. package/dist/export.js +1 -1
  13. package/dist/families.d.ts +1 -1
  14. package/dist/families.js +1 -1
  15. package/dist/help.d.ts +1 -1
  16. package/dist/help.js +9 -2
  17. package/dist/kbdocs.d.ts +18 -0
  18. package/dist/kbdocs.js +393 -0
  19. package/dist/metakb.d.ts +1 -1
  20. package/dist/metakb.js +1 -1
  21. package/dist/naming.d.ts +2 -2
  22. package/dist/naming.js +2 -2
  23. package/dist/ontology-ref.d.ts +20 -0
  24. package/dist/ontology-ref.js +108 -0
  25. package/dist/ops/admin.d.ts +1 -1
  26. package/dist/ops/admin.js +24 -7
  27. package/dist/ops/classes.d.ts +1 -1
  28. package/dist/ops/classes.js +13 -5
  29. package/dist/ops/instances.d.ts +2 -1
  30. package/dist/ops/instances.js +7 -1
  31. package/dist/ops/links.d.ts +1 -1
  32. package/dist/ops/links.js +1 -1
  33. package/dist/ops/naming.d.ts +1 -1
  34. package/dist/ops/naming.js +3 -1
  35. package/dist/ops/scope.d.ts +5 -1
  36. package/dist/ops/scope.js +19 -1
  37. package/dist/ops/slots.d.ts +1 -1
  38. package/dist/ops/slots.js +15 -2
  39. package/dist/ops/values.d.ts +1 -1
  40. package/dist/ops/values.js +5 -1
  41. package/dist/provenance.d.ts +4 -2
  42. package/dist/provenance.js +58 -17
  43. package/dist/release.d.ts +48 -0
  44. package/dist/release.js +318 -0
  45. package/dist/render.d.ts +4 -1
  46. package/dist/render.js +21 -2
  47. package/dist/resync.d.ts +98 -0
  48. package/dist/resync.js +234 -0
  49. package/dist/review.d.ts +1 -1
  50. package/dist/review.js +1 -1
  51. package/dist/reviewdocs.d.ts +42 -0
  52. package/dist/reviewdocs.js +263 -0
  53. package/dist/skills.js +1 -1
  54. package/dist/status.d.ts +1 -1
  55. package/dist/status.js +1 -1
  56. package/dist/types.d.ts +1 -1
  57. package/dist/types.js +1 -1
  58. package/dist/verifynote.d.ts +18 -0
  59. package/dist/verifynote.js +92 -0
  60. package/meta-kb/data/manifest.json +2 -2
  61. package/meta-kb/data/nodes.json +8 -8
  62. package/package.json +7 -3
  63. package/schema/edge.schema.json +68 -0
  64. package/schema/edges.schema.json +9 -0
  65. package/schema/node.schema.json +893 -0
  66. package/schema/nodes.schema.json +9 -0
  67. package/schema/okb.schema.json +41 -0
  68. package/skills/build-domain-kb-from-docs/SKILL.md +20 -2
  69. package/skills/ontology-coach/SKILL.md +6 -2
  70. package/skills/ontology-maintainer/SKILL.md +152 -0
  71. package/skills/ontology-review/SKILL.md +3 -1
  72. package/skills/ontology-signoff/SKILL.md +182 -0
  73. package/templates/okb-check.yml +132 -0
  74. package/templates/pull_request_template.md +16 -0
@@ -0,0 +1,318 @@
1
+ /**
2
+ * `okb release <version>` and `okb release verify`: versioned releases of a knowledge base that
3
+ * consumers (an MCP server, an eval run) can pin. A release writes, inside the KB folder:
4
+ *
5
+ * manifest.json the pin: id, version, and the SHA-256 of every file (the latest release)
6
+ * RELEASES.md every release's change log, newest first
7
+ * releases/<version>/ manifest.json, okb.json, nodes.jsonl, edges.jsonl as released,
8
+ * CHANGES.md and changes.json: what changed since the release before it
9
+ *
10
+ * The change log is `okb diff` between the previous release's snapshot and the working folder, so a
11
+ * release needs no git. The last release is the `version` in `manifest.json`. Output is a function of
12
+ * the files and `SOURCE_DATE_EPOCH` (the date in a change log heading), so cutting the same release
13
+ * twice gives the same bytes. The manifest's shape is the Canvas KB's; docs/FORMAT.md ("Releases")
14
+ * says where it differs.
15
+ */
16
+ import { createHash } from "node:crypto";
17
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
18
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
19
+ import { OkbError, Ontology, slug } from "@ontology-kit/reader";
20
+ import { today } from "./clock.js";
21
+ import { diffMarkdown, diffOntologies, isEmpty } from "./diff.js";
22
+ import { sourcePath } from "./provenance.js";
23
+ export const MANIFEST_FILE = "manifest.json";
24
+ export const RELEASES_DIR = "releases";
25
+ const ONTOLOGY_FILES = ["okb.json", "nodes.jsonl", "edges.jsonl"];
26
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
27
+ /** <0 if a is older than b, 0 if equal, >0 if newer. Semver precedence; a version with a pre-release tag is older than the plain one. */
28
+ export function compareVersions(a, b) {
29
+ const x = SEMVER.exec(a);
30
+ const y = SEMVER.exec(b);
31
+ for (let i = 1; i <= 3; i++)
32
+ if (Number(x[i]) !== Number(y[i]))
33
+ return Number(x[i]) - Number(y[i]);
34
+ if (x[4] === y[4])
35
+ return 0;
36
+ if (x[4] === undefined)
37
+ return 1;
38
+ if (y[4] === undefined)
39
+ return -1;
40
+ const pa = x[4].split(".");
41
+ const pb = y[4].split(".");
42
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
43
+ if (pa[i] === undefined)
44
+ return -1;
45
+ if (pb[i] === undefined)
46
+ return 1;
47
+ if (pa[i] === pb[i])
48
+ continue;
49
+ const na = /^\d+$/.test(pa[i]);
50
+ const nb = /^\d+$/.test(pb[i]);
51
+ if (na && nb)
52
+ return Number(pa[i]) - Number(pb[i]);
53
+ if (na !== nb)
54
+ return na ? -1 : 1;
55
+ return pa[i] < pb[i] ? -1 : 1;
56
+ }
57
+ return 0;
58
+ }
59
+ export const isVersion = (v) => SEMVER.test(v);
60
+ const sha256 = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");
61
+ const posix = (p) => p.split(sep).join("/");
62
+ const sortedRecord = (o) => Object.fromEntries(Object.keys(o).sort().map((k) => [k, o[k]]));
63
+ const json = (v) => JSON.stringify(v, null, 2) + "\n";
64
+ /** Read and check the shape of a manifest.json. Throws OkbError naming the problem. */
65
+ export function readReleaseManifest(file) {
66
+ let raw;
67
+ try {
68
+ raw = JSON.parse(readFileSync(file, "utf8"));
69
+ }
70
+ catch (e) {
71
+ throw new OkbError(`Can't read ${file}: ${e.message}`);
72
+ }
73
+ const bad = (why) => {
74
+ throw new OkbError(`${file} isn't a valid release manifest: ${why}`);
75
+ };
76
+ if (!raw || typeof raw !== "object")
77
+ return bad("it should be a JSON object.");
78
+ if (typeof raw.id !== "string" || !raw.id)
79
+ bad("it has no id.");
80
+ if (typeof raw.version !== "string" || !raw.version)
81
+ bad("it has no version.");
82
+ if (!raw.datasets || typeof raw.datasets !== "object")
83
+ bad("it has no datasets.");
84
+ for (const [name, d] of Object.entries(raw.datasets)) {
85
+ if (!d || typeof d.path !== "string" || !d.files || typeof d.files !== "object")
86
+ bad(`dataset ${name} needs a path and files.`);
87
+ for (const [f, h] of Object.entries(d.files))
88
+ if (typeof h !== "string" || !/^[0-9a-f]{64}$/.test(h))
89
+ bad(`dataset ${name}: ${f} has no SHA-256 (64 lowercase hex digits).`);
90
+ }
91
+ return raw;
92
+ }
93
+ /** The registered sources as a dataset: the folder they share and each file's hash. Throws if a source file is missing. */
94
+ function sourcesDataset(ont) {
95
+ const files = new Map();
96
+ const missing = [];
97
+ for (const s of ont.ofType("Source")) {
98
+ if (!s.localPath)
99
+ continue;
100
+ const abs = resolve(sourcePath(ont, s));
101
+ if (!existsSync(abs) || !statSync(abs).isFile())
102
+ missing.push(`${s.title || s.id} (${s.localPath})`);
103
+ else
104
+ files.set(abs, sha256(abs));
105
+ }
106
+ if (missing.length)
107
+ throw new OkbError(`Can't release: ${missing.length} source file(s) are missing, so their hashes can't be pinned: ${missing.join(", ")}. Restore them or remove the source nodes.`);
108
+ if (!files.size)
109
+ return undefined;
110
+ const segs = [...files.keys()].map((f) => dirname(f).split(sep));
111
+ let common = segs[0];
112
+ for (const s of segs) {
113
+ let i = 0;
114
+ while (i < common.length && i < s.length && common[i] === s[i])
115
+ i++;
116
+ common = common.slice(0, i);
117
+ }
118
+ const base = common.join(sep) || sep;
119
+ const rel = posix(relative(ont.root, base)) || ".";
120
+ return {
121
+ path: rel,
122
+ description: `${files.size} source file${files.size === 1 ? "" : "s"} that quotes in the ontology cite.`,
123
+ files: sortedRecord(Object.fromEntries([...files].map(([abs, h]) => [posix(relative(base, abs)), h]))),
124
+ };
125
+ }
126
+ function sourceChanges(before, after) {
127
+ const a = before?.files ?? {};
128
+ const b = after?.files ?? {};
129
+ const out = { added: [], removed: [], changed: [] };
130
+ for (const f of Object.keys(b).sort()) {
131
+ if (!(f in a))
132
+ out.added.push(f);
133
+ else if (a[f] !== b[f])
134
+ out.changed.push(f);
135
+ }
136
+ for (const f of Object.keys(a).sort())
137
+ if (!(f in b))
138
+ out.removed.push(f);
139
+ return out;
140
+ }
141
+ const noSourceChanges = (s) => !s.added.length && !s.removed.length && !s.changed.length;
142
+ function countsLine(ont) {
143
+ const n = (t) => ont.ofType(t).length;
144
+ return `${n("Class")} classes, ${n("Slot")} slots, ${n("Instance")} instances and ${n("Source")} sources.`;
145
+ }
146
+ /** Whether okb.json differs from the released copy in anything but its version (`okb pin` changes okbVersion alone, and that is pinned too). */
147
+ function manifestChanged(snap, ont) {
148
+ try {
149
+ const was = JSON.parse(readFileSync(join(snap, "okb.json"), "utf8"));
150
+ const strip = (m) => JSON.stringify(Object.entries(m).filter(([k]) => k !== "version").sort(([a], [b]) => (a < b ? -1 : 1)));
151
+ return strip(was) !== strip(ont.manifest);
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ }
157
+ /** One release's section of the change log (also the whole of CHANGES.md). */
158
+ function changesMarkdown(version, previous, date, diff, sources, ont, note) {
159
+ const out = [`## ${version} (${date})`, ""];
160
+ if (!previous)
161
+ out.push(`The first release: ${countsLine(ont)}`, "");
162
+ else
163
+ out.push(`Changes since ${previous}.`, "");
164
+ if (note)
165
+ out.push(note, "");
166
+ if (diff) {
167
+ // the diff's own Markdown, one heading level down
168
+ const body = diffMarkdown(diff).split("\n").slice(2).join("\n").replace(/^## /gm, "### ").trimEnd();
169
+ out.push(body, "");
170
+ }
171
+ if (!noSourceChanges(sources) && previous) {
172
+ out.push("### Source files", "");
173
+ for (const f of sources.added)
174
+ out.push(`- **Added** \`${f}\``);
175
+ for (const f of sources.removed)
176
+ out.push(`- **Removed** \`${f}\``);
177
+ for (const f of sources.changed)
178
+ out.push(`- **Changed** \`${f}\``);
179
+ out.push("");
180
+ }
181
+ return out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
182
+ }
183
+ /** The versions that have a releases/<version>/ folder, newest first. */
184
+ function releasedVersions(root) {
185
+ const dir = join(root, RELEASES_DIR);
186
+ if (!existsSync(dir))
187
+ return [];
188
+ return readdirSync(dir, { withFileTypes: true })
189
+ .filter((e) => e.isDirectory() && isVersion(e.name) && existsSync(join(dir, e.name, "CHANGES.md")))
190
+ .map((e) => e.name)
191
+ .sort((a, b) => compareVersions(b, a));
192
+ }
193
+ function writeReleasesMd(root, name) {
194
+ const sections = releasedVersions(root).map((v) => readFileSync(join(root, RELEASES_DIR, v, "CHANGES.md"), "utf8").trimEnd());
195
+ writeFileSync(join(root, "RELEASES.md"), `# Releases of ${name}\n\nEach release's changes, newest first. \`manifest.json\` pins the latest one; \`okb release verify\` checks the files against it.\n\n${sections.join("\n\n")}\n`);
196
+ }
197
+ /**
198
+ * Cut release `version` of the folder `ont` was loaded from. Call it inside `Ontology.edit` (it saves
199
+ * and writes files under the lock). `findings` are the validator's results; any open error stops the release.
200
+ * Writes nothing when it refuses.
201
+ */
202
+ export function cutRelease(ont, version, findings) {
203
+ if (!isVersion(version))
204
+ throw new OkbError(`'${version}' isn't a version. Use semver: 1.0.0, 1.2.3 or 2.0.0-rc.1.`);
205
+ const errors = findings.filter((f) => f.severity === "error" && !f.explainedBy);
206
+ if (errors.length) {
207
+ throw new OkbError(`Can't release: okb validate reports ${errors.length} error(s). Fix them first (okb validate shows them). The first: ${errors[0].message}`);
208
+ }
209
+ const root = ont.root;
210
+ const lastFile = join(root, MANIFEST_FILE);
211
+ const last = existsSync(lastFile) ? readReleaseManifest(lastFile) : undefined;
212
+ if (last && isVersion(last.version) && compareVersions(version, last.version) <= 0) {
213
+ throw new OkbError(`Version ${version} isn't newer than the last release, ${last.version}. Pick a higher version.`);
214
+ }
215
+ // The root manifest.json is what makes a release exist, and it is written last. So a releases/<version>/
216
+ // folder for a version newer than the one it pins is what a release that stopped half-way leaves (even when
217
+ // the folder's own manifest.json got written), and it is written over. A finished release is never newer
218
+ // than the pinned one, so the check above already refuses to rewrite it.
219
+ const docs = sourcesDataset(ont);
220
+ let diff;
221
+ let note;
222
+ if (last) {
223
+ const snap = join(root, RELEASES_DIR, last.version);
224
+ if (existsSync(join(snap, "nodes.jsonl")) && existsSync(join(snap, "okb.json"))) {
225
+ diff = diffOntologies(Ontology.load(snap), ont, last.version, version);
226
+ }
227
+ else
228
+ note = `There's no snapshot of ${last.version} in ${RELEASES_DIR}/, so this release can't list what changed in the knowledge.`;
229
+ }
230
+ const sources = sourceChanges(last?.datasets.docs, docs);
231
+ if (diff && isEmpty(diff) && !diff.summary.stampOnly && noSourceChanges(sources) && !manifestChanged(join(root, RELEASES_DIR, last.version), ont)) {
232
+ throw new OkbError(`Nothing has changed since ${last.version}, so there is nothing to release.`);
233
+ }
234
+ const date = today(); // an invalid SOURCE_DATE_EPOCH stops here, before anything is written
235
+ // Everything is checked; from here on it writes.
236
+ ont.manifest.version = version;
237
+ ont.save();
238
+ const ontologyFiles = Object.fromEntries(ONTOLOGY_FILES.map((f) => [f, sha256(join(root, f))]));
239
+ const manifest = {
240
+ id: last?.id ?? (slug(ont.meta.name || ont.manifest.name || "") || "ontology"),
241
+ version,
242
+ title: ont.meta.name || ont.manifest.name || last?.title,
243
+ ...(last?.description ? { description: last.description } : {}),
244
+ datasets: {
245
+ ...(docs ? { docs } : {}),
246
+ ontology: {
247
+ path: ".",
248
+ description: `okb graph (${ont.manifest.format}): ${ont.nodes.length} nodes and ${ont.edges.length} edges. Pinned files only; the folder also holds ${MANIFEST_FILE}, ${RELEASES_DIR}/ and RELEASES.md.`,
249
+ files: sortedRecord(ontologyFiles),
250
+ },
251
+ },
252
+ ...(last?.provenance ? { provenance: last.provenance } : {}),
253
+ };
254
+ const snap = join(root, RELEASES_DIR, version);
255
+ mkdirSync(snap, { recursive: true });
256
+ for (const f of ONTOLOGY_FILES)
257
+ copyFileSync(join(root, f), join(snap, f));
258
+ writeFileSync(join(snap, "changes.json"), json({ version, previous: last?.version ?? null, changes: diff ?? null, sources }));
259
+ writeFileSync(join(snap, "CHANGES.md"), changesMarkdown(version, last?.version, date, diff, sources, ont, note));
260
+ writeReleasesMd(root, manifest.title ?? manifest.id);
261
+ // The manifests go last: they are what makes the release exist, so a failure above leaves nothing pinned.
262
+ // Dataset paths are relative to the manifest, so the snapshot's copy points at the sources from its own folder.
263
+ const snapManifest = { ...manifest, datasets: { ...manifest.datasets, ...(docs ? { docs: { ...docs, path: posix(relative(snap, resolve(root, docs.path))) || "." } } : {}) } };
264
+ writeFileSync(join(snap, MANIFEST_FILE), json(snapManifest));
265
+ writeFileSync(lastFile, json(manifest));
266
+ const notes = [`Released ${version}${last ? ` (was ${last.version})` : ""}: ${countsLine(ont)}`];
267
+ if (diff) {
268
+ const s = diff.summary;
269
+ notes.push(`Since ${last.version}: ${s.nodesAdded} node(s) added, ${s.nodesRemoved} removed, ${s.nodesChanged} changed; ${diff.relationshipTypeRenames.length} edge type(s) renamed.`);
270
+ }
271
+ if (note)
272
+ notes.push(note);
273
+ notes.push(`Wrote ${MANIFEST_FILE}, RELEASES.md and ${join(RELEASES_DIR, version)}/. Commit them, and tag the commit if you want a git ref for ${version}.`);
274
+ return { version, previous: last?.version, manifest, notes };
275
+ }
276
+ /** Check the files in `root` against its manifest.json. Read-only. */
277
+ export function verifyRelease(root) {
278
+ const file = join(root, MANIFEST_FILE);
279
+ if (!existsSync(file))
280
+ throw new OkbError(`There is no ${MANIFEST_FILE} in ${resolve(root)}. Cut a release first: okb release <version>.`);
281
+ const m = readReleaseManifest(file);
282
+ const problems = [];
283
+ let checked = 0;
284
+ // The knowledge itself must be pinned: a manifest that leaves out the ontology files would verify anything.
285
+ for (const f of ONTOLOGY_FILES)
286
+ if (!m.datasets.ontology?.files[f])
287
+ problems.push(`ontology: ${f} isn't pinned in the manifest`);
288
+ const inside = (base, p) => !relative(base, p).startsWith("..") && !isAbsolute(relative(base, p));
289
+ for (const [name, d] of Object.entries(m.datasets)) {
290
+ const dir = resolve(root, d.path);
291
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) {
292
+ problems.push(`${name}: folder ${d.path} is missing`);
293
+ continue;
294
+ }
295
+ for (const [f, expected] of Object.entries(d.files).sort(([p], [q]) => (p < q ? -1 : 1))) {
296
+ checked++;
297
+ const p = join(dir, f);
298
+ if (!inside(dir, p))
299
+ problems.push(`${name}: ${f} points outside its folder`);
300
+ else if (!existsSync(p) || !statSync(p).isFile())
301
+ problems.push(`${name}: ${f} is missing`);
302
+ else {
303
+ const got = sha256(p);
304
+ if (got !== expected)
305
+ problems.push(`${name}: ${f} differs from the release (SHA-256 ${got.slice(0, 12)}…, the manifest says ${expected.slice(0, 12)}…)`);
306
+ }
307
+ }
308
+ }
309
+ try {
310
+ const v = JSON.parse(readFileSync(join(root, "okb.json"), "utf8")).version;
311
+ if (v !== m.version)
312
+ problems.push(`okb.json says version ${v ?? "(none)"}, the manifest says ${m.version}`);
313
+ }
314
+ catch {
315
+ // an unreadable okb.json shows up above as a hash mismatch or a missing file
316
+ }
317
+ return { id: m.id, version: m.version, ok: problems.length === 0, checked, problems };
318
+ }
package/dist/render.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type Explainable, type MetaStep } from "./metakb.js";
2
- import { type Ontology, type OkbNode } from "@ontology-kit/format";
2
+ import { type Ontology, type OkbNode } from "@ontology-kit/reader";
3
3
  import { type Finding } from "./types.js";
4
+ import type { CheckReport } from "./check.js";
4
5
  export declare const c: {
5
6
  bold: (s: string) => string;
6
7
  dim: (s: string) => string;
@@ -28,3 +29,5 @@ export declare function listExplainable(): string;
28
29
  export declare function tree(ont: Ontology, withInstances?: boolean): string;
29
30
  export declare function show(ont: Ontology, n: OkbNode): string;
30
31
  export declare function mermaid(ont: Ontology): string;
32
+ /** The `okb check` summary: one line per check, the problems under the ones that failed, and a verdict. */
33
+ export declare function formatCheck(report: CheckReport, name: string): string;
package/dist/render.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Human-readable output: findings, explanations, trees, node details, Mermaid diagrams. */
2
2
  import { ruleUrl } from "./site.js";
3
3
  import { MetaKB } from "./metakb.js";
4
- import { edgeProps, nodeLabel } from "@ontology-kit/format";
4
+ import { edgeProps, nodeLabel } from "@ontology-kit/reader";
5
5
  import {} from "./types.js";
6
6
  import * as naming from "./naming.js";
7
7
  const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
@@ -279,6 +279,10 @@ export function show(ont, n) {
279
279
  out.push(`${c.bold(nodeLabel(n))} ${c.dim(`${n.type} · ${n.id}`)}`);
280
280
  if ("description" in n && n.description)
281
281
  out.push(indent(n.description, " "));
282
+ if (n.createdAt)
283
+ line("created", n.createdAt);
284
+ if (n.updatedAt)
285
+ line("updated", n.updatedAt);
282
286
  if (n.type === "Class") {
283
287
  line("parents", ont.parents(n.id).map((p) => ont.label(p)).join(", ") || "(top level)");
284
288
  line("subclasses", ont.children(n.id).map((p) => ont.label(p)).join(", ") || "—");
@@ -339,7 +343,7 @@ export function show(ont, n) {
339
343
  }
340
344
  else {
341
345
  for (const [k, v] of Object.entries(n))
342
- if (!["id", "type", "name", "values", "authored"].includes(k))
346
+ if (!["id", "type", "name", "values", "authored", "createdAt", "updatedAt"].includes(k))
343
347
  line(k, typeof v === "string" ? v : JSON.stringify(v));
344
348
  if (n.type === "Rule") {
345
349
  if (n.authored)
@@ -411,3 +415,18 @@ export function mermaid(ont) {
411
415
  out.push("", `Disjoint: ${disj.join(" · ")}`);
412
416
  return out.join("\n");
413
417
  }
418
+ /** The `okb check` summary: one line per check, the problems under the ones that failed, and a verdict. */
419
+ export function formatCheck(report, name) {
420
+ const out = [c.bold(`okb check: ${name}`) + c.dim(` (okb ${report.installed}${report.pinned ? `, KB pins ${report.pinned}` : ""})`), ""];
421
+ const mark = { pass: SYMBOL.ok, warn: SYMBOL.warning, fail: SYMBOL.error };
422
+ for (const s of report.steps) {
423
+ out.push(`${mark[s.status]} ${c.bold(s.title)}: ${s.summary}`);
424
+ for (const p of s.problems)
425
+ out.push(` ${SYMBOL.error} ${p}`);
426
+ }
427
+ const failed = report.steps.filter((s) => s.status === "fail").length;
428
+ const warned = report.steps.filter((s) => s.status === "warn").length;
429
+ const safe = warned ? `no check failed, but ${warned} warned (marked ${SYMBOL.warning} above).` : "every check passed.";
430
+ out.push("", report.ok ? `${SYMBOL.ok} Safe to merge: ${safe}` : `${SYMBOL.error} Not safe to merge: ${failed} of ${report.steps.length} checks failed.`);
431
+ return out.join("\n");
432
+ }
@@ -0,0 +1,98 @@
1
+ import type { Ontology, SourceBlock } from "@ontology-kit/reader";
2
+ import { type MdDoc } from "./markdown.js";
3
+ /** Which block a baseline or current record describes, plus its hash. */
4
+ export type BlockRecord = SourceBlock;
5
+ export declare const RESYNC_SCHEMA = "okb-resync/1";
6
+ export declare const hashText: (text: string) => string;
7
+ /** The records for a document's quotable blocks, in document order. */
8
+ export declare function blockRecords(doc: MdDoc): BlockRecord[];
9
+ export type Change = "new" | "changed" | "removed";
10
+ export interface WorklistItem {
11
+ /** Stable across runs while the block's text is unchanged: `<source id>:<first 12 hex of the hash>`. */
12
+ id: string;
13
+ source: string;
14
+ change: Change;
15
+ headingPath: string[];
16
+ blockKind: string;
17
+ /** Line range in the current document; null for a removed block. */
18
+ lines: [number, number] | null;
19
+ /** Hash of the current text; null for a removed block. */
20
+ hash: string | null;
21
+ /** Hash of the text the baseline recorded; null for a new block. */
22
+ oldHash: string | null;
23
+ preview: string | null;
24
+ oldPreview: string | null;
25
+ }
26
+ export interface BlockDiff {
27
+ change: Change;
28
+ old?: BlockRecord;
29
+ /** The index into the current list. */
30
+ current?: number;
31
+ }
32
+ /**
33
+ * Compare a baseline with the current blocks. Pure. A block whose hash is still present is unchanged, wherever it
34
+ * moved. What's left is paired up as "changed" (same place, similar text), and the rest is "new" or "removed".
35
+ */
36
+ export declare function diffBlocks(baseline: BlockRecord[], current: BlockRecord[]): BlockDiff[];
37
+ export interface Citer {
38
+ id: string;
39
+ type: string;
40
+ label: string;
41
+ }
42
+ export interface QuoteIssue {
43
+ source: string;
44
+ /** The SourceLocation id. */
45
+ quote: string;
46
+ text: string;
47
+ was: {
48
+ locator?: string;
49
+ lines?: string;
50
+ };
51
+ /** Nodes that cite the quote: rules, facts, classes. */
52
+ citedBy: Citer[];
53
+ }
54
+ export interface MovedQuote extends QuoteIssue {
55
+ now: {
56
+ locator?: string;
57
+ lines?: string;
58
+ };
59
+ }
60
+ export interface SourceStatus {
61
+ id: string;
62
+ path: string | null;
63
+ format: string | null;
64
+ /** "checked", or why the source couldn't be (no local file, file missing). */
65
+ state: "checked" | "unreadable";
66
+ problem?: string;
67
+ /** Whether the Source has baseline hashes to compare against. Only markdown sources do. */
68
+ baseline: boolean;
69
+ quotes: number;
70
+ moved: number;
71
+ gone: number;
72
+ }
73
+ export interface ResyncReport {
74
+ schema: typeof RESYNC_SCHEMA;
75
+ /** False when a quote is gone or a source can't be read: the KB no longer matches its documents. */
76
+ ok: boolean;
77
+ /** True when the current blocks were stored as the new baseline (`--record`). */
78
+ recorded: boolean;
79
+ sources: SourceStatus[];
80
+ gone: QuoteIssue[];
81
+ moved: MovedQuote[];
82
+ worklist: WorklistItem[];
83
+ }
84
+ export interface ResyncOptions {
85
+ /** Update moved quotes in `ont` (the quote's own lines and links). Never touches a quote that can't be found. */
86
+ write: boolean;
87
+ /** Also store the current blocks as the baseline. Implies `write`. */
88
+ record: boolean;
89
+ }
90
+ /**
91
+ * Re-locate every quote in every source and compare each markdown source's blocks to its baseline. `pages` is
92
+ * `loadSourcePages(ont)`. With `write` false nothing in `ont` changes.
93
+ */
94
+ export declare function resync(ont: Ontology, pages: Map<string, string[] | MdDoc | Error>, o: ResyncOptions): ResyncReport;
95
+ /** The human-readable report, as lines. */
96
+ export declare function renderResync(r: ResyncReport, o: {
97
+ dryRun: boolean;
98
+ }): string[];