virtudoc 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.
virtudoc/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """VirtuDoc — a local documentation server for AI agents."""
2
+
3
+ __version__ = "0.1.0"
virtudoc/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
virtudoc/cli.py ADDED
@@ -0,0 +1,559 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ import shutil
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .config import DATA_DIR_ENV, Config, data_dir
10
+ from .db import open_db
11
+ from .doctor import run_doctor
12
+ from .indexer.chunker import Chunker
13
+ from .indexer.indexer import (
14
+ IndexLockError,
15
+ LibraryExistsError,
16
+ LibraryNotFoundError,
17
+ add_library,
18
+ delete_library,
19
+ get_library,
20
+ index_library,
21
+ list_libraries,
22
+ reindex_library,
23
+ update_all,
24
+ )
25
+ from .logging_setup import setup_logging
26
+ from .notes import add_note, list_notes, relevant_notes, remove_note
27
+ from .search.engine import library_outline, search
28
+ from .versions import link_library, unlink_library
29
+
30
+
31
+ def _chunker_from_config(cfg: Config) -> Chunker:
32
+ return Chunker(
33
+ target_tokens=cfg.get_int("chunk.target_tokens"),
34
+ max_tokens=cfg.get_int("chunk.max_tokens"),
35
+ overlap_tokens=cfg.get_int("chunk.overlap_tokens"),
36
+ )
37
+
38
+
39
+ def _open(cfg: Config):
40
+ return open_db(cfg.db_path)
41
+
42
+
43
+ def _print_skipped(skipped_files: list[str]) -> None:
44
+ for rel_path in skipped_files:
45
+ print(f" ! skipped (over 5 MB): {rel_path}", file=sys.stderr)
46
+
47
+
48
+ def cmd_add(args: argparse.Namespace, cfg: Config) -> int:
49
+ with _open(cfg) as conn:
50
+ try:
51
+ lib_id = add_library(
52
+ conn,
53
+ Path(args.path),
54
+ args.name,
55
+ version=args.version,
56
+ description=args.description,
57
+ replace=args.replace,
58
+ )
59
+ stats = index_library(conn, lib_id, _chunker_from_config(cfg))
60
+ except (LibraryExistsError, ValueError, IndexLockError) as exc:
61
+ print(f"error: {exc}", file=sys.stderr)
62
+ return 1
63
+ print(f"added library {lib_id}")
64
+ print(stats.summary())
65
+ _print_skipped(stats.skipped_files)
66
+ return 0 if stats.errors == 0 else 1
67
+
68
+
69
+ def cmd_update(args: argparse.Namespace, cfg: Config) -> int:
70
+ chunker = _chunker_from_config(cfg)
71
+ with _open(cfg) as conn:
72
+ try:
73
+ if args.name:
74
+ lib = get_library(conn, args.name)
75
+ stats = index_library(conn, lib["id"], chunker)
76
+ print(f"{lib['id']}: {stats.summary()}")
77
+ _print_skipped(stats.skipped_files)
78
+ return 0 if stats.errors == 0 else 1
79
+ results = update_all(conn, chunker)
80
+ except (LibraryNotFoundError, IndexLockError, ValueError) as exc:
81
+ print(f"error: {exc}", file=sys.stderr)
82
+ return 1
83
+ if not results:
84
+ print("no libraries registered")
85
+ return 0
86
+ for lib_id, stats in results.items():
87
+ print(f"{lib_id}: {stats.summary()}")
88
+ _print_skipped(stats.skipped_files)
89
+ chunk_keys = [
90
+ key
91
+ for key in ("chunk.target_tokens", "chunk.max_tokens", "chunk.overlap_tokens")
92
+ if cfg.values.get(key) != Config().values[key]
93
+ ]
94
+ if chunk_keys:
95
+ print(
96
+ "note: changed chunk.* settings only affect new indexing; "
97
+ f"rebuild the index with: virtudoc reindex {args.name or '<name>'}"
98
+ )
99
+ return 0
100
+
101
+
102
+ def cmd_reindex(args: argparse.Namespace, cfg: Config) -> int:
103
+ chunker = _chunker_from_config(cfg)
104
+ with _open(cfg) as conn:
105
+ try:
106
+ lib = get_library(conn, args.name)
107
+ stats = reindex_library(conn, lib["id"], chunker)
108
+ except (LibraryNotFoundError, IndexLockError, ValueError) as exc:
109
+ print(f"error: {exc}", file=sys.stderr)
110
+ return 1
111
+ print(f"{lib['id']}: {stats.summary()}")
112
+ _print_skipped(stats.skipped_files)
113
+ return 0 if stats.errors == 0 else 1
114
+
115
+
116
+ def cmd_list(args: argparse.Namespace, cfg: Config) -> int:
117
+ with _open(cfg) as conn:
118
+ rows = list_libraries(conn)
119
+ if not rows:
120
+ print("no libraries registered")
121
+ return 0
122
+ header = f"{'ID':<28} {'Documents':>9} {'Chunks':>8} {'Size':>10} {'Updated':<20} Source"
123
+ print(header)
124
+ for row in rows:
125
+ size = row["index_bytes"]
126
+ size_str = f"{size / 1024:.0f} KB" if size < 1024 * 1024 else f"{size / 1024 / 1024:.1f} MB"
127
+ print(
128
+ f"{row['id']:<28} {row['doc_count']:>9} {row['chunk_count']:>8} "
129
+ f"{size_str:>10} {row['updated_at']:<20} {row['source_path']}"
130
+ )
131
+ return 0
132
+
133
+
134
+ def cmd_remove(args: argparse.Namespace, cfg: Config) -> int:
135
+ lib_id = f"local/{args.name}"
136
+ if not args.yes:
137
+ answer = input(f"Remove library {lib_id} and all its data? [y/N] ")
138
+ if answer.strip().lower() not in ("y", "yes"):
139
+ print("cancelled")
140
+ return 0
141
+ with _open(cfg) as conn:
142
+ try:
143
+ get_library(conn, args.name)
144
+ except LibraryNotFoundError as exc:
145
+ print(f"error: {exc}", file=sys.stderr)
146
+ return 1
147
+ delete_library(conn, args.name)
148
+ print(f"removed library {lib_id}")
149
+ return 0
150
+
151
+
152
+ def cmd_search(args: argparse.Namespace, cfg: Config) -> int:
153
+ with _open(cfg) as conn:
154
+ library_id = None
155
+ if args.name:
156
+ try:
157
+ library_id = get_library(conn, args.name)["id"]
158
+ except LibraryNotFoundError as exc:
159
+ print(f"error: {exc}", file=sys.stderr)
160
+ return 1
161
+ if args.outline:
162
+ if not library_id:
163
+ print("error: --outline requires --name", file=sys.stderr)
164
+ return 1
165
+ tree = library_outline(conn, library_id, section=args.section)
166
+ print(
167
+ f"outline of {library_id}" + (f" (section: {args.section})" if args.section else "")
168
+ )
169
+ _print_outline(tree)
170
+ return 0
171
+ result = search(
172
+ conn,
173
+ args.query,
174
+ library_id=library_id,
175
+ token_budget=args.tokens or cfg.get_int("search.default_tokens"),
176
+ max_results=cfg.get_int("search.max_results"),
177
+ section=args.section,
178
+ window_tokens=cfg.get_int("search.snippet_window_tokens"),
179
+ )
180
+ notes = []
181
+ if library_id:
182
+ notes = relevant_notes(
183
+ conn,
184
+ library_id,
185
+ args.query,
186
+ budget_tokens=cfg.get_int("notes.max_tokens"),
187
+ )
188
+ if notes:
189
+ print("=== project notes ===")
190
+ for note in notes:
191
+ print(f"[note #{note.id} | {note.created_at}]\n{note.text}\n")
192
+ if not result.snippets:
193
+ print("nothing found; try rephrasing the query with keywords")
194
+ return 0
195
+ for snippet in result.snippets:
196
+ heading = snippet.heading_path or "(no section)"
197
+ print(f"\n## [{snippet.score:.2f}] {heading} — {snippet.source} (~{snippet.tokens} tokens)")
198
+ print(snippet.text)
199
+ print(f"\n---\nfragments: {result.total_chunks}, tokens: {result.total_tokens}")
200
+ return 0
201
+
202
+
203
+ def cmd_serve(args: argparse.Namespace, cfg: Config) -> int:
204
+ from .mcp_server import run_serve
205
+
206
+ return run_serve(cfg, http=args.http)
207
+
208
+
209
+ def _print_outline(nodes, indent: int = 0) -> None:
210
+ for node in nodes:
211
+ print(
212
+ f"{' ' * indent}- {node.section} ({node.chunk_count} chunks, ~{node.token_est} tokens)"
213
+ )
214
+ _print_outline(node.children, indent + 1)
215
+
216
+
217
+ def cmd_note_add(args: argparse.Namespace, cfg: Config) -> int:
218
+ with _open(cfg) as conn:
219
+ try:
220
+ lib = get_library(conn, args.name)
221
+ except LibraryNotFoundError as exc:
222
+ print(f"error: {exc}", file=sys.stderr)
223
+ return 1
224
+ note_id = add_note(conn, lib["id"], args.text)
225
+ print(f"added note #{note_id} to {lib['id']}")
226
+ return 0
227
+
228
+
229
+ def cmd_note_list(args: argparse.Namespace, cfg: Config) -> int:
230
+ with _open(cfg) as conn:
231
+ try:
232
+ lib = get_library(conn, args.name)
233
+ except LibraryNotFoundError as exc:
234
+ print(f"error: {exc}", file=sys.stderr)
235
+ return 1
236
+ notes = list_notes(conn, lib["id"])
237
+ if not notes:
238
+ print(f"no notes for {lib['id']}")
239
+ return 0
240
+ for note in notes:
241
+ print(f"#{note.id}\t{note.created_at}\t{note.text}")
242
+ return 0
243
+
244
+
245
+ def cmd_note_remove(args: argparse.Namespace, cfg: Config) -> int:
246
+ with _open(cfg) as conn:
247
+ try:
248
+ lib = get_library(conn, args.name)
249
+ except LibraryNotFoundError as exc:
250
+ print(f"error: {exc}", file=sys.stderr)
251
+ return 1
252
+ removed = remove_note(conn, lib["id"], args.id)
253
+ if not removed:
254
+ print(f"error: note #{args.id} not found in {lib['id']}", file=sys.stderr)
255
+ return 1
256
+ print(f"removed note #{args.id} from {lib['id']}")
257
+ return 0
258
+
259
+
260
+ def cmd_link(args: argparse.Namespace, cfg: Config) -> int:
261
+ with _open(cfg) as conn:
262
+ try:
263
+ lib = get_library(conn, args.name)
264
+ except LibraryNotFoundError as exc:
265
+ print(f"error: {exc}", file=sys.stderr)
266
+ return 1
267
+ try:
268
+ info = link_library(conn, lib["id"], Path(args.project))
269
+ except ValueError as exc:
270
+ print(f"error: {exc}", file=sys.stderr)
271
+ return 1
272
+ print(f"linked {lib['id']} -> {info.manifest_path} (project version: {info.dep_version})")
273
+ return 0
274
+
275
+
276
+ def cmd_unlink(args: argparse.Namespace, cfg: Config) -> int:
277
+ with _open(cfg) as conn:
278
+ try:
279
+ lib = get_library(conn, args.name)
280
+ except LibraryNotFoundError as exc:
281
+ print(f"error: {exc}", file=sys.stderr)
282
+ return 1
283
+ removed = unlink_library(conn, lib["id"])
284
+ if not removed:
285
+ print(f"{lib['id']} has no project link")
286
+ return 0
287
+ print(f"unlinked {lib['id']}")
288
+ return 0
289
+
290
+
291
+ def _server_command() -> str:
292
+ """Absolute path of the virtudoc binary as an MCP client will see it."""
293
+ argv0 = Path(sys.argv[0]).resolve() if sys.argv[0] else None
294
+ if argv0 and argv0.name == "virtudoc" and argv0.is_file():
295
+ return str(argv0)
296
+ resolved = shutil.which("virtudoc")
297
+ if resolved:
298
+ return str(Path(resolved).resolve())
299
+ return f"{sys.executable} -m virtudoc"
300
+
301
+
302
+ def cmd_mcp_config(args: argparse.Namespace, cfg: Config) -> int:
303
+ import json
304
+
305
+ server_entry: dict[str, object] = {
306
+ "command": _server_command(),
307
+ "args": ["serve"],
308
+ }
309
+ env = {"VIRTUDOC_HOME": str(data_dir())} if os.environ.get(DATA_DIR_ENV) else {}
310
+ if env:
311
+ server_entry["env"] = env
312
+ print(
313
+ "Paste into the MCP client config (Claude Code, Cursor, etc.):",
314
+ file=sys.stderr,
315
+ )
316
+ print(json.dumps({"mcpServers": {"virtudoc": server_entry}}, indent=2))
317
+ return 0
318
+
319
+
320
+ def cmd_doctor(args: argparse.Namespace, cfg: Config) -> int:
321
+ with _open(cfg) as conn:
322
+ result = run_doctor(conn, cfg)
323
+ print("virtudoc doctor")
324
+ for line in result.lines:
325
+ print(line)
326
+ return 1 if result.problems else 0
327
+
328
+
329
+ def cmd_fetch(args: argparse.Namespace, cfg: Config) -> int:
330
+ from .fetcher import FetchError, fetch_source
331
+
332
+ configured_branch = cfg.values.get("fetch.branch")
333
+ branch = args.branch or (str(configured_branch) if configured_branch else None)
334
+ try:
335
+ source = fetch_source(args.repo, args.name, branch=branch)
336
+ except (FetchError, ValueError) as exc:
337
+ print(f"error: {exc}", file=sys.stderr)
338
+ return 1
339
+ with _open(cfg) as conn:
340
+ try:
341
+ lib_id = add_library(
342
+ conn,
343
+ source,
344
+ args.name,
345
+ version=args.version,
346
+ description=args.repo,
347
+ replace=args.replace,
348
+ )
349
+ stats = index_library(conn, lib_id, _chunker_from_config(cfg))
350
+ except (LibraryExistsError, ValueError, IndexLockError) as exc:
351
+ print(f"error: {exc}", file=sys.stderr)
352
+ return 1
353
+ print(f"fetched {args.repo} into {source}")
354
+ print(f"added library {lib_id}")
355
+ print(stats.summary())
356
+ _print_skipped(stats.skipped_files)
357
+ return 0 if stats.errors == 0 else 1
358
+
359
+
360
+ def cmd_export(args: argparse.Namespace, cfg: Config) -> int:
361
+ import json
362
+
363
+ with _open(cfg) as conn:
364
+ rows = list_libraries(conn)
365
+ lines = [
366
+ "# VirtuDoc libraries — restore with: virtudoc import",
367
+ "# Paths are absolute; adjust after moving between machines if needed.",
368
+ "",
369
+ ]
370
+ for row in rows:
371
+ lines.append("[[libraries]]")
372
+ lines.append(f"name = {json.dumps(row['name'], ensure_ascii=False)}")
373
+ lines.append(f"path = {json.dumps(row['source_path'], ensure_ascii=False)}")
374
+ if row["version"]:
375
+ lines.append(f"version = {json.dumps(row['version'], ensure_ascii=False)}")
376
+ lines.append("")
377
+ out = Path(args.path) if args.path else data_dir() / "libraries.toml"
378
+ out.parent.mkdir(parents=True, exist_ok=True)
379
+ out.write_text("\n".join(lines), encoding="utf-8")
380
+ print(f"exported {len(rows)} libraries to {out}")
381
+ return 0
382
+
383
+
384
+ def cmd_import(args: argparse.Namespace, cfg: Config) -> int:
385
+ import tomllib
386
+
387
+ path = Path(args.path) if args.path else data_dir() / "libraries.toml"
388
+ if not path.is_file():
389
+ print(f"error: setup file not found: {path}", file=sys.stderr)
390
+ return 1
391
+ try:
392
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
393
+ except tomllib.TOMLDecodeError as exc:
394
+ print(f"error: cannot parse {path}: {exc}", file=sys.stderr)
395
+ return 1
396
+ libraries = data.get("libraries", [])
397
+ if not libraries:
398
+ print(f"no libraries in {path}")
399
+ return 0
400
+ chunker = _chunker_from_config(cfg)
401
+ imported, failed = 0, 0
402
+ with _open(cfg) as conn:
403
+ for lib in libraries:
404
+ name = str(lib.get("name", ""))
405
+ source = lib.get("path")
406
+ if not name or not source:
407
+ print(f"error: entry without name/path: {lib!r}", file=sys.stderr)
408
+ failed += 1
409
+ continue
410
+ try:
411
+ lib_id = add_library(
412
+ conn,
413
+ Path(str(source)),
414
+ name,
415
+ version=str(lib["version"]) if lib.get("version") else None,
416
+ replace=True,
417
+ )
418
+ stats = index_library(conn, lib_id, chunker)
419
+ except (LibraryExistsError, ValueError, OSError, IndexLockError) as exc:
420
+ print(f"error: {name}: {exc}", file=sys.stderr)
421
+ failed += 1
422
+ continue
423
+ imported += 1
424
+ print(f"{lib_id}: {stats.summary()}")
425
+ print(f"imported: {imported}, failed: {failed}")
426
+ return 1 if failed else 0
427
+
428
+
429
+ def build_parser() -> argparse.ArgumentParser:
430
+ parser = argparse.ArgumentParser(
431
+ prog="virtudoc",
432
+ description="Local documentation server for AI agents",
433
+ )
434
+ sub = parser.add_subparsers(dest="command", required=True)
435
+
436
+ p = sub.add_parser("add", help="register a source and run the first indexing")
437
+ p.add_argument("path", help="path to the documentation directory")
438
+ p.add_argument("--name", required=True, help="library name")
439
+ p.add_argument("--version", help="documentation version")
440
+ p.add_argument("--description", help="library description")
441
+ p.add_argument("--replace", action="store_true", help="replace an existing library")
442
+ p.set_defaults(func=cmd_add)
443
+
444
+ p = sub.add_parser("update", help="incremental reindexing")
445
+ p.add_argument("--name", help="library name (omitted — all libraries)")
446
+ p.set_defaults(func=cmd_update)
447
+
448
+ p = sub.add_parser(
449
+ "reindex",
450
+ help="full rebuild of one library, applying the current chunk.* settings",
451
+ )
452
+ p.add_argument("name", help="library name")
453
+ p.set_defaults(func=cmd_reindex)
454
+
455
+ p = sub.add_parser("list", help="list libraries with index statistics")
456
+ p.set_defaults(func=cmd_list)
457
+
458
+ p = sub.add_parser("remove", help="remove a library and its data")
459
+ p.add_argument("name", help="library name")
460
+ p.add_argument("--yes", action="store_true", help="skip the confirmation prompt")
461
+ p.set_defaults(func=cmd_remove)
462
+
463
+ p = sub.add_parser("search", help="search the index")
464
+ p.add_argument("query", help="search query")
465
+ p.add_argument("--name", help="restrict the search to one library")
466
+ p.add_argument("--tokens", type=int, help="token budget for the output")
467
+ p.add_argument(
468
+ "--section", help="restrict the output to a section branch (e.g. 'API -> Middleware')"
469
+ )
470
+ p.add_argument(
471
+ "--outline",
472
+ action="store_true",
473
+ help="print the section tree instead of fragments (requires --name)",
474
+ )
475
+ p.set_defaults(func=cmd_search)
476
+
477
+ p = sub.add_parser("serve", help="start the MCP server")
478
+ p.add_argument(
479
+ "--http",
480
+ nargs="?",
481
+ const=True,
482
+ default=False,
483
+ type=int,
484
+ metavar="PORT",
485
+ help="use streamable HTTP on 127.0.0.1 (default port: config server.http_port)",
486
+ )
487
+ p.set_defaults(func=cmd_serve)
488
+
489
+ p = sub.add_parser("note", help="project notes attached to a library")
490
+ note_sub = p.add_subparsers(dest="note_command", required=True)
491
+
492
+ n = note_sub.add_parser("add", help="attach a note to a library")
493
+ n.add_argument("name", help="library name")
494
+ n.add_argument("--text", required=True, help="note text")
495
+ n.set_defaults(func=cmd_note_add)
496
+
497
+ n = note_sub.add_parser("list", help="list notes of a library")
498
+ n.add_argument("name", help="library name")
499
+ n.set_defaults(func=cmd_note_list)
500
+
501
+ n = note_sub.add_parser("remove", help="remove a note from a library")
502
+ n.add_argument("name", help="library name")
503
+ n.add_argument("--id", type=int, required=True, help="note id")
504
+ n.set_defaults(func=cmd_note_remove)
505
+
506
+ p = sub.add_parser("link", help="link a library to a project dependency manifest")
507
+ p.add_argument("name", help="library name")
508
+ p.add_argument("--project", required=True, help="path to the consuming project")
509
+ p.set_defaults(func=cmd_link)
510
+
511
+ p = sub.add_parser("unlink", help="remove the project link of a library")
512
+ p.add_argument("name", help="library name")
513
+ p.set_defaults(func=cmd_unlink)
514
+
515
+ p = sub.add_parser("doctor", help="check configuration, sources, index integrity")
516
+ p.set_defaults(func=cmd_doctor)
517
+
518
+ p = sub.add_parser(
519
+ "mcp-config",
520
+ help="print a ready MCP client config snippet with the absolute server path",
521
+ )
522
+ p.set_defaults(func=cmd_mcp_config)
523
+
524
+ p = sub.add_parser(
525
+ "fetch",
526
+ help="download documentation from a URL into the local cache and index it "
527
+ "(the only command that uses the network)",
528
+ )
529
+ p.add_argument("--repo", required=True, help="git URL or archive URL (.zip, .tar.gz)")
530
+ p.add_argument("--name", required=True, help="library name")
531
+ p.add_argument("--version", help="documentation version")
532
+ p.add_argument(
533
+ "--branch",
534
+ help="git branch to fetch (default: config fetch.branch, else the repo default branch)",
535
+ )
536
+ p.add_argument("--replace", action="store_true", help="replace an existing library")
537
+ p.set_defaults(func=cmd_fetch)
538
+
539
+ p = sub.add_parser("export", help="dump the library list to a TOML setup file")
540
+ p.add_argument("path", nargs="?", help="output file (default: ~/.virtudoc/libraries.toml)")
541
+ p.set_defaults(func=cmd_export)
542
+
543
+ p = sub.add_parser("import", help="register and index libraries from a TOML setup file")
544
+ p.add_argument("path", nargs="?", help="setup file (default: ~/.virtudoc/libraries.toml)")
545
+ p.set_defaults(func=cmd_import)
546
+
547
+ return parser
548
+
549
+
550
+ def main(argv: list[str] | None = None) -> int:
551
+ parser = build_parser()
552
+ args = parser.parse_args(argv)
553
+ cfg = Config.load()
554
+ setup_logging(data_dir(), cfg.get_str("log.level"))
555
+ return int(args.func(args, cfg))
556
+
557
+
558
+ if __name__ == "__main__":
559
+ raise SystemExit(main())
virtudoc/config.py ADDED
@@ -0,0 +1,83 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ import tomllib
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ DATA_DIR_ENV = "VIRTUDOC_HOME"
10
+
11
+ DEFAULTS: dict[str, dict[str, object]] = {
12
+ "db": {"path": None},
13
+ "fetch": {"branch": None},
14
+ "chunk": {"target_tokens": 600, "max_tokens": 1200, "overlap_tokens": 60},
15
+ "index": {"auto_refresh": True},
16
+ "search": {"default_tokens": 5000, "max_results": 20, "snippet_window_tokens": 400},
17
+ "notes": {"max_tokens": 800},
18
+ "server": {
19
+ "transport": "stdio",
20
+ "http_host": "127.0.0.1",
21
+ "http_port": 8765,
22
+ },
23
+ "log": {"level": "INFO"},
24
+ }
25
+
26
+ _FLAT_DEFAULTS = {
27
+ f"{section}.{key}": val for section, vals in DEFAULTS.items() for key, val in vals.items()
28
+ }
29
+
30
+
31
+ def data_dir() -> Path:
32
+ override = os.environ.get(DATA_DIR_ENV)
33
+ if override:
34
+ return Path(override)
35
+ return Path.home() / ".virtudoc"
36
+
37
+
38
+ @dataclass
39
+ class Config:
40
+ values: dict[str, object] = field(default_factory=lambda: dict(_FLAT_DEFAULTS))
41
+
42
+ @classmethod
43
+ def load(cls, config_dir: Path | None = None) -> Config:
44
+ cfg = cls()
45
+ base = config_dir if config_dir is not None else data_dir()
46
+ path = base / "config.toml"
47
+ if path.is_file():
48
+ with open(path, "rb") as fh:
49
+ raw = tomllib.load(fh)
50
+ for section, vals in raw.items():
51
+ if not isinstance(vals, dict):
52
+ continue
53
+ for key, val in vals.items():
54
+ full = f"{section}.{key}"
55
+ if full not in _FLAT_DEFAULTS:
56
+ print(f"warning: unknown configuration key '{full}'", file=sys.stderr)
57
+ continue
58
+ cfg.values[full] = val
59
+ return cfg
60
+
61
+ def get(self, key: str) -> object:
62
+ if key not in self.values:
63
+ raise KeyError(f"unknown configuration key: {key}")
64
+ return self.values[key]
65
+
66
+ def get_int(self, key: str) -> int:
67
+ return int(self.get(key))
68
+
69
+ def get_str(self, key: str) -> str:
70
+ return str(self.get(key))
71
+
72
+ def get_bool(self, key: str) -> bool:
73
+ val = self.get(key)
74
+ if isinstance(val, str):
75
+ return val.strip().lower() in ("1", "true", "yes", "on")
76
+ return bool(val)
77
+
78
+ @property
79
+ def db_path(self) -> Path:
80
+ configured = self.values.get("db.path")
81
+ if configured:
82
+ return Path(str(configured)).expanduser()
83
+ return data_dir() / "index.db"