okf-wiki-kit 0.2.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.
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: okf-wiki-kit
3
+ Version: 0.2.0
4
+ Summary: Build Open-Knowledge-Format (OKF) / Obsidian LLM wikis from any source material.
5
+ Author: okf-wiki-kit contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/olivermorgan2/okf-wiki-kit
8
+ Project-URL: Issues, https://github.com/olivermorgan2/okf-wiki-kit/issues
9
+ Project-URL: Repository, https://github.com/olivermorgan2/okf-wiki-kit
10
+ Keywords: okf,obsidian,knowledge-graph,llm,rag,wiki,markdown
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: PyYAML>=6.0
21
+ Provides-Extra: anthropic
22
+ Requires-Dist: anthropic>=0.40; extra == "anthropic"
23
+ Provides-Extra: openai
24
+ Requires-Dist: openai>=1.40; extra == "openai"
25
+ Provides-Extra: rag
26
+ Requires-Dist: numpy>=1.24; extra == "rag"
27
+ Provides-Extra: voyage
28
+ Requires-Dist: voyageai>=0.3; extra == "voyage"
29
+ Provides-Extra: local-embeddings
30
+ Requires-Dist: numpy>=1.24; extra == "local-embeddings"
31
+ Requires-Dist: model2vec>=0.3; extra == "local-embeddings"
32
+ Provides-Extra: mcp
33
+ Requires-Dist: mcp>=1.2; extra == "mcp"
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest>=7.0; extra == "dev"
36
+ Dynamic: license-file
37
+
38
+ # okf-wiki-kit
39
+
40
+ Build a cross-linked **[Open Knowledge Format](https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf)
41
+ (OKF)** knowledge wiki — browsable in **Obsidian** and consumable by **LLMs/agents** — from *any*
42
+ source material.
43
+
44
+ OKF represents knowledge as a directory of markdown files: each file is a typed node with YAML
45
+ frontmatter (only `type` is required) and `[[wikilinks]]` that form a knowledge graph richer than
46
+ the folder hierarchy. `okf-wiki-kit` gives you a small, dependency-light engine that turns your
47
+ content into such a bundle, with optional LLM enrichment.
48
+
49
+ ## How it works
50
+
51
+ ```
52
+ your source ──► SourceAdapter.load() ──► [Node, Node, …] ──► engine ──► OKF/Obsidian vault
53
+ (you write ~40 lines, (normalized) (generic: frontmatter, wikilinks,
54
+ or use a built-in one) indexes, link-inference, validate)
55
+ ```
56
+
57
+ You implement **one method** — `load() -> Iterable[Node]` — that turns your source into a list of
58
+ `Node`s. The engine does everything else: unique filenames, frontmatter, wikilinks, per-type and
59
+ root `index.md` files, optional mention-based link inference, validation, and optional LLM
60
+ enrichment.
61
+
62
+ ## Quickstart (zero code)
63
+
64
+ Point the built-in *markdown-folder* adapter at any folder of `.md` files:
65
+
66
+ ```bash
67
+ pip install -e . # or: pip install okf-wiki-kit
68
+ cp okf.config.example.yaml okf.config.yaml
69
+ # edit okf.config.yaml -> adapter_options.path: ./my-notes
70
+ okf build # writes ./vault
71
+ okf validate # every node typed, every wikilink resolves
72
+ ```
73
+
74
+ Open the `./vault` folder in Obsidian and look at the Graph View.
75
+
76
+ ## Optional: LLM enrichment
77
+
78
+ ```bash
79
+ pip install -e ".[openai]" # or ".[anthropic]"
80
+ export OPENROUTER_API_KEY=... # or ANTHROPIC_API_KEY
81
+ okf enrich # writes enrichment.json (canonical concepts + descriptions)
82
+ okf build # rebuild, applying the enrichment
83
+ ```
84
+
85
+ Enrichment is **provider-flexible**: Anthropic (`claude-sonnet-4-6`) or any OpenAI-compatible
86
+ endpoint such as **OpenRouter** (`qwen/qwen3.7-plus`). Provider is auto-detected from your env keys.
87
+
88
+ ## Writing your own adapter
89
+
90
+ For structured sources (JSON, a database, a CMS), write a small adapter:
91
+
92
+ ```python
93
+ from okfkit.model import Node, Link
94
+ from okfkit.adapters.base import SourceAdapter
95
+
96
+ class MyAdapter(SourceAdapter):
97
+ def load(self):
98
+ for row in my_source():
99
+ yield Node(
100
+ id=row["slug"], type="Article", title=row["title"],
101
+ body=row["markdown"],
102
+ frontmatter={"author": row["author"]},
103
+ links=[Link(target=t, rel="related", section="See also")
104
+ for t in row["related_slugs"]],
105
+ tags=row["tags"],
106
+ )
107
+ ```
108
+
109
+ Point `okf.config.yaml` at it: `adapter: path/to/my_adapter.py:MyAdapter`. See
110
+ [`docs/writing-an-adapter.md`](docs/writing-an-adapter.md) and the worked example in
111
+ [`examples/textbook/`](examples/textbook/).
112
+
113
+ ## The `Node` model
114
+
115
+ | field | meaning |
116
+ |-------|---------|
117
+ | `id` | stable unique id → becomes the filename / wikilink target |
118
+ | `type` | OKF `type:` value (required) — `"Chapter"`, `"Concept"`, or anything you invent |
119
+ | `title` | human-readable name (wikilink display) |
120
+ | `body` | markdown body (no frontmatter) |
121
+ | `frontmatter` | any extra YAML fields (may contain `[[wikilinks]]`) |
122
+ | `links` | edges to other nodes; each `Link(target, rel, section)` renders under a `## section` heading |
123
+ | `tags`, `aliases` | Obsidian-native tags and aliases |
124
+
125
+ ## Use with Claude Code / Claude Desktop
126
+
127
+ Serve a built vault as a read-only MCP server so agents can query it as tools:
128
+
129
+ ```bash
130
+ pip install -e ".[mcp]"
131
+ claude mcp add okf-wiki -- okf serve -c /abs/path/okf.config.yaml
132
+ ```
133
+
134
+ The server exposes five read-only tools: `okf_vault_info` (orientation — call first),
135
+ `okf_search` (semantic; needs a prior `okf index`), `okf_list_notes` (browse/paginate by type or
136
+ tag), `okf_get_note` (full note with links and backlinks), and `okf_neighbors` (walk the link
137
+ graph). The graph tools need no API keys. Use `okf serve --vault /abs/path/vault` to serve any
138
+ OKF vault without a config, and `--no-rag` for graph tools only.
139
+
140
+ ## Roadmap
141
+
142
+ - **Build** — engine, markdown-folder adapter, custom adapters, link inference, LLM enrichment, CLI.
143
+ - **Semantic RAG (Phase 7) ✓** — `okf index` / `okf search` / `okf ask`: embeddings index + retrieval-augmented Q&A.
144
+ - **MCP server (Phase 8) ✓** — `okf serve`: expose the vault as read-only tools for Claude Code / Desktop / any MCP client.
145
+
146
+ See [`docs/roadmap.md`](docs/roadmap.md) for details.
147
+
148
+ ## License
149
+
150
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,21 @@
1
+ okf_wiki_kit-0.2.0.dist-info/licenses/LICENSE,sha256=p34ts6qpfM42vGnl33KtSvTJkDJIHmbANW70Iv6hrV8,1082
2
+ okfkit/__init__.py,sha256=equkfQ-3hNkNatZGLs-yc-EhboAxhDVPby8Z9Zv0R1g,165
3
+ okfkit/cli.py,sha256=gTbO_la9h1Wcm5fD-qK_EJ-63gUfcUB3gQQsp0loIY8,10604
4
+ okfkit/config.py,sha256=uNdMNDkK4IZTSgoUtnORyOBs8N0zPbjQ8JhOkAfoqy8,1878
5
+ okfkit/engine.py,sha256=pRVr7_IRgrufuqsJSVHv4VQHWVW0GIBUkt7leVge3ow,13500
6
+ okfkit/enrich.py,sha256=23jcefvOKP0Con6S_tdqP8Q8H86tKLIudXiV7r5l9fQ,12431
7
+ okfkit/model.py,sha256=DyZdelyPEDTihbOVicYBexEF1_rcRjzkiHkxY6VWWZ8,1995
8
+ okfkit/render.py,sha256=yUEHI4O_eXdrCcUv9TXvjgXE3MDQO4qHjfBKUy61SPU,3651
9
+ okfkit/adapters/__init__.py,sha256=Xrn0GsKkfPvt-28n_X8G_NbsYgYS0v1iCSNu7WlsnaA,304
10
+ okfkit/adapters/base.py,sha256=-FiMJ7mvLAV0NyHLCv4gLrif3xfdUD8q5oTZymXG-P8,2243
11
+ okfkit/adapters/markdown_folder.py,sha256=PMTZNyTGI7iXQPf22AAYrLBflQnB7jQNXuMc1r1CYLc,1838
12
+ okfkit/serve/__init__.py,sha256=CiOmNuIOslhcHaJ38q9_BIZ9a0bht5boYt8l_A2q5YY,1504
13
+ okfkit/serve/embeddings.py,sha256=QJ0GTPXPxBwl94PqkxepONt_fb9xKIQX-zoiaeb892I,4591
14
+ okfkit/serve/mcp.py,sha256=N-nsh_oWrfoowlDqpk1D5bLdIO3BElfsRKY3xy9jdKc,15845
15
+ okfkit/serve/rag.py,sha256=hwLLXP03xxOiIrEyIkPbOMmnNv200IME3qyFA45MALA,13837
16
+ okfkit/serve/vault.py,sha256=9ATzPI56PpZZQQq4FZaI4cWGjxQg3DYPqUDS-l-dSks,4421
17
+ okf_wiki_kit-0.2.0.dist-info/METADATA,sha256=8qrF7IxVB1x5ojR_jHF3Zc-_vco7h1Sw1noOWqqjIeA,6285
18
+ okf_wiki_kit-0.2.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
19
+ okf_wiki_kit-0.2.0.dist-info/entry_points.txt,sha256=nDpPHk-9s0enmCcp2qWXCBEmqkUZQuRLXcjXjew3xRM,40
20
+ okf_wiki_kit-0.2.0.dist-info/top_level.txt,sha256=ztDdsEtk2Q5K-r4FSr9XO8pCqIvduT0JrGg_vMUvJsw,7
21
+ okf_wiki_kit-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ okf = okfkit.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 okf-wiki-kit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ okfkit
okfkit/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """okf-wiki-kit — build OKF/Obsidian LLM wikis from any source material."""
2
+
3
+ from okfkit.model import Node, Link
4
+
5
+ __version__ = "0.2.0"
6
+ __all__ = ["Node", "Link"]
@@ -0,0 +1,9 @@
1
+ """Source adapters — turn a specific source into `Node`s.
2
+
3
+ Built-in adapters are resolved by short name (e.g. "markdown_folder"). Custom
4
+ adapters are resolved by "path/to/file.py:ClassName".
5
+ """
6
+
7
+ from okfkit.adapters.base import SourceAdapter, load_adapter
8
+
9
+ __all__ = ["SourceAdapter", "load_adapter"]
@@ -0,0 +1,66 @@
1
+ """The SourceAdapter contract and the resolver that loads one by name/path."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import importlib.util
7
+ import os
8
+ from abc import ABC, abstractmethod
9
+ from collections.abc import Iterable
10
+
11
+ from okfkit.model import Node
12
+
13
+ # short name -> "module:Class" for built-in adapters
14
+ BUILTINS = {
15
+ "markdown_folder": "okfkit.adapters.markdown_folder:MarkdownFolderAdapter",
16
+ }
17
+
18
+
19
+ class SourceAdapter(ABC):
20
+ """Subclass this and implement `load()`. That is the entire contract.
21
+
22
+ Options from `okf.config.yaml`'s `adapter_options:` are passed as keyword
23
+ arguments and stored on `self.options`.
24
+ """
25
+
26
+ def __init__(self, **options):
27
+ self.options = options
28
+
29
+ @abstractmethod
30
+ def load(self) -> Iterable[Node]:
31
+ """Yield (or return a list of) `Node`s built from the source."""
32
+ raise NotImplementedError
33
+
34
+
35
+ def load_adapter(spec: str, options: dict | None = None) -> SourceAdapter:
36
+ """Instantiate an adapter from a built-in name or a "path.py:Class" / "module:Class" spec."""
37
+ options = options or {}
38
+ if spec in BUILTINS:
39
+ spec = BUILTINS[spec]
40
+ if ":" not in spec:
41
+ raise ValueError(
42
+ f"Adapter spec {spec!r} must be a built-in name ({', '.join(BUILTINS)}) "
43
+ f"or 'module_or_path:ClassName'."
44
+ )
45
+ target, class_name = spec.rsplit(":", 1)
46
+
47
+ if target.endswith(".py") or os.path.sep in target or os.path.exists(target):
48
+ module = _import_from_path(target)
49
+ else:
50
+ module = importlib.import_module(target)
51
+
52
+ cls = getattr(module, class_name, None)
53
+ if cls is None or not (isinstance(cls, type) and issubclass(cls, SourceAdapter)):
54
+ raise ValueError(f"{class_name!r} in {target!r} is not a SourceAdapter subclass.")
55
+ return cls(**options)
56
+
57
+
58
+ def _import_from_path(path: str):
59
+ path = os.path.abspath(os.path.expanduser(path))
60
+ if not os.path.exists(path):
61
+ raise FileNotFoundError(f"Adapter file not found: {path}")
62
+ name = "okfkit_adapter_" + os.path.splitext(os.path.basename(path))[0]
63
+ spec = importlib.util.spec_from_file_location(name, path)
64
+ module = importlib.util.module_from_spec(spec)
65
+ spec.loader.exec_module(module)
66
+ return module
@@ -0,0 +1,48 @@
1
+ """Built-in zero-code adapter: turn a folder of markdown files into OKF nodes.
2
+
3
+ Each `.md` file becomes one node. `type`, `title`, `tags`, and `aliases` are read
4
+ from YAML frontmatter if present (falling back to sensible defaults). The file's
5
+ existing inline `[[wikilinks]]` are left in the body untouched — filenames are
6
+ preserved as node ids so those links keep resolving.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+
13
+ from okfkit import render
14
+ from okfkit.adapters.base import SourceAdapter
15
+ from okfkit.model import Node
16
+
17
+
18
+ class MarkdownFolderAdapter(SourceAdapter):
19
+ def load(self):
20
+ root = Path(self.options.get("path", ".")).expanduser()
21
+ if not root.is_dir():
22
+ raise NotADirectoryError(f"markdown_folder: path is not a directory: {root}")
23
+ default_type = self.options.get("default_type", "Note")
24
+
25
+ for f in sorted(root.glob("**/*.md")):
26
+ if f.name.lower() == "readme.md":
27
+ continue
28
+ fm, body = render.split_frontmatter(f.read_text(encoding="utf-8"))
29
+ node_id = str(fm.get("id") or f.stem) # preserve filename → inline links resolve
30
+ yield Node(
31
+ id=node_id,
32
+ type=str(fm.get("type") or default_type),
33
+ title=str(fm.get("title") or f.stem),
34
+ body=body.strip(),
35
+ frontmatter={k: v for k, v in fm.items()
36
+ if k not in ("id", "title", "type", "tags", "aliases")},
37
+ links=[], # inline [[wikilinks]] already live in the body
38
+ tags=_as_list(fm.get("tags")),
39
+ aliases=_as_list(fm.get("aliases")),
40
+ )
41
+
42
+
43
+ def _as_list(v):
44
+ if v is None:
45
+ return []
46
+ if isinstance(v, (list, tuple)):
47
+ return [str(x) for x in v]
48
+ return [str(v)]
okfkit/cli.py ADDED
@@ -0,0 +1,298 @@
1
+ """The `okf` command: build | enrich | validate | init | index | search | ask | serve."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+
10
+ from okfkit import __version__
11
+
12
+
13
+ def main(argv=None):
14
+ ap = argparse.ArgumentParser(prog="okf", description="Build OKF/Obsidian wikis from any source.")
15
+ ap.add_argument("--version", action="version", version=f"okf-wiki-kit {__version__}")
16
+ sub = ap.add_subparsers(dest="cmd", required=True)
17
+
18
+ helps = {
19
+ "build": "build the wiki",
20
+ "enrich": "enrich the wiki",
21
+ "validate": "validate the wiki",
22
+ "index": "build/refresh the semantic embeddings index over the built vault",
23
+ "search": "semantic search over the indexed vault (offline)",
24
+ "ask": "answer a question from the vault (retrieve + LLM)",
25
+ "serve": "run a read-only MCP server over the built vault (stdio)",
26
+ }
27
+ for name in ("build", "enrich", "validate", "index", "search", "ask", "serve"):
28
+ p = sub.add_parser(name, help=helps[name])
29
+ p.add_argument("-c", "--config", default="okf.config.yaml", help="path to okf.config.yaml")
30
+ # enrich-only overrides
31
+ ep = sub._name_parser_map["enrich"]
32
+ ep.add_argument("--provider", choices=["anthropic", "openai"], default=None)
33
+ ep.add_argument("--model", default=None)
34
+ ep.add_argument("--base-url", default=None)
35
+ # index-only flags
36
+ xp = sub._name_parser_map["index"]
37
+ xp.add_argument("--force", action="store_true", help="re-embed everything (ignore cached rows)")
38
+ # search/ask shared flags
39
+ for name in ("search", "ask"):
40
+ qp = sub._name_parser_map[name]
41
+ qp.add_argument("query", help="natural-language query")
42
+ qp.add_argument("-k", type=int, default=None, help="number of notes to retrieve (default: config top_k, else 8)")
43
+ qp.add_argument("--type", action="append", default=None, metavar="TYPE",
44
+ help="restrict to this note type (repeatable)")
45
+ # ask-only chat-backend overrides (mirrors `okf enrich`)
46
+ kp = sub._name_parser_map["ask"]
47
+ kp.add_argument("--provider", choices=["anthropic", "openai"], default=None)
48
+ kp.add_argument("--model", default=None)
49
+ kp.add_argument("--base-url", default=None)
50
+ # serve-only flags
51
+ sp = sub._name_parser_map["serve"]
52
+ sp.add_argument("--vault", default=None, metavar="PATH",
53
+ help="serve this OKF vault directly (bypasses the config)")
54
+ sp.add_argument("--no-rag", action="store_true",
55
+ help="disable okf_search (graph tools only; no index needed)")
56
+
57
+ ip = sub.add_parser("init", help="scaffold okf.config.yaml (and an adapter stub)")
58
+ ip.add_argument("--adapter-stub", action="store_true", help="also write adapter.py template")
59
+
60
+ args = ap.parse_args(argv)
61
+ return {"build": _build, "enrich": _enrich, "validate": _validate, "init": _init,
62
+ "index": _index, "search": _search, "ask": _ask, "serve": _serve}[args.cmd](args)
63
+
64
+
65
+ def _load(args):
66
+ from okfkit import config
67
+ from okfkit.adapters.base import load_adapter
68
+ cfg = config.load(args.config)
69
+ adapter = load_adapter(cfg.adapter, cfg.adapter_options)
70
+ nodes = list(adapter.load())
71
+ if not nodes:
72
+ raise SystemExit(f"Adapter {cfg.adapter!r} produced no nodes — check your source path.")
73
+ return cfg, nodes
74
+
75
+
76
+ def _enrichment_path(cfg):
77
+ return os.path.join(cfg.base_dir, "enrichment.json")
78
+
79
+
80
+ def _build(args):
81
+ from okfkit import engine
82
+ cfg, nodes = _load(args)
83
+ enrichment = None
84
+ ep = _enrichment_path(cfg)
85
+ if os.path.exists(ep):
86
+ with open(ep, encoding="utf-8") as fh:
87
+ enrichment = json.load(fh)
88
+ print(f"(using {os.path.relpath(ep)})")
89
+ result = engine.build(nodes, cfg.resolve(cfg.output),
90
+ link_style=cfg.link_style,
91
+ link_inference=cfg.link_inference,
92
+ enrichment=enrichment)
93
+ print(result.summary())
94
+ print(f"\nVault written to {cfg.resolve(cfg.output)}")
95
+ return 0 if result.ok else 2
96
+
97
+
98
+ def _enrich(args):
99
+ from okfkit import enrich
100
+ cfg, nodes = _load(args)
101
+ e = cfg.enrich or {}
102
+ enrich.run(
103
+ nodes, _enrichment_path(cfg),
104
+ canonicalize_type=e.get("canonicalize_type", ""),
105
+ describe_types=e.get("describe_types", []),
106
+ provider=args.provider or e.get("provider"),
107
+ model=args.model or e.get("model"),
108
+ base_url=args.base_url or e.get("base_url"),
109
+ )
110
+ print("Now run: okf build")
111
+ return 0
112
+
113
+
114
+ def _validate(args):
115
+ from okfkit import config, engine
116
+ cfg = config.load(args.config)
117
+ output = cfg.resolve(cfg.output)
118
+ if not os.path.isdir(output):
119
+ raise SystemExit(f"No vault at {output}. Run `okf build` first.")
120
+ unresolved, total, counts = engine.validate_vault(output)
121
+ print(f"Vault: {output}")
122
+ for t in sorted(counts):
123
+ print(f" {t:16s}: {counts[t]}")
124
+ print(f" {'TOTAL files':16s}: {total}")
125
+ if unresolved:
126
+ print(f"\n!! {len(unresolved)} unresolved wikilink target(s):")
127
+ for tgt, srcs in list(sorted(unresolved.items()))[:25]:
128
+ print(f" [[{tgt}]] <- {srcs[0]}")
129
+ return 2
130
+ print("\n All wikilinks resolve. ✓")
131
+ return 0
132
+
133
+
134
+ def _rag_settings(cfg):
135
+ """The `serve.rag` block of the config (all keys optional)."""
136
+ return (cfg.serve or {}).get("rag") or {}
137
+
138
+
139
+ def _load_index(cfg, backend=None):
140
+ from okfkit.serve import Index
141
+ try:
142
+ return Index.load(cfg.base_dir, backend=backend)
143
+ except FileNotFoundError as exc:
144
+ raise SystemExit(str(exc))
145
+
146
+
147
+ def _index(args):
148
+ from okfkit import config
149
+ from okfkit.serve import Index, chunk_notes, load_vault, make_embedder
150
+ cfg = config.load(args.config)
151
+ vault = cfg.resolve(cfg.output)
152
+ rag = _rag_settings(cfg)
153
+ emb = rag.get("embedding") or {}
154
+ backend = make_embedder(provider=emb.get("provider"), model=emb.get("model"),
155
+ base_url=emb.get("base_url"))
156
+ notes = load_vault(vault)
157
+ chunks = chunk_notes(
158
+ notes,
159
+ max_chars=rag.get("chunk_max_chars") or 4000,
160
+ exclude_types=tuple(rag.get("exclude_types") or ("Index", "Home")),
161
+ )
162
+ try:
163
+ idx = (Index(backend, vault_path=vault) if args.force
164
+ else Index.load(cfg.base_dir, backend=backend))
165
+ except FileNotFoundError:
166
+ idx = Index(backend, vault_path=vault)
167
+ idx.vault_path = vault
168
+ print(f"Vault: {vault} ({len(notes)} notes -> {len(chunks)} chunks)")
169
+ stats = idx.build(chunks, force=args.force)
170
+ npz_path, chunks_path = idx.save(cfg.base_dir)
171
+ print(f" embedded {stats['embedded']}, reused {stats['reused']}, total {stats['total']}")
172
+ print(f"Index written to {os.path.dirname(npz_path)}")
173
+ return 0
174
+
175
+
176
+ def _search(args):
177
+ from okfkit import config
178
+ cfg = config.load(args.config)
179
+ k = args.k or _rag_settings(cfg).get("top_k") or 8
180
+ idx = _load_index(cfg)
181
+ hits = idx.search(args.query, k=k, types=args.type)
182
+ if not hits:
183
+ print("No matches.")
184
+ return 2
185
+ for h in hits:
186
+ head = f" · {h.heading}" if h.heading else ""
187
+ print(f" {h.score:6.3f} [{h.type or '-'}] {h.node_id} — {h.title}{head}")
188
+ return 0
189
+
190
+
191
+ def _ask(args):
192
+ from okfkit import config, enrich
193
+ from okfkit.serve import ask
194
+ cfg = config.load(args.config)
195
+ rag = _rag_settings(cfg)
196
+ k = args.k or rag.get("top_k") or 8
197
+ idx = _load_index(cfg)
198
+ e = cfg.enrich or {}
199
+ backend = enrich.make_backend(
200
+ provider=args.provider or e.get("provider"),
201
+ model=args.model or e.get("model"),
202
+ base_url=args.base_url or e.get("base_url"),
203
+ )
204
+ answer, hits = ask(args.query, idx, backend, k=k, types=args.type)
205
+ print(answer)
206
+ if not hits:
207
+ return 2
208
+ print("\nSources:")
209
+ for h in hits:
210
+ print(f" {h.score:6.3f} [[{h.node_id}]] {h.title}")
211
+ return 0
212
+
213
+
214
+ def _serve(args):
215
+ """Run the read-only MCP server (stdio). stdout belongs to the MCP
216
+ transport once `run()` starts — all diagnostics go to stderr."""
217
+ from okfkit.serve import mcp as mcpmod
218
+ if args.vault:
219
+ target = os.path.abspath(os.path.expanduser(args.vault))
220
+ if not os.path.isdir(target):
221
+ raise SystemExit(f"No vault at {target}.")
222
+ register = f"claude mcp add okf-wiki -- okf serve --vault {target}"
223
+ else:
224
+ from okfkit import config
225
+ target = config.load(args.config)
226
+ register = f"claude mcp add okf-wiki -- okf serve -c {os.path.abspath(args.config)}"
227
+ if args.no_rag:
228
+ register += " --no-rag"
229
+ print("okf MCP server starting (stdio). Register it with e.g.:", file=sys.stderr)
230
+ print(f" {register}", file=sys.stderr)
231
+ return mcpmod.run(target, use_rag=not args.no_rag)
232
+
233
+
234
+ def _init(args):
235
+ dst = "okf.config.yaml"
236
+ if os.path.exists(dst):
237
+ print(f"{dst} already exists — leaving it untouched.")
238
+ else:
239
+ with open(dst, "w", encoding="utf-8") as fh:
240
+ fh.write(_CONFIG_TEMPLATE)
241
+ print(f"Wrote {dst}")
242
+ if args.adapter_stub:
243
+ if os.path.exists("adapter.py"):
244
+ print("adapter.py already exists — leaving it untouched.")
245
+ else:
246
+ with open("adapter.py", "w", encoding="utf-8") as fh:
247
+ fh.write(_ADAPTER_TEMPLATE)
248
+ print("Wrote adapter.py")
249
+ print("\nNext: edit okf.config.yaml, then run `okf build`.")
250
+ return 0
251
+
252
+
253
+ _CONFIG_TEMPLATE = """\
254
+ adapter: markdown_folder
255
+ adapter_options:
256
+ path: ./notes
257
+ default_type: Note
258
+ output: ./vault
259
+ link_style: wikilink
260
+ link_inference:
261
+ concept_type: ""
262
+ scan_types: []
263
+ min_surface_len: 5
264
+ exclude_titles: ["References"]
265
+ enrich:
266
+ provider: null
267
+ model: null
268
+ base_url: null
269
+ describe_types: []
270
+ canonicalize_type: ""
271
+ """
272
+
273
+ _ADAPTER_TEMPLATE = '''\
274
+ """Custom source adapter. Point okf.config.yaml at it: adapter: adapter.py:MyAdapter"""
275
+
276
+ from okfkit.model import Node, Link
277
+ from okfkit.adapters.base import SourceAdapter
278
+
279
+
280
+ class MyAdapter(SourceAdapter):
281
+ def load(self):
282
+ # self.options holds adapter_options from okf.config.yaml
283
+ # Yield one Node per knowledge item:
284
+ yield Node(
285
+ id="example-1",
286
+ type="Article",
287
+ title="Example",
288
+ body="# Example\\n\\nBody markdown here.",
289
+ frontmatter={},
290
+ links=[], # e.g. [Link(target="example-2", rel="related", section="See also")]
291
+ tags=[],
292
+ aliases=[],
293
+ )
294
+ '''
295
+
296
+
297
+ if __name__ == "__main__":
298
+ sys.exit(main())