File size: 15,775 Bytes
d5885e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""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())