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

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 (97) 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 +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 +134 -0
  11. package/dist/command-table.js +82 -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 +433 -0
  20. package/dist/commands/planning.d.ts +3 -0
  21. package/dist/commands/planning.js +212 -0
  22. package/dist/commands/reviewing.d.ts +3 -0
  23. package/dist/commands/reviewing.js +177 -0
  24. package/dist/commands/skills.d.ts +3 -0
  25. package/dist/commands/skills.js +52 -0
  26. package/dist/commands.d.ts +10 -22
  27. package/dist/commands.js +15 -622
  28. package/dist/diff.d.ts +85 -0
  29. package/dist/diff.js +323 -0
  30. package/dist/export.d.ts +1 -1
  31. package/dist/export.js +1 -1
  32. package/dist/families.d.ts +1 -1
  33. package/dist/families.js +1 -1
  34. package/dist/help.d.ts +11 -2
  35. package/dist/help.js +51 -57
  36. package/dist/kbdocs.d.ts +18 -0
  37. package/dist/kbdocs.js +393 -0
  38. package/dist/metakb.d.ts +1 -1
  39. package/dist/metakb.js +1 -1
  40. package/dist/naming.d.ts +2 -2
  41. package/dist/naming.js +2 -2
  42. package/dist/ontology-ref.d.ts +20 -0
  43. package/dist/ontology-ref.js +108 -0
  44. package/dist/ops/admin.d.ts +1 -1
  45. package/dist/ops/admin.js +24 -7
  46. package/dist/ops/classes.d.ts +1 -1
  47. package/dist/ops/classes.js +13 -5
  48. package/dist/ops/instances.d.ts +2 -1
  49. package/dist/ops/instances.js +7 -1
  50. package/dist/ops/links.d.ts +1 -1
  51. package/dist/ops/links.js +1 -1
  52. package/dist/ops/naming.d.ts +1 -1
  53. package/dist/ops/naming.js +3 -1
  54. package/dist/ops/scope.d.ts +5 -1
  55. package/dist/ops/scope.js +19 -1
  56. package/dist/ops/slots.d.ts +1 -1
  57. package/dist/ops/slots.js +15 -2
  58. package/dist/ops/values.d.ts +1 -1
  59. package/dist/ops/values.js +5 -1
  60. package/dist/provenance.d.ts +4 -2
  61. package/dist/provenance.js +58 -17
  62. package/dist/release.d.ts +52 -0
  63. package/dist/release.js +337 -0
  64. package/dist/render.d.ts +64 -1
  65. package/dist/render.js +240 -3
  66. package/dist/resync.d.ts +98 -0
  67. package/dist/resync.js +234 -0
  68. package/dist/review.d.ts +1 -1
  69. package/dist/review.js +1 -1
  70. package/dist/reviewdocs.d.ts +42 -0
  71. package/dist/reviewdocs.js +263 -0
  72. package/dist/runner.d.ts +3 -0
  73. package/dist/runner.js +79 -0
  74. package/dist/skills.js +1 -1
  75. package/dist/status.d.ts +1 -1
  76. package/dist/status.js +1 -1
  77. package/dist/types.d.ts +1 -1
  78. package/dist/types.js +1 -1
  79. package/dist/verifynote.d.ts +18 -0
  80. package/dist/verifynote.js +92 -0
  81. package/dist/workflows.d.ts +256 -0
  82. package/dist/workflows.js +223 -0
  83. package/meta-kb/data/manifest.json +2 -2
  84. package/meta-kb/data/nodes.json +8 -8
  85. package/package.json +9 -4
  86. package/schema/edge.schema.json +68 -0
  87. package/schema/edges.schema.json +9 -0
  88. package/schema/node.schema.json +893 -0
  89. package/schema/nodes.schema.json +9 -0
  90. package/schema/okb.schema.json +41 -0
  91. package/skills/build-domain-kb-from-docs/SKILL.md +20 -2
  92. package/skills/ontology-coach/SKILL.md +6 -2
  93. package/skills/ontology-maintainer/SKILL.md +152 -0
  94. package/skills/ontology-review/SKILL.md +3 -1
  95. package/skills/ontology-signoff/SKILL.md +182 -0
  96. package/templates/okb-check.yml +132 -0
  97. package/templates/pull_request_template.md +16 -0
package/dist/render.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Human-readable output: findings, explanations, trees, node details, Mermaid diagrams. */
2
2
  import { ruleUrl } from "./site.js";
3
- import { MetaKB } from "./metakb.js";
4
- import { edgeProps, nodeLabel } from "@ontology-kit/format";
3
+ import { MetaKB, explainName } from "./metakb.js";
4
+ import { edgeProps, nodeLabel } from "@ontology-kit/reader";
5
5
  import {} from "./types.js";
6
6
  import * as naming from "./naming.js";
7
7
  const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
@@ -279,6 +279,10 @@ export function show(ont, n) {
279
279
  out.push(`${c.bold(nodeLabel(n))} ${c.dim(`${n.type} · ${n.id}`)}`);
280
280
  if ("description" in n && n.description)
281
281
  out.push(indent(n.description, " "));
282
+ if (n.createdAt)
283
+ line("created", n.createdAt);
284
+ if (n.updatedAt)
285
+ line("updated", n.updatedAt);
282
286
  if (n.type === "Class") {
283
287
  line("parents", ont.parents(n.id).map((p) => ont.label(p)).join(", ") || "(top level)");
284
288
  line("subclasses", ont.children(n.id).map((p) => ont.label(p)).join(", ") || "—");
@@ -339,7 +343,7 @@ export function show(ont, n) {
339
343
  }
340
344
  else {
341
345
  for (const [k, v] of Object.entries(n))
342
- if (!["id", "type", "name", "values", "authored"].includes(k))
346
+ if (!["id", "type", "name", "values", "authored", "createdAt", "updatedAt"].includes(k))
343
347
  line(k, typeof v === "string" ? v : JSON.stringify(v));
344
348
  if (n.type === "Rule") {
345
349
  if (n.authored)
@@ -411,3 +415,236 @@ export function mermaid(ont) {
411
415
  out.push("", `Disjoint: ${disj.join(" · ")}`);
412
416
  return out.join("\n");
413
417
  }
418
+ /** The `okb check` summary: one line per check, the problems under the ones that failed, and a verdict. */
419
+ export function formatCheck(report, name) {
420
+ const out = [c.bold(`okb check: ${name}`) + c.dim(` (okb ${report.installed}${report.pinned ? `, KB pins ${report.pinned}` : ""})`), ""];
421
+ const mark = { pass: SYMBOL.ok, warn: SYMBOL.warning, fail: SYMBOL.error };
422
+ for (const s of report.steps) {
423
+ out.push(`${mark[s.status]} ${c.bold(s.title)}: ${s.summary}`);
424
+ for (const p of s.problems)
425
+ out.push(` ${SYMBOL.error} ${p}`);
426
+ }
427
+ const failed = report.steps.filter((s) => s.status === "fail").length;
428
+ const warned = report.steps.filter((s) => s.status === "warn").length;
429
+ const safe = warned ? `no check failed, but ${warned} warned (marked ${SYMBOL.warning} above).` : "every check passed.";
430
+ out.push("", report.ok ? `${SYMBOL.ok} Safe to merge: ${safe}` : `${SYMBOL.error} Not safe to merge: ${failed} of ${report.steps.length} checks failed.`);
431
+ return out.join("\n");
432
+ }
433
+ // ---- Terminal output for the command records (src/commands/). Each returns lines; the runner prints them. ----
434
+ /** A note that teaches rather than reports is shown dimmed. */
435
+ const TIP = /^(Tip|Add a|Attach|Decide|Say which|List the)/;
436
+ export function formatNotes(notes) {
437
+ return notes.map((n) => (TIP.test(n) ? c.dim(" " + n) : n));
438
+ }
439
+ export function renderInit(name, root, folder, guide) {
440
+ return [`${SYMBOL.ok} Created ontology '${name}' in ${root}\n`, guide, c.dim(`\nNext: cd ${folder} && okb scope --domain "..." --purpose "..." --users "..."`)];
441
+ }
442
+ export function renderScope(m) {
443
+ const row = (k, val) => ` ${c.dim(k.padEnd(13))} ${Array.isArray(val) ? val.join(", ") || c.yellow("—") : val || c.yellow("—")}`;
444
+ return [c.bold(m.name), row("domain", m.domain), row("purpose", m.purpose), row("users", m.users), row("maintainers", m.maintainers), row("out of scope", m.outOfScope), row("kind", m.kind)];
445
+ }
446
+ export function renderConvention(ont) {
447
+ const cv = ont.conventions;
448
+ return `Naming convention: classes ${cv.classCase} (${cv.classNumber}) · slots ${cv.slotCase}${cv.slotAffix !== "none" ? ` (${cv.slotAffix})` : ""} · instances ${cv.instanceCase ?? "free text"}`;
449
+ }
450
+ export function renderQuestions(ont, qs) {
451
+ if (!qs.length)
452
+ return [c.dim('No competency questions yet. okb cq add "..."')];
453
+ const out = [];
454
+ for (const q of qs) {
455
+ const needs = ont.targets(q.id, "NEEDS").map((n) => ont.label(n));
456
+ const num = ont.displayNumber(q);
457
+ out.push(`${c.bold(String(num).padEnd(3))} ${q.text} ${c.dim(`[${q.status ?? "draft"}]`)}`);
458
+ out.push(c.dim(` needs: ${needs.length ? needs.join(", ") : "(not linked yet: okb cq link " + num + " <Class|slot>...)"}`));
459
+ }
460
+ return out;
461
+ }
462
+ export function renderTerms(ont) {
463
+ const ts = ont.ofType("Term");
464
+ const groups = new Map();
465
+ for (const t of ts) {
466
+ const d = t.disposition ?? "undecided";
467
+ const became = ont.targets(t.id, "BECAME").map((x) => ont.label(x));
468
+ groups.set(d, [...(groups.get(d) ?? []), t.text + (became.length ? c.dim(` → ${became.join(", ")}`) : "")]);
469
+ }
470
+ const out = [...groups].map(([d, items]) => `${c.bold(d.padEnd(13))} ${items.join(" · ")}`);
471
+ if (!ts.length)
472
+ out.push(c.dim("No terms yet. okb term add wine grape winery ..."));
473
+ return out;
474
+ }
475
+ export function renderReuse(ont) {
476
+ const rs = ont.ofType("ReusedOntology");
477
+ const out = rs.map((r) => `${c.bold(r.name)} ${c.dim(`[${r.decision}]`)} ${r.url ?? ""} ${r.notes ? "\n " + r.notes : ""}`);
478
+ if (!rs.length)
479
+ out.push(c.dim(ont.meta.reuseReviewed ? "Reviewed: nothing reused." : "Not reviewed yet."));
480
+ return out;
481
+ }
482
+ export function renderDecisions(ont, ds) {
483
+ const out = [];
484
+ for (const d of ds) {
485
+ out.push(`${c.bold(String(ont.displayNumber(d)).padEnd(3))} ${d.title}`);
486
+ out.push(` ${d.decision}${d.rationale ? c.dim(" · why: " + d.rationale) : ""}`);
487
+ const about = ont.targets(d.id, "ABOUT").map((x) => ont.label(x));
488
+ if (about.length || d.metaRules)
489
+ out.push(c.dim(` about: ${about.join(", ") || "—"}${d.metaRules ? " · explains: " + d.metaRules.join(", ") : ""}`));
490
+ }
491
+ if (!ds.length)
492
+ out.push(c.dim("No design decisions recorded yet."));
493
+ return out;
494
+ }
495
+ export function renderFindings(findings, hiddenLater, ont, opts) {
496
+ const out = [formatFindings(findings, ont, opts)];
497
+ if (hiddenLater)
498
+ out.push(c.dim(`(${hiddenLater} warning(s)/hint(s) from later steps are hidden until you get there; okb validate --all shows them. Errors are never hidden.)`));
499
+ return out;
500
+ }
501
+ export function renderStatus(ont, findings, st) {
502
+ const meta = MetaKB.get();
503
+ const shown = findings.filter((f) => !f.explainedBy && (f.severity === "error" || (meta.rule(f.rule).fromStep ?? 1) <= ont.step));
504
+ const count = (sev) => shown.filter((f) => f.severity === sev).length;
505
+ const out = [c.bold(ont.meta.name) + c.dim(` · ${ont.ofType("Class").length} classes · ${ont.ofType("Slot").length} slots · ${ont.ofType("Instance").length} instances · ${ont.ofType("CompetencyQuestion").length} questions`), ""];
506
+ for (const s of st.steps) {
507
+ const here = s.order === ont.step ? c.cyan(" ◀ you are here") : "";
508
+ const mark = s.complete ? SYMBOL.ok : s.order === ont.step ? c.cyan("▶") : SYMBOL.todo;
509
+ out.push(`${mark} ${c.bold(`${s.order}. ${s.name}`)}${here}`);
510
+ if (s.order === ont.step || (!s.complete && s.order < ont.step)) {
511
+ for (const it of s.items)
512
+ out.push(` ${it.done === null ? SYMBOL.ask : it.done ? SYMBOL.ok : SYMBOL.todo} ${it.text}`);
513
+ }
514
+ }
515
+ out.push("");
516
+ out.push(`Validator (steps 1–${ont.step}): ${SYMBOL.error} ${count("error")} ${SYMBOL.warning} ${count("warning")} ${SYMBOL.info} ${count("info")} ${c.dim("okb validate for details")}`);
517
+ const cur = st.steps.find((s) => s.order === ont.step);
518
+ if (cur.complete && ont.step < st.steps.length)
519
+ out.push(c.green(`\nStep ${ont.step} looks done. When you're happy with it: okb step next`));
520
+ else if (st.suggested < ont.step)
521
+ out.push(c.yellow(`\nStep ${st.suggested} still has open items. It's fine to go back: okb step ${st.suggested}`));
522
+ else
523
+ out.push(c.dim(`\nSee the guide for this step: okb step`));
524
+ return out;
525
+ }
526
+ /** What `okb step <n>` prints after moving: a warning if the step you left isn't finished, then the new step's guide. */
527
+ export function renderStepMove(target, leaving) {
528
+ const out = [];
529
+ if (target > leaving.order && !leaving.complete) {
530
+ out.push(c.yellow(`Moving on with step ${leaving.order} unfinished (${leaving.items.filter((i) => i.done === false).map((i) => i.text).join("; ")}). That's allowed; the method is iterative.`));
531
+ }
532
+ out.push(c.cyan(`Now on step ${target}.`) + c.dim(` (To read a step's guide without moving: okb explain ${target})`) + "\n");
533
+ out.push(stepGuide(MetaKB.get().step(target)));
534
+ return out;
535
+ }
536
+ export function renderExplainHits(hits, q) {
537
+ if (!hits.length)
538
+ return [`Nothing called '${q}'. Try: okb explain --search ${q}`];
539
+ const out = [explain(hits[0])];
540
+ if (hits.length > 1)
541
+ out.push(c.dim(`\nAlso matches: ${hits.slice(1, 6).map(explainName).join(", ")}`));
542
+ return out;
543
+ }
544
+ export function renderSearchHits(hits, query) {
545
+ if (!hits.length)
546
+ return [`Nothing mentions '${query}'.`];
547
+ return hits.map((h) => `${(h.type === "Rule" ? h.key : h.id).padEnd(40)} ${c.dim(h.type)} ${h.type === "Rule" ? h.statement.slice(0, 60) : h.name}`);
548
+ }
549
+ /** `okb review` lists this many prompts per rule in the terminal; --json has them all. */
550
+ const REVIEW_PROMPTS_SHOWN = 12;
551
+ export function renderReview(ont, items, all) {
552
+ const out = [c.bold(all ? "Review: what only a person can judge (all rules)" : `Review: what only a person can judge (step ${ont.step} and anything already visible)`) + "\n"];
553
+ for (const it of items) {
554
+ out.push(`${SYMBOL.ask} ${c.bold(it.rule)} ${c.dim(`(${it.modality.replace("_", " ")})`)} ${it.question}`);
555
+ for (const f of it.flags)
556
+ out.push(` ${SYMBOL.warning} ${f}`);
557
+ for (const x of it.prompts.slice(0, REVIEW_PROMPTS_SHOWN))
558
+ out.push(` · ${x}`);
559
+ if (it.prompts.length > REVIEW_PROMPTS_SHOWN)
560
+ out.push(c.dim(` · ...and ${it.prompts.length - REVIEW_PROMPTS_SHOWN} more (okb review --json)`));
561
+ if (it.source)
562
+ out.push(c.dim(` ${it.source}`));
563
+ out.push("");
564
+ }
565
+ out.push(c.dim("Record answers that needed thought (or that someone might question later): okb decision add ..."));
566
+ return out;
567
+ }
568
+ export function renderSources(ont) {
569
+ const out = ont.ofType("Source").map((s) => `${c.bold(s.id)} ${s.title} ${c.dim(`(${s.format ?? "?"}, ${ont.sources(s.id, "PART_OF").length} quotes)`)} ${c.dim(s.localPath ?? s.url ?? "")}`);
570
+ if (!out.length)
571
+ out.push(c.dim("No sources yet. okb source add <file>"));
572
+ return out;
573
+ }
574
+ export function renderOutline(src, doc, blocks, quoted, onlyProblems) {
575
+ const out = [c.bold(`${doc.title ?? src.id}`) + c.dim(` ${src.localPath} · ${doc.blocks.length} blocks, ${doc.blocks.filter((b) => b.quotable).length} quotable`)];
576
+ if (doc.problems.length) {
577
+ out.push(c.yellow(`\n${doc.problems.length} problem(s) in the document:`));
578
+ for (const pr of doc.problems)
579
+ out.push(c.yellow(` line ${pr.line}: ${pr.message}`));
580
+ }
581
+ if (onlyProblems)
582
+ return out;
583
+ let lastPath = "";
584
+ for (const b of blocks) {
585
+ const pth = b.headingPath.join(" > ");
586
+ if (pth !== lastPath) {
587
+ out.push("\n" + c.bold(pth || "(top)"));
588
+ lastPath = pth;
589
+ }
590
+ const mark = !b.quotable ? c.dim("·") : quoted.has(b.startLine) ? SYMBOL.ok : SYMBOL.todo;
591
+ const where = `L${b.startLine}${b.endLine > b.startLine ? `-${b.endLine}` : ""}`.padEnd(9);
592
+ const label = b.kind === "code" ? c.dim(`code (${b.lang || "text"}), not quotable`) : b.kind === "comment" ? c.dim("comment") : b.kind === "frontmatter" ? c.dim("frontmatter") : (b.calloutType ? c.cyan(`[${b.calloutType}] `) : "") + b.text.slice(0, 110) + (b.text.length > 110 ? "…" : "");
593
+ out.push(` ${mark} ${c.dim(where)} ${c.dim(b.kind.padEnd(10))} ${label}${b.note?.startsWith("malformed") ? c.yellow(" ⚠ " + b.note) : ""}`);
594
+ }
595
+ out.push(c.dim(`\n${SYMBOL.ok} quoted ${SYMBOL.todo} not quoted yet · not quotable · okb quote add ${src.id} "..."`));
596
+ return out;
597
+ }
598
+ export function renderQuotes(ont, locs) {
599
+ return locs.map((l) => {
600
+ const by = ont.sources(l.id, "CITES").map((x) => ont.label(x));
601
+ return `${c.bold(l.id)} ${c.dim(`${l.locator}${l.lines ? `, line ${l.lines}` : ""}`)}\n "${l.quote}"${by.length ? c.dim(`\n cited by: ${by.join(", ")}`) : ""}`;
602
+ });
603
+ }
604
+ export function renderRules(ont) {
605
+ return ont.ofType("Rule").map((r) => {
606
+ const st = r.verification?.status ?? "unverified";
607
+ return `${c.bold(r.id)} ${c.dim(`[${r.modality} · ${r.authored ? "authored · " : ""}${st}${r.extractionConfidence ? " · " + r.extractionConfidence : ""}]`)}\n ${r.statement}${c.dim(`\n governs: ${ont.targets(r.id, "GOVERNS").map((x) => ont.label(x)).join(", ") || "—"} · cites: ${ont.targets(r.id, "CITES").join(", ")}`)}`;
608
+ });
609
+ }
610
+ export function renderDrift(hits) {
611
+ if (!hits.length)
612
+ return [`${SYMBOL.ok} No near-duplicate quotes across different sources.`];
613
+ return hits.map((h) => `${SYMBOL.info} ${h.message}`);
614
+ }
615
+ export function renderReleaseVerify(r) {
616
+ if (r.ok)
617
+ return [`${SYMBOL.ok} ${r.id} ${r.version} matches its manifest (${r.checked} files).`];
618
+ return [
619
+ `${SYMBOL.error} ${r.id} ${r.version} doesn't match its manifest:`,
620
+ ...r.problems.map((pr) => ` - ${pr}`),
621
+ c.dim(" If the changes are intended, cut a new release: okb release <version>. If not, restore the files (git checkout)."),
622
+ ];
623
+ }
624
+ export function renderPin(version) {
625
+ return `${SYMBOL.ok} Pinned okb ${version} in okb.json. okb check warns anyone with an older okb, and the CI workflow installs this version.`;
626
+ }
627
+ export function renderSkillsInstall(dir, lines) {
628
+ return [`${SYMBOL.ok} Skills in ${dir}`, ...lines.map((l) => ` ${l}`), c.dim("\n Start a new Claude Code or Cursor session to load them.")];
629
+ }
630
+ export function renderSkillsStatus(dir, metaVersion, skills) {
631
+ const good = (s) => s === "current";
632
+ const out = [c.bold(`Skills in ${dir}`) + c.dim(` (okb meta-KB ${metaVersion})`)];
633
+ for (const s of skills)
634
+ out.push(` ${good(s.state) ? SYMBOL.ok : s.state === "missing" ? SYMBOL.todo : SYMBOL.warning} ${s.name.padEnd(26)} ${s.detail}`);
635
+ if (!skills.every((s) => good(s.state)))
636
+ out.push(c.dim("\n Fix it with: okb skills install"));
637
+ return out;
638
+ }
639
+ export function renderWrote(out, what, hint) {
640
+ return `${SYMBOL.ok} Wrote ${what} to ${out}${hint}.`;
641
+ }
642
+ export function renderStepGuide(order) {
643
+ return stepGuide(MetaKB.get().step(order));
644
+ }
645
+ export function renderDiagramWritten(out) {
646
+ return `Wrote ${out}. Open it in GitHub, VS Code (Markdown preview), or mermaid.live.`;
647
+ }
648
+ export function renderExportWritten(out, g, fmt) {
649
+ return [`Wrote ${out}: ${g.nodes.length} nodes, ${g.relationships.length} relationships (${fmt}).`, ...g.notes.map((n) => c.dim(" " + n))];
650
+ }
@@ -0,0 +1,98 @@
1
+ import type { Ontology, SourceBlock } from "@ontology-kit/reader";
2
+ import { type MdDoc } from "./markdown.js";
3
+ /** Which block a baseline or current record describes, plus its hash. */
4
+ export type BlockRecord = SourceBlock;
5
+ export declare const RESYNC_SCHEMA = "okb-resync/1";
6
+ export declare const hashText: (text: string) => string;
7
+ /** The records for a document's quotable blocks, in document order. */
8
+ export declare function blockRecords(doc: MdDoc): BlockRecord[];
9
+ export type Change = "new" | "changed" | "removed";
10
+ export interface WorklistItem {
11
+ /** Stable across runs while the block's text is unchanged: `<source id>:<first 12 hex of the hash>`. */
12
+ id: string;
13
+ source: string;
14
+ change: Change;
15
+ headingPath: string[];
16
+ blockKind: string;
17
+ /** Line range in the current document; null for a removed block. */
18
+ lines: [number, number] | null;
19
+ /** Hash of the current text; null for a removed block. */
20
+ hash: string | null;
21
+ /** Hash of the text the baseline recorded; null for a new block. */
22
+ oldHash: string | null;
23
+ preview: string | null;
24
+ oldPreview: string | null;
25
+ }
26
+ export interface BlockDiff {
27
+ change: Change;
28
+ old?: BlockRecord;
29
+ /** The index into the current list. */
30
+ current?: number;
31
+ }
32
+ /**
33
+ * Compare a baseline with the current blocks. Pure. A block whose hash is still present is unchanged, wherever it
34
+ * moved. What's left is paired up as "changed" (same place, similar text), and the rest is "new" or "removed".
35
+ */
36
+ export declare function diffBlocks(baseline: BlockRecord[], current: BlockRecord[]): BlockDiff[];
37
+ export interface Citer {
38
+ id: string;
39
+ type: string;
40
+ label: string;
41
+ }
42
+ export interface QuoteIssue {
43
+ source: string;
44
+ /** The SourceLocation id. */
45
+ quote: string;
46
+ text: string;
47
+ was: {
48
+ locator?: string;
49
+ lines?: string;
50
+ };
51
+ /** Nodes that cite the quote: rules, facts, classes. */
52
+ citedBy: Citer[];
53
+ }
54
+ export interface MovedQuote extends QuoteIssue {
55
+ now: {
56
+ locator?: string;
57
+ lines?: string;
58
+ };
59
+ }
60
+ export interface SourceStatus {
61
+ id: string;
62
+ path: string | null;
63
+ format: string | null;
64
+ /** "checked", or why the source couldn't be (no local file, file missing). */
65
+ state: "checked" | "unreadable";
66
+ problem?: string;
67
+ /** Whether the Source has baseline hashes to compare against. Only markdown sources do. */
68
+ baseline: boolean;
69
+ quotes: number;
70
+ moved: number;
71
+ gone: number;
72
+ }
73
+ export interface ResyncReport {
74
+ schema: typeof RESYNC_SCHEMA;
75
+ /** False when a quote is gone or a source can't be read: the KB no longer matches its documents. */
76
+ ok: boolean;
77
+ /** True when the current blocks were stored as the new baseline (`--record`). */
78
+ recorded: boolean;
79
+ sources: SourceStatus[];
80
+ gone: QuoteIssue[];
81
+ moved: MovedQuote[];
82
+ worklist: WorklistItem[];
83
+ }
84
+ export interface ResyncOptions {
85
+ /** Update moved quotes in `ont` (the quote's own lines and links). Never touches a quote that can't be found. */
86
+ write: boolean;
87
+ /** Also store the current blocks as the baseline. Implies `write`. */
88
+ record: boolean;
89
+ }
90
+ /**
91
+ * Re-locate every quote in every source and compare each markdown source's blocks to its baseline. `pages` is
92
+ * `loadSourcePages(ont)`. With `write` false nothing in `ont` changes.
93
+ */
94
+ export declare function resync(ont: Ontology, pages: Map<string, string[] | MdDoc | Error>, o: ResyncOptions): ResyncReport;
95
+ /** The human-readable report, as lines. */
96
+ export declare function renderResync(r: ResyncReport, o: {
97
+ dryRun: boolean;
98
+ }): string[];
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;