@ontology-kit/okb 0.1.0 → 0.3.0-alpha.133

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 (109) hide show
  1. package/README.md +1 -1
  2. package/dist/check.d.ts +43 -0
  3. package/dist/check.js +102 -0
  4. package/dist/checks.d.ts +1 -1
  5. package/dist/checks.js +27 -4
  6. package/dist/cli.js +11 -705
  7. package/dist/clidocs.d.ts +0 -2
  8. package/dist/clidocs.js +5 -27
  9. package/dist/clock.js +1 -1
  10. package/dist/command-table.d.ts +144 -0
  11. package/dist/command-table.js +85 -0
  12. package/dist/commands/documents.d.ts +3 -0
  13. package/dist/commands/documents.js +250 -0
  14. package/dist/commands/getting-started.d.ts +3 -0
  15. package/dist/commands/getting-started.js +135 -0
  16. package/dist/commands/housekeeping.d.ts +3 -0
  17. package/dist/commands/housekeeping.js +203 -0
  18. package/dist/commands/modeling.d.ts +3 -0
  19. package/dist/commands/modeling.js +467 -0
  20. package/dist/commands/planning.d.ts +3 -0
  21. package/dist/commands/planning.js +251 -0
  22. package/dist/commands/reviewing.d.ts +3 -0
  23. package/dist/commands/reviewing.js +234 -0
  24. package/dist/commands/skills.d.ts +3 -0
  25. package/dist/commands/skills.js +53 -0
  26. package/dist/commands.d.ts +10 -22
  27. package/dist/commands.js +15 -622
  28. package/dist/cqanswer.d.ts +51 -0
  29. package/dist/cqanswer.js +76 -0
  30. package/dist/diff.d.ts +85 -0
  31. package/dist/diff.js +323 -0
  32. package/dist/export-changes.d.ts +40 -0
  33. package/dist/export-changes.js +115 -0
  34. package/dist/export-csv.d.ts +17 -0
  35. package/dist/export-csv.js +188 -0
  36. package/dist/export-eval-cases.d.ts +38 -0
  37. package/dist/export-eval-cases.js +40 -0
  38. package/dist/export.d.ts +34 -3
  39. package/dist/export.js +70 -12
  40. package/dist/families.d.ts +1 -1
  41. package/dist/families.js +1 -1
  42. package/dist/help.d.ts +11 -2
  43. package/dist/help.js +51 -57
  44. package/dist/kbdocs.d.ts +18 -0
  45. package/dist/kbdocs.js +393 -0
  46. package/dist/metakb.d.ts +1 -1
  47. package/dist/metakb.js +1 -1
  48. package/dist/naming.d.ts +2 -2
  49. package/dist/naming.js +2 -2
  50. package/dist/ontology-ref.d.ts +20 -0
  51. package/dist/ontology-ref.js +108 -0
  52. package/dist/ops/admin.d.ts +2 -2
  53. package/dist/ops/admin.js +26 -8
  54. package/dist/ops/classes.d.ts +1 -1
  55. package/dist/ops/classes.js +15 -7
  56. package/dist/ops/common.d.ts +12 -2
  57. package/dist/ops/common.js +3 -0
  58. package/dist/ops/instances.d.ts +2 -1
  59. package/dist/ops/instances.js +9 -3
  60. package/dist/ops/links.d.ts +2 -2
  61. package/dist/ops/links.js +3 -2
  62. package/dist/ops/naming.d.ts +1 -1
  63. package/dist/ops/naming.js +3 -1
  64. package/dist/ops/scope.d.ts +14 -3
  65. package/dist/ops/scope.js +38 -4
  66. package/dist/ops/slots.d.ts +1 -1
  67. package/dist/ops/slots.js +21 -8
  68. package/dist/ops/values.d.ts +1 -1
  69. package/dist/ops/values.js +5 -1
  70. package/dist/provenance.d.ts +5 -3
  71. package/dist/provenance.js +61 -19
  72. package/dist/release.d.ts +52 -0
  73. package/dist/release.js +337 -0
  74. package/dist/render.d.ts +88 -1
  75. package/dist/render.js +265 -3
  76. package/dist/resync.d.ts +98 -0
  77. package/dist/resync.js +234 -0
  78. package/dist/review.d.ts +1 -1
  79. package/dist/review.js +1 -1
  80. package/dist/reviewdocs.d.ts +42 -0
  81. package/dist/reviewdocs.js +263 -0
  82. package/dist/runner.d.ts +3 -0
  83. package/dist/runner.js +84 -0
  84. package/dist/skills.d.ts +19 -3
  85. package/dist/skills.js +130 -14
  86. package/dist/status.d.ts +1 -1
  87. package/dist/status.js +1 -1
  88. package/dist/types.d.ts +1 -1
  89. package/dist/types.js +1 -1
  90. package/dist/verifynote.d.ts +19 -0
  91. package/dist/verifynote.js +93 -0
  92. package/dist/workflows.d.ts +283 -0
  93. package/dist/workflows.js +270 -0
  94. package/meta-kb/data/edges.json +25 -0
  95. package/meta-kb/data/manifest.json +5 -5
  96. package/meta-kb/data/nodes.json +46 -9
  97. package/package.json +9 -4
  98. package/schema/edge.schema.json +68 -0
  99. package/schema/edges.schema.json +9 -0
  100. package/schema/node.schema.json +914 -0
  101. package/schema/nodes.schema.json +9 -0
  102. package/schema/okb.schema.json +41 -0
  103. package/skills/build-domain-kb-from-docs/SKILL.md +21 -3
  104. package/skills/ontology-coach/SKILL.md +8 -4
  105. package/skills/ontology-maintainer/SKILL.md +152 -0
  106. package/skills/ontology-review/SKILL.md +4 -2
  107. package/skills/ontology-signoff/SKILL.md +182 -0
  108. package/templates/okb-check.yml +148 -0
  109. package/templates/pull_request_template.md +16 -0
@@ -1,6 +1,6 @@
1
1
  /** Parsing and storing values: instance values, class fixed values, defaults and restrictions. */
2
2
  import * as naming from "../naming.js";
3
- import { OkbError, literalValues, nameOrText } from "@ontology-kit/format";
3
+ import { OkbError, literalValues, nameOrText } from "@ontology-kit/reader";
4
4
  import { an, splitList as list } from "./common.js";
5
5
  export function parseAssignments(args) {
6
6
  return args.map((a) => {
@@ -106,6 +106,7 @@ export function assign(ont, ownerId, assignments, mode = "value") {
106
106
  delete stored[slot.id];
107
107
  else
108
108
  stored[slot.id] = slot.cardinality === "multiple" ? next : next[0];
109
+ ont.touch(owner);
109
110
  notes.push(`${owner.name}.${slot.name} ${mode === "fixed" ? "fixed to" : "="} ${next.map((v) => JSON.stringify(v)).join(", ") || "(nothing)"}`);
110
111
  }
111
112
  }
@@ -123,6 +124,7 @@ export function classDefault(ont, ref, assignments) {
123
124
  delete cl.defaults[slot.id];
124
125
  else
125
126
  cl.defaults[slot.id] = coerce(ont, slot, a.raw);
127
+ ont.touch(cl);
126
128
  notes.push(`New ${cl.name} instances will start with ${slot.name} = ${JSON.stringify(cl.defaults[slot.id] ?? null)} (can be changed per instance).`);
127
129
  }
128
130
  return notes;
@@ -133,6 +135,7 @@ export function restrict(ont, ref, slotRef, o) {
133
135
  cl.facetOverrides ??= {};
134
136
  if (o.clear) {
135
137
  delete cl.facetOverrides[slot.id];
138
+ ont.touch(cl);
136
139
  return [`Removed ${cl.name}'s restrictions on ${slot.name}.`];
137
140
  }
138
141
  const ov = (cl.facetOverrides[slot.id] ??= {});
@@ -144,6 +147,7 @@ export function restrict(ont, ref, slotRef, o) {
144
147
  ov.maxCardinality = o.max;
145
148
  if (o.range?.length)
146
149
  ov.range = o.range.map((r) => ont.find(r, "Class").id);
150
+ ont.touch(cl);
147
151
  const notes = [`${cl.name} now restricts ${slot.name}: ${JSON.stringify(ov)}.`];
148
152
  if (o.max === 0)
149
153
  notes.push(`Maximum 0 means ${cl.name} never has a ${slot.name} (Ontology 101 §3, Step 6).`);
@@ -1,6 +1,6 @@
1
- import { type MdDoc } from "./markdown.js";
2
- import { type Ontology, type SourceNode } from "@ontology-kit/format";
3
- import type { Notes } from "./ops.js";
1
+ import { type MdDoc, type QuoteHit } from "./markdown.js";
2
+ import { type Ontology, type SourceLocationNode, type SourceNode } from "@ontology-kit/reader";
3
+ import { type Notes } from "./ops.js";
4
4
  export declare const isMarkdown: (p: string) => boolean;
5
5
  export declare function sourcePath(ont: Ontology, src: SourceNode): string;
6
6
  export declare function readMarkdownSource(ont: Ontology, src: SourceNode): MdDoc;
@@ -18,6 +18,7 @@ export interface AddQuoteOpts {
18
18
  export declare function addQuote(ont: Ontology, sourceRef: string, quote: string, o?: AddQuoteOpts): Promise<Notes>;
19
19
  /** Attach an existing quote to a node: a CITES edge. Marks the node extracted, except an authored rule. */
20
20
  export declare function cite(ont: Ontology, nodeRef: string, locRef: string): Notes;
21
+ export declare function locFields(hit: QuoteHit, src: SourceNode): Partial<SourceLocationNode>;
21
22
  /** Re-locate every quote of a markdown source after the file changed; updates lines and links. */
22
23
  export declare function refreshSource(ont: Ontology, sourceRef: string): Notes;
23
24
  export interface AddRuleOpts {
@@ -49,5 +50,6 @@ export declare function verify(ont: Ontology, ref: string, o: {
49
50
  corrected?: string;
50
51
  confidence?: string;
51
52
  note?: string;
53
+ ref?: string;
52
54
  approve?: boolean;
53
55
  }): Notes;
@@ -6,11 +6,14 @@
6
6
  import { existsSync, readFileSync } from "node:fs";
7
7
  import { isAbsolute, join, relative, resolve } from "node:path";
8
8
  import { deepLinks, locate, parseMarkdown } from "./markdown.js";
9
- import { OkbError, nameOrText, MODALITIES, VERIFICATION_STATUSES as STATUSES } from "@ontology-kit/format";
9
+ import { OkbError, nameOrText, MODALITIES, VERIFICATION_STATUSES as STATUSES } from "@ontology-kit/reader";
10
10
  import { isOneOf } from "./types.js";
11
+ import { UNSUPPORTED_NOTE_TIP, overreachNoteTips, shellQuote, statedModality } from "./verifynote.js";
11
12
  import * as naming from "./naming.js";
13
+ import { tip } from "./ops.js";
12
14
  import { assign } from "./ops/values.js";
13
15
  import { findQuote, loadPages } from "./quotes.js";
16
+ import { blockRecords } from "./resync.js";
14
17
  /** Suggest the closest block for a failed quote only if it shares at least this share of the quote's words. */
15
18
  const MIN_CLOSEST_WORD_OVERLAP = 0.4;
16
19
  export const isMarkdown = (p) => /\.(md|markdown)$/i.test(p);
@@ -42,6 +45,7 @@ export function addSource(ont, file, o) {
42
45
  node.title ||= doc.title ?? file;
43
46
  if (doc.frontmatter)
44
47
  node.meta = doc.frontmatter;
48
+ node.blocks = blockRecords(doc);
45
49
  const quotable = doc.blocks.filter((b) => b.quotable).length;
46
50
  notes.push(`Read ${doc.blocks.length} blocks (${quotable} quotable) under ${doc.headings.length} headings.`);
47
51
  for (const p of doc.problems)
@@ -55,7 +59,7 @@ export function addSource(ont, file, o) {
55
59
  ont.addNode(Object.fromEntries(Object.entries(node).filter(([, v]) => v !== undefined)));
56
60
  notes.unshift(`Registered source ${node.id}: ${node.title}`);
57
61
  if (node.format === "markdown" && !o.repoUrl)
58
- notes.push("Tip: add --repo-url <GitHub URL of this file> so quotes get links to the exact lines.");
62
+ notes.push(tip("Tip: add --repo-url <GitHub URL of this file> so quotes get links to the exact lines."));
59
63
  notes.push(`Next: okb source outline ${node.id} (the list of quotable blocks to work through)`);
60
64
  return notes;
61
65
  }
@@ -116,11 +120,13 @@ export function cite(ont, nodeRef, locRef) {
116
120
  const loc = ont.find(locRef, "SourceLocation");
117
121
  const had = ont.targets(n.id, "CITES").includes(loc.id);
118
122
  ont.addEdge(n.id, "CITES", loc.id);
119
- if (!(n.type === "Rule" && n.authored))
123
+ if (!(n.type === "Rule" && n.authored) && !n.extracted) {
120
124
  n.extracted = true;
125
+ ont.touch(n);
126
+ }
121
127
  return [had ? `${n.type} ${nameOrText(n) ?? n.id} already cited ${loc.id}.` : `${n.type} ${nameOrText(n) ?? n.id} now cites ${loc.id}.`];
122
128
  }
123
- function locFields(hit, src) {
129
+ export function locFields(hit, src) {
124
130
  const links = deepLinks(hit, src.repoUrl, src.url);
125
131
  return Object.fromEntries(Object.entries({
126
132
  locator: hit.locator,
@@ -134,11 +140,7 @@ function locFields(hit, src) {
134
140
  }).filter(([, v]) => v !== undefined));
135
141
  }
136
142
  function nextLocId(ont, src) {
137
- const base = `loc.${naming.slug(src.title ?? src.id).slice(0, 30)}`;
138
- let i = 1;
139
- while (ont.get(`${base}.${i}`))
140
- i++;
141
- return `${base}.${i}`;
143
+ return ont.newId("SourceLocation", naming.slug(src.title ?? src.id).slice(0, 30));
142
144
  }
143
145
  /** Suggest the block that shares the most words with a failed quote. */
144
146
  function closest(doc, quote) {
@@ -179,6 +181,7 @@ export function refreshSource(ont, sourceRef) {
179
181
  moved++;
180
182
  notes.push(` ${loc.id}: line ${loc.lines} → ${hit.startLine}${hit.locator !== loc.locator ? ` (now under ${hit.locator})` : ""}`);
181
183
  Object.assign(loc, locFields(hit, src));
184
+ ont.touch(loc);
182
185
  }
183
186
  }
184
187
  notes.unshift(`${src.id}: ${moved} quote(s) moved, ${missing} missing.${missing ? " Missing quotes are errors in okb validate (prov-quote-current); re-extract them from the current text." : ""}`);
@@ -233,7 +236,7 @@ export function refine(ont, ruleRef, broaderRef, o = {}) {
233
236
  ont.addEdge(rule.id, "REFINES", broader.id, adds ? { adds } : {});
234
237
  const notes = [`${rule.id} refines ${broader.id}${adds ? ` (adds: ${adds})` : ""}.`];
235
238
  if (!adds)
236
- notes.push("Tip: say what it adds with --adds \"...\" so a verifier can check that detail appears in its quote.");
239
+ notes.push(tip("Tip: say what it adds with --adds \"...\" so a verifier can check that detail appears in its quote."));
237
240
  return notes;
238
241
  }
239
242
  /** `instance` FULFILLS `rule`: a descriptive fact that meets the rule. Many instances may fulfill one rule. */
@@ -247,7 +250,23 @@ export function fulfill(ont, instanceRef, ruleRef, o = {}) {
247
250
  ont.addEdge(inst.id, "FULFILLS", rule.id);
248
251
  return [`${inst.name} fulfills ${rule.id}.`];
249
252
  }
253
+ /** `--ref`: a link to the discussion behind a verification. Only web links, so nothing local or private leaks into the graph. */
254
+ function checkRef(ref) {
255
+ if (ref === undefined)
256
+ return;
257
+ let ok = /^https?:\/\/\S+$/i.test(ref);
258
+ if (ok)
259
+ try {
260
+ new URL(ref);
261
+ }
262
+ catch {
263
+ ok = false;
264
+ }
265
+ if (!ok)
266
+ throw new OkbError(`--ref must be an http:// or https:// link (to a PR comment, issue or review thread), not "${ref}".`);
267
+ }
250
268
  export function verify(ont, ref, o) {
269
+ checkRef(o.ref);
251
270
  const n = ont.find(ref, ["Rule", "Class", "Slot", "Instance"]);
252
271
  const cited = ont.targets(n.id, "CITES");
253
272
  if (!cited.length)
@@ -259,25 +278,41 @@ export function verify(ont, ref, o) {
259
278
  throw new OkbError(`${n.id} hasn't been through verification yet.`);
260
279
  if (n.verification.status === "UNSUPPORTED")
261
280
  throw new OkbError("An UNSUPPORTED item can't be approved; remove it or re-extract from a quote that supports it.");
262
- n.verification = { ...n.verification, status: "SUPPORTED", approvedAfter: n.verification.status, ...(o.note ? { note: o.note } : {}) };
281
+ n.verification = { ...n.verification, status: "SUPPORTED", approvedAfter: n.verification.status, ...(o.note ? { note: o.note } : {}), ...(o.ref ? { ref: o.ref } : {}) };
282
+ ont.touch(n);
263
283
  return [`${n.id}: approved by a person (was ${n.verification.approvedAfter}).`];
264
284
  }
265
285
  const status = (o.status ?? "").toUpperCase();
266
286
  if (!isOneOf(STATUSES, status))
267
287
  throw new OkbError(`--status must be one of ${STATUSES.join(", ")} (or use --approve after a human review).`);
268
288
  const notes = [];
289
+ const noteTips = [];
290
+ // The earlier result, when this runs again on an item still waiting for approval: its note and link stay unless replaced.
291
+ // Only for the same correction: a different one makes the old note wrong ("changed 44 to 24" after a change to 18).
292
+ const waiting = n.verification?.status === "OVERREACH" ? n.verification : undefined;
293
+ const again = waiting && status === "OVERREACH" && (n.type === "Rule" ? n.statement : n.description) === o.corrected ? waiting : undefined;
269
294
  if (status === "OVERREACH") {
270
295
  if (!o.corrected)
271
296
  throw new OkbError('OVERREACH needs --corrected "<the narrower statement the quote does support>".');
272
- if (n.type === "Rule") {
273
- n._originalDraft = n.statement;
297
+ const current = n.type === "Rule" ? n.statement : n.description ?? "";
298
+ // Running OVERREACH again on an item that is still waiting for approval (to add a note or a link, as the
299
+ // suggested command does) must not replace the original wording with the earlier correction.
300
+ const original = n.verification?.status === "OVERREACH" && n._originalDraft !== undefined ? n._originalDraft : current;
301
+ if (!o.note && !again?.note)
302
+ noteTips.push(...overreachNoteTips(n.id, original, o.corrected, o.ref ? ` --ref ${shellQuote(o.ref)}` : ""));
303
+ n._originalDraft = original;
304
+ if (n.type === "Rule")
274
305
  n.statement = o.corrected;
275
- }
276
- else {
277
- n._originalDraft = n.description;
306
+ else
278
307
  n.description = o.corrected;
279
- }
280
308
  n.extractionConfidence = "corrected";
309
+ // A rule's strength lives in `modality`, not in the statement: keep the two in step, or approving the correction
310
+ // would publish a SHOULD statement as a MUST rule. The original wording (and its keyword) stays in _originalDraft.
311
+ const stated = n.type === "Rule" ? statedModality(o.corrected) : null;
312
+ if (n.type === "Rule" && stated && stated !== n.modality) {
313
+ notes.push(`Modality changed from ${n.modality} to ${stated} to match the corrected statement. Whoever approves it should check the new strength against the quote.`);
314
+ n.modality = stated;
315
+ }
281
316
  notes.push(`Corrected ${field}: "${o.corrected}" (original kept in _originalDraft).`);
282
317
  notes.push(`It stays blocked (prov-verified) until a person checks the correction: okb verify ${n.id} --approve`);
283
318
  }
@@ -288,9 +323,16 @@ export function verify(ont, ref, o) {
288
323
  }
289
324
  else
290
325
  n.extractionConfidence ??= "paraphrased";
291
- n.verification = { status, checkedAgainst: cited, ...(o.note ? { note: o.note } : {}) };
292
- if (status === "UNSUPPORTED")
326
+ const note = o.note ?? (status === "OVERREACH" ? again?.note : undefined);
327
+ const link = o.ref ?? (status === "OVERREACH" ? again?.ref : undefined);
328
+ n.verification = { status, checkedAgainst: cited, ...(note ? { note } : {}), ...(link ? { ref: link } : {}) };
329
+ ont.touch(n);
330
+ if (status === "UNSUPPORTED") {
293
331
  notes.push(`${n.id} is UNSUPPORTED and blocks okb validate (prov-verified). Remove it: okb remove ${n.id}`);
332
+ if (!o.note)
333
+ noteTips.push(UNSUPPORTED_NOTE_TIP);
334
+ }
335
+ notes.push(...noteTips);
294
336
  notes.unshift(`${n.id}: ${status}.`);
295
337
  return notes;
296
338
  }
@@ -0,0 +1,52 @@
1
+ import { Ontology } from "@ontology-kit/reader";
2
+ import type { Finding } from "./types.js";
3
+ import type { Notes } from "./ops.js";
4
+ export declare const MANIFEST_FILE = "manifest.json";
5
+ export declare const RELEASES_DIR = "releases";
6
+ /** A dataset in a manifest: a folder (relative to the manifest) and the SHA-256 of the files pinned in it. */
7
+ export interface Dataset {
8
+ path: string;
9
+ description?: string;
10
+ files: Record<string, string>;
11
+ }
12
+ export interface ReleaseManifest {
13
+ id: string;
14
+ version: string;
15
+ title?: string;
16
+ description?: string;
17
+ datasets: {
18
+ docs?: Dataset;
19
+ ontology?: Dataset;
20
+ };
21
+ provenance?: Record<string, unknown>;
22
+ }
23
+ /** <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. */
24
+ export declare function compareVersions(a: string, b: string): number;
25
+ export declare const isVersion: (v: string) => boolean;
26
+ /** Read and check the shape of a manifest.json. Throws OkbError naming the problem. */
27
+ export declare function readReleaseManifest(file: string): ReleaseManifest;
28
+ /** The writer `writeFileAtomic` uses; tests swap `write` to simulate a failed write. */
29
+ export declare const releaseIo: {
30
+ write: (file: string, text: string) => void;
31
+ };
32
+ export interface ReleaseResult {
33
+ version: string;
34
+ previous?: string;
35
+ manifest: ReleaseManifest;
36
+ notes: Notes;
37
+ }
38
+ /**
39
+ * Cut release `version` of the folder `ont` was loaded from. Call it inside `Ontology.edit` (it saves
40
+ * and writes files under the lock). `findings` are the validator's results; any open error stops the release.
41
+ * Writes nothing when it refuses.
42
+ */
43
+ export declare function cutRelease(ont: Ontology, version: string, findings: Finding[]): ReleaseResult;
44
+ export interface VerifyResult {
45
+ id: string;
46
+ version: string;
47
+ ok: boolean;
48
+ checked: number;
49
+ problems: string[];
50
+ }
51
+ /** Check the files in `root` against its manifest.json. Read-only. */
52
+ export declare function verifyRelease(root: string): VerifyResult;
@@ -0,0 +1,337 @@
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, renameSync, rmSync, 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
+ /** The writer `writeFileAtomic` uses; tests swap `write` to simulate a failed write. */
198
+ export const releaseIo = {
199
+ write: (file, text) => writeFileSync(file, text, "utf8"),
200
+ };
201
+ /**
202
+ * Write `text` to a temp file next to `file`, then rename it into place, so a failed write leaves the
203
+ * previous `file` whole. The temp file is removed if the write or the rename fails.
204
+ */
205
+ function writeFileAtomic(file, text) {
206
+ const tmp = `${file}.tmp`;
207
+ try {
208
+ releaseIo.write(tmp, text);
209
+ renameSync(tmp, file);
210
+ }
211
+ catch (e) {
212
+ rmSync(tmp, { force: true });
213
+ throw e;
214
+ }
215
+ }
216
+ /**
217
+ * Cut release `version` of the folder `ont` was loaded from. Call it inside `Ontology.edit` (it saves
218
+ * and writes files under the lock). `findings` are the validator's results; any open error stops the release.
219
+ * Writes nothing when it refuses.
220
+ */
221
+ export function cutRelease(ont, version, findings) {
222
+ if (!isVersion(version))
223
+ throw new OkbError(`'${version}' isn't a version. Use semver: 1.0.0, 1.2.3 or 2.0.0-rc.1.`);
224
+ const errors = findings.filter((f) => f.severity === "error" && !f.explainedBy);
225
+ if (errors.length) {
226
+ 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}`);
227
+ }
228
+ const root = ont.root;
229
+ const lastFile = join(root, MANIFEST_FILE);
230
+ const last = existsSync(lastFile) ? readReleaseManifest(lastFile) : undefined;
231
+ if (last && isVersion(last.version) && compareVersions(version, last.version) <= 0) {
232
+ throw new OkbError(`Version ${version} isn't newer than the last release, ${last.version}. Pick a higher version.`);
233
+ }
234
+ // The root manifest.json is what makes a release exist, and it is written last. So a releases/<version>/
235
+ // folder for a version newer than the one it pins is what a release that stopped half-way leaves (even when
236
+ // the folder's own manifest.json got written), and it is written over. A finished release is never newer
237
+ // than the pinned one, so the check above already refuses to rewrite it.
238
+ const docs = sourcesDataset(ont);
239
+ let diff;
240
+ let note;
241
+ if (last) {
242
+ const snap = join(root, RELEASES_DIR, last.version);
243
+ if (existsSync(join(snap, "nodes.jsonl")) && existsSync(join(snap, "okb.json"))) {
244
+ diff = diffOntologies(Ontology.load(snap), ont, last.version, version);
245
+ }
246
+ else
247
+ note = `There's no snapshot of ${last.version} in ${RELEASES_DIR}/, so this release can't list what changed in the knowledge.`;
248
+ }
249
+ const sources = sourceChanges(last?.datasets.docs, docs);
250
+ if (diff && isEmpty(diff) && !diff.summary.stampOnly && noSourceChanges(sources) && !manifestChanged(join(root, RELEASES_DIR, last.version), ont)) {
251
+ throw new OkbError(`Nothing has changed since ${last.version}, so there is nothing to release.`);
252
+ }
253
+ const date = today(); // an invalid SOURCE_DATE_EPOCH stops here, before anything is written
254
+ // Everything is checked; from here on it writes.
255
+ ont.manifest.version = version;
256
+ ont.save();
257
+ const ontologyFiles = Object.fromEntries(ONTOLOGY_FILES.map((f) => [f, sha256(join(root, f))]));
258
+ const manifest = {
259
+ id: last?.id ?? (slug(ont.meta.name || ont.manifest.name || "") || "ontology"),
260
+ version,
261
+ title: ont.meta.name || ont.manifest.name || last?.title,
262
+ ...(last?.description ? { description: last.description } : {}),
263
+ datasets: {
264
+ ...(docs ? { docs } : {}),
265
+ ontology: {
266
+ path: ".",
267
+ 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.`,
268
+ files: sortedRecord(ontologyFiles),
269
+ },
270
+ },
271
+ ...(last?.provenance ? { provenance: last.provenance } : {}),
272
+ };
273
+ const snap = join(root, RELEASES_DIR, version);
274
+ mkdirSync(snap, { recursive: true });
275
+ for (const f of ONTOLOGY_FILES)
276
+ copyFileSync(join(root, f), join(snap, f));
277
+ writeFileSync(join(snap, "changes.json"), json({ version, previous: last?.version ?? null, changes: diff ?? null, sources }));
278
+ writeFileSync(join(snap, "CHANGES.md"), changesMarkdown(version, last?.version, date, diff, sources, ont, note));
279
+ writeReleasesMd(root, manifest.title ?? manifest.id);
280
+ // The manifests go last: they are what makes the release exist, so a failure above leaves nothing pinned.
281
+ // Dataset paths are relative to the manifest, so the snapshot's copy points at the sources from its own folder.
282
+ const snapManifest = { ...manifest, datasets: { ...manifest.datasets, ...(docs ? { docs: { ...docs, path: posix(relative(snap, resolve(root, docs.path))) || "." } } : {}) } };
283
+ writeFileAtomic(join(snap, MANIFEST_FILE), json(snapManifest));
284
+ writeFileAtomic(lastFile, json(manifest));
285
+ const notes = [`Released ${version}${last ? ` (was ${last.version})` : ""}: ${countsLine(ont)}`];
286
+ if (diff) {
287
+ const s = diff.summary;
288
+ notes.push(`Since ${last.version}: ${s.nodesAdded} node(s) added, ${s.nodesRemoved} removed, ${s.nodesChanged} changed; ${diff.relationshipTypeRenames.length} edge type(s) renamed.`);
289
+ }
290
+ if (note)
291
+ notes.push(note);
292
+ 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}.`);
293
+ return { version, previous: last?.version, manifest, notes };
294
+ }
295
+ /** Check the files in `root` against its manifest.json. Read-only. */
296
+ export function verifyRelease(root) {
297
+ const file = join(root, MANIFEST_FILE);
298
+ if (!existsSync(file))
299
+ throw new OkbError(`There is no ${MANIFEST_FILE} in ${resolve(root)}. Cut a release first: okb release <version>.`);
300
+ const m = readReleaseManifest(file);
301
+ const problems = [];
302
+ let checked = 0;
303
+ // The knowledge itself must be pinned: a manifest that leaves out the ontology files would verify anything.
304
+ for (const f of ONTOLOGY_FILES)
305
+ if (!m.datasets.ontology?.files[f])
306
+ problems.push(`ontology: ${f} isn't pinned in the manifest`);
307
+ const inside = (base, p) => !relative(base, p).startsWith("..") && !isAbsolute(relative(base, p));
308
+ for (const [name, d] of Object.entries(m.datasets)) {
309
+ const dir = resolve(root, d.path);
310
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) {
311
+ problems.push(`${name}: folder ${d.path} is missing`);
312
+ continue;
313
+ }
314
+ for (const [f, expected] of Object.entries(d.files).sort(([p], [q]) => (p < q ? -1 : 1))) {
315
+ checked++;
316
+ const p = join(dir, f);
317
+ if (!inside(dir, p))
318
+ problems.push(`${name}: ${f} points outside its folder`);
319
+ else if (!existsSync(p) || !statSync(p).isFile())
320
+ problems.push(`${name}: ${f} is missing`);
321
+ else {
322
+ const got = sha256(p);
323
+ if (got !== expected)
324
+ problems.push(`${name}: ${f} differs from the release (SHA-256 ${got.slice(0, 12)}…, the manifest says ${expected.slice(0, 12)}…)`);
325
+ }
326
+ }
327
+ }
328
+ try {
329
+ const v = JSON.parse(readFileSync(join(root, "okb.json"), "utf8")).version;
330
+ if (v !== m.version)
331
+ problems.push(`okb.json says version ${v ?? "(none)"}, the manifest says ${m.version}`);
332
+ }
333
+ catch {
334
+ // an unreadable okb.json shows up above as a hash mismatch or a missing file
335
+ }
336
+ return { id: m.id, version: m.version, ok: problems.length === 0, checked, problems };
337
+ }