okforest 0.4.0 → 0.6.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.
package/README.md CHANGED
@@ -8,7 +8,7 @@ v0.2 trees.
8
8
  npx okforest validate . # exit 1 on errors; warnings never fail
9
9
  npx okforest validate . --format json # for CI and tools
10
10
  npx okforest inventory . # types, tags, keys, near-duplicates
11
- npx okforest init sales-okf --template company --owner jane@acme.example
11
+ npx okforest init sales-okf --template company --name "Sales knowledge"
12
12
  ```
13
13
 
14
14
  To also check D2 and Mermaid diagram syntax, install the optional packages
package/dist/cli.mjs CHANGED
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
- import { spawnSync } from "node:child_process";
4
3
  import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
5
4
  import { basename, join, resolve } from "node:path";
6
5
  import { fileURLToPath } from "node:url";
7
6
  import { parseArgs, styleText } from "node:util";
8
7
  import { buildInventory } from "@okforest/okf";
9
8
  import { readTree } from "@okforest/okf/node";
10
- import { ruleUrl, toReport, validate } from "@okforest/validate";
9
+ import { defaultRules, okfRules, ruleDocs, ruleUrl, toReport, validate } from "@okforest/validate";
11
10
  //#region src/io.ts
12
11
  /** Exit codes: 0 success, 1 validation errors, 2 usage or read problems. */
13
12
  const EXIT = {
@@ -52,7 +51,7 @@ function formatOption(value) {
52
51
  }
53
52
  //#endregion
54
53
  //#region src/commands/init.ts
55
- const HELP$3 = `Usage: okforest init [path] --template <name> [--owner <email>] [--tree <name>] [--title <title>]
54
+ const HELP$4 = `Usage: okforest init [path] --template <name> [--name <name>]
56
55
 
57
56
  Create a new OKF v0.2 tree at path (default: the current directory, which must
58
57
  be empty apart from .git) from a starter template. Starter concepts are drafts
@@ -60,19 +59,16 @@ for you to fill in.
60
59
 
61
60
  Options
62
61
  --template <name> Starter template (available: company).
63
- --owner <email> The tree's Owner, one person (default: git config user.email).
64
- --tree <name> The tree's short name (default: the folder name without -okf).
65
- --title <title> Display title (default: "<Tree> knowledge").
62
+ --name <name> The bundle's name, up to 100 characters
63
+ (default: "<Folder> knowledge", without a -okf suffix).
66
64
  `;
67
65
  async function initCommand(args, io) {
68
66
  const { values, path } = parseCommand(args, {
69
67
  template: { type: "string" },
70
- owner: { type: "string" },
71
- tree: { type: "string" },
72
- title: { type: "string" }
68
+ name: { type: "string" }
73
69
  });
74
70
  if (values.help) {
75
- io.stdout(HELP$3);
71
+ io.stdout(HELP$4);
76
72
  return EXIT.ok;
77
73
  }
78
74
  const templates = await listTemplates();
@@ -81,16 +77,12 @@ async function initCommand(args, io) {
81
77
  const target = resolve(io.cwd, path);
82
78
  const blocking = (await readdir(target).catch(() => [])).filter((name) => name !== ".git" && name !== ".DS_Store");
83
79
  if (blocking.length > 0) throw new UsageError(`${path} is not empty (${blocking.slice(0, 3).join(", ")}${blocking.length > 3 ? ", ..." : ""}).`);
84
- const owner = (typeof values.owner === "string" ? values.owner : gitEmail(target, io.cwd))?.replace(/^user:/, "").trim();
85
- if (!owner || /\s/.test(owner)) throw new UsageError(owner ? `--owner must be one identifier with no spaces (got \`${owner}\`).` : "Name the tree's Owner with --owner <email> (no git user.email is configured).");
86
- const tree = slug(typeof values.tree === "string" ? values.tree : basename(target).replace(/-okf$/, "")) || "company";
87
- const title = typeof values.title === "string" && values.title.trim() !== "" ? values.title.trim() : `${capitalize(tree)} knowledge`;
80
+ const name = typeof values.name === "string" ? values.name.trim() : `${capitalize(slug(basename(target).replace(/-okf$/, "")) || "company")} knowledge`;
81
+ if (name === "" || [...name].length > 100) throw new UsageError(`--name must be 1 to 100 characters (got ${[...name].length.toLocaleString("en-US")}).`);
88
82
  const now = /* @__PURE__ */ new Date();
89
83
  const tokens = {
90
- owner,
91
- tree,
92
- title,
93
- title_yaml: JSON.stringify(title),
84
+ name,
85
+ name_yaml: JSON.stringify(name),
94
86
  version: VERSION,
95
87
  date: now.toISOString().slice(0, 10),
96
88
  now: `${now.toISOString().slice(0, 19)}Z`
@@ -99,7 +91,7 @@ async function initCommand(args, io) {
99
91
  const where = path;
100
92
  const drafts = written.filter((f) => f.endsWith(".md") && !/(^|\/)(index|log|README)\.md$/.test(f));
101
93
  io.stdout(`Created a ${template} tree in ${where} (${written.length} files).\n\nNext steps
102
- 1. Review .okforest/tree.yaml (Owner: user:${owner}).\n 2. Fill in the draft concepts: ${drafts.join(", ")}.\n 3. Validate: npx okforest validate ${where}\n 4. Commit and push; the included workflow validates every pull request.
94
+ 1. Review .okforest/settings.yaml (name: ${name}).\n 2. Fill in the draft concepts: ${drafts.join(", ")}.\n 3. Validate: npx okforest validate ${where}\n 4. Commit and push; the included workflow validates every pull request.
103
95
  `);
104
96
  return EXIT.ok;
105
97
  }
@@ -127,15 +119,6 @@ async function copyTemplate(from, to, tokens) {
127
119
  await walk("");
128
120
  return written;
129
121
  }
130
- function gitEmail(target, cwd) {
131
- for (const dir of [target, cwd]) {
132
- const result = spawnSync("git", ["config", "user.email"], {
133
- cwd: dir,
134
- encoding: "utf8"
135
- });
136
- if (result.status === 0 && result.stdout.trim()) return result.stdout.trim();
137
- }
138
- }
139
122
  function slug(value) {
140
123
  return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
141
124
  }
@@ -158,7 +141,7 @@ async function loadTree(path, io) {
158
141
  }
159
142
  //#endregion
160
143
  //#region src/commands/inventory.ts
161
- const HELP$2 = `Usage: okforest inventory [path] [--format text|json]
144
+ const HELP$3 = `Usage: okforest inventory [path] [--format text|json]
162
145
 
163
146
  List every type, tag, and frontmatter key in use in the tree at path (default:
164
147
  the current directory), with counts, lifecycle and trust totals, and likely
@@ -170,7 +153,7 @@ Options
170
153
  async function inventoryCommand(args, io) {
171
154
  const { values, path } = parseCommand(args, { format: { type: "string" } });
172
155
  if (values.help) {
173
- io.stdout(HELP$2);
156
+ io.stdout(HELP$3);
174
157
  return EXIT.ok;
175
158
  }
176
159
  const format = formatOption(values.format);
@@ -215,6 +198,170 @@ function inventoryText(inventory, io) {
215
198
  return `${out.join("\n")}\n`;
216
199
  }
217
200
  //#endregion
201
+ //#region src/commands/rule.ts
202
+ const HELP$2 = `Usage: okforest rule [rule] [--format text|json]
203
+
204
+ Explain a rule: why it exists, an example that breaks it, what
205
+ \`okforest validate\` reports for it, and the fix. Without a rule, list every
206
+ rule with its severity.
207
+
208
+ Options
209
+ --format text|json Output format (default: text). JSON is for tools and agents.
210
+
211
+ Examples
212
+ okforest rule okf/type
213
+ okforest rule --format json okforest/slug
214
+ `;
215
+ const COLOR$1 = {
216
+ error: "red",
217
+ warning: "yellow",
218
+ info: "cyan"
219
+ };
220
+ /** Text is wrapped to this width, as a terminal shows it comfortably. */
221
+ const WIDTH = 80;
222
+ async function ruleCommand(args, io) {
223
+ const { values, positionals } = parseArgs({
224
+ args: [...args],
225
+ options: {
226
+ format: { type: "string" },
227
+ help: {
228
+ type: "boolean",
229
+ short: "h"
230
+ }
231
+ },
232
+ allowPositionals: true,
233
+ strict: true
234
+ });
235
+ if (values.help) {
236
+ io.stdout(HELP$2);
237
+ return EXIT.ok;
238
+ }
239
+ if (positionals.length > 1) throw new UsageError(`Expected one rule, got ${positionals.length}: ${positionals.join(" ")}`);
240
+ const format = formatOption(values.format);
241
+ const [id] = positionals;
242
+ if (id === void 0) {
243
+ io.stdout(format === "json" ? json(defaultRules.map(describe)) : list(io));
244
+ return EXIT.ok;
245
+ }
246
+ const rule = defaultRules.find((found) => found.id === id);
247
+ if (!rule) {
248
+ const near = closest(id);
249
+ throw new UsageError(`Unknown rule \`${id}\`.${near ? ` Did you mean \`${near}\`?` : ""} Run \`okforest rule\` to list them.`);
250
+ }
251
+ io.stdout(format === "json" ? json(describe(rule)) : explain(rule, io));
252
+ return EXIT.ok;
253
+ }
254
+ /** Which set a rule belongs to. */
255
+ const set = (rule) => okfRules.includes(rule) ? "OKF specification" : "OKForest conventions";
256
+ /** A rule as data: what `--format json` prints. */
257
+ function describe(rule) {
258
+ const docs = ruleDocs[rule.id];
259
+ return {
260
+ id: rule.id,
261
+ severity: rule.severity,
262
+ set: set(rule),
263
+ description: rule.description,
264
+ url: ruleUrl(rule.id),
265
+ ...docs && {
266
+ why: docs.why,
267
+ example: docs.example
268
+ }
269
+ };
270
+ }
271
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
272
+ /** Every rule, by set and then by ID (as the docs list them), with its
273
+ * severity and description. */
274
+ function list(io) {
275
+ const width = Math.max(...defaultRules.map((rule) => rule.id.length));
276
+ const out = [];
277
+ for (const name of ["OKF specification", "OKForest conventions"]) {
278
+ out.push(paint(io, "underline", name));
279
+ const rules = defaultRules.filter((found) => set(found) === name).sort((a, b) => a.id.localeCompare(b.id));
280
+ for (const rule of rules) out.push(` ${rule.id.padEnd(width)} ${paint(io, COLOR$1[rule.severity], rule.severity.padEnd(7))} ${rule.description}`);
281
+ out.push("");
282
+ }
283
+ out.push("Run `okforest rule <rule>` for why a rule exists and how to fix it.");
284
+ return `${out.join("\n")}\n`;
285
+ }
286
+ /** One rule, explained: what the text format prints. */
287
+ function explain(rule, io) {
288
+ const docs = ruleDocs[rule.id];
289
+ const heading = (text) => paint(io, "underline", text);
290
+ const out = [
291
+ `${paint(io, "bold", rule.id)} ${paint(io, COLOR$1[rule.severity], rule.severity)} ${paint(io, "dim", set(rule))}`,
292
+ "",
293
+ ...wrap(rule.description, ""),
294
+ ""
295
+ ];
296
+ const links = [];
297
+ if (docs) {
298
+ out.push(heading("Why"), ...wrap(plain(docs.why, links), " "), "");
299
+ const { file, fails, findings, fixed, fixedFile = file } = docs.example;
300
+ out.push(heading(`Example: ${file} breaks the rule`), ...block(fails), "");
301
+ out.push(heading("okforest validate reports"), ` ${file}`);
302
+ for (const finding of findings) {
303
+ const [at = "", ...message] = finding.split(" ");
304
+ out.push(` ${at === "-:-" ? "" : at} ${paint(io, COLOR$1[rule.severity], rule.severity.padEnd(7))} ${message.join(" ")}`);
305
+ }
306
+ out.push("");
307
+ if (fixed === void 0) out.push(heading("Nothing to fix"), "");
308
+ else {
309
+ const renamed = fixedFile === file ? "" : `, renamed to ${fixedFile}`;
310
+ out.push(heading(`Fixed${renamed}`), ...block(fixed), "");
311
+ }
312
+ }
313
+ if (links.length > 0) out.push(heading("Links"), ...links.map((url, i) => ` [${i + 1}] ${url}`), "");
314
+ out.push(`Docs: ${ruleUrl(rule.id)}`);
315
+ return `${out.join("\n")}\n`;
316
+ }
317
+ /** Markdown as terminal text: each link becomes `text [n]`, its URL listed
318
+ * under Links; bold is dropped; code spans keep their backticks. */
319
+ function plain(markdown, links) {
320
+ return markdown.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, text, url) => {
321
+ const known = links.indexOf(url);
322
+ return `${text} [${known === -1 ? links.push(url) : known + 1}]`;
323
+ }).replace(/\*\*([^*]+)\*\*/g, "$1");
324
+ }
325
+ /** A paragraph wrapped to WIDTH, each line indented. */
326
+ function wrap(text, indent) {
327
+ const lines = [];
328
+ let line = "";
329
+ for (const word of text.split(/\s+/)) if (line && indent.length + line.length + 1 + word.length > WIDTH) {
330
+ lines.push(`${indent}${line}`);
331
+ line = word;
332
+ } else line = line ? `${line} ${word}` : word;
333
+ if (line) lines.push(`${indent}${line}`);
334
+ return lines;
335
+ }
336
+ /** A file's text, indented as a block. */
337
+ const block = (text) => text.trimEnd().split("\n").map((line) => line ? ` ${line}` : "");
338
+ /** The rule ID nearest to a mistyped one, if any is close: the same name
339
+ * in the other set (`okf/slug` → `okforest/slug`), or one or two edits away. */
340
+ function closest(id) {
341
+ const name = id.split("/").pop() ?? id;
342
+ const sameName = defaultRules.find((rule) => rule.id.split("/").pop() === name);
343
+ if (sameName) return sameName.id;
344
+ let best;
345
+ for (const rule of defaultRules) {
346
+ const distance = edits(id, rule.id);
347
+ if (distance <= 2 && (!best || distance < best.distance)) best = {
348
+ id: rule.id,
349
+ distance
350
+ };
351
+ }
352
+ return best?.id;
353
+ }
354
+ /** Levenshtein distance. */
355
+ function edits(a, b) {
356
+ let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
357
+ for (let i = 1; i <= a.length; i++) {
358
+ const current = [i];
359
+ for (let j = 1; j <= b.length; j++) current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
360
+ previous = current;
361
+ }
362
+ return previous[b.length];
363
+ }
364
+ //#endregion
218
365
  //#region src/commands/validate.ts
219
366
  const HELP$1 = `Usage: okforest validate [path] [--format text|json]
220
367
 
@@ -269,18 +416,19 @@ function toText(result, io) {
269
416
  });
270
417
  out.push("");
271
418
  }
272
- out.push(...ruleDocs(result.findings, io));
419
+ out.push(...ruleDocs$1(result.findings, io));
273
420
  out.push(summary(result, io));
274
421
  return `${out.join("\n")}\n`;
275
422
  }
276
423
  /** Each rule that reported something, with its documentation page. */
277
- function ruleDocs(findings, io) {
424
+ function ruleDocs$1(findings, io) {
278
425
  const ids = [...new Set(findings.map((f) => f.ruleId))];
279
426
  if (ids.length === 0) return [];
280
427
  const width = Math.max(...ids.map((id) => id.length));
281
428
  return [
282
429
  paint(io, "underline", "Rule docs"),
283
430
  ...ids.map((id) => ` ${id.padEnd(width)} ${paint(io, "dim", ruleUrl(id))}`),
431
+ ` ${paint(io, "dim", "Run `okforest rule <rule>` for why and how to fix.")}`,
284
432
  ""
285
433
  ];
286
434
  }
@@ -298,7 +446,8 @@ const HELP = `okforest ${VERSION}: validate, inventory, and scaffold Open Knowle
298
446
  Usage
299
447
  okforest validate [path] [--format text|json]
300
448
  okforest inventory [path] [--format text|json]
301
- okforest init [path] --template company [--owner <email>] [--tree <name>] [--title <title>]
449
+ okforest init [path] --template company [--name <name>]
450
+ okforest rule [rule] [--format text|json]
302
451
 
303
452
  Commands
304
453
  validate Check a tree against OKF v0.2 and OKForest conventions.
@@ -306,6 +455,8 @@ Commands
306
455
  inventory List every type, tag, and frontmatter key in use, with counts
307
456
  and likely near-duplicates.
308
457
  init Create a new tree from a starter template (templates: company).
458
+ rule Explain a rule: why it exists, an example, and the fix.
459
+ Without a rule, list every rule.
309
460
 
310
461
  Options
311
462
  -h, --help Show help (also: okforest <command> --help)
@@ -320,7 +471,8 @@ Docs and source: https://github.com/okforest/cli
320
471
  const COMMANDS = {
321
472
  validate: validateCommand,
322
473
  inventory: inventoryCommand,
323
- init: initCommand
474
+ init: initCommand,
475
+ rule: ruleCommand
324
476
  };
325
477
  /** Run the CLI and return its exit code. */
326
478
  async function main(argv, io) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "okforest",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "The OKForest CLI: validate Open Knowledge Format (OKF) v0.2 trees, inventory their metadata, and scaffold new trees from templates.",
5
5
  "keywords": [
6
6
  "okf",
@@ -32,15 +32,15 @@
32
32
  "node": ">=22"
33
33
  },
34
34
  "dependencies": {
35
- "@okforest/okf": "0.4.0",
36
- "@okforest/validate": "0.4.0"
35
+ "@okforest/okf": "0.6.0",
36
+ "@okforest/validate": "0.6.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@types/node": "^26.6.5",
40
- "@vitest/coverage-v8": "^5.0.4",
40
+ "@vitest/coverage-v8": "^5.0.5",
41
41
  "tsdown": "^0.23.0",
42
42
  "typescript": "^7.0.2",
43
- "vitest": "^5.0.4"
43
+ "vitest": "^5.0.5"
44
44
  },
45
45
  "scripts": {
46
46
  "build": "tsdown",
@@ -0,0 +1,8 @@
1
+ # yaml-language-server: $schema=https://www.okforest.ai/schemas/settings.schema.json
2
+ # OKForest's settings for this bundle (an OKForest convention, not part of OKF).
3
+ # Every setting is optional: https://www.okforest.ai/docs/settings/
4
+ name: {{name_yaml}}
5
+ # description: What this bundle covers, in up to 4,000 characters.
6
+ # Markdown files that are not concepts; every other .md file is one.
7
+ ignore:
8
+ - README.md
@@ -1,4 +1,4 @@
1
- # {{title}}
1
+ # {{name}}
2
2
 
3
3
  An [Open Knowledge Format (OKF)](https://github.com/GoogleCloudPlatform/open-knowledge-format)
4
4
  v0.2 tree: one markdown file per concept, with YAML frontmatter.
@@ -7,7 +7,8 @@ v0.2 tree: one markdown file per concept, with YAML frontmatter.
7
7
  every other `.md` file is a concept.
8
8
  - The starter concepts are drafts (`status: draft`): fill them in, then remove
9
9
  the guidance comments.
10
- - Owner and Stewards are in [`.okforest/tree.yaml`](.okforest/tree.yaml).
10
+ - This README is not a concept: [`.okforest/settings.yaml`](.okforest/settings.yaml)
11
+ lists it under `ignore`.
11
12
  - Validate with `npx okforest validate .`; the workflow in
12
13
  `.github/workflows/okforest-validate.yml` runs it on every pull request.
13
14
 
@@ -1,15 +0,0 @@
1
- # yaml-language-server: $schema=https://www.okforest.ai/schemas/tree.schema.json
2
- # OKForest settings for this tree (an OKForest convention, not part of OKF).
3
- # Every setting: https://www.okforest.ai/docs/tree-settings/
4
- tree: {{tree}}
5
- title: {{title_yaml}}
6
- owner: user:{{owner}} # exactly one person, accountable for the tree
7
- # backup_owner: user:... # optional; acts for the Owner during absences
8
- stewards: # review and approve changes; groups are recommended
9
- - user: {{owner}}
10
- sensitivity_default: internal
11
- # Files that are not concepts, in addition to README.md, LICENSE.md,
12
- # CONTRIBUTING.md, CHANGELOG.md, SECURITY.md, and CODE_OF_CONDUCT.md at the
13
- # root. Globs are relative to the tree root.
14
- # ignore:
15
- # - FOLLOWUPS.md