"""Command-line entry point. Every command prints one JSON object (machine-readable handoff).""" from __future__ import annotations import argparse import json import sys import time from pathlib import Path from . import store from .config import Config from .crawl import crawl, iter_files def _cfg(a: argparse.Namespace) -> Config: return Config.load(database_url=a.database_url, data_dir=a.data_dir, max_pages=getattr(a, "max_pages", None), max_depth=getattr(a, "max_depth", None), crawl_delay=getattr(a, "delay", None), models=a.models.split(",") if getattr(a, "models", None) else None) def _emit(obj: dict) -> None: print(json.dumps(obj, indent=2, default=str)) def cmd_migrate(a): with store.connect(_cfg(a)) as conn: _emit({"applied": store.migrate(conn), "status": store.status(conn)}) def _ingest_items(a, items): cfg = _cfg(a) t0 = time.time() results = [] with store.connect(cfg) as conn: for item in items(cfg): results.append(store.ingest(conn, cfg, item).__dict__) emb = store.embed_pending(conn, cfg) if not a.no_embed else {} summary = {s: sum(r["status"] == s for r in results) for s in ("created", "updated", "unchanged", "duplicate", "rejected", "failed")} _emit({"summary": summary, "embedded": emb, "seconds": round(time.time() - t0, 2), "status": store.status(conn), "lossless_failures": store.verify_lossless(conn), "results": results}) def cmd_ingest(a): if a.jekyll and not a.source_url_prefix: raise SystemExit("--jekyll requires --source-url-prefix.") if a.source_url_prefix and not a.source_url_prefix.startswith(("http://", "https://")): raise SystemExit("--source-url-prefix must start with http:// or https://.") url_root = Path(a.source_url_root) if a.source_url_root else None _ingest_items( a, lambda cfg: ( f for p in a.paths for f in iter_files( cfg, Path(p), source_url_prefix=a.source_url_prefix, source_url_root=url_root, jekyll=a.jekyll, ) ), ) def cmd_crawl(a): _ingest_items(a, lambda cfg: crawl(cfg, a.seeds, set(a.allow_host) if a.allow_host else None)) def cmd_embed(a): cfg = _cfg(a) with store.connect(cfg) as conn: _emit({"embedded": store.embed_pending(conn, cfg), "status": store.status(conn)}) def cmd_search(a): with store.connect(_cfg(a)) as conn: rows = store.search(conn, a.query, a.mode, a.k, json.loads(a.filter) if a.filter else None, a.min_bge, a.min_gte, a.min_keyword_coverage) for r in rows: r["content"] = r["content"][: a.snippet] _emit({"query": a.query, "mode": a.mode, "results": rows}) def cmd_export(a): from .export import LocalOnlyExportError, export_all, staging_statements if a.staging_sql and not (a.source_key or a.source_prefix or a.all_sources): raise SystemExit("Choose --source-key, --source-prefix, or --all-sources for a staging SQL export.") cfg = _cfg(a) out = Path(a.out or cfg.export_dir) if out.exists() and (not out.is_dir() or any(out.iterdir())): raise SystemExit("Export directory is not empty. Choose a new --out directory.") with store.connect(cfg) as conn: conn.execute("set transaction isolation level repeatable read, read only") keys = a.source_key if a.source_prefix is not None: keys = [r["source_key"] for r in conn.execute( "select source_key from rag_documents where starts_with(source_key, %s)", (a.source_prefix,))] try: staging_blocks = staging_statements(conn, keys) if a.staging_sql else [] except LocalOnlyExportError as exc: raise SystemExit(str(exc)) from exc files = export_all(conn, out, keys) oversized = {} if a.staging_sql: p = out / "staging_load" p.mkdir() # Statements carry their own revision checks and are never split. # A large statement is emitted in its own part and reported. n, buf, size = 0, [], 0 def flush(): part = p / f"{n:05d}.sql" part.write_text(";\n".join(buf) + ";\n", encoding="utf-8") if size > a.max_file_bytes: oversized[part.name] = size for stmts in staging_blocks: for st in stmts: st_size = len(st.encode("utf-8")) + 2 if buf and size + st_size > a.max_file_bytes: flush() n, buf, size = n + 1, [], 0 buf.append(st) size += st_size if buf: flush() n += 1 files["staging_load"] = f"{p} ({n} files)" _emit({"files": files, "oversized_sql_parts": oversized}) def _nonblank(value: str) -> str: if not value.strip(): raise argparse.ArgumentTypeError("source selector must not be empty") return value def _positive(value: str) -> int: number = int(value) if number <= 0: raise argparse.ArgumentTypeError("must be a positive integer") return number def cmd_backfill_sql(a): """Read remote chunk rows (JSON list of {id, content, content_sha256}); write guarded UPDATEs.""" from .export import backfill_sql, contracts_sql cfg = _cfg(a) rows = json.loads(Path(a.input).read_text()) stmts = [contracts_sql()] + backfill_sql(rows, cfg.models, cfg.embed_batch_size) Path(a.out).write_text(";\n".join(stmts) + ";\n") _emit({"rows": len(rows), "statements": len(stmts), "out": a.out, "models": cfg.models}) def cmd_status(a): with store.connect(_cfg(a)) as conn: _emit({"status": store.status(conn), "lossless_failures": store.verify_lossless(conn)}) def _models_dir(a: argparse.Namespace) -> Path: if getattr(a, "models_dir", None): return Path(a.models_dir) return _cfg(a).data_dir / "models" def cmd_llm_catalog(a): from .local_llm import DEFAULT_MODEL_ID, list_catalog mdir = _models_dir(a) _emit({"default_model": DEFAULT_MODEL_ID, "models_dir": str(mdir), "models": list_catalog(mdir)}) def cmd_llm_check_updates(a): from .local_llm import check_hf_updates _emit({"checked": check_hf_updates(a.model)}) def cmd_llm_download(a): from .local_llm import download_model _emit(download_model(a.model, _models_dir(a), verify=not a.no_verify, force=a.force)) def cmd_llm_inspect(a): from .local_llm import inspect_model, resolve_model_path path, spec = resolve_model_path(a.model, _models_dir(a)) out = inspect_model(path) out["catalog_model_id"] = spec.model_id if spec else None _emit(out) def cmd_llm_run(a): from .local_llm import generate_local, resolve_model_path path, spec = resolve_model_path(a.model, _models_dir(a)) out = generate_local( a.prompt, path, backend=a.backend, threads=a.threads, cache_dir=Path(a.cache_dir) if a.cache_dir else None, system_message=a.system, max_num_tokens=a.max_context, max_output_tokens=a.max_tokens, temperature=a.temperature, top_k=a.top_k, top_p=a.top_p, thinking=a.thinking, verify_sha256=spec.sha256 if (spec and a.verify) else None, ) out["catalog_model_id"] = spec.model_id if spec else None _emit(out) def cmd_llm_rag_answer(a): from .local_llm import build_rag_prompt, generate_local, resolve_model_path cfg = _cfg(a) path, spec = resolve_model_path(a.model, _models_dir(a)) with store.connect(cfg) as conn: rows = store.search( conn, a.query, a.mode, a.k, json.loads(a.filter) if a.filter else None, a.min_bge, a.min_gte, a.min_keyword_coverage, ) system, user_prompt = build_rag_prompt(a.query, rows, max_context_chars=a.max_context_chars) gen = generate_local( user_prompt, path, backend=a.backend, threads=a.threads, cache_dir=Path(a.cache_dir) if a.cache_dir else None, system_message=system, max_num_tokens=a.max_context, max_output_tokens=a.max_tokens, temperature=a.temperature, thinking=a.thinking, ) _emit( { "query": a.query, "mode": a.mode, "catalog_model_id": spec.model_id if spec else None, "retrieved_count": len(rows), "citations": [ { "source_key": r.get("source_key"), "chunk_id": r.get("chunk_index") if r.get("chunk_index") is not None else r.get("id"), "heading_path": r.get("heading_path"), "score": r.get("rrf_score") if r.get("rrf_score") is not None else r.get("similarity"), "bge_rank": r.get("bge_rank"), "gte_rank": r.get("gte_rank"), "keyword_rank": r.get("keyword_rank"), } for r in rows ], **gen, } ) def main(argv: list[str] | None = None) -> int: p = argparse.ArgumentParser(prog="cdi", description=__doc__) p.add_argument("--database-url") p.add_argument("--data-dir") sub = p.add_subparsers(dest="cmd", required=True) sub.add_parser("migrate").set_defaults(fn=cmd_migrate) s = sub.add_parser("ingest", help="ingest local files/folders") s.add_argument("paths", nargs="+") s.add_argument("--no-embed", action="store_true") s.add_argument("--models") s.add_argument("--source-url-prefix", help="map local files to canonical http(s):// source_keys") s.add_argument("--source-url-root", help="base directory for --source-url-prefix relative paths") s.add_argument("--jekyll", action="store_true", help="map Jekyll frontmatter permalinks and _collections to canonical URLs") s.set_defaults(fn=cmd_ingest) s = sub.add_parser("crawl", help="bounded same-host crawl then ingest") s.add_argument("seeds", nargs="+") s.add_argument("--allow-host", action="append") s.add_argument("--max-pages", type=int) s.add_argument("--max-depth", type=int) s.add_argument("--delay", type=float) s.add_argument("--no-embed", action="store_true") s.add_argument("--models") s.set_defaults(fn=cmd_crawl) s = sub.add_parser("embed", help="fill missing vectors") s.add_argument("--models") s.set_defaults(fn=cmd_embed) s = sub.add_parser("search") s.add_argument("query") s.add_argument("--mode", choices=["hybrid", "bge", "gte", "keyword"], default="hybrid") s.add_argument("-k", type=int, default=5) s.add_argument("--filter", help="JSON metadata containment filter") s.add_argument("--snippet", type=int, default=240) s.add_argument("--min-bge", type=float, help="hybrid: BGE cosine floor (encoder-specific)") s.add_argument("--min-gte", type=float, help="hybrid: GTE cosine floor (encoder-specific)") s.add_argument("--min-keyword-coverage", type=float, help="share of distinct query terms a keyword hit must contain") s.set_defaults(fn=cmd_search) s = sub.add_parser("export") s.add_argument("--out") s.add_argument("--staging-sql", action="store_true", help="also write per-document SQL load files") selector = s.add_mutually_exclusive_group() selector.add_argument("--source-key", action="append", type=_nonblank) selector.add_argument("--source-prefix", type=_nonblank, help="only docs with this literal source_key prefix") selector.add_argument("--all-sources", action="store_true", help="explicitly export the full corpus") s.add_argument("--max-file-bytes", type=_positive, default=1_000_000, help="target SQL part size; oversized indivisible statements are reported") s.set_defaults(fn=cmd_export) s = sub.add_parser("backfill-sql", help="vectors for chunks already stored remotely") s.add_argument("input") s.add_argument("--out", required=True) s.add_argument("--models") s.set_defaults(fn=cmd_backfill_sql) sub.add_parser("status").set_defaults(fn=cmd_status) llm = sub.add_parser("llm", help="offline Gemma LiteRT-LM catalog, download, update-check, and local inference") llm_sub = llm.add_subparsers(dest="llm_cmd", required=True) lc = llm_sub.add_parser("catalog", help="list pinned Gemma LiteRT-LM bundles") lc.add_argument("--models-dir") lc.set_defaults(fn=cmd_llm_catalog) lu = llm_sub.add_parser("check-updates", help="query Hugging Face for newer Gemma .litertlm builds") lu.add_argument("--model", help="optional catalog model_id (default: check all)") lu.set_defaults(fn=cmd_llm_check_updates) ld = llm_sub.add_parser("download", help="download and SHA-256 verify a Gemma .litertlm model") ld.add_argument("--model", default="gemma-4-e4b") ld.add_argument("--models-dir") ld.add_argument("--no-verify", action="store_true") ld.add_argument("--force", action="store_true") ld.set_defaults(fn=cmd_llm_download) li = llm_sub.add_parser("inspect", help="inspect .litertlm capabilities via LiteRT-LM ModelInfo") li.add_argument("--model", default="gemma-4-e4b") li.add_argument("--models-dir") li.set_defaults(fn=cmd_llm_inspect) lr = llm_sub.add_parser("run", help="run offline inference on a local Gemma .litertlm bundle") lr.add_argument("--model", default="gemma-4-e4b") lr.add_argument("--models-dir") lr.add_argument("--prompt", required=True) lr.add_argument("--system") lr.add_argument("--backend", choices=["cpu", "gpu"], default="cpu") lr.add_argument("--threads", type=int) lr.add_argument("--cache-dir") lr.add_argument("--max-context", type=_positive, default=4096) lr.add_argument("--max-tokens", type=_positive, default=512) lr.add_argument("--temperature", type=float, default=0.2) lr.add_argument("--top-k", type=int, default=40) lr.add_argument("--top-p", type=float, default=0.95) lr.add_argument("--thinking", action="store_true") lr.add_argument("--verify", action="store_true") lr.set_defaults(fn=cmd_llm_run) lrag = llm_sub.add_parser("rag-answer", help="retrieve hybrid pgvector chunks and synthesize locally offline") lrag.add_argument("query") lrag.add_argument("--model", default="gemma-4-e4b") lrag.add_argument("--models-dir") lrag.add_argument("--mode", choices=["hybrid", "bge", "gte", "keyword"], default="hybrid") lrag.add_argument("-k", type=int, default=5) lrag.add_argument("--filter", help="JSON metadata containment filter") lrag.add_argument("--min-bge", type=float) lrag.add_argument("--min-gte", type=float) lrag.add_argument("--min-keyword-coverage", type=float) lrag.add_argument("--max-context-chars", type=_positive, default=8000) lrag.add_argument("--backend", choices=["cpu", "gpu"], default="cpu") lrag.add_argument("--threads", type=int) lrag.add_argument("--cache-dir") lrag.add_argument("--max-context", type=_positive, default=4096) lrag.add_argument("--max-tokens", type=_positive, default=512) lrag.add_argument("--temperature", type=float, default=0.2) lrag.add_argument("--thinking", action="store_true") lrag.set_defaults(fn=cmd_llm_rag_answer) a = p.parse_args(argv) a.fn(a) return 0 if __name__ == "__main__": sys.exit(main())