@ontology-kit/okb 0.1.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
package/dist/resync.js ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Re-sync a KB after its source documents change (`okb source refresh --all`).
3
+ *
4
+ * Two questions, answered together:
5
+ * 1. Which quotes are gone, and which moved? Each gone quote is reported with the nodes that cite it.
6
+ * 2. Which quotable blocks of a document are new, changed or removed since the KB last looked at it?
7
+ * That list is the worklist for re-extraction (see RESYNC_SCHEMA for its shape).
8
+ *
9
+ * "Since the KB last looked" is the baseline stored on the Source node: one record per quotable block
10
+ * (`Source.blocks`), written by `okb source add` and by `refresh --all --record`. A block's hash is the SHA-256
11
+ * (the same algorithm `okb release` uses for files) of its plain text with layout, case and punctuation
12
+ * folded away, so reflowing a paragraph or moving it under another heading changes nothing, and
13
+ * changing a word does. Hashes are per block, not per source, because "this file changed" doesn't say
14
+ * what to extract again.
15
+ */
16
+ import { createHash } from "node:crypto";
17
+ import { locate } from "./markdown.js";
18
+ import { locFields } from "./provenance.js";
19
+ import { findQuote, normalize } from "./quotes.js";
20
+ export const RESYNC_SCHEMA = "okb-resync/1";
21
+ const PREVIEW_CHARS = 120;
22
+ /** Two blocks with this share of their preview words in common count as the same block, edited. */
23
+ const SAME_BLOCK_SIMILARITY = 0.3;
24
+ /** Across different headings (a renamed or moved-and-edited block), ask for more. */
25
+ const MOVED_BLOCK_SIMILARITY = 0.6;
26
+ export const hashText = (text) => createHash("sha256").update(normalize(text)).digest("hex");
27
+ /** The records for a document's quotable blocks, in document order. */
28
+ export function blockRecords(doc) {
29
+ return doc.blocks
30
+ .filter((b) => b.quotable)
31
+ .map((b) => ({
32
+ hash: hashText(b.text),
33
+ kind: b.kind,
34
+ headingPath: b.headingPath,
35
+ ...(b.row ? { rowKey: b.row.key } : {}),
36
+ preview: b.text.slice(0, PREVIEW_CHARS),
37
+ }));
38
+ }
39
+ const wordCache = new Map();
40
+ const words = (s) => {
41
+ let w = wordCache.get(s);
42
+ if (!w)
43
+ wordCache.set(s, (w = new Set(s.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((x) => x.length > 2))));
44
+ return w;
45
+ };
46
+ function similarity(a, b) {
47
+ const x = words(a), y = words(b);
48
+ if (!x.size || !y.size)
49
+ return 0;
50
+ let both = 0;
51
+ for (const w of x)
52
+ if (y.has(w))
53
+ both++;
54
+ return both / (x.size + y.size - both);
55
+ }
56
+ const keyOf = (b) => JSON.stringify([b.headingPath, b.kind, b.rowKey ?? null]);
57
+ /**
58
+ * Compare a baseline with the current blocks. Pure. A block whose hash is still present is unchanged, wherever it
59
+ * moved. What's left is paired up as "changed" (same place, similar text), and the rest is "new" or "removed".
60
+ */
61
+ export function diffBlocks(baseline, current) {
62
+ const left = new Map(); // hash -> unmatched baseline indexes
63
+ baseline.forEach((b, i) => left.set(b.hash, [...(left.get(b.hash) ?? []), i]));
64
+ const newOnes = [];
65
+ current.forEach((b, j) => {
66
+ const idxs = left.get(b.hash);
67
+ if (idxs?.length)
68
+ idxs.shift();
69
+ else
70
+ newOnes.push(j);
71
+ });
72
+ const oldOnes = new Set([...left.values()].flat());
73
+ const out = [];
74
+ const oldKeys = baseline.map(keyOf);
75
+ const newKeys = current.map(keyOf);
76
+ // How many unmatched blocks share each place (heading path, kind, row key), on each side. A block that is
77
+ // alone in its place on both sides is the same block, edited. Counted once, not per comparison.
78
+ const placeCount = (idxs, keys) => {
79
+ const m = new Map();
80
+ for (const i of idxs)
81
+ m.set(keys[i], (m.get(keys[i]) ?? 0) + 1);
82
+ return m;
83
+ };
84
+ const pair = (minScore, sameKey) => {
85
+ const oldPlaces = placeCount(oldOnes, oldKeys);
86
+ const newPlaces = placeCount(newOnes, newKeys);
87
+ for (const j of [...newOnes]) {
88
+ const c = current[j];
89
+ const place = newKeys[j];
90
+ const alone = sameKey && oldPlaces.get(place) === 1 && newPlaces.get(place) === 1;
91
+ let best = null;
92
+ for (const i of oldOnes) {
93
+ const o = baseline[i];
94
+ if (sameKey !== (oldKeys[i] === place))
95
+ continue;
96
+ const score = alone ? 1 : similarity(o.preview, c.preview);
97
+ if (score >= minScore && (!best || score > best.score))
98
+ best = { i, score };
99
+ }
100
+ if (best) {
101
+ oldPlaces.set(oldKeys[best.i], (oldPlaces.get(oldKeys[best.i]) ?? 1) - 1);
102
+ newPlaces.set(place, (newPlaces.get(place) ?? 1) - 1);
103
+ oldOnes.delete(best.i);
104
+ newOnes.splice(newOnes.indexOf(j), 1);
105
+ out.push({ change: "changed", old: baseline[best.i], current: j });
106
+ }
107
+ }
108
+ };
109
+ pair(SAME_BLOCK_SIMILARITY, true);
110
+ pair(MOVED_BLOCK_SIMILARITY, false);
111
+ for (const j of newOnes)
112
+ out.push({ change: "new", current: j });
113
+ for (const i of oldOnes)
114
+ out.push({ change: "removed", old: baseline[i] });
115
+ return out;
116
+ }
117
+ const citers = (ont, locId) => ont.sources(locId, "CITES").map((id) => ont.get(id)).filter((n) => !!n).map((n) => ({ id: n.id, type: n.type, label: ont.label(n.id) }));
118
+ /**
119
+ * Re-locate every quote in every source and compare each markdown source's blocks to its baseline. `pages` is
120
+ * `loadSourcePages(ont)`. With `write` false nothing in `ont` changes.
121
+ */
122
+ export function resync(ont, pages, o) {
123
+ const write = o.write || o.record;
124
+ const report = { schema: RESYNC_SCHEMA, ok: true, recorded: false, sources: [], gone: [], moved: [], worklist: [] };
125
+ for (const src of ont.ofType("Source")) {
126
+ const locs = ont.sources(src.id, "PART_OF").map((i) => ont.get(i)).filter((n) => n?.type === "SourceLocation");
127
+ const status = { id: src.id, path: src.localPath ?? null, format: src.format ?? null, state: "checked", baseline: false, quotes: locs.length, moved: 0, gone: 0 };
128
+ report.sources.push(status);
129
+ const got = pages.get(src.id);
130
+ if (!src.localPath || !got || got instanceof Error) {
131
+ // A source with quotes that can't be read proves nothing, so it fails the report (as it does in okb check).
132
+ if (locs.length || src.localPath) {
133
+ status.state = "unreadable";
134
+ status.problem = !src.localPath ? "no local file (localPath)" : got instanceof Error ? got.message : "not loaded";
135
+ report.ok = false;
136
+ }
137
+ continue;
138
+ }
139
+ const issue = (loc) => ({ source: src.id, quote: loc.id, text: loc.quote, was: { locator: loc.locator, lines: loc.lines }, citedBy: citers(ont, loc.id) });
140
+ if (Array.isArray(got)) {
141
+ for (const loc of locs)
142
+ if (!findQuote(loc.quote, got).found) {
143
+ status.gone++;
144
+ report.gone.push(issue(loc));
145
+ }
146
+ continue;
147
+ }
148
+ for (const loc of locs) {
149
+ const hits = locate(got, loc.quote);
150
+ if (!hits.length) {
151
+ status.gone++;
152
+ report.gone.push(issue(loc));
153
+ continue;
154
+ }
155
+ const near = hits.reduce((a, b) => (Math.abs(b.startLine - (loc.startLine ?? 0)) < Math.abs(a.startLine - (loc.startLine ?? 0)) ? b : a));
156
+ if (near.startLine === loc.startLine && near.endLine === (loc.endLine ?? loc.startLine) && near.locator === loc.locator)
157
+ continue;
158
+ status.moved++;
159
+ const was = issue(loc);
160
+ if (write) {
161
+ Object.assign(loc, locFields(near, src));
162
+ ont.touch(loc);
163
+ }
164
+ report.moved.push({ ...was, now: { locator: near.locator, lines: near.startLine === near.endLine ? String(near.startLine) : `${near.startLine}-${near.endLine}` } });
165
+ }
166
+ const current = blockRecords(got);
167
+ const quotable = got.blocks.filter((b) => b.quotable);
168
+ if (src.blocks) {
169
+ status.baseline = true;
170
+ for (const d of diffBlocks(src.blocks, current)) {
171
+ const cur = d.current === undefined ? undefined : current[d.current];
172
+ const block = d.current === undefined ? undefined : quotable[d.current];
173
+ const ref = cur ?? d.old;
174
+ report.worklist.push({
175
+ id: `${src.id}:${(cur?.hash ?? d.old.hash).slice(0, 12)}`,
176
+ source: src.id,
177
+ change: d.change,
178
+ headingPath: ref.headingPath,
179
+ blockKind: ref.kind,
180
+ lines: block ? [block.startLine, block.endLine] : null,
181
+ hash: cur?.hash ?? null,
182
+ oldHash: d.old?.hash ?? null,
183
+ preview: cur?.preview ?? null,
184
+ oldPreview: d.old?.preview ?? null,
185
+ });
186
+ }
187
+ }
188
+ if (o.record) {
189
+ if (JSON.stringify(src.blocks) !== JSON.stringify(current)) {
190
+ src.blocks = current;
191
+ ont.touch(src);
192
+ }
193
+ }
194
+ }
195
+ if (report.gone.length)
196
+ report.ok = false;
197
+ report.recorded = o.record;
198
+ // Document order for new and changed blocks, removed ones last.
199
+ report.worklist.sort((a, b) => a.source.localeCompare(b.source) || (a.lines?.[0] ?? Infinity) - (b.lines?.[0] ?? Infinity));
200
+ return report;
201
+ }
202
+ /** The human-readable report, as lines. */
203
+ export function renderResync(r, o) {
204
+ const out = [];
205
+ const n = (k, w) => `${k} ${w}${k === 1 ? "" : "s"}`;
206
+ for (const s of r.sources) {
207
+ if (s.state === "unreadable")
208
+ out.push(`✗ ${s.id}: can't read it (${s.problem}); its quotes weren't checked.`);
209
+ }
210
+ out.push(`${n(r.sources.filter((s) => s.state === "checked").length, "source")} checked: ${n(r.moved.length, "quote")} moved${o.dryRun || !r.moved.length ? "" : " (updated)"}, ${n(r.gone.length, "quote")} gone, ${n(r.worklist.length, "block")} on the worklist.`);
211
+ if (r.gone.length) {
212
+ out.push("", "Quotes that are gone (not changed; re-extract them from the current text):");
213
+ for (const g of r.gone) {
214
+ out.push(` ✗ ${g.quote} (${g.source}, was ${g.was.locator ?? "?"}${g.was.lines ? `, line ${g.was.lines}` : ""}): "${g.text.slice(0, 70)}${g.text.length > 70 ? "…" : ""}"`);
215
+ out.push(` cited by ${g.citedBy.length ? g.citedBy.map((c) => `${c.type} ${c.label} (${c.id})`).join(", ") : "nothing"}`);
216
+ }
217
+ }
218
+ if (r.moved.length) {
219
+ out.push("", "Quotes that moved:");
220
+ for (const m of r.moved)
221
+ out.push(` ${m.quote}: line ${m.was.lines} → ${m.now.lines}${m.now.locator !== m.was.locator ? ` (now under ${m.now.locator})` : ""}`);
222
+ }
223
+ if (r.worklist.length) {
224
+ out.push("", "Worklist (blocks to extract or re-check):");
225
+ for (const w of r.worklist) {
226
+ const where = w.lines ? `L${w.lines[0]}${w.lines[1] > w.lines[0] ? `-${w.lines[1]}` : ""}` : "removed";
227
+ out.push(` ${w.change.padEnd(7)} ${w.source} ${where.padEnd(9)} ${w.headingPath.join(" > ") || "(top)"} ${w.change === "removed" ? w.oldPreview : w.preview}`);
228
+ }
229
+ }
230
+ const noBase = r.sources.filter((s) => s.format === "markdown" && s.state === "checked" && !s.baseline).map((s) => s.id);
231
+ if (noBase.length)
232
+ out.push("", `No baseline hashes yet for ${noBase.join(", ")}: there's nothing to compare, so no worklist. Run okb source refresh --all --record to record them.`);
233
+ return out;
234
+ }
package/dist/review.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Ontology } from "@ontology-kit/format";
1
+ import { type Ontology } from "@ontology-kit/reader";
2
2
  export interface ReviewItem {
3
3
  rule: string;
4
4
  modality: string;
package/dist/review.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * answers the questions; nothing here is enforced.
6
6
  */
7
7
  import { MetaKB } from "./metakb.js";
8
- import {} from "@ontology-kit/format";
8
+ import {} from "@ontology-kit/reader";
9
9
  import { questionFamilies } from "./families.js";
10
10
  import * as naming from "./naming.js";
11
11
  const PART_WORDS = new Set(["part", "section", "chapter", "page", "component", "piece", "member", "step", "segment", "module", "element", "unit", "room", "wheel", "door"]);
@@ -0,0 +1,42 @@
1
+ import { type Ontology } from "@ontology-kit/reader";
2
+ import { type DocFiles } from "./kbdocs.js";
3
+ import { type MdDoc } from "./markdown.js";
4
+ import type { ResyncReport } from "./resync.js";
5
+ export interface PageChanges {
6
+ /** Pages whose text differs between the two renderings. */
7
+ changed: string[];
8
+ /** Pages that exist now and didn't at the ref. */
9
+ added: string[];
10
+ /** Pages that existed at the ref and no longer do. */
11
+ removed: string[];
12
+ /** Pages included only because they link to or from a changed class page (`--hops`). */
13
+ context: string[];
14
+ }
15
+ /** Compare two renderings page by page. Pure. */
16
+ export declare function diffPages(before: DocFiles, after: DocFiles): Omit<PageChanges, "context">;
17
+ /**
18
+ * Class pages within `hops` links of the starting pages, in either direction. Only class pages are walked:
19
+ * the index, rules and sources pages link to everything, so going through them would pull in the whole KB.
20
+ * Returns the pages that are new to the set, sorted.
21
+ */
22
+ export declare function expandHops(files: DocFiles, start: string[], hops: number): string[];
23
+ /** The pages to write for a changed-only view: changed and added ones, plus the `--hops` neighbors. */
24
+ export declare function changedPageSet(before: DocFiles, after: DocFiles, hops?: number): {
25
+ pages: string[];
26
+ changes: PageChanges;
27
+ };
28
+ /** `changes.md`: what changed, which pages follow, and the quotes and source blocks the sources changed under the KB. */
29
+ export declare function changesPage(o: {
30
+ against: string;
31
+ name: string;
32
+ changes: PageChanges;
33
+ hops: number;
34
+ resync: ResyncReport | null;
35
+ }): string;
36
+ /** Source lines shown above and below a quote. */
37
+ export declare const CONTEXT_LINES = 3;
38
+ /**
39
+ * `rules-in-context.md`: every rule beside the source text around its quote, problem cases first (then by
40
+ * name). `pages` is `loadSourcePages(ont)`; sources that aren't there or aren't markdown show the quote alone.
41
+ */
42
+ export declare function contextPage(ont: Ontology, pages: Map<string, string[] | MdDoc | Error>): string;
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Review aids built on `okb docs` (issue #133), for a subject matter expert or a PR reviewer.
3
+ *
4
+ * 1. The changed-only view (`okb docs --changed <ref>`): render the pages at `<ref>` and for the working
5
+ * folder, keep the pages whose text differs. A changed inherited rule changes every subclass page that
6
+ * shows it, so the ripple comes for free. `--hops N` adds the class pages that link to or from a changed
7
+ * class page, for context. `changes.md` lists what changed and adds the stale-quote worklist from
8
+ * `okb source refresh --all`, because a source edit that hasn't been re-synced changes no page.
9
+ * 2. The context view (`okb docs --context`): each rule beside the source text around its quote.
10
+ *
11
+ * Everything here is pure (loaded ontologies and parsed documents in, Markdown out). No clock, no disk,
12
+ * stable ordering, so the same inputs always give the same text.
13
+ */
14
+ import { posix } from "node:path";
15
+ import { nameOrText } from "@ontology-kit/reader";
16
+ import { BANNER } from "./kbdocs.js";
17
+ import { locate } from "./markdown.js";
18
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
19
+ const oneLine = (s) => s.replace(/\s*\n\s*/g, " ").trim();
20
+ const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
21
+ /** Compare two renderings page by page. Pure. */
22
+ export function diffPages(before, after) {
23
+ const names = (pred) => Object.keys({ ...before, ...after }).filter(pred).sort(byText);
24
+ return {
25
+ changed: names((n) => n in before && n in after && before[n] !== after[n]),
26
+ added: names((n) => !(n in before) && n in after),
27
+ removed: names((n) => n in before && !(n in after)),
28
+ };
29
+ }
30
+ const isClassPage = (name) => name.startsWith("classes/");
31
+ /** The class pages a page links to (`](c-x.md#anchor)`, resolved against its own folder). */
32
+ function classLinks(name, text) {
33
+ const out = new Set();
34
+ for (const m of text.matchAll(/\]\(([^)\s#]+\.md)(?:#[^)\s]*)?\)/g)) {
35
+ if (/^[a-z]+:/i.test(m[1]))
36
+ continue;
37
+ const target = posix.normalize(posix.join(posix.dirname(name), m[1]));
38
+ if (isClassPage(target))
39
+ out.add(target);
40
+ }
41
+ return [...out];
42
+ }
43
+ /**
44
+ * Class pages within `hops` links of the starting pages, in either direction. Only class pages are walked:
45
+ * the index, rules and sources pages link to everything, so going through them would pull in the whole KB.
46
+ * Returns the pages that are new to the set, sorted.
47
+ */
48
+ export function expandHops(files, start, hops) {
49
+ const links = new Map();
50
+ const touch = (a, b) => {
51
+ if (!links.has(a))
52
+ links.set(a, new Set());
53
+ links.get(a).add(b);
54
+ };
55
+ for (const [name, text] of Object.entries(files)) {
56
+ if (!isClassPage(name))
57
+ continue;
58
+ for (const t of classLinks(name, text))
59
+ if (t in files) {
60
+ touch(name, t);
61
+ touch(t, name);
62
+ }
63
+ }
64
+ const seen = new Set(start);
65
+ let edge = start.filter(isClassPage);
66
+ for (let i = 0; i < hops; i++) {
67
+ const next = [];
68
+ for (const p of edge)
69
+ for (const q of links.get(p) ?? [])
70
+ if (!seen.has(q)) {
71
+ seen.add(q);
72
+ next.push(q);
73
+ }
74
+ edge = next;
75
+ }
76
+ return [...seen].filter((p) => !start.includes(p)).sort(byText);
77
+ }
78
+ /** The pages to write for a changed-only view: changed and added ones, plus the `--hops` neighbors. */
79
+ export function changedPageSet(before, after, hops = 0) {
80
+ const d = diffPages(before, after);
81
+ const core = [...d.changed, ...d.added].sort(byText);
82
+ const context = hops > 0 ? expandHops(after, core, hops) : [];
83
+ return { pages: [...core, ...context].sort(byText), changes: { ...d, context } };
84
+ }
85
+ const pageLink = (name) => `[${name}](${name})`;
86
+ /** `changes.md`: what changed, which pages follow, and the quotes and source blocks the sources changed under the KB. */
87
+ export function changesPage(o) {
88
+ const { changes: c } = o;
89
+ const out = [BANNER, "", `# Changes in ${o.name} since ${o.against}`, ""];
90
+ out.push(`This folder holds only the reference pages whose text differs from \`${o.against}\`${o.hops ? `, plus the class pages within ${plural(o.hops, "link")} of one that changed` : ""}. Links to pages that aren't here point into the full \`okb docs\` output.`, "");
91
+ const section = (title, pages, none) => {
92
+ out.push(`## ${title}`, "");
93
+ if (pages.length)
94
+ out.push(...pages.map((p) => `- ${pageLink(p)}`));
95
+ else
96
+ out.push(none);
97
+ out.push("");
98
+ };
99
+ section("Pages that changed", [...c.changed, ...c.added].sort(byText), "No page's text changed.");
100
+ if (c.added.length)
101
+ out.push(`New pages: ${c.added.map((p) => `\`${p}\``).join(", ")}.`, "");
102
+ if (o.hops)
103
+ section(`Neighbors, for context (${plural(o.hops, "hop")})`, c.context, "No class page links to a changed one.");
104
+ if (c.removed.length)
105
+ out.push("## Pages that no longer exist", "", ...c.removed.map((p) => `- \`${p}\``), "");
106
+ out.push(...staleSection(o.resync));
107
+ return out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
108
+ }
109
+ function staleSection(r) {
110
+ const out = ["## Source changes not yet in the knowledge base", ""];
111
+ if (!r)
112
+ return [...out, "Not checked.", ""];
113
+ out.push("A document that changed since the last `okb source refresh` changes no page until someone acts on it. This is what `okb source refresh --all --dry-run` finds now.", "");
114
+ const unreadable = r.sources.filter((s) => s.state === "unreadable");
115
+ for (const s of unreadable)
116
+ out.push(`- Can't read \`${s.id}\` (${s.problem}); its quotes weren't checked.`);
117
+ if (unreadable.length)
118
+ out.push("");
119
+ if (!r.gone.length && !r.moved.length && !r.worklist.length && !unreadable.length)
120
+ return [...out, "Nothing: every quote is still in its source, and no block changed since the baseline.", ""];
121
+ const cites = (cs) => (cs.length ? cs.map((x) => `${x.type.toLowerCase()} ${x.label} (\`${x.id}\`)`).join(", ") : "nothing");
122
+ if (r.gone.length) {
123
+ out.push(`### Quotes that are gone (${r.gone.length})`, "", "The text is no longer in the source. Whatever cites it needs a new quote or a decision.", "");
124
+ for (const g of [...r.gone].sort((a, b) => byText(a.quote, b.quote)))
125
+ out.push(`- \`${g.quote}\` in \`${g.source}\` (was ${g.was.locator ?? "?"}${g.was.lines ? `, line ${g.was.lines}` : ""}): "${oneLine(g.text)}"`, ` - Cited by ${cites(g.citedBy)}.`);
126
+ out.push("");
127
+ }
128
+ if (r.moved.length) {
129
+ out.push(`### Quotes that moved (${r.moved.length})`, "", "Still in the source, at other lines. `okb source refresh --all` updates them.", "");
130
+ for (const m of [...r.moved].sort((a, b) => byText(a.quote, b.quote)))
131
+ out.push(`- \`${m.quote}\`: line ${m.was.lines ?? "?"} → ${m.now.lines ?? "?"}${m.now.locator !== m.was.locator ? ` (now under ${m.now.locator})` : ""}. Cited by ${cites(m.citedBy)}.`);
132
+ out.push("");
133
+ }
134
+ if (r.worklist.length) {
135
+ out.push(`### Blocks to extract or re-check (${r.worklist.length})`, "");
136
+ for (const w of r.worklist) {
137
+ const where = w.lines ? `line ${w.lines[0]}${w.lines[1] > w.lines[0] ? `-${w.lines[1]}` : ""}` : "removed";
138
+ out.push(`- ${w.change}, \`${w.source}\`, ${where}, ${w.headingPath.join(" > ") || "(top)"}: ${oneLine((w.change === "removed" ? w.oldPreview : w.preview) ?? "")}`);
139
+ }
140
+ out.push("");
141
+ }
142
+ return out;
143
+ }
144
+ // ---------------------------------------------------------------------------
145
+ // The context view
146
+ // ---------------------------------------------------------------------------
147
+ /** Source lines shown above and below a quote. */
148
+ export const CONTEXT_LINES = 3;
149
+ const PROBLEM_ORDER = ["unsupported", "overreach", "unverified", "no quote", "quote gone"];
150
+ const PROBLEM_TEXT = {
151
+ unsupported: "UNSUPPORTED: the verifier found nothing in the quote that supports it",
152
+ overreach: "OVERREACH: corrected, and no person has approved the correction yet",
153
+ unverified: "Not verified yet",
154
+ "no quote": "Cites no quote",
155
+ "quote gone": "Its quote is no longer in the source",
156
+ };
157
+ function quoteContext(loc, doc, hasFile) {
158
+ if (doc === undefined)
159
+ return { note: hasFile ? "The source file wasn't loaded." : "This source has no local file, so there is no text around the quote to show." };
160
+ if (doc instanceof Error)
161
+ return { note: `Can't read the source (${doc.message}).` };
162
+ if (Array.isArray(doc))
163
+ return { note: `The source isn't markdown. The quote is on page ${loc.page ?? "?"}; open the document to read around it.` };
164
+ const hits = locate(doc, loc.quote);
165
+ if (!hits.length)
166
+ return { note: "The quote is no longer in the source (okb source refresh --all says more)." };
167
+ const want = loc.startLine ?? 0;
168
+ const hit = hits.reduce((a, b) => (Math.abs(b.startLine - want) < Math.abs(a.startLine - want) ? b : a));
169
+ const first = Math.max(1, hit.startLine - CONTEXT_LINES);
170
+ const last = Math.min(doc.lines.length, hit.endLine + CONTEXT_LINES);
171
+ return { lines: doc.lines.slice(first - 1, last), first, marked: [hit.startLine, hit.endLine] };
172
+ }
173
+ /** A fence longer than any run of backticks in the text, so source code samples can't close it early. */
174
+ function fenced(body) {
175
+ const longest = Math.max(0, ...body.map((l) => Math.max(0, ...(l.match(/`+/g) ?? []).map((r) => r.length))));
176
+ const fence = "`".repeat(Math.max(3, longest + 1));
177
+ return [`${fence}text`, ...body, fence];
178
+ }
179
+ /** Every reason the rule needs a person, most urgent first. */
180
+ function problemsOf(rule, shown) {
181
+ const v = rule.verification;
182
+ const out = [];
183
+ if (v?.status === "UNSUPPORTED")
184
+ out.push("unsupported");
185
+ if (v?.status === "OVERREACH")
186
+ out.push("overreach");
187
+ if (!v)
188
+ out.push("unverified");
189
+ if (!shown.length)
190
+ out.push("no quote");
191
+ if (shown.some((s) => "note" in s.context && s.context.note.startsWith("The quote is no longer")))
192
+ out.push("quote gone");
193
+ return out;
194
+ }
195
+ function ruleInContext(ont, rule, problems, shown) {
196
+ const out = [`### ${rule.name}`, "", `**${rule.modality.replace("_", " ")}.** ${rule.statement}`, ""];
197
+ const v = rule.verification;
198
+ const bullets = [];
199
+ for (const p of problems)
200
+ bullets.push(`- Needs a person: ${PROBLEM_TEXT[p]}.`);
201
+ bullets.push(`- Rule: \`${rule.id}\`${rule.authored ? " (written by the owner)" : ""}`);
202
+ const governs = ont.targets(rule.id, "GOVERNS").map((g) => nameOrText(ont.require(g)) ?? g).sort(byText);
203
+ if (governs.length)
204
+ bullets.push(`- Governs: ${governs.join(", ")}`);
205
+ bullets.push(`- Verification: ${v ? v.status.toLowerCase() : "not verified"}${v?.approvedAfter ? ` (a person approved it after ${v.approvedAfter.toLowerCase()})` : ""}${rule.extractionConfidence ? `, confidence ${rule.extractionConfidence}` : ""}`);
206
+ if (v?.note || v?.ref)
207
+ bullets.push(`- Verifier's note: ${[v.note ? oneLine(v.note) : "", v.ref ? `<${v.ref}>` : ""].filter(Boolean).join(" ")}`);
208
+ if (rule._originalDraft)
209
+ bullets.push(`- Original draft, before the correction: ${oneLine(rule._originalDraft)}`);
210
+ out.push(...bullets, "");
211
+ for (const { loc, context } of shown) {
212
+ const src = ont.targets(loc.id, "PART_OF").map((i) => ont.get(i)).find((n) => n?.type === "Source");
213
+ out.push(`**Quote** (${src && "title" in src ? `${src.title}, ` : ""}${loc.locator ?? loc.id}${loc.lines ? `, line ${loc.lines}` : ""}):`, "", `> ${oneLine(loc.quote)}`, "");
214
+ if ("note" in context) {
215
+ out.push(context.note, "");
216
+ continue;
217
+ }
218
+ const width = String(context.first + context.lines.length - 1).length;
219
+ out.push(`The source around it (the quoted lines are marked with \`>\`):`, "");
220
+ out.push(...fenced(context.lines.map((text, i) => {
221
+ const n = context.first + i;
222
+ const mark = n >= context.marked[0] && n <= context.marked[1] ? ">" : " ";
223
+ return `${mark} ${String(n).padStart(width)} | ${text}`.trimEnd();
224
+ })), "");
225
+ }
226
+ return out;
227
+ }
228
+ /**
229
+ * `rules-in-context.md`: every rule beside the source text around its quote, problem cases first (then by
230
+ * name). `pages` is `loadSourcePages(ont)`; sources that aren't there or aren't markdown show the quote alone.
231
+ */
232
+ export function contextPage(ont, pages) {
233
+ const rules = ont.ofType("Rule");
234
+ const rows = rules.map((rule) => {
235
+ const shown = ont.targets(rule.id, "CITES").map((id) => ont.get(id)).filter((n) => n?.type === "SourceLocation")
236
+ .sort((a, b) => byText(a.id, b.id)).map((loc) => {
237
+ const src = ont.targets(loc.id, "PART_OF").map((i) => ont.get(i)).find((n) => n?.type === "Source");
238
+ return { loc, context: quoteContext(loc, src ? pages.get(src.id) : undefined, !!(src && src.type === "Source" && src.localPath)) };
239
+ });
240
+ return { rule, shown, problems: problemsOf(rule, shown) };
241
+ });
242
+ const rank = (p) => (p.length ? PROBLEM_ORDER.indexOf(p[0]) : PROBLEM_ORDER.length);
243
+ rows.sort((a, b) => rank(a.problems) - rank(b.problems) || byText(a.rule.name.toLowerCase(), b.rule.name.toLowerCase()) || byText(a.rule.id, b.rule.id));
244
+ const problems = rows.filter((r) => r.problems.length);
245
+ const out = [BANNER, "", `# Rules in context: ${ont.meta.name}`, ""];
246
+ if (!rows.length)
247
+ return [...out, "This knowledge base has no rules yet.", ""].join("\n");
248
+ out.push(`${plural(rows.length, "rule")}, each beside the source text around its quote, so you can check the rule against what the document says nearby, not just the sentence it quotes. The verifier saw only the quote and the statement; this page is the first place the rule meets its surroundings.`, "");
249
+ out.push("## Needs a person", "");
250
+ if (!problems.length)
251
+ out.push("Nothing is flagged. Every rule is verified and its quote is in the source.", "");
252
+ else
253
+ out.push(`${plural(problems.length, "rule")}: ${PROBLEM_ORDER.map((p) => [p, problems.filter((r) => r.problems[0] === p).length]).filter(([, n]) => n).map(([p, n]) => `${n} ${p}`).join(", ")}.`, "");
254
+ for (const r of problems)
255
+ out.push(...ruleInContext(ont, r.rule, r.problems, r.shown));
256
+ const rest = rows.filter((r) => !r.problems.length);
257
+ if (rest.length) {
258
+ out.push("## Everything else", "");
259
+ for (const r of rest)
260
+ out.push(...ruleInContext(ont, r.rule, [], r.shown));
261
+ }
262
+ return out.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
263
+ }
package/dist/skills.js CHANGED
@@ -7,7 +7,7 @@ import { cpSync, lstatSync, existsSync, mkdirSync, readdirSync, readFileSync, re
7
7
  import { homedir } from "node:os";
8
8
  import { dirname, join, resolve } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
- import { OkbError } from "@ontology-kit/format";
10
+ import { OkbError } from "@ontology-kit/reader";
11
11
  /** The skills in this package. From src/ and from dist/ the package root is one folder up. */
12
12
  export const PACKAGED_SKILLS_DIR = join(dirname(dirname(fileURLToPath(import.meta.url))), "skills");
13
13
  /** Where skills go when `--dir` is not given: `$OKB_SKILLS_DIR`, else `~/.claude/skills` (Cursor reads that folder too). */
package/dist/status.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Ontology } from "@ontology-kit/format";
1
+ import { type Ontology } from "@ontology-kit/reader";
2
2
  import { type Finding } from "./types.js";
3
3
  type StepCheck = (ont: Ontology, all: Finding[]) => boolean;
4
4
  export declare const STEP_CHECKS: Record<string, StepCheck>;
package/dist/status.js CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { MIN_COMPETENCY_QUESTIONS, runChecks } from "./checks.js";
7
7
  import { MetaKB } from "./metakb.js";
8
- import {} from "@ontology-kit/format";
8
+ import {} from "@ontology-kit/reader";
9
9
  import {} from "./types.js";
10
10
  /** Step 3's brainstorm should reach this many terms before sorting them into classes and slots. */
11
11
  const MIN_TERMS = 10;
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** Small types and guards that only okb needs (the file format's own types are in @ontology-kit/format). */
1
+ /** Small types and guards that only okb needs (the file format's own types are in @ontology-kit/reader). */
2
2
  /** Narrows a string from the command line or a file to one of a fixed set of values. */
3
3
  export declare function isOneOf<T extends string>(values: readonly T[], v: string | undefined): v is T;
4
4
  export type Severity = "error" | "warning" | "info";
package/dist/types.js CHANGED
@@ -1,4 +1,4 @@
1
- /** Small types and guards that only okb needs (the file format's own types are in @ontology-kit/format). */
1
+ /** Small types and guards that only okb needs (the file format's own types are in @ontology-kit/reader). */
2
2
  /** Narrows a string from the command line or a file to one of a fixed set of values. */
3
3
  export function isOneOf(values, v) {
4
4
  return values.includes(v);
@@ -0,0 +1,18 @@
1
+ import type { Modality } from "@ontology-kit/reader";
2
+ /**
3
+ * One sentence naming what changed: a modality, a number, or a few words. Null when the difference
4
+ * can't be named this way (a rewording, or a change too big to list), so the caller falls back to the
5
+ * generic tip.
6
+ */
7
+ export declare function suggestNote(original: string, corrected: string): string | null;
8
+ /**
9
+ * The one modality a statement states in capitals (`... SHOULD be ...` is SHOULD, `MUST NOT` is MUST_NOT), or null
10
+ * when it states none or more than one. Lower-case "may" or "should" is ordinary prose and doesn't count.
11
+ */
12
+ export declare function statedModality(statement: string): Modality | null;
13
+ /** A double-quoted shell argument. */
14
+ export declare const shellQuote: (s: string) => string;
15
+ export declare const GENERIC_NOTE_TIP = "Tip: add a note so a reviewer sees why, not just the verdict: --note \"<one sentence naming the word or number you changed>\". Skip it when the correction speaks for itself.";
16
+ export declare const UNSUPPORTED_NOTE_TIP = "Tip: add --note \"<which part of the statement the quote doesn't support>\". One sentence naming the word or claim; don't restate UNSUPPORTED.";
17
+ /** Lines to print after OVERREACH with no --note. */
18
+ export declare function overreachNoteTips(id: string, original: string, corrected: string, extra: string): string[];