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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/check.js +21 -2
  2. package/dist/checks.js +23 -0
  3. package/dist/cli.js +11 -819
  4. package/dist/clidocs.d.ts +0 -2
  5. package/dist/clidocs.js +5 -27
  6. package/dist/command-table.d.ts +144 -0
  7. package/dist/command-table.js +85 -0
  8. package/dist/commands/documents.d.ts +3 -0
  9. package/dist/commands/documents.js +250 -0
  10. package/dist/commands/getting-started.d.ts +3 -0
  11. package/dist/commands/getting-started.js +135 -0
  12. package/dist/commands/housekeeping.d.ts +3 -0
  13. package/dist/commands/housekeeping.js +203 -0
  14. package/dist/commands/modeling.d.ts +3 -0
  15. package/dist/commands/modeling.js +467 -0
  16. package/dist/commands/planning.d.ts +3 -0
  17. package/dist/commands/planning.js +251 -0
  18. package/dist/commands/reviewing.d.ts +3 -0
  19. package/dist/commands/reviewing.js +234 -0
  20. package/dist/commands/skills.d.ts +3 -0
  21. package/dist/commands/skills.js +53 -0
  22. package/dist/commands.d.ts +10 -22
  23. package/dist/commands.js +15 -716
  24. package/dist/cqanswer.d.ts +51 -0
  25. package/dist/cqanswer.js +76 -0
  26. package/dist/export-changes.d.ts +40 -0
  27. package/dist/export-changes.js +115 -0
  28. package/dist/export-csv.d.ts +17 -0
  29. package/dist/export-csv.js +188 -0
  30. package/dist/export-eval-cases.d.ts +38 -0
  31. package/dist/export-eval-cases.js +40 -0
  32. package/dist/export.d.ts +33 -2
  33. package/dist/export.js +69 -11
  34. package/dist/help.d.ts +11 -2
  35. package/dist/help.js +51 -64
  36. package/dist/ops/admin.d.ts +1 -1
  37. package/dist/ops/admin.js +2 -1
  38. package/dist/ops/classes.js +2 -2
  39. package/dist/ops/common.d.ts +12 -2
  40. package/dist/ops/common.js +3 -0
  41. package/dist/ops/instances.js +2 -2
  42. package/dist/ops/links.d.ts +1 -1
  43. package/dist/ops/links.js +2 -1
  44. package/dist/ops/scope.d.ts +9 -2
  45. package/dist/ops/scope.js +19 -3
  46. package/dist/ops/slots.js +6 -6
  47. package/dist/provenance.d.ts +1 -1
  48. package/dist/provenance.js +3 -2
  49. package/dist/release.d.ts +4 -0
  50. package/dist/release.js +22 -3
  51. package/dist/render.d.ts +85 -1
  52. package/dist/render.js +244 -1
  53. package/dist/runner.d.ts +3 -0
  54. package/dist/runner.js +84 -0
  55. package/dist/skills.d.ts +19 -3
  56. package/dist/skills.js +129 -13
  57. package/dist/verifynote.d.ts +4 -3
  58. package/dist/verifynote.js +3 -2
  59. package/dist/workflows.d.ts +283 -0
  60. package/dist/workflows.js +270 -0
  61. package/meta-kb/data/edges.json +25 -0
  62. package/meta-kb/data/manifest.json +4 -4
  63. package/meta-kb/data/nodes.json +39 -2
  64. package/package.json +4 -3
  65. package/schema/node.schema.json +22 -1
  66. package/skills/build-domain-kb-from-docs/SKILL.md +2 -2
  67. package/skills/ontology-coach/SKILL.md +3 -3
  68. package/skills/ontology-maintainer/SKILL.md +2 -2
  69. package/skills/ontology-review/SKILL.md +2 -2
  70. package/skills/ontology-signoff/SKILL.md +2 -2
  71. package/templates/okb-check.yml +17 -1
package/dist/render.d.ts CHANGED
@@ -1,7 +1,14 @@
1
+ import type { Note } from "./ops.js";
1
2
  import { type Explainable, type MetaStep } from "./metakb.js";
2
- import { type Ontology, type OkbNode } from "@ontology-kit/reader";
3
+ import { type CompetencyQuestionNode, type DesignDecisionNode, type Ontology, type OkbNode, type SourceLocationNode, type SourceNode } from "@ontology-kit/reader";
3
4
  import { type Finding } from "./types.js";
5
+ import type { QueryResult } from "@ontology-kit/reader";
4
6
  import type { CheckReport } from "./check.js";
7
+ import type { MdDoc } from "./markdown.js";
8
+ import type { ReviewItem } from "./review.js";
9
+ import type { SkillState } from "./skills.js";
10
+ import type { computeStatus } from "./status.js";
11
+ type Status = ReturnType<typeof computeStatus>;
5
12
  export declare const c: {
6
13
  bold: (s: string) => string;
7
14
  dim: (s: string) => string;
@@ -31,3 +38,80 @@ export declare function show(ont: Ontology, n: OkbNode): string;
31
38
  export declare function mermaid(ont: Ontology): string;
32
39
  /** The `okb check` summary: one line per check, the problems under the ones that failed, and a verdict. */
33
40
  export declare function formatCheck(report: CheckReport, name: string): string;
41
+ /** A tip teaches rather than reports, so it is shown dimmed and indented. */
42
+ export declare function formatNotes(notes: readonly Note[]): string[];
43
+ export declare function renderInit(name: string, root: string, folder: string, guide: string): string[];
44
+ export declare function renderScope(m: Ontology["meta"]): string[];
45
+ export declare function renderConvention(ont: Ontology): string;
46
+ export declare function renderQuestions(ont: Ontology, qs: readonly CompetencyQuestionNode[]): string[];
47
+ export declare function renderTerms(ont: Ontology): string[];
48
+ export declare function renderReuse(ont: Ontology): string[];
49
+ export declare function renderDecisions(ont: Ontology, ds: readonly DesignDecisionNode[]): string[];
50
+ export declare function renderFindings(findings: Finding[], hiddenLater: number, ont: Ontology, opts: {
51
+ all?: boolean;
52
+ verbose?: boolean;
53
+ }): string[];
54
+ export declare function renderStatus(ont: Ontology, findings: Finding[], st: Status): string[];
55
+ /** What `okb step <n>` prints after moving: a warning if the step you left isn't finished, then the new step's guide. */
56
+ export declare function renderStepMove(target: number, leaving: {
57
+ order: number;
58
+ complete: boolean;
59
+ items: {
60
+ done: boolean | null;
61
+ text: string;
62
+ }[];
63
+ }): string[];
64
+ export declare function renderExplainHits(hits: readonly Explainable[], q: string): string[];
65
+ export declare function renderSearchHits(hits: readonly Explainable[], query: string): string[];
66
+ export declare function renderReview(ont: Ontology, items: ReviewItem[], all: boolean): string[];
67
+ export declare function renderSources(ont: Ontology): string[];
68
+ export declare function renderOutline(src: SourceNode, doc: MdDoc, blocks: MdDoc["blocks"], quoted: ReadonlyMap<number, unknown>, onlyProblems: boolean): string[];
69
+ export declare function renderQuotes(ont: Ontology, locs: readonly SourceLocationNode[]): string[];
70
+ export declare function renderRules(ont: Ontology): string[];
71
+ export declare function renderDrift(hits: readonly {
72
+ message: string;
73
+ }[]): string[];
74
+ export declare function renderReleaseVerify(r: {
75
+ ok: boolean;
76
+ id: string;
77
+ version: string;
78
+ checked: number;
79
+ problems: string[];
80
+ }): string[];
81
+ export declare function renderPin(version: string): string;
82
+ export declare function renderSkillsInstall(dir: string, lines: readonly string[]): string[];
83
+ export declare function renderSkillsStatus(dir: string, metaVersion: string, skills: readonly {
84
+ name: string;
85
+ state: SkillState;
86
+ detail: string;
87
+ }[]): string[];
88
+ export declare function renderWrote(out: string, what: string, hint: string): string;
89
+ export declare function renderStepGuide(order: number): string;
90
+ export declare function renderDiagramWritten(out: string): string;
91
+ export declare function renderChangeSetWritten(out: string, s: {
92
+ nodesAdded: number;
93
+ nodesChanged: number;
94
+ nodesRemoved: number;
95
+ relationshipsAdded: number;
96
+ relationshipsChanged: number;
97
+ relationshipsRemoved: number;
98
+ }): string[];
99
+ export declare function renderExportWritten(out: string, g: {
100
+ nodes: unknown[];
101
+ relationships: unknown[];
102
+ notes: string[];
103
+ }, fmt: string, files?: string[]): string[];
104
+ /** `okb export --format eval-cases` written to a file. */
105
+ export declare function renderEvalCasesWritten(out: string, e: {
106
+ kb: {
107
+ version: string | null;
108
+ };
109
+ cases: unknown[];
110
+ skipped: {
111
+ number: number;
112
+ }[];
113
+ notes: string[];
114
+ }): string[];
115
+ /** `okb query` as text: one line per hit, the kind in a heading. */
116
+ export declare function renderQueryResult(ont: Ontology, r: QueryResult): string[];
117
+ export {};
package/dist/render.js CHANGED
@@ -1,6 +1,6 @@
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";
3
+ import { MetaKB, explainName } from "./metakb.js";
4
4
  import { edgeProps, nodeLabel } from "@ontology-kit/reader";
5
5
  import {} from "./types.js";
6
6
  import * as naming from "./naming.js";
@@ -430,3 +430,246 @@ export function formatCheck(report, name) {
430
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
431
  return out.join("\n");
432
432
  }
433
+ // ---- Terminal output for the command records (src/commands/). Each returns lines; the runner prints them. ----
434
+ /** A tip teaches rather than reports, so it is shown dimmed and indented. */
435
+ export function formatNotes(notes) {
436
+ return notes.map((n) => (typeof n === "string" ? n : c.dim(" " + n.text)));
437
+ }
438
+ export function renderInit(name, root, folder, guide) {
439
+ return [`${SYMBOL.ok} Created ontology '${name}' in ${root}\n`, guide, c.dim(`\nNext: cd ${folder} && okb scope --domain "..." --purpose "..." --users "..."`)];
440
+ }
441
+ export function renderScope(m) {
442
+ const row = (k, val) => ` ${c.dim(k.padEnd(13))} ${Array.isArray(val) ? val.join(", ") || c.yellow("—") : val || c.yellow("—")}`;
443
+ 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)];
444
+ }
445
+ export function renderConvention(ont) {
446
+ const cv = ont.conventions;
447
+ return `Naming convention: classes ${cv.classCase} (${cv.classNumber}) · slots ${cv.slotCase}${cv.slotAffix !== "none" ? ` (${cv.slotAffix})` : ""} · instances ${cv.instanceCase ?? "free text"}`;
448
+ }
449
+ export function renderQuestions(ont, qs) {
450
+ if (!qs.length)
451
+ return [c.dim('No competency questions yet. okb cq add "..."')];
452
+ const out = [];
453
+ for (const q of qs) {
454
+ const needs = ont.targets(q.id, "NEEDS").map((n) => ont.label(n));
455
+ const num = ont.displayNumber(q);
456
+ out.push(`${c.bold(String(num).padEnd(3))} ${q.text} ${c.dim(`[${q.status ?? "draft"}]`)}`);
457
+ out.push(c.dim(` needs: ${needs.length ? needs.join(", ") : "(not linked yet: okb cq link " + num + " <Class|slot>...)"}`));
458
+ out.push(c.dim(` answer: ${q.answer ? q.answer.expect.join(", ") + (q.answer.match === "includes" ? " (and maybe more)" : "") : "(none stored: okb cq answer " + num + " --query '...' --expect ...)"}`));
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 renderChangeSetWritten(out, s) {
649
+ return [`Wrote ${out}: a change set (cypher). Nodes: ${s.nodesAdded} added, ${s.nodesChanged} changed, ${s.nodesRemoved} removed. Relationships: ${s.relationshipsAdded} added, ${s.relationshipsChanged} changed, ${s.relationshipsRemoved} removed.`];
650
+ }
651
+ export function renderExportWritten(out, g, fmt, files) {
652
+ const where = files ? `${out}/ (${files.join(", ")})` : out;
653
+ return [`Wrote ${where}: ${g.nodes.length} nodes, ${g.relationships.length} relationships (${fmt}).`, ...g.notes.map((n) => c.dim(" " + n))];
654
+ }
655
+ /** `okb export --format eval-cases` written to a file. */
656
+ export function renderEvalCasesWritten(out, e) {
657
+ const skipped = e.skipped.length ? `, skipped ${e.skipped.length} with no stored answer (${e.skipped.map((s) => s.number).join(", ")})` : "";
658
+ return [`Wrote ${out}: ${e.cases.length} eval cases${e.kb.version ? ` from release ${e.kb.version}` : ""}${skipped}.`, ...e.notes.map((n) => c.dim(" " + n))];
659
+ }
660
+ /** `okb query` as text: one line per hit, the kind in a heading. */
661
+ export function renderQueryResult(ont, r) {
662
+ if (!r.hits.length)
663
+ return [c.dim(`No ${r.kind} results.`)];
664
+ const out = [];
665
+ if (r.kind === "find")
666
+ for (const h of r.hits)
667
+ out.push(h.name);
668
+ else if (r.kind === "slots")
669
+ for (const h of r.hits)
670
+ out.push(`${h.name} ${c.dim(`(${h.relationship ? "relationship" : "property"}${h.valueType ? `, ${h.valueType}` : ""})`)}`);
671
+ else
672
+ for (const h of r.hits)
673
+ out.push(`${h.name}${h.type ? " " + c.dim(`(${h.type})`) : ""} ${c.dim(`from ${ont.label(h.from)}${h.depth > 1 ? `, hop ${h.depth}` : ""}${h.inheritedFrom ? `, inherited from ${ont.label(h.inheritedFrom)}` : ""}`)}`);
674
+ return out;
675
+ }
@@ -0,0 +1,3 @@
1
+ import { type Command, type Globals } from "./command-table.js";
2
+ /** Run one command line (without the program name) against the table. */
3
+ export declare function runCommand(commands: readonly Command[], argv: readonly string[], globals: Partial<Globals>): Promise<void>;
package/dist/runner.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The runners a command record uses through its `Ctx`: load the folder, change it under the
3
+ * lock, print. Records never touch the filesystem, the lock or `console` themselves.
4
+ */
5
+ import { mkdirSync, writeFileSync } from "node:fs";
6
+ import { dirname, resolve as resolvePath } from "node:path";
7
+ import { OkbError, Ontology } from "@ontology-kit/reader";
8
+ import { formatNotes } from "./render.js";
9
+ import { resolve, parseForm } from "./command-table.js";
10
+ function lines(text) {
11
+ return Array.isArray(text) ? text : [text];
12
+ }
13
+ function makeCtx(commands, opts, args, globals) {
14
+ const dir = globals.C ?? opts.C ?? ".";
15
+ const print = (text) => {
16
+ for (const l of lines(text))
17
+ console.log(l);
18
+ };
19
+ const say = (notes) => print(formatNotes(notes));
20
+ const edit = (fn) => Ontology.edit(dir, fn);
21
+ const json = globals.json ?? !!opts.json;
22
+ /** One clock read, save and print around `fn`, which may be async (`Ontology.edit` takes either). */
23
+ const mutateWith = (fn) => edit((ont) => {
24
+ const finish = (notes) => {
25
+ ont.save();
26
+ say(notes);
27
+ };
28
+ const notes = ont.tick(() => fn(ont));
29
+ return notes instanceof Promise ? notes.then(finish) : finish(notes);
30
+ });
31
+ return {
32
+ opts,
33
+ args,
34
+ json,
35
+ commands,
36
+ dir,
37
+ int(name) {
38
+ const x = opts[name];
39
+ if (x === undefined)
40
+ return undefined;
41
+ if (!/^\d+$/.test(x))
42
+ throw new OkbError(`--${name} needs a whole number (0 or more).`);
43
+ return Number(x);
44
+ },
45
+ load: () => Ontology.load(dir),
46
+ edit,
47
+ mutate(fn) {
48
+ mutateWith(fn);
49
+ },
50
+ async mutateAsync(fn) {
51
+ await mutateWith(fn);
52
+ },
53
+ emit(data, build) {
54
+ if (json)
55
+ console.log(JSON.stringify(data(), null, 2));
56
+ else {
57
+ const out = lines(build());
58
+ if (out.length)
59
+ print(out);
60
+ }
61
+ },
62
+ emitRaw(data, text) {
63
+ if (json)
64
+ console.log(JSON.stringify(data(), null, 2));
65
+ else
66
+ process.stdout.write(text());
67
+ },
68
+ say,
69
+ print,
70
+ printRaw: (text) => void process.stdout.write(text),
71
+ write: (path, text) => {
72
+ const full = resolvePath(path);
73
+ mkdirSync(dirname(full), { recursive: true });
74
+ writeFileSync(full, text);
75
+ },
76
+ exit: (code) => void (process.exitCode = code),
77
+ };
78
+ }
79
+ /** Run one command line (without the program name) against the table. */
80
+ export async function runCommand(commands, argv, globals) {
81
+ const { form, rest } = resolve(commands, argv);
82
+ const { opts, args } = parseForm(form, rest);
83
+ await form.run(makeCtx(commands, opts, args, globals));
84
+ }
package/dist/skills.d.ts CHANGED
@@ -37,16 +37,32 @@ export declare function skillsStatus(opts: SkillsOptions): {
37
37
  dir: string;
38
38
  skills: SkillReport[];
39
39
  };
40
+ /** Gives the answer to a question, or `undefined` when the input ended. Tests pass their own. */
41
+ export type Ask = (question: string) => Promise<string | undefined>;
42
+ /** Asks on the terminal, with `node:readline`. */
43
+ export declare const terminalAsk: Ask;
40
44
  export interface InstallOptions extends SkillsOptions {
41
45
  /** Copy the folders instead of linking to them. */
42
46
  copy?: boolean;
43
- /** Replace things that are not okb skills. */
47
+ /** Replace without asking. */
44
48
  force?: boolean;
49
+ /** Where answers come from. The default reads the terminal. */
50
+ ask?: Ask;
51
+ /** Whether there is a person to ask. The default is that both stdin and stdout are terminals. */
52
+ interactive?: boolean;
53
+ /** The clock for the backup folder's name. */
54
+ now?: () => Date;
45
55
  }
46
56
  export interface InstallResult {
47
57
  dir: string;
48
58
  /** What happened to each skill, one sentence each. */
49
59
  lines: string[];
60
+ /** Where each replaced folder was kept. */
61
+ backups: string[];
50
62
  }
51
- /** Installs the packaged skills. Checks everything first, so a refusal changes nothing. */
52
- export declare function installSkills(opts: InstallOptions): InstallResult;
63
+ /**
64
+ * Installs the packaged skills. Checks everything first, so a refusal or a "no" changes nothing. Something that would be replaced and might
65
+ * lose something (an older or edited copy, a folder that isn't this skill, a link to somewhere else) is shown and the person is asked,
66
+ * once per skill. Without a terminal it is refused unless `force`. A replaced folder is kept in `<dir>.backup/`.
67
+ */
68
+ export declare function installSkills(opts: InstallOptions): Promise<InstallResult>;
package/dist/skills.js CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { cpSync, lstatSync, existsSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, symlinkSync } from "node:fs";
7
7
  import { homedir } from "node:os";
8
+ import { createInterface } from "node:readline";
8
9
  import { dirname, join, resolve } from "node:path";
9
10
  import { fileURLToPath } from "node:url";
10
11
  import { OkbError } from "@ontology-kit/reader";
@@ -81,18 +82,111 @@ export function skillsStatus(opts) {
81
82
  const dir = resolve(opts.dir ?? defaultSkillsDir());
82
83
  return { dir, skills: packagedSkills().map((n) => inspect(n, dir, opts.metaVersion)) };
83
84
  }
84
- /** Installs the packaged skills. Checks everything first, so a refusal changes nothing. */
85
- export function installSkills(opts) {
85
+ /** Asks on the terminal, with `node:readline`. */
86
+ export const terminalAsk = (question) => new Promise((done) => {
87
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
88
+ let answered = false;
89
+ rl.on("close", () => {
90
+ if (!answered)
91
+ done(undefined);
92
+ });
93
+ rl.question(question, (answer) => {
94
+ answered = true;
95
+ rl.close();
96
+ done(answer);
97
+ });
98
+ });
99
+ /** Whether install must ask before replacing this: anything that isn't missing, current, a link to this okb or a broken link. */
100
+ function needsAsk(r) {
101
+ if (r.state === "foreign" || r.state === "modified" || r.state === "other-install")
102
+ return true;
103
+ return r.state === "stale" && r.how === "copy"; // a stale link into this okb loses nothing
104
+ }
105
+ /** Files that differ, only in the installed folder, only in the packaged one. */
106
+ function compare(found, source) {
107
+ const old = files(found);
108
+ const now = files(source);
109
+ return {
110
+ differ: old.filter((f) => now.includes(f) && !readFileSync(join(found, f)).equals(readFileSync(join(source, f)))),
111
+ onlyOld: old.filter((f) => !now.includes(f)),
112
+ onlyNew: now.filter((f) => !old.includes(f)),
113
+ };
114
+ }
115
+ /** Where a replaced folder is kept: a sibling of the skills folder, since a host loads every folder in it that has a SKILL.md. */
116
+ const backupRoot = (dir) => `${dir}.backup`;
117
+ const stamp = (d) => d.toISOString().replace(/\.\d+Z$/, "Z").replace(/[-:]/g, "");
118
+ /** Moves `from` to `to`, copying when they are on different filesystems. */
119
+ function moveTo(from, to) {
120
+ mkdirSync(dirname(to), { recursive: true });
121
+ try {
122
+ renameSync(from, to);
123
+ }
124
+ catch (err) {
125
+ if (err.code !== "EXDEV")
126
+ throw err;
127
+ cpSync(from, to, { recursive: true, verbatimSymlinks: true });
128
+ rmSync(from, { recursive: true, force: true });
129
+ }
130
+ }
131
+ /** What the person sees before the question: what is there, how it differs, what would change and what is kept. */
132
+ function explain(r, source, want, backup) {
133
+ const lines = [`${r.name}: ${r.path} is ${r.detail}.`];
134
+ let looked;
135
+ try {
136
+ looked = lstatSync(r.path).isSymbolicLink() ? realpathSync(r.path) : r.path;
137
+ if (!lstatSync(looked).isDirectory())
138
+ looked = undefined;
139
+ }
140
+ catch {
141
+ looked = undefined;
142
+ }
143
+ if (looked) {
144
+ const d = compare(looked, source);
145
+ if (d.differ.length)
146
+ lines.push(` Files that differ from the packaged skill: ${d.differ.join(", ")}`);
147
+ if (d.onlyOld.length)
148
+ lines.push(` Files only in the installed folder (the packaged skill doesn't have them): ${d.onlyOld.join(", ")}`);
149
+ if (d.onlyNew.length)
150
+ lines.push(` Files only in the packaged skill (missing from the installed one): ${d.onlyNew.join(", ")}`);
151
+ if (!d.differ.length && !d.onlyOld.length && !d.onlyNew.length)
152
+ lines.push(" Its files are the same as the packaged skill's.");
153
+ }
154
+ lines.push(` It would be replaced with ${want === "copy" ? "a copy of" : "a link to"} ${source}.`);
155
+ lines.push(backup ? ` The old one is moved, not deleted, and kept in ${backup}.` : " A link needs no backup: only the link is replaced, and what it points to isn't touched.");
156
+ return lines.join("\n");
157
+ }
158
+ /**
159
+ * Installs the packaged skills. Checks everything first, so a refusal or a "no" changes nothing. Something that would be replaced and might
160
+ * lose something (an older or edited copy, a folder that isn't this skill, a link to somewhere else) is shown and the person is asked,
161
+ * once per skill. Without a terminal it is refused unless `force`. A replaced folder is kept in `<dir>.backup/`.
162
+ */
163
+ export async function installSkills(opts) {
86
164
  const dir = resolve(opts.dir ?? defaultSkillsDir());
87
165
  const want = opts.copy ? "copy" : "link";
166
+ const interactive = opts.interactive ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY));
167
+ const ask = opts.ask ?? terminalAsk;
168
+ const at = stamp((opts.now ?? (() => new Date()))());
88
169
  const before = packagedSkills().map((n) => inspect(n, dir, opts.metaVersion));
89
- const refused = before.filter((r) => (r.state === "foreign" || r.state === "modified") && !opts.force);
90
- if (refused.length) {
91
- const why = refused.map((r) => ` ${r.path}: ${r.detail}`).join("\n");
92
- throw new OkbError(`Not installing: ${refused.length === 1 ? "this is" : "these are"} not okb's to replace.\n${why}\nNothing was changed. Move ${refused.length === 1 ? "it" : "them"} away, or run okb skills install --force to delete ${refused.length === 1 ? "it" : "them"} and put the ${want === "copy" ? "copies" : "links"} in place.`);
170
+ const toAsk = before.filter(needsAsk);
171
+ const backups = new Map();
172
+ for (const r of toAsk)
173
+ if (!lstatSync(r.path).isSymbolicLink())
174
+ backups.set(r.name, join(backupRoot(dir), `${r.name}-${at}`));
175
+ if (toAsk.length && !opts.force) {
176
+ if (!interactive) {
177
+ const why = toAsk.map((r) => ` ${r.path}: ${r.detail}`).join("\n");
178
+ const them = toAsk.length === 1 ? "it" : "them";
179
+ throw new OkbError(`Not installing: ${toAsk.length === 1 ? "this isn't" : "these aren't"} this package's to replace.\n${why}\nNothing was changed. Move ${them} away, run okb skills install in a terminal to be asked, or pass --force to replace ${them} and put the ${want === "copy" ? "copies" : "links"} in place. A replaced folder is kept in ${backupRoot(dir)}.`);
180
+ }
181
+ for (const r of toAsk) {
182
+ const answer = await ask(`${explain(r, join(PACKAGED_SKILLS_DIR, r.name), want, backups.get(r.name))}\nReplace it? (y/N) `);
183
+ if (!/^\s*(y|yes)\s*$/i.test(answer ?? ""))
184
+ throw new OkbError(`Not installing: the answer for ${r.name} wasn't y. Nothing was changed.`);
185
+ }
93
186
  }
94
187
  mkdirSync(dir, { recursive: true });
95
188
  const lines = [];
189
+ const kept = [];
96
190
  for (const r of before) {
97
191
  const source = join(PACKAGED_SKILLS_DIR, r.name);
98
192
  if (r.state === "current" && r.how === want) {
@@ -105,16 +199,38 @@ export function installSkills(opts) {
105
199
  cpSync(source, tmp, { recursive: true });
106
200
  else
107
201
  symlinkSync(source, tmp, "junction");
108
- // rm on a link removes the link, never the folder it points to.
109
- if (lstatOrUndefined(r.path))
110
- rmSync(r.path, { recursive: true, force: true });
111
- renameSync(tmp, r.path);
202
+ let note = "";
203
+ if (lstatOrUndefined(r.path)) {
204
+ // Move the old one aside, activate the new one, then dispose of the old: an interruption leaves one of them in place, never neither.
205
+ // Renaming a link moves the link, not its target.
206
+ const old = join(dir, `.${r.name}.okb-old-${process.pid}`);
207
+ rmSync(old, { recursive: true, force: true });
208
+ renameSync(r.path, old);
209
+ try {
210
+ renameSync(tmp, r.path);
211
+ }
212
+ catch (err) {
213
+ renameSync(old, r.path);
214
+ rmSync(tmp, { recursive: true, force: true });
215
+ throw err;
216
+ }
217
+ const backup = backups.get(r.name);
218
+ if (backup) {
219
+ moveTo(old, backup);
220
+ kept.push(backup);
221
+ note = `; the old one is kept in ${backup}`;
222
+ }
223
+ else
224
+ rmSync(old, { recursive: true, force: true }); // on a link this removes the link, not its target
225
+ }
226
+ else
227
+ renameSync(tmp, r.path);
112
228
  const verb = want === "copy" ? "copied" : "linked";
113
229
  const replaced = {
114
- missing: "", current: ` (was ${r.how === "link" ? "a link" : "a copy"})`, stale: ` (replaced ${r.how === "link" ? "an old link" : `a copy at version ${r.version}`})`,
115
- modified: " (replaced a modified copy)", "other-install": " (replaced a link to a different okb)", "broken-link": " (replaced a broken link)", foreign: " (replaced what was there, because of --force)",
230
+ missing: "", current: ` (was ${r.how === "link" ? "a link" : "a copy"})`, stale: ` (replaced ${r.how === "link" ? "an old link" : `a copy at version ${r.version}`}${note})`,
231
+ modified: ` (replaced a modified copy${note})`, "other-install": " (replaced a link to a different okb)", "broken-link": " (replaced a broken link)", foreign: ` (replaced what was there${note})`,
116
232
  };
117
233
  lines.push(`${r.name}: ${verb}${replaced[r.state]}`);
118
234
  }
119
- return { dir, lines };
235
+ return { dir, lines, backups: kept };
120
236
  }