okf-toolkit 0.1.0__py3-none-any.whl
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.
okf.py
ADDED
|
@@ -0,0 +1,869 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
okf-toolkit — CLI for working with Google's Open Knowledge Format (OKF) bundles.
|
|
4
|
+
|
|
5
|
+
OKF is an open, vendor-neutral format for representing knowledge as a directory
|
|
6
|
+
tree of markdown files with YAML frontmatter. Each file (except index.md and
|
|
7
|
+
log.md) is a self-contained "concept" with typed metadata.
|
|
8
|
+
|
|
9
|
+
Commands:
|
|
10
|
+
init Initialize a new OKF bundle directory
|
|
11
|
+
new Interactively create a new concept
|
|
12
|
+
validate Validate bundle structure and frontmatter
|
|
13
|
+
list List all concepts with type and description
|
|
14
|
+
show Display a single concept's frontmatter and body
|
|
15
|
+
index Auto-generate index.md files from frontmatter
|
|
16
|
+
search Full-text search across concept bodies
|
|
17
|
+
graph Output the concept link graph
|
|
18
|
+
stats Bundle statistics
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import argparse
|
|
22
|
+
import hashlib
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import sys
|
|
26
|
+
import textwrap
|
|
27
|
+
from datetime import datetime, timezone
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
import yaml
|
|
32
|
+
except ImportError:
|
|
33
|
+
yaml = None # type: ignore[assignment]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ── ANSI terminal helpers ────────────────────────────────────────────────
|
|
37
|
+
|
|
38
|
+
def _color(code: str, text: str) -> str:
|
|
39
|
+
return f"\033[{code}m{text}\033[0m" if sys.stdout.isatty() else text
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def green(text: str) -> str:
|
|
43
|
+
return _color("32", text)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def yellow(text: str) -> str:
|
|
47
|
+
return _color("33", text)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def red(text: str) -> str:
|
|
51
|
+
return _color("31", text)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def cyan(text: str) -> str:
|
|
55
|
+
return _color("36", text)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def bold(text: str) -> str:
|
|
59
|
+
return _color("1", text)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def dim(text: str) -> str:
|
|
63
|
+
return _color("2", text)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# ── Constants ────────────────────────────────────────────────────────────
|
|
67
|
+
|
|
68
|
+
RESERVED_NAMES = {"index.md", "log.md"}
|
|
69
|
+
REQUIRED_FRONTMATTER_FIELDS = {"type"}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# ── OKF Bundle helpers ───────────────────────────────────────────────────
|
|
73
|
+
|
|
74
|
+
def _find_md_files(bundle_path: Path) -> list[Path]:
|
|
75
|
+
"""Return all .md files in the bundle recursively, sorted."""
|
|
76
|
+
if not bundle_path.is_dir():
|
|
77
|
+
return []
|
|
78
|
+
files: list[Path] = []
|
|
79
|
+
for root, _dirs, _names in os.walk(str(bundle_path)):
|
|
80
|
+
for name in _names:
|
|
81
|
+
if name.endswith(".md"):
|
|
82
|
+
files.append(Path(root) / name)
|
|
83
|
+
return sorted(files)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _rel_path(bundle_path: Path, file_path: Path) -> str:
|
|
87
|
+
"""Return the path of *file_path* relative to *bundle_path*."""
|
|
88
|
+
return str(file_path.relative_to(bundle_path))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _read_file(path: Path) -> str | None:
|
|
92
|
+
"""Read a file as UTF-8. Return None on encoding errors."""
|
|
93
|
+
try:
|
|
94
|
+
return path.read_text(encoding="utf-8")
|
|
95
|
+
except UnicodeDecodeError:
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _parse_frontmatter(text: str) -> tuple[dict, str]:
|
|
100
|
+
"""
|
|
101
|
+
Split markdown text into (frontmatter_dict, body).
|
|
102
|
+
Returns ({}, text) if no valid frontmatter is found.
|
|
103
|
+
"""
|
|
104
|
+
if not text.startswith("---"):
|
|
105
|
+
return {}, text
|
|
106
|
+
# Find the closing ---. Must be on its own line.
|
|
107
|
+
# The first --- is at index 0. We search for "\n---\n" or "\n---$"
|
|
108
|
+
# to find the closing delimiter.
|
|
109
|
+
after_first = text[3:]
|
|
110
|
+
# Support both "---\n" and "--- " (inline) opening
|
|
111
|
+
if after_first.startswith("\n"):
|
|
112
|
+
rest = after_first[1:]
|
|
113
|
+
else:
|
|
114
|
+
# Opening --- not followed by newline — try to find closing anyway
|
|
115
|
+
rest = after_first
|
|
116
|
+
|
|
117
|
+
# Find the closing delimiter. It could be at position 0 (if opening was "---\n---")
|
|
118
|
+
# or elsewhere preceded by newline.
|
|
119
|
+
end = -1
|
|
120
|
+
skip = 3 # number of chars to skip past "---"
|
|
121
|
+
if rest.startswith("---"):
|
|
122
|
+
# Closing delimiter immediately after the opening
|
|
123
|
+
end = 0
|
|
124
|
+
skip = 3
|
|
125
|
+
else:
|
|
126
|
+
pos = rest.find("\n---")
|
|
127
|
+
if pos != -1:
|
|
128
|
+
end = pos
|
|
129
|
+
skip = 4 # skip \n + ---
|
|
130
|
+
|
|
131
|
+
if end == -1:
|
|
132
|
+
return {}, text
|
|
133
|
+
|
|
134
|
+
fm_str = rest[:end]
|
|
135
|
+
body = rest[end + skip:] # skip past the delimiter
|
|
136
|
+
body = body.lstrip("\n")
|
|
137
|
+
|
|
138
|
+
# If fm_str has no content, return empty dict + full original text as body
|
|
139
|
+
if not fm_str.strip():
|
|
140
|
+
return {}, body
|
|
141
|
+
|
|
142
|
+
try:
|
|
143
|
+
if yaml is None:
|
|
144
|
+
return {}, body
|
|
145
|
+
data = yaml.safe_load(fm_str)
|
|
146
|
+
if data is None:
|
|
147
|
+
fm_str_clean = fm_str.strip()
|
|
148
|
+
if not fm_str_clean:
|
|
149
|
+
return {}, body
|
|
150
|
+
return {}, body
|
|
151
|
+
if not isinstance(data, dict):
|
|
152
|
+
return {}, body
|
|
153
|
+
return data, body
|
|
154
|
+
except yaml.YAMLError:
|
|
155
|
+
return {}, text
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _get_bundle_id(path: Path) -> str:
|
|
159
|
+
"""
|
|
160
|
+
Return a stable, human-friendly identifier for a concept file.
|
|
161
|
+
Uses the path relative to the bundle root, minus the .md extension.
|
|
162
|
+
"""
|
|
163
|
+
return str(path.with_suffix("")).replace(os.sep, "/")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _find_markdown_links(text: str) -> list[str]:
|
|
167
|
+
"""
|
|
168
|
+
Extract all markdown link targets (wiki-style, standard, reference-style)
|
|
169
|
+
that point to .md files.
|
|
170
|
+
"""
|
|
171
|
+
links: list[str] = []
|
|
172
|
+
# Standard [text](target)
|
|
173
|
+
for m in re.finditer(r"\[([^\]]*)\]\(([^)]+)\)", text):
|
|
174
|
+
target = m.group(2).split("#")[0].split("?")[0]
|
|
175
|
+
if target.endswith(".md"):
|
|
176
|
+
links.append(target)
|
|
177
|
+
# Reference-style [text][ref] and [ref]: target
|
|
178
|
+
# Links defined at bottom with [ref]: target
|
|
179
|
+
for m in re.finditer(r"^\[([^\]]+)\]:\s*(\S+)", text, re.MULTILINE):
|
|
180
|
+
target = m.group(2).split("#")[0].split("?")[0]
|
|
181
|
+
if target.endswith(".md"):
|
|
182
|
+
links.append(target)
|
|
183
|
+
return links
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _resolve_link(source_path: Path, bundle_path: Path, target: str) -> Path | None:
|
|
187
|
+
"""
|
|
188
|
+
Resolve a markdown link target (which may be absolute or relative)
|
|
189
|
+
against the bundle root. Returns the absolute Path if it exists.
|
|
190
|
+
"""
|
|
191
|
+
if target.startswith("/"):
|
|
192
|
+
# Absolute from bundle root
|
|
193
|
+
candidate = (bundle_path / target.lstrip("/")).resolve()
|
|
194
|
+
else:
|
|
195
|
+
# Relative to the source file's directory
|
|
196
|
+
candidate = (source_path.parent / target).resolve()
|
|
197
|
+
if candidate.exists():
|
|
198
|
+
return candidate
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# ── Commands ─────────────────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
def cmd_init(args: argparse.Namespace) -> int:
|
|
205
|
+
"""Initialize a new OKF bundle at the given path."""
|
|
206
|
+
bundle = Path(args.path).resolve()
|
|
207
|
+
if bundle.exists():
|
|
208
|
+
if not bundle.is_dir():
|
|
209
|
+
print(red(f"Error: {bundle} exists and is not a directory"))
|
|
210
|
+
return 1
|
|
211
|
+
existing = list(bundle.iterdir())
|
|
212
|
+
if existing:
|
|
213
|
+
print(red(f"Error: {bundle} is not empty"))
|
|
214
|
+
return 1
|
|
215
|
+
else:
|
|
216
|
+
bundle.mkdir(parents=True, exist_ok=True)
|
|
217
|
+
|
|
218
|
+
index_path = bundle / "index.md"
|
|
219
|
+
log_path = bundle / "log.md"
|
|
220
|
+
|
|
221
|
+
if not index_path.exists():
|
|
222
|
+
index_path.write_text(
|
|
223
|
+
f"# {bundle.name}\n\n"
|
|
224
|
+
"<!-- OKF Bundle -- auto-generated index.md -->\n\n"
|
|
225
|
+
"## Sections\n\n"
|
|
226
|
+
"<!-- Add links to sections here -->\n",
|
|
227
|
+
encoding="utf-8",
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
if not log_path.exists():
|
|
231
|
+
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
232
|
+
log_path.write_text(
|
|
233
|
+
f"# Update Log\n\n## {timestamp}\n\n- Bundle initialized\n",
|
|
234
|
+
encoding="utf-8",
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
print(green(f"OKF bundle initialized at {bundle}"))
|
|
238
|
+
print(f" {index_path} (created)")
|
|
239
|
+
print(f" {log_path} (created)")
|
|
240
|
+
return 0
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def cmd_new(args: argparse.Namespace) -> int:
|
|
244
|
+
"""Interactively create a new concept in the bundle."""
|
|
245
|
+
bundle = Path(args.bundle).resolve()
|
|
246
|
+
if not bundle.is_dir():
|
|
247
|
+
print(red(f"Error: {bundle} is not a directory"))
|
|
248
|
+
return 1
|
|
249
|
+
|
|
250
|
+
concept_id = args.id
|
|
251
|
+
if not concept_id:
|
|
252
|
+
print(red("Error: concept id is required"))
|
|
253
|
+
return 1
|
|
254
|
+
|
|
255
|
+
# Prevent creating index.md or log.md as concepts
|
|
256
|
+
filename = os.path.basename(concept_id) if "/" not in concept_id else os.path.basename(concept_id.rstrip("/"))
|
|
257
|
+
md_filename = filename if filename.endswith(".md") else f"{filename}.md"
|
|
258
|
+
if md_filename in RESERVED_NAMES:
|
|
259
|
+
print(red(f"Error: '{md_filename}' is a reserved filename (cannot be a concept)"))
|
|
260
|
+
return 1
|
|
261
|
+
|
|
262
|
+
target_path = (bundle / concept_id).resolve()
|
|
263
|
+
if not target_path.suffix:
|
|
264
|
+
target_path = target_path.with_suffix(".md")
|
|
265
|
+
|
|
266
|
+
# Ensure parent dir exists
|
|
267
|
+
target_path.parent.mkdir(parents=True, exist_ok=True)
|
|
268
|
+
|
|
269
|
+
if target_path.exists():
|
|
270
|
+
print(yellow(f"Warning: {_rel_path(bundle, target_path)} already exists"))
|
|
271
|
+
overwrite = input("Overwrite? [y/N] ").strip().lower()
|
|
272
|
+
if overwrite != "y":
|
|
273
|
+
print("Aborted.")
|
|
274
|
+
return 0
|
|
275
|
+
|
|
276
|
+
# Interactive frontmatter input
|
|
277
|
+
print(cyan("Enter concept metadata (press Enter to skip optional fields):"))
|
|
278
|
+
concept_type = ""
|
|
279
|
+
while not concept_type.strip():
|
|
280
|
+
concept_type = input(f" {bold('type')} (required) [{green('e.g.')} BigQuery Table, Metric, Playbook]: ").strip()
|
|
281
|
+
if not concept_type:
|
|
282
|
+
print(red(" type is required"))
|
|
283
|
+
|
|
284
|
+
title = input(f" {bold('title')} [{green('optional')}]: ").strip()
|
|
285
|
+
description = input(f" {bold('description')} [{green('optional')}]: ").strip()
|
|
286
|
+
resource = input(f" {bold('resource')} [{green('optional')}]: ").strip()
|
|
287
|
+
tags_input = input(f" {bold('tags')} [{green('optional, comma-separated')}]: ").strip()
|
|
288
|
+
|
|
289
|
+
tags = []
|
|
290
|
+
if tags_input:
|
|
291
|
+
tags = [t.strip() for t in tags_input.split(",") if t.strip()]
|
|
292
|
+
|
|
293
|
+
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
294
|
+
|
|
295
|
+
# Build YAML frontmatter
|
|
296
|
+
fm: dict = {"type": concept_type, "timestamp": timestamp}
|
|
297
|
+
if title:
|
|
298
|
+
fm["title"] = title
|
|
299
|
+
if description:
|
|
300
|
+
fm["description"] = description
|
|
301
|
+
if resource:
|
|
302
|
+
fm["resource"] = resource
|
|
303
|
+
if tags:
|
|
304
|
+
fm["tags"] = tags
|
|
305
|
+
|
|
306
|
+
fm_str = yaml.dump(fm, default_flow_style=False, allow_unicode=True, sort_keys=False).strip()
|
|
307
|
+
|
|
308
|
+
header = f"# {title or concept_id}\n\n"
|
|
309
|
+
body_placeholder = "<!-- Add concept body here -->\n"
|
|
310
|
+
|
|
311
|
+
content = f"---\n{fm_str}\n---\n\n{header}{body_placeholder}"
|
|
312
|
+
target_path.write_text(content, encoding="utf-8")
|
|
313
|
+
|
|
314
|
+
rel = _rel_path(bundle, target_path)
|
|
315
|
+
print(green(f"Created concept: {rel}"))
|
|
316
|
+
return 0
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def cmd_validate(args: argparse.Namespace) -> int:
|
|
320
|
+
"""Validate an OKF bundle structure and frontmatter."""
|
|
321
|
+
bundle = Path(args.bundle).resolve()
|
|
322
|
+
if not bundle.is_dir():
|
|
323
|
+
print(red(f"Error: {bundle} is not a directory"))
|
|
324
|
+
return 1
|
|
325
|
+
|
|
326
|
+
md_files = _find_md_files(bundle)
|
|
327
|
+
if not md_files:
|
|
328
|
+
print(yellow(f"Warning: no markdown files found in {bundle}"))
|
|
329
|
+
return 0
|
|
330
|
+
|
|
331
|
+
errors = 0
|
|
332
|
+
warnings = 0
|
|
333
|
+
concept_count = 0
|
|
334
|
+
|
|
335
|
+
for fpath in md_files:
|
|
336
|
+
rel = _rel_path(bundle, fpath)
|
|
337
|
+
fname = fpath.name
|
|
338
|
+
|
|
339
|
+
# ── 1. UTF-8 encoding ──
|
|
340
|
+
raw = _read_file(fpath)
|
|
341
|
+
if raw is None:
|
|
342
|
+
print(red(f" UTF-8 ERROR: {rel}"))
|
|
343
|
+
errors += 1
|
|
344
|
+
continue
|
|
345
|
+
|
|
346
|
+
# ── 2. Reserved filenames as concepts ──
|
|
347
|
+
if fname in RESERVED_NAMES:
|
|
348
|
+
# index.md and log.md are allowed, but they must NOT have frontmatter with 'type'
|
|
349
|
+
fm, _body = _parse_frontmatter(raw)
|
|
350
|
+
if fm.get("type"):
|
|
351
|
+
print(red(f" RESERVED FILENAME with type: {rel}"))
|
|
352
|
+
errors += 1
|
|
353
|
+
continue # skip further validation for reserved files
|
|
354
|
+
|
|
355
|
+
# ── 3. YAML validity ──
|
|
356
|
+
fm, body = _parse_frontmatter(raw)
|
|
357
|
+
if not fm:
|
|
358
|
+
print(yellow(f" WARN: No frontmatter in {rel}"))
|
|
359
|
+
warnings += 1
|
|
360
|
+
continue
|
|
361
|
+
|
|
362
|
+
concept_count += 1
|
|
363
|
+
|
|
364
|
+
# ── 4. Required fields ──
|
|
365
|
+
for field in REQUIRED_FRONTMATTER_FIELDS:
|
|
366
|
+
if field not in fm:
|
|
367
|
+
print(red(f" MISSING required field '{field}': {rel}"))
|
|
368
|
+
errors += 1
|
|
369
|
+
|
|
370
|
+
# ── 5. Broken cross-links (warnings only) ──
|
|
371
|
+
links = _find_markdown_links(body)
|
|
372
|
+
for link in links:
|
|
373
|
+
resolved = _resolve_link(fpath, bundle, link)
|
|
374
|
+
if resolved is None:
|
|
375
|
+
print(yellow(f" WARN: Broken link '{link}' in {rel}"))
|
|
376
|
+
warnings += 1
|
|
377
|
+
|
|
378
|
+
# ── 6. Extra checks ──
|
|
379
|
+
if fm.get("tags") is not None and not isinstance(fm["tags"], list):
|
|
380
|
+
print(yellow(f" WARN: 'tags' should be a list in {rel}"))
|
|
381
|
+
warnings += 1
|
|
382
|
+
|
|
383
|
+
ts = fm.get("timestamp")
|
|
384
|
+
if ts is not None:
|
|
385
|
+
if isinstance(ts, str) and ts == "":
|
|
386
|
+
print(yellow(f" WARN: 'timestamp' is empty in {rel}"))
|
|
387
|
+
warnings += 1
|
|
388
|
+
|
|
389
|
+
print(f"\n{bold('Summary:')}")
|
|
390
|
+
print(f" Concepts: {concept_count}")
|
|
391
|
+
print(f" Errors: {red(str(errors)) if errors else green('0')}")
|
|
392
|
+
print(f" Warnings: {yellow(str(warnings)) if warnings else green('0')}")
|
|
393
|
+
|
|
394
|
+
if errors:
|
|
395
|
+
return 1
|
|
396
|
+
return 0
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def cmd_list(args: argparse.Namespace) -> int:
|
|
400
|
+
"""List all concepts with their type and description."""
|
|
401
|
+
bundle = Path(args.bundle).resolve()
|
|
402
|
+
if not bundle.is_dir():
|
|
403
|
+
print(red(f"Error: {bundle} is not a directory"))
|
|
404
|
+
return 1
|
|
405
|
+
|
|
406
|
+
md_files = _find_md_files(bundle)
|
|
407
|
+
if not md_files:
|
|
408
|
+
print(yellow(f"No markdown files found in {bundle}"))
|
|
409
|
+
return 0
|
|
410
|
+
|
|
411
|
+
found = 0
|
|
412
|
+
for fpath in md_files:
|
|
413
|
+
rel = _rel_path(bundle, fpath)
|
|
414
|
+
fname = fpath.name
|
|
415
|
+
if fname in RESERVED_NAMES:
|
|
416
|
+
continue
|
|
417
|
+
|
|
418
|
+
raw = _read_file(fpath)
|
|
419
|
+
if raw is None:
|
|
420
|
+
continue
|
|
421
|
+
|
|
422
|
+
fm, _body = _parse_frontmatter(raw)
|
|
423
|
+
if not fm or "type" not in fm:
|
|
424
|
+
continue
|
|
425
|
+
|
|
426
|
+
found += 1
|
|
427
|
+
ctype = fm.get("type", "?")
|
|
428
|
+
desc = str(fm.get("description", "")).strip()
|
|
429
|
+
if desc:
|
|
430
|
+
print(f" {bold(rel)} {dim(f'[{ctype}]')} {desc}")
|
|
431
|
+
else:
|
|
432
|
+
print(f" {bold(rel)} {dim(f'[{ctype}]')}")
|
|
433
|
+
|
|
434
|
+
if found == 0:
|
|
435
|
+
print(yellow("No concepts found (no markdown files with 'type' frontmatter)."))
|
|
436
|
+
|
|
437
|
+
print(f"\n{found} concept(s)")
|
|
438
|
+
return 0
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def cmd_show(args: argparse.Namespace) -> int:
|
|
442
|
+
"""Display a single concept's frontmatter and body."""
|
|
443
|
+
bundle = Path(args.bundle).resolve()
|
|
444
|
+
concept_id = args.id
|
|
445
|
+
|
|
446
|
+
if not bundle.is_dir():
|
|
447
|
+
print(red(f"Error: {bundle} is not a directory"))
|
|
448
|
+
return 1
|
|
449
|
+
|
|
450
|
+
# Resolve concept path: try as-is, then with .md suffix
|
|
451
|
+
target = (bundle / concept_id).resolve()
|
|
452
|
+
if not target.exists():
|
|
453
|
+
target = target.with_suffix(".md")
|
|
454
|
+
if not target.exists() or not target.is_file():
|
|
455
|
+
print(red(f"Error: concept '{concept_id}' not found in {bundle}"))
|
|
456
|
+
return 1
|
|
457
|
+
|
|
458
|
+
raw = _read_file(target)
|
|
459
|
+
if raw is None:
|
|
460
|
+
print(red(f"Error: {target} is not valid UTF-8"))
|
|
461
|
+
return 1
|
|
462
|
+
|
|
463
|
+
fm, body = _parse_frontmatter(raw)
|
|
464
|
+
rel = _rel_path(bundle, target)
|
|
465
|
+
|
|
466
|
+
print(f"\n{bold('Concept:')} {rel}")
|
|
467
|
+
print(f"{bold('Path:')} {target}")
|
|
468
|
+
|
|
469
|
+
if fm:
|
|
470
|
+
print(f"\n{bold('Frontmatter:')}")
|
|
471
|
+
# Pretty-print the frontmatter
|
|
472
|
+
fm_lines = yaml.dump(fm, default_flow_style=False, allow_unicode=True, sort_keys=False).strip()
|
|
473
|
+
for line in fm_lines.split("\n"):
|
|
474
|
+
print(f" {dim(line)}")
|
|
475
|
+
|
|
476
|
+
print(f"\n{bold('Body:')}")
|
|
477
|
+
if body.strip():
|
|
478
|
+
# Show first 50 lines
|
|
479
|
+
body_lines = body.split("\n")
|
|
480
|
+
for line in body_lines[:50]:
|
|
481
|
+
print(f" {line}")
|
|
482
|
+
if len(body_lines) > 50:
|
|
483
|
+
print(cyan(f" ... ({len(body_lines) - 50} more lines)"))
|
|
484
|
+
else:
|
|
485
|
+
print(dim(" (empty)"))
|
|
486
|
+
|
|
487
|
+
return 0
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def cmd_index(args: argparse.Namespace) -> int:
|
|
491
|
+
"""Auto-generate index.md files for all directories that contain concepts."""
|
|
492
|
+
bundle = Path(args.bundle).resolve()
|
|
493
|
+
if not bundle.is_dir():
|
|
494
|
+
print(red(f"Error: {bundle} is not a directory"))
|
|
495
|
+
return 1
|
|
496
|
+
|
|
497
|
+
md_files = _find_md_files(bundle)
|
|
498
|
+
|
|
499
|
+
# Collect concepts by parent directory
|
|
500
|
+
concepts_by_dir: dict[Path, list[Path]] = {}
|
|
501
|
+
for fpath in md_files:
|
|
502
|
+
rel = _rel_path(bundle, fpath)
|
|
503
|
+
if fpath.name in RESERVED_NAMES:
|
|
504
|
+
continue
|
|
505
|
+
raw = _read_file(fpath)
|
|
506
|
+
if raw is None:
|
|
507
|
+
continue
|
|
508
|
+
fm, _body = _parse_frontmatter(raw)
|
|
509
|
+
if not fm or "type" not in fm:
|
|
510
|
+
continue
|
|
511
|
+
parent = fpath.parent
|
|
512
|
+
if parent not in concepts_by_dir:
|
|
513
|
+
concepts_by_dir[parent] = []
|
|
514
|
+
concepts_by_dir[parent].append(fpath)
|
|
515
|
+
|
|
516
|
+
generated = 0
|
|
517
|
+
for parent_dir, concept_paths in sorted(concepts_by_dir.items()):
|
|
518
|
+
index_path = parent_dir / "index.md"
|
|
519
|
+
rel_parent = _rel_path(bundle, parent_dir) if parent_dir != bundle else "."
|
|
520
|
+
|
|
521
|
+
# Build index content
|
|
522
|
+
lines = [f"# {parent_dir.name}", ""]
|
|
523
|
+
lines.append(f"Auto-generated index for concepts in `{rel_parent}`.")
|
|
524
|
+
lines.append("")
|
|
525
|
+
|
|
526
|
+
for cp in sorted(concept_paths):
|
|
527
|
+
raw = _read_file(cp)
|
|
528
|
+
if raw is None:
|
|
529
|
+
continue
|
|
530
|
+
fm, _body = _parse_frontmatter(raw)
|
|
531
|
+
if not fm:
|
|
532
|
+
continue
|
|
533
|
+
ctype = fm.get("type", "?")
|
|
534
|
+
title = fm.get("title", cp.stem)
|
|
535
|
+
desc = str(fm.get("description", "")).strip()
|
|
536
|
+
link_rel = _rel_path(bundle, cp)
|
|
537
|
+
if desc:
|
|
538
|
+
lines.append(f"- [{title}]({link_rel}) — {desc} [{ctype}]")
|
|
539
|
+
else:
|
|
540
|
+
lines.append(f"- [{title}]({link_rel}) [{ctype}]")
|
|
541
|
+
|
|
542
|
+
lines.append("")
|
|
543
|
+
content = "\n".join(lines)
|
|
544
|
+
|
|
545
|
+
# Only write if content changed
|
|
546
|
+
if index_path.exists():
|
|
547
|
+
existing = index_path.read_text(encoding="utf-8")
|
|
548
|
+
if existing.strip() == content.strip():
|
|
549
|
+
continue
|
|
550
|
+
|
|
551
|
+
index_path.write_text(content, encoding="utf-8")
|
|
552
|
+
print(green(f" Generated: {_rel_path(bundle, index_path)}"))
|
|
553
|
+
generated += 1
|
|
554
|
+
|
|
555
|
+
if generated == 0:
|
|
556
|
+
print(yellow("No index.md files needed regeneration."))
|
|
557
|
+
else:
|
|
558
|
+
print(f"\n{generated} index.md file(s) generated.")
|
|
559
|
+
|
|
560
|
+
return 0
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def cmd_search(args: argparse.Namespace) -> int:
|
|
564
|
+
"""Full-text search across all concept bodies and frontmatter."""
|
|
565
|
+
bundle = Path(args.bundle).resolve()
|
|
566
|
+
query = args.q.lower()
|
|
567
|
+
if not bundle.is_dir():
|
|
568
|
+
print(red(f"Error: {bundle} is not a directory"))
|
|
569
|
+
return 1
|
|
570
|
+
if not query:
|
|
571
|
+
print(red("Error: search query is empty"))
|
|
572
|
+
return 1
|
|
573
|
+
|
|
574
|
+
md_files = _find_md_files(bundle)
|
|
575
|
+
results: list[tuple[str, str, str]] = [] # (rel_path, type, matched_snippet)
|
|
576
|
+
|
|
577
|
+
for fpath in md_files:
|
|
578
|
+
if fpath.name in RESERVED_NAMES:
|
|
579
|
+
continue
|
|
580
|
+
raw = _read_file(fpath)
|
|
581
|
+
if raw is None:
|
|
582
|
+
continue
|
|
583
|
+
# Search in entire file (frontmatter + body)
|
|
584
|
+
lower = raw.lower()
|
|
585
|
+
if query not in lower:
|
|
586
|
+
continue
|
|
587
|
+
fm, _body = _parse_frontmatter(raw)
|
|
588
|
+
ctype = fm.get("type", "?") if fm else "?"
|
|
589
|
+
rel = _rel_path(bundle, fpath)
|
|
590
|
+
|
|
591
|
+
# Extract snippet around the match
|
|
592
|
+
idx = lower.find(query)
|
|
593
|
+
start = max(0, idx - 40)
|
|
594
|
+
end = min(len(raw), idx + len(query) + 40)
|
|
595
|
+
snippet = raw[start:end].replace("\n", " ").strip()
|
|
596
|
+
if len(snippet) > 80:
|
|
597
|
+
snippet = "..." + snippet[:77] + "..."
|
|
598
|
+
|
|
599
|
+
results.append((rel, ctype, snippet))
|
|
600
|
+
|
|
601
|
+
if not results:
|
|
602
|
+
print(yellow(f'No results for "{args.q}".'))
|
|
603
|
+
return 0
|
|
604
|
+
|
|
605
|
+
for rel, ctype, snippet in results:
|
|
606
|
+
highlight = snippet.replace(query, yellow(query), 1) if snippet else ""
|
|
607
|
+
print(f" {bold(rel)} {dim(f'[{ctype}]')}")
|
|
608
|
+
print(f" {highlight}")
|
|
609
|
+
print()
|
|
610
|
+
|
|
611
|
+
print(f"{len(results)} match(es)")
|
|
612
|
+
return 0
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def cmd_graph(args: argparse.Namespace) -> int:
|
|
616
|
+
"""Output the concept link graph."""
|
|
617
|
+
bundle = Path(args.bundle).resolve()
|
|
618
|
+
if not bundle.is_dir():
|
|
619
|
+
print(red(f"Error: {bundle} is not a directory"))
|
|
620
|
+
return 1
|
|
621
|
+
|
|
622
|
+
md_files = _find_md_files(bundle)
|
|
623
|
+
concepts = {} # rel_path -> concept_id (display name)
|
|
624
|
+
edges = [] # (source_rel, target_rel)
|
|
625
|
+
|
|
626
|
+
# Build concept lookup + collect links
|
|
627
|
+
concept_paths = {}
|
|
628
|
+
for fpath in md_files:
|
|
629
|
+
if fpath.name in RESERVED_NAMES:
|
|
630
|
+
continue
|
|
631
|
+
raw = _read_file(fpath)
|
|
632
|
+
if raw is None:
|
|
633
|
+
continue
|
|
634
|
+
fm, body = _parse_frontmatter(raw)
|
|
635
|
+
if not fm or "type" not in fm:
|
|
636
|
+
continue
|
|
637
|
+
rel = _rel_path(bundle, fpath)
|
|
638
|
+
concepts[rel] = fm.get("title", _get_bundle_id(fpath))
|
|
639
|
+
concept_paths[rel] = fpath
|
|
640
|
+
|
|
641
|
+
links = _find_markdown_links(body)
|
|
642
|
+
for link in links:
|
|
643
|
+
resolved = _resolve_link(fpath, bundle, link)
|
|
644
|
+
if resolved:
|
|
645
|
+
try:
|
|
646
|
+
target_rel = _rel_path(bundle, resolved)
|
|
647
|
+
if target_rel in concepts or resolved.exists():
|
|
648
|
+
edges.append((rel, target_rel))
|
|
649
|
+
except ValueError:
|
|
650
|
+
pass
|
|
651
|
+
|
|
652
|
+
if not concepts:
|
|
653
|
+
print(yellow("No concepts found to graph."))
|
|
654
|
+
return 0
|
|
655
|
+
|
|
656
|
+
# Determine output format
|
|
657
|
+
fmt = getattr(args, "format", "mermaid")
|
|
658
|
+
|
|
659
|
+
if fmt == "mermaid":
|
|
660
|
+
print(bold("Mermaid Graph:"))
|
|
661
|
+
print("```mermaid")
|
|
662
|
+
print("graph LR")
|
|
663
|
+
for rel, title in sorted(concepts.items()):
|
|
664
|
+
# Create a safe node ID
|
|
665
|
+
node_id = f"n{abs(hash(rel)) % 10**9}"
|
|
666
|
+
safe_title = title.replace('"', "'")
|
|
667
|
+
print(f' {node_id}["{safe_title}"]')
|
|
668
|
+
for src, tgt in sorted(edges):
|
|
669
|
+
src_id = f"n{abs(hash(src)) % 10**9}"
|
|
670
|
+
tgt_id = f"n{abs(hash(tgt)) % 10**9}"
|
|
671
|
+
if src_id != tgt_id:
|
|
672
|
+
print(f" {src_id} --> {tgt_id}")
|
|
673
|
+
print("```")
|
|
674
|
+
|
|
675
|
+
elif fmt == "ascii":
|
|
676
|
+
print(bold("ASCII Link Graph:"))
|
|
677
|
+
for rel, title in sorted(concepts.items()):
|
|
678
|
+
print(f"\n {title}")
|
|
679
|
+
print(f" Path: {dim(rel)}")
|
|
680
|
+
outgoing = [(t, concepts.get(t, t)) for s, t in edges if s == rel]
|
|
681
|
+
if outgoing:
|
|
682
|
+
for _t, _ttl in outgoing:
|
|
683
|
+
print(f" ├──→ {_ttl}")
|
|
684
|
+
incoming = [(s, concepts.get(s, s)) for s, t in edges if t == rel]
|
|
685
|
+
if incoming:
|
|
686
|
+
for _s, _sttl in incoming:
|
|
687
|
+
print(f" ├──← {_sttl}")
|
|
688
|
+
|
|
689
|
+
print(f"\n{len(concepts)} concept(s), {len(edges)} edge(s)")
|
|
690
|
+
return 0
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def cmd_stats(args: argparse.Namespace) -> int:
|
|
694
|
+
"""Print bundle statistics."""
|
|
695
|
+
bundle = Path(args.bundle).resolve()
|
|
696
|
+
if not bundle.is_dir():
|
|
697
|
+
print(red(f"Error: {bundle} is not a directory"))
|
|
698
|
+
return 1
|
|
699
|
+
|
|
700
|
+
md_files = _find_md_files(bundle)
|
|
701
|
+
total_md = len(md_files)
|
|
702
|
+
|
|
703
|
+
types: dict[str, int] = {}
|
|
704
|
+
tags: dict[str, int] = {}
|
|
705
|
+
total_links = 0
|
|
706
|
+
total_size = 0
|
|
707
|
+
concept_count = 0
|
|
708
|
+
broken_links = 0
|
|
709
|
+
missing_fm = 0
|
|
710
|
+
|
|
711
|
+
for fpath in md_files:
|
|
712
|
+
size = fpath.stat().st_size
|
|
713
|
+
total_size += size
|
|
714
|
+
|
|
715
|
+
if fpath.name in RESERVED_NAMES:
|
|
716
|
+
continue
|
|
717
|
+
|
|
718
|
+
raw = _read_file(fpath)
|
|
719
|
+
if raw is None:
|
|
720
|
+
continue
|
|
721
|
+
|
|
722
|
+
fm, body = _parse_frontmatter(raw)
|
|
723
|
+
if not fm or "type" not in fm:
|
|
724
|
+
missing_fm += 1
|
|
725
|
+
continue
|
|
726
|
+
|
|
727
|
+
concept_count += 1
|
|
728
|
+
ctype = str(fm.get("type", "unknown"))
|
|
729
|
+
types[ctype] = types.get(ctype, 0) + 1
|
|
730
|
+
|
|
731
|
+
tag_list = fm.get("tags", [])
|
|
732
|
+
if isinstance(tag_list, list):
|
|
733
|
+
for t in tag_list:
|
|
734
|
+
t_str = str(t)
|
|
735
|
+
tags[t_str] = tags.get(t_str, 0) + 1
|
|
736
|
+
|
|
737
|
+
links = _find_markdown_links(body)
|
|
738
|
+
total_links += len(links)
|
|
739
|
+
for link in links:
|
|
740
|
+
if _resolve_link(fpath, bundle, link) is None:
|
|
741
|
+
broken_links += 1
|
|
742
|
+
|
|
743
|
+
# Build size representation
|
|
744
|
+
if total_size < 1024:
|
|
745
|
+
size_str = f"{total_size} B"
|
|
746
|
+
elif total_size < 1024 * 1024:
|
|
747
|
+
size_str = f"{total_size / 1024:.1f} KB"
|
|
748
|
+
else:
|
|
749
|
+
size_str = f"{total_size / 1024 / 1024:.1f} MB"
|
|
750
|
+
|
|
751
|
+
print(f"\n{bold('Bundle Statistics')}")
|
|
752
|
+
print(f" {bold('Bundle root:')} {bundle}")
|
|
753
|
+
print(f" {bold('Total files:')} {total_md}")
|
|
754
|
+
print(f" {bold('Concepts:')} {concept_count}")
|
|
755
|
+
print(f" {bold('No frontmatter:')} {missing_fm}")
|
|
756
|
+
print(f" {bold('Total size:')} {size_str}")
|
|
757
|
+
print()
|
|
758
|
+
|
|
759
|
+
if types:
|
|
760
|
+
print(f" {bold('By Type:')}")
|
|
761
|
+
for t, count in sorted(types.items(), key=lambda x: -x[1]):
|
|
762
|
+
bar = "█" * count
|
|
763
|
+
print(f" {t:25s} {count:3d} {bar}")
|
|
764
|
+
print()
|
|
765
|
+
|
|
766
|
+
if tags:
|
|
767
|
+
print(f" {bold('Tags Cloud:')}")
|
|
768
|
+
max_tag_len = max(len(t) for t in tags)
|
|
769
|
+
# Sort by frequency desc, then alphabetically
|
|
770
|
+
sorted_tags = sorted(tags.items(), key=lambda x: (-x[1], x[0]))
|
|
771
|
+
for t, count in sorted_tags:
|
|
772
|
+
bar = "▓" * count
|
|
773
|
+
print(f" {t:{max_tag_len}s} {count:3d} {bar}")
|
|
774
|
+
print()
|
|
775
|
+
|
|
776
|
+
print(f" {bold('Links:')} {total_links} total, {broken_links} broken")
|
|
777
|
+
return 0
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
# ── Main CLI ─────────────────────────────────────────────────────────────
|
|
781
|
+
|
|
782
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
783
|
+
parser = argparse.ArgumentParser(
|
|
784
|
+
prog="okf",
|
|
785
|
+
description="okf-toolkit — CLI for Google's Open Knowledge Format (OKF)",
|
|
786
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
787
|
+
epilog=textwrap.dedent("""\
|
|
788
|
+
See https://github.com/akdira/okf-toolkit for full documentation.
|
|
789
|
+
Report issues at https://github.com/akdira/okf-toolkit/issues.
|
|
790
|
+
Created by akdira — https://www.akdira.id
|
|
791
|
+
"""),
|
|
792
|
+
)
|
|
793
|
+
parser.add_argument("--version", action="store_true", help="Show version and exit")
|
|
794
|
+
|
|
795
|
+
sub = parser.add_subparsers(dest="command", title="Commands")
|
|
796
|
+
|
|
797
|
+
p_init = sub.add_parser("init", help="Initialize a new OKF bundle")
|
|
798
|
+
p_init.add_argument("path", help="Directory path for the new bundle")
|
|
799
|
+
|
|
800
|
+
p_new = sub.add_parser("new", help="Create a new concept interactively")
|
|
801
|
+
p_new.add_argument("bundle", help="Path to the OKF bundle")
|
|
802
|
+
p_new.add_argument("id", help="Concept identifier (e.g. tables/orders)")
|
|
803
|
+
|
|
804
|
+
p_validate = sub.add_parser("validate", help="Validate bundle structure and frontmatter")
|
|
805
|
+
p_validate.add_argument("bundle", help="Path to the OKF bundle")
|
|
806
|
+
|
|
807
|
+
p_list = sub.add_parser("list", help="List all concepts in the bundle")
|
|
808
|
+
p_list.add_argument("bundle", help="Path to the OKF bundle")
|
|
809
|
+
|
|
810
|
+
p_show = sub.add_parser("show", help="Display a single concept")
|
|
811
|
+
p_show.add_argument("bundle", help="Path to the OKF bundle")
|
|
812
|
+
p_show.add_argument("id", help="Concept identifier (e.g. tables/orders)")
|
|
813
|
+
|
|
814
|
+
p_index = sub.add_parser("index", help="Auto-generate index.md files")
|
|
815
|
+
p_index.add_argument("bundle", help="Path to the OKF bundle")
|
|
816
|
+
|
|
817
|
+
p_search = sub.add_parser("search", help="Full-text search across concepts")
|
|
818
|
+
p_search.add_argument("bundle", help="Path to the OKF bundle")
|
|
819
|
+
p_search.add_argument("q", help="Search query")
|
|
820
|
+
|
|
821
|
+
p_graph = sub.add_parser("graph", help="Output the concept link graph")
|
|
822
|
+
p_graph.add_argument("bundle", help="Path to the OKF bundle")
|
|
823
|
+
p_graph.add_argument("--format", choices=["mermaid", "ascii"], default="mermaid",
|
|
824
|
+
help="Output format (default: mermaid)")
|
|
825
|
+
|
|
826
|
+
p_stats = sub.add_parser("stats", help="Bundle statistics")
|
|
827
|
+
p_stats.add_argument("bundle", help="Path to the OKF bundle")
|
|
828
|
+
|
|
829
|
+
return parser
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def main(argv: list[str] | None = None) -> int:
|
|
833
|
+
if yaml is None:
|
|
834
|
+
print(red("Error: PyYAML is required. Install it with: pip install pyyaml"), file=sys.stderr)
|
|
835
|
+
return 1
|
|
836
|
+
|
|
837
|
+
parser = build_parser()
|
|
838
|
+
args = parser.parse_args(argv)
|
|
839
|
+
|
|
840
|
+
if args.version:
|
|
841
|
+
print("okf-toolkit v0.1.0")
|
|
842
|
+
return 0
|
|
843
|
+
|
|
844
|
+
if not args.command:
|
|
845
|
+
parser.print_help()
|
|
846
|
+
return 0
|
|
847
|
+
|
|
848
|
+
commands = {
|
|
849
|
+
"init": cmd_init,
|
|
850
|
+
"new": cmd_new,
|
|
851
|
+
"validate": cmd_validate,
|
|
852
|
+
"list": cmd_list,
|
|
853
|
+
"show": cmd_show,
|
|
854
|
+
"index": cmd_index,
|
|
855
|
+
"search": cmd_search,
|
|
856
|
+
"graph": cmd_graph,
|
|
857
|
+
"stats": cmd_stats,
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
handler = commands.get(args.command)
|
|
861
|
+
if handler:
|
|
862
|
+
return handler(args)
|
|
863
|
+
|
|
864
|
+
print(red(f"Unknown command: {args.command}"))
|
|
865
|
+
return 1
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
if __name__ == "__main__":
|
|
869
|
+
sys.exit(main())
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [2026] [okf-toolkit contributors]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: okf-toolkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CLI toolkit for working with Google's Open Knowledge Format (OKF)
|
|
5
|
+
Home-page: https://github.com/akdira/okf-toolkit
|
|
6
|
+
License: Apache 2.0
|
|
7
|
+
Project-URL: Homepage, https://www.akdira.id
|
|
8
|
+
Project-URL: Source, https://github.com/akdira/okf-toolkit
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Information Technology
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Software Development :: Documentation
|
|
18
|
+
Classifier: Topic :: Text Processing :: Markup
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: pyyaml >=6.0
|
|
23
|
+
|
|
24
|
+
# okf-toolkit
|
|
25
|
+
|
|
26
|
+
**CLI toolkit for working with Google's Open Knowledge Format (OKF)**
|
|
27
|
+
|
|
28
|
+
okf-toolkit is a command-line tool for creating, validating, traversing, and maintaining knowledge bases stored in the Open Knowledge Format (OKF). OKF is a vendor-neutral, human-and-agent-friendly format announced by Google Cloud on June 12, 2026. It represents knowledge as a directory tree of plain-text markdown files with YAML frontmatter, making knowledge bases portable, version-controllable, and accessible to both humans and AI agents.
|
|
29
|
+
|
|
30
|
+
## What is OKF?
|
|
31
|
+
|
|
32
|
+
The Open Knowledge Format is a specification for organizing structured and unstructured knowledge in a file-system-based bundle. Each unit of knowledge — a "concept" — lives in its own `.md` file with YAML frontmatter that provides typed metadata. Key principles:
|
|
33
|
+
|
|
34
|
+
- **Simplicity:** Everything is markdown. No databases, no proprietary schemas.
|
|
35
|
+
- **Portability:** A bundle is a directory tree. Copy it, commit it to Git, distribute it via any channel.
|
|
36
|
+
- **Agent-friendly:** Typed frontmatter and clear linking make it trivial for AI agents to traverse, understand, and augment knowledge bases.
|
|
37
|
+
- **Extensibility:** Producers can add any extra frontmatter keys; consumers tolerate unknown ones.
|
|
38
|
+
- **UTF-8 throughout:** No encoding guesswork.
|
|
39
|
+
|
|
40
|
+
## Features
|
|
41
|
+
|
|
42
|
+
okf-toolkit provides everything you need to work with OKF bundles:
|
|
43
|
+
|
|
44
|
+
| Command | Description |
|
|
45
|
+
|-------------|----------------------------------------------------------------------------|
|
|
46
|
+
| `okf init` | Scaffold a new OKF bundle directory with index.md and log.md |
|
|
47
|
+
| `okf new` | Interactively create a new concept with guided frontmatter prompts |
|
|
48
|
+
| `okf validate` | Validate bundle structure: required fields, reserved names, UTF-8, links |
|
|
49
|
+
| `okf list` | List all concepts with their type and description |
|
|
50
|
+
| `okf show` | Display a concept's full frontmatter and body content |
|
|
51
|
+
| `okf index` | Auto-generate or refresh index.md files from concept frontmatter |
|
|
52
|
+
| `okf search`| Full-text substring search across all concept bodies |
|
|
53
|
+
| `okf graph` | Output the link graph as Mermaid or ASCII for visualization |
|
|
54
|
+
| `okf stats` | Bundle statistics: concept count, type breakdown, tag cloud, link counts |
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
# Clone the repository
|
|
60
|
+
git clone https://github.com/openclaw/okf-toolkit.git
|
|
61
|
+
cd okf-toolkit
|
|
62
|
+
|
|
63
|
+
# Install the dependency
|
|
64
|
+
pip install pyyaml>=6.0
|
|
65
|
+
|
|
66
|
+
# (optional) Install as a package
|
|
67
|
+
pip install -e .
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Python 3.10 or newer is required. Only `pyyaml` is needed beyond the standard library.
|
|
71
|
+
|
|
72
|
+
## Quick Start
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
# Initialize a new bundle
|
|
76
|
+
okf init my-knowledge-base
|
|
77
|
+
|
|
78
|
+
# Navigate into it
|
|
79
|
+
cd my-knowledge-base
|
|
80
|
+
|
|
81
|
+
# Create a concept interactively
|
|
82
|
+
okf new . tables/user-sessions
|
|
83
|
+
|
|
84
|
+
# Validate the bundle
|
|
85
|
+
okf validate .
|
|
86
|
+
|
|
87
|
+
# List all concepts
|
|
88
|
+
okf list .
|
|
89
|
+
|
|
90
|
+
# Search across concepts
|
|
91
|
+
okf search . user
|
|
92
|
+
|
|
93
|
+
# Generate index.md files from frontmatter
|
|
94
|
+
okf index .
|
|
95
|
+
|
|
96
|
+
# Show the link graph
|
|
97
|
+
okf graph .
|
|
98
|
+
|
|
99
|
+
# Get bundle statistics
|
|
100
|
+
okf stats .
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Usage Examples
|
|
104
|
+
|
|
105
|
+
### Creating a New Knowledge Base
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
okf init docs/knowledge-base
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
This creates:
|
|
112
|
+
```
|
|
113
|
+
docs/knowledge-base/
|
|
114
|
+
├── index.md # Directory listing (auto-editable)
|
|
115
|
+
└── log.md # Update history
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### Adding a Concept
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
okf new docs/knowledge-base api/checkout-endpoint
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
You'll be prompted for:
|
|
125
|
+
- `type` (required) — e.g., "API Endpoint", "BigQuery Table", "Playbook"
|
|
126
|
+
- `title` (optional)
|
|
127
|
+
- `description` (optional)
|
|
128
|
+
- `resource` (optional URI)
|
|
129
|
+
- `tags` (optional, comma-separated)
|
|
130
|
+
|
|
131
|
+
The tool generates a markdown file with proper YAML frontmatter and a template body.
|
|
132
|
+
|
|
133
|
+
### Validating a Bundle
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
okf validate docs/knowledge-base
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Checks every `.md` file for:
|
|
140
|
+
- Valid UTF-8 encoding
|
|
141
|
+
- Reserved filename violations (`index.md` and `log.md` must not have a `type` field)
|
|
142
|
+
- Required frontmatter fields (`type`)
|
|
143
|
+
- YAML parseability
|
|
144
|
+
- Broken markdown cross-links (reported as warnings)
|
|
145
|
+
- Type correctness for `tags` (must be a list) and `timestamp` (must be a string)
|
|
146
|
+
|
|
147
|
+
Exits with code 1 if any errors found, 0 otherwise.
|
|
148
|
+
|
|
149
|
+
### Searching Across Concepts
|
|
150
|
+
|
|
151
|
+
```bash
|
|
152
|
+
okf search docs/knowledge-base revenue
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Performs case-insensitive substring matching across all concept files (excluding `index.md` and `log.md`). Shows the matching file, its type, and a highlighted snippet around the match.
|
|
156
|
+
|
|
157
|
+
### Generating Index Files
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
okf index docs/knowledge-base
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Walks every directory containing concepts and generates or updates an `index.md` with properly formatted links, titles, types, and descriptions pulled from frontmatter. Skips directories where nothing has changed.
|
|
164
|
+
|
|
165
|
+
### Visualizing the Link Graph
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
# Mermaid format (default) — paste into GitHub-flavored markdown
|
|
169
|
+
okf graph docs/knowledge-base
|
|
170
|
+
|
|
171
|
+
# ASCII format for terminal inspection
|
|
172
|
+
okf graph docs/knowledge-base --format ascii
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## Why OKF Matters for AI Agents
|
|
176
|
+
|
|
177
|
+
AI agents that work with knowledge bases face two fundamental challenges: understanding the structure of the knowledge, and knowing how to add to it. OKF addresses both:
|
|
178
|
+
|
|
179
|
+
1. **Typed frontmatter gives agents semantic understanding.** When an agent encounters a concept file, the `type` field immediately tells it what kind of thing this is — a table, a metric, a playbook, a reference. This reduces hallucination and improves retrieval accuracy.
|
|
180
|
+
|
|
181
|
+
2. **Clear linking creates a traversable graph.** Agents can follow markdown links between concepts just like humans do, building a graph of related knowledge.
|
|
182
|
+
|
|
183
|
+
3. **The format is append-friendly.** An agent that discovers new knowledge can create a new `.md` file with proper frontmatter using the same tools a human would.
|
|
184
|
+
|
|
185
|
+
4. **Version control works out of the box.** Git tracks every change to every concept. Agents can see what changed, when, and why.
|
|
186
|
+
|
|
187
|
+
5. **No lock-in.** Unlike a proprietary knowledge graph or database, OKF bundles are plain files. Any tool — AI or otherwise — that can read markdown and YAML can work with OKF.
|
|
188
|
+
|
|
189
|
+
## Contributing
|
|
190
|
+
|
|
191
|
+
Contributions are welcome! Here's how to get started:
|
|
192
|
+
|
|
193
|
+
1. **Read the AGENTS.md** file in the repository root — it contains detailed instructions for AI agents and human contributors alike.
|
|
194
|
+
2. **Open an issue** to discuss your proposed change before writing code.
|
|
195
|
+
3. **Fork the repository** and create a feature branch.
|
|
196
|
+
4. **Write tests** for any new functionality. Tests live in `tests/` and use Python's `unittest` framework.
|
|
197
|
+
5. **Ensure existing tests pass** with `python3 -m unittest tests/test_okf.py -v`.
|
|
198
|
+
6. **Submit a pull request** with a clear description of what and why.
|
|
199
|
+
|
|
200
|
+
Conventions:
|
|
201
|
+
- Python 3.10+ only, stdlib-first approach
|
|
202
|
+
- `pyyaml` is the sole external dependency — keep it that way
|
|
203
|
+
- New CLI commands should follow the existing pattern (see `cmd_*` functions in `okf.py`)
|
|
204
|
+
- Keep ANSI color helpers in the `_color` / `green`/`red`/etc. functions
|
|
205
|
+
|
|
206
|
+
## Credits
|
|
207
|
+
|
|
208
|
+
Created and maintained by [akdira](https://www.akdira.id).
|
|
209
|
+
|
|
210
|
+
## License
|
|
211
|
+
|
|
212
|
+
Apache 2.0. See [LICENSE](LICENSE) for the full text.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
okf.py,sha256=GYlauDuD4XUiULIau_TBpgBc7BCPEJM4d5U2fIXlang,28763
|
|
2
|
+
okf_toolkit-0.1.0.dist-info/LICENSE,sha256=sfzJv4jOvnmufof_2Ey8HC906upwHfG3ce9E9tQPgxI,11358
|
|
3
|
+
okf_toolkit-0.1.0.dist-info/METADATA,sha256=d6pmp7qFJ2xc5cLGCBNYjamc5oLtv-R2_qniaDSb0ns,8081
|
|
4
|
+
okf_toolkit-0.1.0.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
|
|
5
|
+
okf_toolkit-0.1.0.dist-info/entry_points.txt,sha256=NGLTeYEiqGyefDk0sI-n3FGrwdV93kP2BXwtFENE-vM,33
|
|
6
|
+
okf_toolkit-0.1.0.dist-info/top_level.txt,sha256=JroCkPdgA8rb0oVPBM72QkzUXVWD8jNLNU6C84uVYUw,4
|
|
7
|
+
okf_toolkit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
okf
|