okforest 0.14.1 → 0.16.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
@@ -1,14 +1,14 @@
1
1
  # okforest
2
2
 
3
3
  The OKForest CLI: validate, inventory, and scaffold
4
- [Open Knowledge Format (OKF)](https://github.com/GoogleCloudPlatform/open-knowledge-format)
5
- v0.2 trees.
4
+ [Open Knowledge Format (OKF)](https://github.com/open-knowledge-format/open-knowledge-format)
5
+ trees, 0.2 and 0.3.
6
6
 
7
7
  ```sh
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 --name "Sales knowledge"
11
+ npx okforest init sales-knowledge # a repository with an empty tree in okf/
12
12
  npx okforest rule okf/type # why a rule exists, and how to fix it
13
13
  npx okforest types init . # draft a JSON Schema for each type
14
14
  ```
package/dist/cli.mjs CHANGED
@@ -2,11 +2,10 @@
2
2
  import { createRequire } from "node:module";
3
3
  import { access, mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, join, posix, resolve } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
5
  import { parseArgs, styleText } from "node:util";
7
6
  import { TYPES_FOLDER, buildInventory, startPage } from "@okforest/okf";
8
7
  import { readTree } from "@okforest/okf/node";
9
- import { defaultRules, draftTypeSchema, okfRules, ruleDocs, ruleUrl, toReport, validate } from "@okforest/validate";
8
+ import { defaultRules, draftTypeSchema, okfRules, ruleDocs as ruleDocs$1, ruleUrl, toReport, validate } from "@okforest/validate";
10
9
  // src/io.ts
11
10
  /** Exit codes: 0 success, 1 validation errors, 2 usage or read problems. */
12
11
  const EXIT = {
@@ -19,9 +18,7 @@ var UsageError = class extends Error {};
19
18
  function paint(io, style, text) {
20
19
  return io.color ? styleText(style, text, { validateStream: false }) : text;
21
20
  }
22
- const packageRoot = new URL("../", import.meta.url);
23
21
  const VERSION = createRequire(import.meta.url)("../package.json").version;
24
- const TEMPLATES_DIR = new URL("templates/", packageRoot);
25
22
  // src/args.ts
26
23
  /** Parse a command's arguments: options plus at most one positional path. */
27
24
  function parseCommand(args, options) {
@@ -48,75 +45,294 @@ function formatOption(value) {
48
45
  if (value === "json") return "json";
49
46
  throw new UsageError(`--format must be \`text\` or \`json\` (got \`${String(value)}\`).`);
50
47
  }
48
+ /** The files of a new repository, by path. */
49
+ function starterFiles(name, date) {
50
+ const yamlName = JSON.stringify(name);
51
+ return {
52
+ ".github/dependabot.yaml": DEPENDABOT,
53
+ ".github/workflows/ci.yaml": CI,
54
+ ".gitignore": GITIGNORE,
55
+ ".betterleaks.toml": BETTERLEAKS,
56
+ "AGENTS.md": `# AGENTS.md
57
+
58
+ <!-- Started by \`okforest init\`. Make it yours: add how your team works with
59
+ this repository, and remove anything that doesn't apply. -->
60
+
61
+ ${name}: an [OKF 0.3](https://github.com/open-knowledge-format/open-knowledge-format)
62
+ bundle in \`okf/\`, managed with [OKForest](https://www.okforest.ai). People
63
+ read it to learn; AI assistants use it to answer questions. Write for both.
64
+
65
+ Everything outside \`okf/\` (this file, \`README.md\`, \`.github/\`,
66
+ \`.betterleaks.toml\`) is repository setup, not knowledge. Commands below run
67
+ from the repository root.
68
+
69
+ ## Before you finish
70
+
71
+ - \`npx okforest validate okf\` must report no errors. Fix warnings you
72
+ introduced. \`npx okforest rule <rule>\` explains any finding.
73
+ - Pull requests run a secret scan and the same validation
74
+ (\`.github/workflows/ci.yaml\`). The scan checks the whole git history, so a
75
+ secret must never be committed, even briefly.
76
+
77
+ ## Writing concepts
78
+
79
+ - One concept per file, in the folder for its area. File and folder names
80
+ are lowercase slugs: \`refund-policy.md\`.
81
+ - Start new pages from their type's template:
82
+ \`npx okforest new <Type> <path> --root okf --title "…" --description "…"\`.
83
+ The path is inside \`okf/\`, e.g. \`policies/refunds.md\`.
84
+ - Use the types defined in \`okf/.okforest/types/\`, spelled exactly (\`Policy\`,
85
+ not \`policy\`). If none fits, add a schema and template in the same change
86
+ and say why. Check \`npx okforest inventory okf\` before adding a type or
87
+ tag, to reuse an existing one.
88
+ - Every concept has a \`title\` and a one-sentence \`description\`. New or
89
+ unreviewed pages are \`status: draft\`.
90
+ - Link with standard markdown links, using absolute paths from the bundle
91
+ root (\`okf/\`): \`[refunds](/policies/refunds.md)\`.
92
+ - \`index.md\` and \`log.md\` are reserved names in every folder. Keep each
93
+ folder's \`index.md\` up to date when you add, rename, or remove a page, and
94
+ give a new folder its own \`index.md\`, listed in its parent's. Record notable
95
+ changes in \`okf/log.md\` under a \`## YYYY-MM-DD\` heading, newest first.
96
+
97
+ ## Accuracy
98
+
99
+ - Don't invent facts. If something is unknown, leave the guidance comment in
100
+ place and ask, rather than filling it in with a guess.
101
+ - When content comes from a document or site, cite it in \`sources\` and use
102
+ footnotes in the body.
103
+ - When you write content, set \`generated: { by: <agent>/<version>, at: <time> }\`.
104
+ Never add a \`verified\` entry for a person (\`human:…\`); only that person
105
+ can do that.
106
+
107
+ ## Secrets and personal data
108
+
109
+ - **Never write:** passwords, API keys, tokens, private keys, recovery codes,
110
+ bank account or routing numbers, card numbers, or anyone's government ID
111
+ number.
112
+ - **Instead,** record where a secret is kept (its password manager, vault,
113
+ and item), never the secret itself.
114
+ - **Keep personal data out:** no home addresses, personal phone numbers, pay,
115
+ performance reviews, or health information. Work names, job titles, and
116
+ roles are fine.
117
+ - If you find a secret already in the repository, don't just delete it: it
118
+ stays in the git history. Tell a person so it can be rotated.
119
+ `,
120
+ "README.md": `# ${name}
121
+
122
+ ${name}: an [Open Knowledge Format (OKF)](https://github.com/open-knowledge-format/open-knowledge-format)
123
+ 0.3 bundle in [\`okf/\`](okf/index.md), one markdown file per concept, with
124
+ YAML frontmatter. Start at [\`okf/index.md\`](okf/index.md).
125
+
126
+ ## Getting started
127
+
128
+ <!-- Delete this section once setup is done. -->
129
+
130
+ This repository was started with \`okforest init\`, which makes an empty tree.
131
+ For a company's knowledge, the
132
+ [company knowledge template](https://github.com/okforest/template-company-knowledge)
133
+ starts with its folders, types, and draft pages instead.
134
+
135
+ - [ ] Say what this knowledge covers, above, and in \`description\` in
136
+ \`okf/.okforest/settings.yaml\`.
137
+ - [ ] Add a folder for each area, with its own \`index.md\`, listed in
138
+ \`okf/index.md\`.
139
+ - [ ] Define your types: a schema and a template for each, in
140
+ \`okf/.okforest/types/\` ([Types](https://www.okforest.ai/docs/types/)).
141
+ - [ ] In the repository's settings, require the **Scan and Validate** check
142
+ before merging to \`main\`.
143
+ - [ ] Delete this section.
144
+
145
+ ## Layout
146
+
147
+ | Path | What it holds |
148
+ |---|---|
149
+ | \`okf/\` | The knowledge: one markdown file per concept |
150
+ | \`okf/.okforest/\` | OKForest settings, and each type's schema and template |
151
+ | \`AGENTS.md\` | Instructions for AI agents editing this repository |
152
+ | \`.github/\` | CI (secret scan and validation on every pull request) and Dependabot |
153
+
154
+ ## Working with it
155
+
156
+ \`\`\`sh
157
+ # Add a page, from its type's template when it has one
158
+ npx okforest new Policy policies/refunds.md --root okf \\
159
+ --title "Refunds" --description "When we give money back, and how."
160
+
161
+ # Check the bundle
162
+ npx okforest validate okf
163
+
164
+ # List the types, tags, and fields in use
165
+ npx okforest inventory okf
166
+ \`\`\`
167
+
168
+ New pages are drafts (\`status: draft\`): fill them in and mark them \`stable\`.
169
+ Never commit secrets; record where each is kept instead.
170
+ `,
171
+ [`okf/index.md`]: `---
172
+ okf_version: "0.3"
173
+ ---
174
+
175
+ # ${name}
176
+
177
+ <!-- List each folder and concept here, one a line:
178
+ * [Title](folder/index.md) - One sentence on what it holds. -->
179
+ `,
180
+ [`okf/log.md`]: `# Log
181
+
182
+ ## ${date}
183
+
184
+ * **Creation:** Started an empty tree with \`okforest init\`.
185
+ `,
186
+ [`okf/.okforest/settings.yaml`]: `# yaml-language-server: $schema=https://www.okforest.ai/schemas/settings.schema.json
187
+ # OKForest's settings for this bundle (an OKForest convention, not part of OKF).
188
+ # Every setting is optional: https://www.okforest.ai/docs/settings/
189
+ name: ${yamlName}
190
+ # description: What this bundle covers, in up to 4,000 characters.
191
+ `
192
+ };
193
+ }
194
+ const CI = `name: CI
195
+
196
+ on:
197
+ pull_request:
198
+ push:
199
+ branches: [main]
200
+ workflow_dispatch:
201
+
202
+ permissions:
203
+ contents: read
204
+
205
+ env:
206
+ # Pinned to the stable v1 line; Dependabot doesn't track this, so bump it by
207
+ # hand: https://github.com/betterleaks/betterleaks/releases
208
+ BETTERLEAKS_VERSION: "1.10.1"
209
+
210
+ jobs:
211
+ check:
212
+ name: Scan and Validate
213
+ runs-on: ubuntu-latest
214
+ steps:
215
+ - uses: actions/checkout@v7
216
+ with:
217
+ # Full history, so the secret scan sees every commit, not just the
218
+ # latest files.
219
+ fetch-depth: 0
220
+
221
+ - name: Install Betterleaks
222
+ run: |
223
+ set -euo pipefail
224
+ base="https://github.com/betterleaks/betterleaks/releases/download/v\${BETTERLEAKS_VERSION}"
225
+ archive="betterleaks_\${BETTERLEAKS_VERSION}_linux_x64.tar.gz"
226
+ curl -sSfLO "\${base}/\${archive}"
227
+ curl -sSfLO "\${base}/checksums.txt"
228
+ grep " \${archive}\\$" checksums.txt | sha256sum -c -
229
+ tar -xzf "\${archive}" betterleaks
230
+ sudo mv betterleaks /usr/local/bin/
231
+ betterleaks version
232
+
233
+ # Secrets first: a leaked secret must be rotated, whatever else is wrong.
234
+ # Fails the job if anything is found; --redact keeps secrets out of the log.
235
+ - name: Scan for Secrets
236
+ run: >-
237
+ betterleaks git .
238
+ --config .betterleaks.toml
239
+ --redact --verbose
240
+ --no-banner --no-color
241
+
242
+ # Runs only after the scan passes (GitHub's default: a failed step stops
243
+ # the job). Validation messages can quote a page's values (e.g. "got
244
+ # \`…\`"), which would put a secret in the log and annotations, where it
245
+ # outlives a history rewrite. Fixing a secret takes another push anyway.
246
+ # Annotates each finding on its file and line, lists them in the job
247
+ # summary, and checks D2 and Mermaid diagrams. Fails on OKF errors;
248
+ # warnings don't fail. https://github.com/okforest/validate-action
249
+ - name: OKForest Validate
250
+ uses: okforest/validate-action@v1
251
+ with:
252
+ path: okf
253
+ `;
254
+ const DEPENDABOT = `version: 2
255
+ updates:
256
+ # Keeps the actions in .github/workflows/ (checkout, OKForest Validate)
257
+ # up to date. The Betterleaks version in ci.yaml is a plain variable,
258
+ # which Dependabot doesn't track: bump it by hand.
259
+ - package-ecosystem: "github-actions"
260
+ directory: "/"
261
+ schedule:
262
+ interval: "monthly"
263
+ groups:
264
+ github-actions:
265
+ patterns: ["*"]
266
+ open-pull-requests-limit: 10
267
+ `;
268
+ const GITIGNORE = `.DS_Store
269
+ node_modules/
270
+ `;
271
+ const BETTERLEAKS = `# Betterleaks config: the built-in rules plus one for passwords written in text.
272
+ # Loaded with --config by .github/workflows/ci.yaml; Betterleaks does not load
273
+ # this file automatically.
274
+ [extend]
275
+ useDefault = true
276
+
277
+ # The built-in generic-password rule expects code or config ("password = x").
278
+ # This one also catches how people write passwords in markdown: in prose
279
+ # ("the password is x"), bold labels ("**Password:** x"), table cells
280
+ # ("| password | x |"), and after a dash ("password — x").
281
+ [[rules]]
282
+ id = "prose-password"
283
+ description = "A password written out in text (keep it in a password manager and record where instead)"
284
+ regex = '''(?i)\\bpass(?:word|phrase|code)s?\\b[^\\n|]{0,30}?(?:\\bis\\b|:|=|—|–|\\|)[\\s*_|]*["'\`]?([^\\s"'\`*|]{8,})'''
285
+ secretGroup = 1
286
+ entropy = 3.0
287
+ keywords = ["password", "passphrase", "passcode"]
288
+ # A link or a path after "password:" is where to go, not the password.
289
+ filter = '''
290
+ matchesAny(finding["secret"], [\`^/\`, \`://\`])
291
+ '''
292
+ `;
51
293
  // src/commands/init.ts
52
- const HELP$6 = `Usage: okforest init [path] --template <name> [--name <name>]
294
+ /** The template repository a company tree starts from. */
295
+ const COMPANY_TEMPLATE = "okforest/template-company-knowledge";
296
+ const HELP$6 = `Usage: okforest init [path] [--name <name>]
53
297
 
54
- Create a new OKF v0.2 tree at path (default: the current directory, which must
55
- be empty apart from .git) from a starter template. Starter concepts are drafts
56
- for you to fill in.
298
+ Create a repository for an OKF 0.3 tree at path (default: the current
299
+ directory, which must be empty apart from .git): an empty bundle in okf/
300
+ (its index.md, log.md, and .okforest/settings.yaml), with a README.md, an
301
+ AGENTS.md for AI agents, a .gitignore, and GitHub workflows that scan for
302
+ secrets and validate every pull request. For a company's tree, with its
303
+ folders, types, and starter concepts, start from the template repository
304
+ instead: https://github.com/${COMPANY_TEMPLATE}
57
305
 
58
306
  Options
59
- --template <name> Starter template (available: company).
60
- --name <name> The bundle's name, up to 100 characters
61
- (default: "<Folder> knowledge", without a -okf suffix).
307
+ --name <name> The bundle's name, up to 100 characters (default:
308
+ "<Folder> knowledge", without an -okf or -knowledge
309
+ suffix).
62
310
  `;
63
311
  async function initCommand(args, io) {
64
- const { values, path } = parseCommand(args, {
65
- template: { type: "string" },
66
- name: { type: "string" }
67
- });
312
+ const { values, path } = parseCommand(args, { name: { type: "string" } });
68
313
  if (values.help) {
69
314
  io.stdout(HELP$6);
70
315
  return EXIT.ok;
71
316
  }
72
- const templates = await listTemplates();
73
- const template = values.template;
74
- if (typeof template !== "string" || !templates.includes(template)) throw new UsageError(`${template === void 0 ? "Choose" : `Unknown template \`${template}\`; choose`} a template with --template (${templates.join(", ")}).`);
75
317
  const target = resolve(io.cwd, path);
76
318
  const blocking = (await readdir(target).catch(() => [])).filter((name) => name !== ".git" && name !== ".DS_Store");
77
319
  if (blocking.length > 0) throw new UsageError(`${path} is not empty (${blocking.slice(0, 3).join(", ")}${blocking.length > 3 ? ", ..." : ""}).`);
78
- const name = typeof values.name === "string" ? values.name.trim() : `${capitalize(slug$1(basename(target).replace(/-okf$/, "")) || "company")} knowledge`;
320
+ const name = typeof values.name === "string" ? values.name.trim() : `${capitalize(slug$1(basename(target).replace(/-(okf|knowledge)$/, "")) || "company")} knowledge`;
79
321
  if (name === "" || [...name].length > 100) throw new UsageError(`--name must be 1 to 100 characters (got ${[...name].length.toLocaleString("en-US")}).`);
80
- const now = /* @__PURE__ */ new Date();
81
- const tokens = {
82
- name,
83
- name_yaml: JSON.stringify(name),
84
- version: VERSION,
85
- date: now.toISOString().slice(0, 10),
86
- now: `${now.toISOString().slice(0, 19)}Z`
87
- };
88
- const written = await copyTemplate(fileURLToPath(new URL(`${template}/`, TEMPLATES_DIR)), target, tokens);
89
- const where = path;
90
- const drafts = written.filter((f) => f.endsWith(".md") && !/(^|\/)(index|log|README)\.md$/.test(f));
91
- io.stdout(`Created a ${template} tree in ${where} (${written.length} files).\n\nNext steps
92
- 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.
93
- `);
322
+ const files = starterFiles(name, (/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
323
+ for (const [rel, text] of Object.entries(files)) {
324
+ await mkdir(dirname(join(target, rel)), { recursive: true });
325
+ await writeFile(join(target, rel), text, { flag: "wx" });
326
+ }
327
+ const bundle = path === "." ? "okf" : `${path}/okf`;
328
+ io.stdout(`Created a repository for ${name} in ${path}, with an empty tree in ${bundle}/ (${Object.keys(files).length} files).\n\nNext steps
329
+ 1. Read README.md's setup checklist, and make AGENTS.md yours.
330
+ 2. Add concepts: npx okforest new <Type> <folder>/<name>.md --root ${bundle}\n 3. Validate: npx okforest validate ${bundle}\n 4. Commit and push; the included workflow scans and validates every pull request.
331
+
332
+ For a company's tree, with its folders, types, and starter concepts, start from
333
+ https://github.com/${COMPANY_TEMPLATE} instead.\n`);
94
334
  return EXIT.ok;
95
335
  }
96
- async function listTemplates() {
97
- return (await readdir(TEMPLATES_DIR, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
98
- }
99
- /** Copy a template directory, replacing `{{token}}` for known tokens only
100
- * (GitHub Actions' `${{ ... }}` expressions are left alone). */
101
- async function copyTemplate(from, to, tokens) {
102
- const written = [];
103
- const walk = async (dir) => {
104
- const entries = await readdir(join(from, dir), { withFileTypes: true });
105
- for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : 1)) {
106
- const rel = dir ? `${dir}/${entry.name}` : entry.name;
107
- if (entry.isDirectory()) {
108
- await walk(rel);
109
- continue;
110
- }
111
- const text = (await readFile(join(from, rel), "utf8")).replace(/\{\{(\w+)\}\}/g, (match, key) => Object.hasOwn(tokens, key) ? tokens[key] : match);
112
- await mkdir(join(to, dir), { recursive: true });
113
- await writeFile(join(to, rel), text, { flag: "wx" });
114
- written.push(rel);
115
- }
116
- };
117
- await walk("");
118
- return written;
119
- }
120
336
  function slug$1(value) {
121
337
  return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
122
338
  }
@@ -173,7 +389,7 @@ const REASONS = {
173
389
  function inventoryText(inventory, io) {
174
390
  const out = [];
175
391
  const { statuses: s, trustTiers: t } = inventory;
176
- out.push(`${inventory.concepts} concepts · ${inventory.types.length} types · ${inventory.tags.length} tags · ${inventory.keys.length} frontmatter keys`, `Status: ${s.stable} stable, ${s.draft} draft, ${s.deprecated} deprecated · Trust: ${t["human-reviewed"]} human-reviewed, ${t["machine-confirmed"]} machine-confirmed, ${t.unverified} unverified · ${inventory.stale} stale`);
392
+ out.push(`${inventory.concepts} concepts · ${inventory.types.length} types · ${inventory.tags.length} tags · ${inventory.keys.length} frontmatter keys`, `Status: ${s.stable} stable, ${s.draft} draft, ${s.deprecated} deprecated${s.unrecognized > 0 ? `, ${s.unrecognized} unrecognized` : ""} · Trust: ${t["human-reviewed"]} human-reviewed, ${t["machine-confirmed"]} machine-confirmed, ${t.unverified} unverified · ${inventory.stale} stale`);
177
393
  if (inventory.untyped > 0) out.push(paint(io, "yellow", `${inventory.untyped} concepts have no usable type`));
178
394
  const section = (title, counts) => {
179
395
  out.push("", paint(io, "bold", title));
@@ -196,8 +412,9 @@ function inventoryText(inventory, io) {
196
412
  // src/commands/validate.ts
197
413
  const HELP$4 = `Usage: okforest validate [path] [--format text|json]
198
414
 
199
- Check the OKF v0.2 tree at path (default: the current directory) against the
200
- OKF specification and OKForest conventions. Exits 1 when there are errors;
415
+ Check the OKF tree at path (default: the current directory) against the
416
+ OKF specification, by the version its root index.md declares (0.2, or 0.3),
417
+ and OKForest conventions. Exits 1 when there are errors;
201
418
  warnings and info are reported but never fail.
202
419
 
203
420
  Options
@@ -247,12 +464,12 @@ function toText(result, io) {
247
464
  });
248
465
  out.push("");
249
466
  }
250
- out.push(...ruleDocs$1(result.findings, io));
467
+ out.push(...ruleDocs(result.findings, io));
251
468
  out.push(summary(result, io));
252
469
  return `${out.join("\n")}\n`;
253
470
  }
254
471
  /** Each rule that reported something, with its documentation page. */
255
- function ruleDocs$1(findings, io) {
472
+ function ruleDocs(findings, io) {
256
473
  const ids = [...new Set(findings.map((f) => f.ruleId))];
257
474
  if (ids.length === 0) return [];
258
475
  const width = Math.max(...ids.map((id) => id.length));
@@ -278,8 +495,9 @@ from the type's template, ${TYPES_FOLDER}<type>.template.md, as written: its
278
495
  front matter in its order, its body, and its guidance. The title and
279
496
  description given replace the template's. A type without a template starts
280
497
  with just its type, title, and description. When the file's folder has an
281
- index.md, the new concept is listed in it. Then the new page is checked, so
282
- what's left to fill in shows at once.
498
+ index.md, the new concept is listed in it; a folder it creates gets an
499
+ index.md listing the page, and is listed in its parent's. Then the new page
500
+ is checked, so what's left to fill in shows at once.
283
501
 
284
502
  Options
285
503
  --title <title> The concept's title.
@@ -323,22 +541,39 @@ async function newCommand(args, io) {
323
541
  ...values.title !== void 0 && { title: values.title },
324
542
  ...values.description !== void 0 && { description: values.description }
325
543
  }, template);
544
+ const created = [];
545
+ for (let folder = posix.dirname(path); folder !== "."; folder = posix.dirname(folder)) if (!await exists(resolve(io.cwd, root, folder))) created.unshift(folder);
326
546
  await mkdir(dirname(target), { recursive: true });
327
547
  await writeFile(target, text, { flag: "wx" });
328
- const folder = posix.dirname(path);
329
- const index = folder === "." ? "index.md" : `${folder}/index.md`;
548
+ let entry = `* [${(values.title ?? name.slice(0, -3)).replace(/[[\]]/g, "\\$&")}](${name})${values.description ? ` - ${values.description}` : ""}`;
549
+ const written = [];
550
+ for (const folder of created.toReversed()) {
551
+ const heading = folderTitle(posix.basename(folder));
552
+ const index = `${folder}/index.md`;
553
+ await writeFile(resolve(io.cwd, root, index), `# ${heading}\n\n${entry}\n`, { flag: "wx" });
554
+ written.push(index);
555
+ entry = `* [${heading}](${posix.basename(folder)}/index.md)`;
556
+ }
557
+ const parent = posix.dirname(created[0] ?? path);
558
+ const index = parent === "." ? "index.md" : `${parent}/index.md`;
330
559
  const listed = tree.files.includes(index);
331
560
  if (listed) {
332
561
  const indexFile = resolve(io.cwd, root, index);
333
562
  const before = await readFile(indexFile, "utf8");
334
- const entry = `* [${(values.title ?? name.slice(0, -3)).replace(/[[\]]/g, "\\$&")}](${name})${values.description ? ` - ${values.description}` : ""}`;
335
563
  await writeFile(indexFile, `${before}${before === "" || before.endsWith("\n") ? "" : "\n"}${entry}\n`);
564
+ written.push(index);
336
565
  }
337
- io.stdout(`Created ${path} ${template ? `from ${template.path}` : `(${type} has no template in ${TYPES_FOLDER})`}${listed ? `, listed in ${index}` : ""}.\n\n`);
338
- const mine = (await validate(await loadTree(root, io))).findings.filter((f) => f.file === path || listed && f.file === index);
339
- if (mine.length > 0) io.stdout(toText(onlyThese(mine, listed ? 2 : 1), io));
566
+ io.stdout(`Created ${path} ${template ? `from ${template.path}` : `(${type} has no template in ${TYPES_FOLDER})`}${created.length > 0 ? `, with ${written.slice(0, created.length).toReversed().join(" and ")}` : ""}${listed ? `, listed in ${index}` : ""}.\n\n`);
567
+ const mine = (await validate(await loadTree(root, io))).findings.filter((f) => f.file === path || written.includes(f.file));
568
+ if (mine.length > 0) io.stdout(toText(onlyThese(mine, 1 + written.length), io));
340
569
  return EXIT.ok;
341
570
  }
571
+ /** A folder's title for its index, from its name: `customer-support` is
572
+ * "Customer support". */
573
+ function folderTitle(name) {
574
+ const words = name.replace(/[-_]+/g, " ").trim();
575
+ return (words.charAt(0).toUpperCase() + words.slice(1)).replace(/[[\]]/g, "\\$&");
576
+ }
342
577
  /** A result narrowed to the new page (and its index), counted again. */
343
578
  function onlyThese(findings, files) {
344
579
  const count = (severity) => findings.filter((f) => f.severity === severity).length;
@@ -411,7 +646,7 @@ async function ruleCommand(args, io) {
411
646
  const set = (rule) => okfRules.includes(rule) ? "OKF specification" : "OKForest conventions";
412
647
  /** A rule as data: what `--format json` prints. */
413
648
  function describe(rule) {
414
- const docs = ruleDocs[rule.id];
649
+ const docs = ruleDocs$1[rule.id];
415
650
  return {
416
651
  id: rule.id,
417
652
  severity: rule.severity,
@@ -441,7 +676,7 @@ function list(io) {
441
676
  }
442
677
  /** One rule, explained: what the text format prints. */
443
678
  function explain(rule, io) {
444
- const docs = ruleDocs[rule.id];
679
+ const docs = ruleDocs$1[rule.id];
445
680
  const heading = (text) => paint(io, "underline", text);
446
681
  const out = [
447
682
  `${paint(io, "bold", rule.id)} ${paint(io, COLOR[rule.severity], rule.severity)} ${paint(io, "dim", set(rule))}`,
@@ -614,22 +849,24 @@ function slug(type) {
614
849
  return type.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "") || "type";
615
850
  }
616
851
  // src/main.ts
617
- const HELP = `okforest ${VERSION}: validate, inventory, and scaffold Open Knowledge Format (OKF) v0.2 trees
852
+ const HELP = `okforest ${VERSION}: validate, inventory, and scaffold Open Knowledge Format (OKF) trees
618
853
 
619
854
  Usage
620
855
  okforest validate [path] [--format text|json]
621
856
  okforest inventory [path] [--format text|json]
622
- okforest init [path] --template company [--name <name>]
857
+ okforest init [path] [--name <name>]
623
858
  okforest new <type> <file> [--title <title>] [--description <text>]
624
859
  okforest rule [rule] [--format text|json]
625
860
  okforest types init [path] [--type <type>]... [--dry-run]
626
861
 
627
862
  Commands
628
- validate Check a tree against OKF v0.2 and OKForest conventions.
863
+ validate Check a tree against OKF, by the version it declares, and
864
+ OKForest conventions.
629
865
  Exits 1 when there are errors; warnings and info never fail.
630
866
  inventory List every type, tag, and frontmatter key in use, with counts
631
867
  and likely near-duplicates.
632
- init Create a new tree from a starter template (templates: company).
868
+ init Create an empty tree. For a company tree, start from
869
+ https://github.com/okforest/template-company-knowledge.
633
870
  new Create a concept of a type, from the type's template
634
871
  (.okforest/types/<type>.template.md) when it has one.
635
872
  rule Explain a rule: why it exists, an example, and the fix.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "okforest",
3
- "version": "0.14.1",
4
- "description": "The OKForest CLI: validate Open Knowledge Format (OKF) v0.2 trees, inventory their metadata, and scaffold new trees from templates.",
3
+ "version": "0.16.0",
4
+ "description": "The OKForest CLI: validate Open Knowledge Format (OKF) trees, 0.2 and 0.3, inventory their metadata, and scaffold new trees and pages.",
5
5
  "keywords": [
6
6
  "okf",
7
7
  "open-knowledge-format",
@@ -25,22 +25,21 @@
25
25
  },
26
26
  "files": [
27
27
  "dist",
28
- "templates",
29
28
  "NOTICE"
30
29
  ],
31
30
  "engines": {
32
31
  "node": ">=22"
33
32
  },
34
33
  "dependencies": {
35
- "@okforest/okf": "0.14.1",
36
- "@okforest/validate": "0.14.1"
34
+ "@okforest/okf": "0.16.0",
35
+ "@okforest/validate": "0.16.0"
37
36
  },
38
37
  "devDependencies": {
39
38
  "@types/node": "^26.6.6",
40
- "@vitest/coverage-v8": "^5.1.0",
39
+ "@vitest/coverage-v8": "^5.1.1",
41
40
  "tsdown": "^0.23.7",
42
41
  "typescript": "^7.0.2",
43
- "vitest": "^5.1.0"
42
+ "vitest": "^5.1.1"
44
43
  },
45
44
  "scripts": {
46
45
  "build": "tsdown",
@@ -1,20 +0,0 @@
1
- name: OKForest Validate
2
-
3
- on:
4
- pull_request:
5
- push:
6
- branches: [main]
7
-
8
- permissions:
9
- contents: read
10
-
11
- jobs:
12
- validate:
13
- runs-on: ubuntu-latest
14
- steps:
15
- - uses: actions/checkout@v7
16
- # Annotates each finding on its file and line, lists them all in the job
17
- # summary, and checks D2 and Mermaid diagram syntax. Fails on OKF errors;
18
- # warnings are reported without failing. Inputs and outputs:
19
- # https://github.com/okforest/validate-action
20
- - uses: okforest/validate-action@v1
@@ -1,8 +0,0 @@
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,26 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "title": "Customer Profile",
4
- "description": "A kind of customer the company serves well, and how to recognize one.",
5
- "type": "object",
6
- "properties": {
7
- "industries": {
8
- "type": "array",
9
- "items": { "type": "string" },
10
- "description": "The industries they work in."
11
- },
12
- "company_size": {
13
- "type": "string",
14
- "description": "How big they are, like 50 to 500 employees."
15
- },
16
- "regions": {
17
- "type": "array",
18
- "items": { "type": "string" },
19
- "description": "Where they are."
20
- },
21
- "buyer": {
22
- "type": "string",
23
- "description": "The role of the person who buys, like Head of Operations."
24
- }
25
- }
26
- }
@@ -1,21 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "title": "Organization",
4
- "description": "A company or other organization: what it does, and where and when it began. Named after schema.org's Organization.",
5
- "type": "object",
6
- "properties": {
7
- "website": {
8
- "type": "string",
9
- "format": "uri",
10
- "description": "Its website's address."
11
- },
12
- "founded": {
13
- "type": "integer",
14
- "description": "The year it was founded."
15
- },
16
- "headquarters": {
17
- "type": "string",
18
- "description": "Where it's based: a city and country."
19
- }
20
- }
21
- }
@@ -1,15 +0,0 @@
1
- # {{name}}
2
-
3
- An [Open Knowledge Format (OKF)](https://github.com/GoogleCloudPlatform/open-knowledge-format)
4
- v0.2 tree: one markdown file per concept, with YAML frontmatter.
5
-
6
- - Start at [`index.md`](index.md). `index.md` and `log.md` files are reserved;
7
- every other `.md` file is a concept.
8
- - The starter concepts are drafts (`status: draft`): fill them in, then remove
9
- the guidance comments.
10
- - This README is not a concept: [`.okforest/settings.yaml`](.okforest/settings.yaml)
11
- lists it under `ignore`.
12
- - Validate with `npx okforest validate .`; the workflow in
13
- `.github/workflows/okforest-validate.yaml` runs it on every pull request.
14
-
15
- Created with the [OKForest CLI](https://github.com/okforest/cli) `company` template.
@@ -1,3 +0,0 @@
1
- # Company
2
-
3
- * [Company overview](overview.md) - What the company does, why it exists, and who it serves.
@@ -1,28 +0,0 @@
1
- ---
2
- type: Organization
3
- title: Company overview
4
- description: What the company does, why it exists, and who it serves.
5
- tags: [company]
6
- status: draft
7
- # website: https://www.acme.example
8
- # founded: 2019
9
- # headquarters: Austin, United States
10
- generated: { by: okforest/{{version}}, at: {{now}} }
11
- ---
12
-
13
- # What we do
14
-
15
- <!-- One or two sentences: what the company does, and for whom. -->
16
-
17
- # Why we exist
18
-
19
- <!-- The mission: the problem the company solves and why it matters. -->
20
-
21
- # Products and services
22
-
23
- <!-- What the company sells. As the tree grows, give each product its own
24
- concept (for example under products/) and link to it from here. -->
25
-
26
- # Customers
27
-
28
- Who we serve is described in the [ideal customer profile](/customers/ideal-customer-profile.md).
@@ -1,30 +0,0 @@
1
- ---
2
- type: Customer Profile
3
- title: Ideal customer profile
4
- description: The customers the company serves best, and how to recognize them.
5
- tags: [customers, sales]
6
- status: draft
7
- # industries: [logistics, retail]
8
- # company_size: 50 to 500 employees
9
- # regions: [North America]
10
- # buyer: Head of Operations
11
- generated: { by: okforest/{{version}}, at: {{now}} }
12
- ---
13
-
14
- # Who they are
15
-
16
- <!-- Industry, size, region, and the role of the person who buys. -->
17
-
18
- # Problems we solve for them
19
-
20
- <!-- The pains that bring them to us, in their words. -->
21
-
22
- # Signs of a good fit
23
-
24
- <!-- What a promising prospect looks like. -->
25
-
26
- # Signs of a poor fit
27
-
28
- <!-- When to walk away, and why. -->
29
-
30
- See the [company overview](/company/overview.md) for what we offer.
@@ -1,3 +0,0 @@
1
- # Customers
2
-
3
- * [Ideal customer profile](ideal-customer-profile.md) - The customers the company serves best, and how to recognize them.
@@ -1,8 +0,0 @@
1
- ---
2
- okf_version: "0.2"
3
- ---
4
-
5
- # Company
6
-
7
- * [company](company/index.md) - Who the company is: what it does, why it exists, and what it offers.
8
- * [customers](customers/index.md) - Who the company serves, starting with the ideal customer profile.
@@ -1,4 +0,0 @@
1
- # Directory Update Log
2
-
3
- ## {{date}}
4
- * **Initialization**: Created the tree from the OKForest `company` template.