@ontology-kit/okb 0.0.0-stage → 0.1.0-bootstrap.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 (70) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +26 -2
  3. package/bin/okb.js +8 -0
  4. package/dist/checks.d.ts +33 -0
  5. package/dist/checks.js +966 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +718 -0
  8. package/dist/clidocs.d.ts +6 -0
  9. package/dist/clidocs.js +90 -0
  10. package/dist/clock.d.ts +2 -0
  11. package/dist/clock.js +16 -0
  12. package/dist/commands.d.ts +28 -0
  13. package/dist/commands.js +622 -0
  14. package/dist/export.d.ts +54 -0
  15. package/dist/export.js +290 -0
  16. package/dist/families.d.ts +20 -0
  17. package/dist/families.js +51 -0
  18. package/dist/help.d.ts +2 -0
  19. package/dist/help.js +57 -0
  20. package/dist/markdown.d.ts +60 -0
  21. package/dist/markdown.js +310 -0
  22. package/dist/metakb.d.ts +164 -0
  23. package/dist/metakb.js +130 -0
  24. package/dist/naming.d.ts +20 -0
  25. package/dist/naming.js +140 -0
  26. package/dist/ops/admin.d.ts +16 -0
  27. package/dist/ops/admin.js +119 -0
  28. package/dist/ops/classes.d.ts +21 -0
  29. package/dist/ops/classes.js +105 -0
  30. package/dist/ops/common.d.ts +6 -0
  31. package/dist/ops/common.js +4 -0
  32. package/dist/ops/instances.d.ts +8 -0
  33. package/dist/ops/instances.js +70 -0
  34. package/dist/ops/links.d.ts +9 -0
  35. package/dist/ops/links.js +85 -0
  36. package/dist/ops/naming.d.ts +4 -0
  37. package/dist/ops/naming.js +70 -0
  38. package/dist/ops/scope.d.ts +29 -0
  39. package/dist/ops/scope.js +124 -0
  40. package/dist/ops/slots.d.ts +31 -0
  41. package/dist/ops/slots.js +186 -0
  42. package/dist/ops/values.d.ts +20 -0
  43. package/dist/ops/values.js +151 -0
  44. package/dist/ops.d.ts +14 -0
  45. package/dist/ops.js +14 -0
  46. package/dist/provenance.d.ts +53 -0
  47. package/dist/provenance.js +296 -0
  48. package/dist/quotes.d.ts +14 -0
  49. package/dist/quotes.js +104 -0
  50. package/dist/render.d.ts +30 -0
  51. package/dist/render.js +413 -0
  52. package/dist/review.d.ts +10 -0
  53. package/dist/review.js +145 -0
  54. package/dist/site.d.ts +6 -0
  55. package/dist/site.js +6 -0
  56. package/dist/skills.d.ts +52 -0
  57. package/dist/skills.js +120 -0
  58. package/dist/status.d.ts +18 -0
  59. package/dist/status.js +59 -0
  60. package/dist/types.d.ts +12 -0
  61. package/dist/types.js +5 -0
  62. package/dist/version.d.ts +1 -0
  63. package/dist/version.js +7 -0
  64. package/meta-kb/data/edges.json +3172 -0
  65. package/meta-kb/data/manifest.json +19 -0
  66. package/meta-kb/data/nodes.json +3546 -0
  67. package/package.json +71 -3
  68. package/skills/build-domain-kb-from-docs/SKILL.md +87 -0
  69. package/skills/ontology-coach/SKILL.md +100 -0
  70. package/skills/ontology-review/SKILL.md +66 -0
@@ -0,0 +1,53 @@
1
+ import { type MdDoc } from "./markdown.js";
2
+ import { type Ontology, type SourceNode } from "@ontology-kit/format";
3
+ import type { Notes } from "./ops.js";
4
+ export declare const isMarkdown: (p: string) => boolean;
5
+ export declare function sourcePath(ont: Ontology, src: SourceNode): string;
6
+ export declare function readMarkdownSource(ont: Ontology, src: SourceNode): MdDoc;
7
+ export declare function addSource(ont: Ontology, file: string, o: {
8
+ title?: string;
9
+ url?: string;
10
+ repoUrl?: string;
11
+ id?: string;
12
+ }): Notes;
13
+ export interface AddQuoteOpts {
14
+ line?: number;
15
+ cites?: string[];
16
+ allowCode?: boolean;
17
+ }
18
+ export declare function addQuote(ont: Ontology, sourceRef: string, quote: string, o?: AddQuoteOpts): Promise<Notes>;
19
+ /** Attach an existing quote to a node: a CITES edge. Marks the node extracted, except an authored rule. */
20
+ export declare function cite(ont: Ontology, nodeRef: string, locRef: string): Notes;
21
+ /** Re-locate every quote of a markdown source after the file changed; updates lines and links. */
22
+ export declare function refreshSource(ont: Ontology, sourceRef: string): Notes;
23
+ export interface AddRuleOpts {
24
+ statement: string;
25
+ modality: string;
26
+ governs?: string[];
27
+ cites?: string[];
28
+ name?: string;
29
+ /** Written by the ontology owner rather than extracted. Still needs a quote and verification. */
30
+ authored?: boolean;
31
+ /** Qualifier values as slot=value (slots declared with --on-rules). */
32
+ values?: string[];
33
+ /** Rules this one refines, and what it adds to each. */
34
+ refines?: string[];
35
+ adds?: string;
36
+ }
37
+ export declare function addRule(ont: Ontology, o: AddRuleOpts): Notes;
38
+ /** `rule` REFINES `broader`: it narrows the broader rule by adding a part, condition, key or case. */
39
+ export declare function refine(ont: Ontology, ruleRef: string, broaderRef: string, o?: {
40
+ adds?: string;
41
+ remove?: boolean;
42
+ }): Notes;
43
+ /** `instance` FULFILLS `rule`: a descriptive fact that meets the rule. Many instances may fulfill one rule. */
44
+ export declare function fulfill(ont: Ontology, instanceRef: string, ruleRef: string, o?: {
45
+ remove?: boolean;
46
+ }): Notes;
47
+ export declare function verify(ont: Ontology, ref: string, o: {
48
+ status?: string;
49
+ corrected?: string;
50
+ confidence?: string;
51
+ note?: string;
52
+ approve?: boolean;
53
+ }): Notes;
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Provenance: registering source documents, adding verbatim quotes (located
3
+ * automatically in markdown by heading and line), extracted domain Rules, and the
4
+ * verification results from the extraction pipeline (docs/EXTRACTION-PIPELINE.md).
5
+ */
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import { isAbsolute, join, relative, resolve } from "node:path";
8
+ import { deepLinks, locate, parseMarkdown } from "./markdown.js";
9
+ import { OkbError, nameOrText, MODALITIES, VERIFICATION_STATUSES as STATUSES } from "@ontology-kit/format";
10
+ import { isOneOf } from "./types.js";
11
+ import * as naming from "./naming.js";
12
+ import { assign } from "./ops/values.js";
13
+ import { findQuote, loadPages } from "./quotes.js";
14
+ /** Suggest the closest block for a failed quote only if it shares at least this share of the quote's words. */
15
+ const MIN_CLOSEST_WORD_OVERLAP = 0.4;
16
+ export const isMarkdown = (p) => /\.(md|markdown)$/i.test(p);
17
+ export function sourcePath(ont, src) {
18
+ const p = src.localPath;
19
+ if (!p)
20
+ throw new OkbError(`Source ${src.id} has no local file (localPath), so okb can't read it. Register the file with okb source add.`);
21
+ return isAbsolute(p) ? p : join(ont.root, p);
22
+ }
23
+ export function readMarkdownSource(ont, src) {
24
+ const p = sourcePath(ont, src);
25
+ if (!existsSync(p))
26
+ throw new OkbError(`Source file not found: ${p}`);
27
+ return parseMarkdown(readFileSync(p, "utf8"));
28
+ }
29
+ export function addSource(ont, file, o) {
30
+ const abs = resolve(file);
31
+ if (!existsSync(abs))
32
+ throw new OkbError(`File not found: ${file}`);
33
+ const localPath = relative(ont.root, abs) || abs;
34
+ const existing = ont.ofType("Source").find((s) => s.localPath && resolve(sourcePath(ont, s)) === abs);
35
+ if (existing)
36
+ throw new OkbError(`That file is already registered as ${existing.id} (${existing.title}).`);
37
+ const notes = [];
38
+ const node = { type: "Source", id: "", title: o.title ?? "", localPath, url: o.url, repoUrl: o.repoUrl };
39
+ if (isMarkdown(abs)) {
40
+ const doc = parseMarkdown(readFileSync(abs, "utf8"));
41
+ node.format = "markdown";
42
+ node.title ||= doc.title ?? file;
43
+ if (doc.frontmatter)
44
+ node.meta = doc.frontmatter;
45
+ const quotable = doc.blocks.filter((b) => b.quotable).length;
46
+ notes.push(`Read ${doc.blocks.length} blocks (${quotable} quotable) under ${doc.headings.length} headings.`);
47
+ for (const p of doc.problems)
48
+ notes.push(`Warning (line ${p.line}): ${p.message}`);
49
+ }
50
+ else {
51
+ node.format = abs.toLowerCase().endsWith(".pdf") ? "pdf" : "text";
52
+ node.title ||= file;
53
+ }
54
+ node.id = o.id ?? ont.newId("Source", node.title);
55
+ ont.addNode(Object.fromEntries(Object.entries(node).filter(([, v]) => v !== undefined)));
56
+ notes.unshift(`Registered source ${node.id}: ${node.title}`);
57
+ 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.");
59
+ notes.push(`Next: okb source outline ${node.id} (the list of quotable blocks to work through)`);
60
+ return notes;
61
+ }
62
+ export async function addQuote(ont, sourceRef, quote, o = {}) {
63
+ const src = ont.find(sourceRef, "Source");
64
+ if (!src.localPath)
65
+ throw new OkbError(`Source ${src.id} has no localPath, so the quote can't be checked. Register the file with okb source add.`);
66
+ const notes = [];
67
+ const loc = { type: "SourceLocation", id: nextLocId(ont, src), quote };
68
+ if (src.format === "markdown") {
69
+ const doc = readMarkdownSource(ont, src);
70
+ let hits = locate(doc, quote);
71
+ if (!hits.length)
72
+ throw new OkbError(`Not found in ${src.localPath}. Quotes must be word-for-word (markdown syntax, line wraps and punctuation are ignored).${closest(doc, quote)}`);
73
+ if (o.line !== undefined)
74
+ hits = hits.filter((h) => h.startLine <= o.line && o.line <= h.endLine);
75
+ if (!o.allowCode && hits.length && hits.every((h) => !h.quotable)) {
76
+ const why = hits[0].blocks.find((b) => !b.quotable)?.note ?? "not quotable";
77
+ throw new OkbError(`That text is only in ${hits[0].blocks.map((b) => b.kind).join("/")} block(s) (${why}). Add --allow-code if you really mean to cite it.`);
78
+ }
79
+ if (!o.allowCode)
80
+ hits = hits.filter((h) => h.quotable);
81
+ if (hits.length > 1) {
82
+ throw new OkbError(`That text appears ${hits.length} times. Pick one with --line:\n${hits.map((h) => ` --line ${h.startLine} ${h.locator}`).join("\n")}`);
83
+ }
84
+ if (!hits.length)
85
+ throw new OkbError(`The quote isn't on line ${o.line}.`);
86
+ const hit = hits[0];
87
+ if (!hit.quotable && !o.allowCode) {
88
+ const why = hit.blocks.find((b) => !b.quotable)?.note ?? "not quotable";
89
+ throw new OkbError(`That text is in a ${hit.blocks.map((b) => b.kind).join("/")} block (${why}). Add --allow-code if you really mean to cite it.`);
90
+ }
91
+ Object.assign(loc, locFields(hit, src));
92
+ const bad = hit.blocks.find((b) => b.note?.startsWith("malformed"));
93
+ if (bad)
94
+ notes.push(`Warning: line ${bad.startLine} is a ${bad.note}. Check the columns before drafting from it.`);
95
+ }
96
+ else {
97
+ const pages = await loadPages(sourcePath(ont, src));
98
+ const r = findQuote(quote, pages);
99
+ if (!r.found)
100
+ throw new OkbError(`Not found in ${src.localPath}.`);
101
+ loc.page = r.pages.length > 1 ? `${r.pages[0]}-${r.pages[r.pages.length - 1]}` : r.pages[0];
102
+ loc.locator = `p.${loc.page}`;
103
+ if (src.url)
104
+ loc.pageLink = `${src.url}#page=${r.pages[0]}`;
105
+ }
106
+ ont.addNode(loc);
107
+ ont.addEdge(loc.id, "PART_OF", src.id);
108
+ notes.unshift(`Added ${loc.id} at ${loc.locator}${loc.startLine ? `, line ${loc.lines}` : ""}.`);
109
+ for (const c of o.cites ?? [])
110
+ notes.push(cite(ont, c, loc.id)[0]);
111
+ return notes;
112
+ }
113
+ /** Attach an existing quote to a node: a CITES edge. Marks the node extracted, except an authored rule. */
114
+ export function cite(ont, nodeRef, locRef) {
115
+ const n = ont.find(nodeRef, ["Class", "Slot", "Instance", "Rule", "DesignDecision"]);
116
+ const loc = ont.find(locRef, "SourceLocation");
117
+ const had = ont.targets(n.id, "CITES").includes(loc.id);
118
+ ont.addEdge(n.id, "CITES", loc.id);
119
+ if (!(n.type === "Rule" && n.authored))
120
+ n.extracted = true;
121
+ return [had ? `${n.type} ${nameOrText(n) ?? n.id} already cited ${loc.id}.` : `${n.type} ${nameOrText(n) ?? n.id} now cites ${loc.id}.`];
122
+ }
123
+ function locFields(hit, src) {
124
+ const links = deepLinks(hit, src.repoUrl, src.url);
125
+ return Object.fromEntries(Object.entries({
126
+ locator: hit.locator,
127
+ headingPath: hit.headingPath,
128
+ startLine: hit.startLine,
129
+ endLine: hit.endLine,
130
+ lines: hit.startLine === hit.endLine ? String(hit.startLine) : `${hit.startLine}-${hit.endLine}`,
131
+ blockKind: hit.blocks.map((b) => b.kind).join("+"),
132
+ sourceLink: links.sourceLink,
133
+ pageLink: links.pageLink,
134
+ }).filter(([, v]) => v !== undefined));
135
+ }
136
+ 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}`;
142
+ }
143
+ /** Suggest the block that shares the most words with a failed quote. */
144
+ function closest(doc, quote) {
145
+ const words = new Set(normalizeWords(quote));
146
+ let best = null;
147
+ for (const b of doc.blocks) {
148
+ if (!b.quotable)
149
+ continue;
150
+ const ws = normalizeWords(b.text);
151
+ const score = ws.filter((w) => words.has(w)).length / Math.max(words.size, 1);
152
+ if (!best || score > best.score)
153
+ best = { score, b };
154
+ }
155
+ if (!best || best.score < MIN_CLOSEST_WORD_OVERLAP)
156
+ return "";
157
+ return `\nClosest text (line ${best.b.startLine}, ${best.b.headingPath.join(" > ")}):\n "${best.b.text.slice(0, 200)}"`;
158
+ }
159
+ const normalizeWords = (s) => s.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2);
160
+ /** Re-locate every quote of a markdown source after the file changed; updates lines and links. */
161
+ export function refreshSource(ont, sourceRef) {
162
+ const src = ont.find(sourceRef, "Source");
163
+ if (src.format !== "markdown")
164
+ throw new OkbError("refresh only applies to markdown sources.");
165
+ const doc = readMarkdownSource(ont, src);
166
+ const notes = [];
167
+ let moved = 0;
168
+ let missing = 0;
169
+ for (const id of ont.sources(src.id, "PART_OF")) {
170
+ const loc = ont.require(id, "SourceLocation");
171
+ const hits = locate(doc, loc.quote);
172
+ if (!hits.length) {
173
+ missing++;
174
+ notes.push(`✗ ${loc.id} is gone: "${String(loc.quote).slice(0, 70)}…" (was ${loc.locator}, line ${loc.lines})`);
175
+ continue;
176
+ }
177
+ const hit = hits.reduce((a, b) => (Math.abs(b.startLine - (loc.startLine ?? 0)) < Math.abs(a.startLine - (loc.startLine ?? 0)) ? b : a));
178
+ if (hit.startLine !== loc.startLine || hit.locator !== loc.locator) {
179
+ moved++;
180
+ notes.push(` ${loc.id}: line ${loc.lines} → ${hit.startLine}${hit.locator !== loc.locator ? ` (now under ${hit.locator})` : ""}`);
181
+ Object.assign(loc, locFields(hit, src));
182
+ }
183
+ }
184
+ 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." : ""}`);
185
+ return notes;
186
+ }
187
+ export function addRule(ont, o) {
188
+ const modality = o.modality.toUpperCase().replace(/ /g, "_");
189
+ if (!isOneOf(MODALITIES, modality))
190
+ throw new OkbError(`--modality must be one of ${MODALITIES.join(", ")}.`);
191
+ if (!o.cites?.length)
192
+ throw new OkbError("Quote first: a rule needs --cites <quote id> (add the quote with okb quote add).");
193
+ const name = o.name ?? o.statement.split(/\s+/).slice(0, 6).join(" ");
194
+ const id = ont.newId("Rule", name);
195
+ if (o.adds && !o.refines?.length)
196
+ throw new OkbError("--adds says what a refining rule adds, so it needs --refines <rule>.");
197
+ const refined = (o.refines ?? []).map((r) => ont.find(r, "Rule"));
198
+ ont.addNode({ type: "Rule", id, name, modality, statement: o.statement, ...(o.authored ? { authored: true, extracted: false } : { extracted: true }) });
199
+ for (const c of o.cites) {
200
+ const loc = ont.find(c, "SourceLocation");
201
+ ont.addEdge(id, "CITES", loc.id);
202
+ }
203
+ for (const g of o.governs ?? [])
204
+ ont.addEdge(id, "GOVERNS", ont.find(g, ["Class", "Slot", "Instance"]).id);
205
+ const notes = [`Added ${o.authored ? "authored " : ""}rule ${id} (${modality}): ${o.statement}`];
206
+ if (o.values?.length)
207
+ notes.push(...assign(ont, id, o.values));
208
+ for (const r of refined)
209
+ notes.push(...refine(ont, id, r.id, { adds: o.adds }));
210
+ const quotes = o.cites.map((c) => ont.find(c, "SourceLocation").quote);
211
+ const q = quotes.join(" ").toLowerCase();
212
+ if (/^MUST/.test(modality) && !/\b(must|requir\w*|always|never|shall|mandatory)\b/.test(q)) {
213
+ notes.push(`Careful: ${modality} is strong, and the quote doesn't say "must", "required", "always", "never" or similar. Does it really support ${modality}? (The verification step will check.)`);
214
+ }
215
+ notes.push(`Next: verify it in a fresh context, then okb verify ${id} --status SUPPORTED|OVERREACH|UNSUPPORTED`);
216
+ return notes;
217
+ }
218
+ /** `rule` REFINES `broader`: it narrows the broader rule by adding a part, condition, key or case. */
219
+ export function refine(ont, ruleRef, broaderRef, o = {}) {
220
+ const rule = ont.find(ruleRef, "Rule");
221
+ const broader = ont.find(broaderRef, "Rule");
222
+ if (rule.id === broader.id)
223
+ throw new OkbError("A rule can't refine itself.");
224
+ if (o.remove) {
225
+ const n = ont.removeEdges((e) => e.type === "REFINES" && e.from === rule.id && e.to === broader.id);
226
+ return [n ? `${rule.id} no longer refines ${broader.id}.` : `${rule.id} didn't refine ${broader.id}.`];
227
+ }
228
+ if (ont.reaches(broader.id, rule.id, "REFINES"))
229
+ throw new OkbError(`${broader.id} already refines ${rule.id} (directly or through other rules), so this would be a cycle.`);
230
+ // Refining again replaces the edge, so a new --adds updates the old one instead of adding a second edge.
231
+ const adds = o.adds ?? ont.outEdges(rule.id, "REFINES").find((e) => e.to === broader.id)?.adds;
232
+ ont.removeEdges((e) => e.type === "REFINES" && e.from === rule.id && e.to === broader.id);
233
+ ont.addEdge(rule.id, "REFINES", broader.id, adds ? { adds } : {});
234
+ const notes = [`${rule.id} refines ${broader.id}${adds ? ` (adds: ${adds})` : ""}.`];
235
+ if (!adds)
236
+ notes.push("Tip: say what it adds with --adds \"...\" so a verifier can check that detail appears in its quote.");
237
+ return notes;
238
+ }
239
+ /** `instance` FULFILLS `rule`: a descriptive fact that meets the rule. Many instances may fulfill one rule. */
240
+ export function fulfill(ont, instanceRef, ruleRef, o = {}) {
241
+ const inst = ont.find(instanceRef, "Instance");
242
+ const rule = ont.find(ruleRef, "Rule");
243
+ if (o.remove) {
244
+ const n = ont.removeEdges((e) => e.type === "FULFILLS" && e.from === inst.id && e.to === rule.id);
245
+ return [n ? `${inst.name} no longer fulfills ${rule.id}.` : `${inst.name} didn't fulfill ${rule.id}.`];
246
+ }
247
+ ont.addEdge(inst.id, "FULFILLS", rule.id);
248
+ return [`${inst.name} fulfills ${rule.id}.`];
249
+ }
250
+ export function verify(ont, ref, o) {
251
+ const n = ont.find(ref, ["Rule", "Class", "Slot", "Instance"]);
252
+ const cited = ont.targets(n.id, "CITES");
253
+ if (!cited.length)
254
+ throw new OkbError(`${n.id} doesn't cite a quote, so there's nothing to verify it against.`);
255
+ const field = n.type === "Rule" ? "statement" : "description";
256
+ if (o.approve) {
257
+ // A person has looked at a corrected (or otherwise flagged) item and accepts it.
258
+ if (!n.verification)
259
+ throw new OkbError(`${n.id} hasn't been through verification yet.`);
260
+ if (n.verification.status === "UNSUPPORTED")
261
+ 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 } : {}) };
263
+ return [`${n.id}: approved by a person (was ${n.verification.approvedAfter}).`];
264
+ }
265
+ const status = (o.status ?? "").toUpperCase();
266
+ if (!isOneOf(STATUSES, status))
267
+ throw new OkbError(`--status must be one of ${STATUSES.join(", ")} (or use --approve after a human review).`);
268
+ const notes = [];
269
+ if (status === "OVERREACH") {
270
+ if (!o.corrected)
271
+ throw new OkbError('OVERREACH needs --corrected "<the narrower statement the quote does support>".');
272
+ if (n.type === "Rule") {
273
+ n._originalDraft = n.statement;
274
+ n.statement = o.corrected;
275
+ }
276
+ else {
277
+ n._originalDraft = n.description;
278
+ n.description = o.corrected;
279
+ }
280
+ n.extractionConfidence = "corrected";
281
+ notes.push(`Corrected ${field}: "${o.corrected}" (original kept in _originalDraft).`);
282
+ notes.push(`It stays blocked (prov-verified) until a person checks the correction: okb verify ${n.id} --approve`);
283
+ }
284
+ else if (o.confidence) {
285
+ if (!isOneOf(["verbatim", "paraphrased"], o.confidence))
286
+ throw new OkbError("--confidence must be verbatim or paraphrased.");
287
+ n.extractionConfidence = o.confidence;
288
+ }
289
+ else
290
+ n.extractionConfidence ??= "paraphrased";
291
+ n.verification = { status, checkedAgainst: cited, ...(o.note ? { note: o.note } : {}) };
292
+ if (status === "UNSUPPORTED")
293
+ notes.push(`${n.id} is UNSUPPORTED and blocks okb validate (prov-verified). Remove it: okb remove ${n.id}`);
294
+ notes.unshift(`${n.id}: ${status}.`);
295
+ return notes;
296
+ }
@@ -0,0 +1,14 @@
1
+ import { fold } from "./naming.js";
2
+ /** Letters and digits only, lowercased and without accents (uncached: quotes and pages are long, one-off strings). */
3
+ export declare const normalize: typeof fold;
4
+ /**
5
+ * Return page texts (index 0 = page 1). Supports .pdf (via the `pdftotext`
6
+ * command, or the optional pdfjs-dist package) and text/markdown files
7
+ * (form-feed characters are page breaks; otherwise the file is one page).
8
+ */
9
+ export declare function loadPages(path: string): Promise<string[]>;
10
+ /** Find a quote. Returns the 1-based pages it was found on (empty if not found). */
11
+ export declare function findQuote(quote: string, pages: string[]): {
12
+ found: boolean;
13
+ pages: number[];
14
+ };
package/dist/quotes.js ADDED
@@ -0,0 +1,104 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /**
10
+ * Verbatim-quote checking.
11
+ *
12
+ * A SourceLocation's `quote` must appear, word for word, in its source document.
13
+ * PDF text extraction is messy (line breaks, split words like "t o", curly quotes,
14
+ * soft hyphens, running page numbers), so both sides are normalized before
15
+ * comparing: everything except letters and digits is dropped and case is folded.
16
+ * That is strict about *words* and lenient about *layout*.
17
+ *
18
+ * An ellipsis ("..." or "…") inside a quote marks an intentional gap: each piece
19
+ * must appear, in order.
20
+ */
21
+ import { execFileSync } from "node:child_process";
22
+ import { existsSync, readFileSync } from "node:fs";
23
+ import { fold } from "./naming.js";
24
+ const ELLIPSIS = /\.\.\.|…/;
25
+ /** Letters and digits only, lowercased and without accents (uncached: quotes and pages are long, one-off strings). */
26
+ export const normalize = fold;
27
+ function hasPdftotext() {
28
+ try {
29
+ execFileSync("pdftotext", ["-v"], { stdio: "ignore" });
30
+ return true;
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ /**
37
+ * Return page texts (index 0 = page 1). Supports .pdf (via the `pdftotext`
38
+ * command, or the optional pdfjs-dist package) and text/markdown files
39
+ * (form-feed characters are page breaks; otherwise the file is one page).
40
+ */
41
+ export async function loadPages(path) {
42
+ if (!existsSync(path))
43
+ throw new Error(`File not found: ${path}`);
44
+ if (!path.toLowerCase().endsWith(".pdf")) {
45
+ return readFileSync(path, "utf8").split("\f");
46
+ }
47
+ if (hasPdftotext()) {
48
+ const out = execFileSync("pdftotext", [path, "-"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
49
+ return out.split("\f");
50
+ }
51
+ let pdfjs;
52
+ try {
53
+ pdfjs = await import(__rewriteRelativeImportExtension("pdfjs-dist/legacy/build/pdf.mjs"));
54
+ }
55
+ catch {
56
+ throw new Error("Reading PDFs needs either the `pdftotext` command (brew install poppler) or the optional pdfjs-dist package, which comes with okb unless your install skipped optional dependencies (reinstall okb without `--omit=optional`).");
57
+ }
58
+ const doc = await pdfjs.getDocument({ data: new Uint8Array(readFileSync(path)), verbosity: 0 }).promise;
59
+ const pages = [];
60
+ for (let i = 1; i <= doc.numPages; i++) {
61
+ const content = await (await doc.getPage(i)).getTextContent();
62
+ pages.push(content.items.map((it) => ("str" in it ? it.str : "") + (it.hasEOL ? "\n" : " ")).join(""));
63
+ }
64
+ return pages;
65
+ }
66
+ /** Drop lines that are only a page number (running headers/footers). */
67
+ function stripPageNumbers(page) {
68
+ return page
69
+ .split(/\r?\n/)
70
+ .filter((l) => !/^\s*\d{1,3}\s*$/.test(l))
71
+ .join("\n");
72
+ }
73
+ /** Find a quote. Returns the 1-based pages it was found on (empty if not found). */
74
+ export function findQuote(quote, pages) {
75
+ const pieces = quote.split(ELLIPSIS).map(normalize).filter(Boolean);
76
+ if (pieces.length === 0)
77
+ return { found: false, pages: [] };
78
+ const norm = pages.map((p) => normalize(stripPageNumbers(p)));
79
+ const offsets = [];
80
+ let joined = "";
81
+ for (const p of norm) {
82
+ offsets.push(joined.length);
83
+ joined += p;
84
+ }
85
+ const pageAt = (i) => {
86
+ let page = 1;
87
+ offsets.forEach((off, idx) => {
88
+ if (off <= i)
89
+ page = idx + 1;
90
+ });
91
+ return page;
92
+ };
93
+ let start = 0;
94
+ const hit = new Set();
95
+ for (const piece of pieces) {
96
+ const i = joined.indexOf(piece, start);
97
+ if (i < 0)
98
+ return { found: false, pages: [] };
99
+ hit.add(pageAt(i));
100
+ hit.add(pageAt(i + piece.length - 1));
101
+ start = i + piece.length;
102
+ }
103
+ return { found: true, pages: [...hit].sort((a, b) => a - b) };
104
+ }
@@ -0,0 +1,30 @@
1
+ import { type Explainable, type MetaStep } from "./metakb.js";
2
+ import { type Ontology, type OkbNode } from "@ontology-kit/format";
3
+ import { type Finding } from "./types.js";
4
+ export declare const c: {
5
+ bold: (s: string) => string;
6
+ dim: (s: string) => string;
7
+ red: (s: string) => string;
8
+ green: (s: string) => string;
9
+ yellow: (s: string) => string;
10
+ blue: (s: string) => string;
11
+ cyan: (s: string) => string;
12
+ };
13
+ export declare const SYMBOL: {
14
+ error: string;
15
+ warning: string;
16
+ info: string;
17
+ ok: string;
18
+ todo: string;
19
+ ask: string;
20
+ };
21
+ export declare function formatFindings(findings: Finding[], ont: Ontology, opts: {
22
+ all?: boolean;
23
+ verbose?: boolean;
24
+ }): string;
25
+ export declare function explain(node: Explainable): string;
26
+ export declare function stepGuide(step: MetaStep): string;
27
+ export declare function listExplainable(): string;
28
+ export declare function tree(ont: Ontology, withInstances?: boolean): string;
29
+ export declare function show(ont: Ontology, n: OkbNode): string;
30
+ export declare function mermaid(ont: Ontology): string;