divan-cli 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.
divan/cli.py ADDED
@@ -0,0 +1,415 @@
1
+ """divan command line."""
2
+ import argparse
3
+ import datetime
4
+ import json
5
+ import os
6
+ import re
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import index as ix
11
+ from .check import check_corpus, findings_json
12
+ from .config import ConfigError, Context, load_context
13
+ from .land import land
14
+ from .safe import is_inside
15
+ from .write import new_entry
16
+
17
+
18
+ def _common():
19
+ p = argparse.ArgumentParser(add_help=False)
20
+ p.add_argument("--profile", help="profile name (default: $DIVAN_PROFILE, then 'default')")
21
+ p.add_argument("--path", help="work on one repo directly, without user config (CI)")
22
+ return p
23
+
24
+
25
+ def _emit(obj):
26
+ print(json.dumps(obj, indent=2, ensure_ascii=False))
27
+
28
+
29
+ def cmd_find(ctx: Context, a):
30
+ corpora = ctx.select(a.corpus)
31
+ sections = []
32
+ for c in corpora:
33
+ with ix.session(ctx, c, rebuild=a.rebuild) as db:
34
+ total, hits, weak = ix.find(db, a.query, collection=a.collection, include_all=a.all, n=a.n)
35
+ sections.append((c, total, hits, weak))
36
+ if a.json:
37
+ _emit({"profile": ctx.profile, "query": " ".join(a.query), "corpora": [
38
+ {"corpus": c.name, "total": t, "weak": w, "hits": [
39
+ {"corpus": c.name, "path": h.path, "title": h.title, "collection": h.collection,
40
+ "snippet": re.sub(r"\s+", " ", h.snippet).strip()} for h in hits]}
41
+ for c, t, hits, w in sections]})
42
+ return 0
43
+ if not ix.terms(a.query):
44
+ print("divan: no searchable words in query", file=sys.stderr)
45
+ return 2
46
+ for c, total, hits, weak in sections:
47
+ print(f"== {c.name}" + (" (weak match: no entry has all words; showing entries with any word)" if weak else ""))
48
+ if not hits:
49
+ print("no match; try synonyms or fewer words")
50
+ for h in hits:
51
+ snip = re.sub(r"\s+", " ", h.snippet).strip()[:90]
52
+ title = h.title if len(h.title) <= 90 else h.title[:87] + "..."
53
+ print(f"{c.name}:{h.path} | {title} | {snip}")
54
+ if total > len(hits):
55
+ print(f"{total - len(hits)} more; add terms, or use -n, --collection, --all")
56
+ return 0
57
+
58
+
59
+ def cmd_new(ctx: Context, a):
60
+ name = a.corpus or ctx.write
61
+ if not name:
62
+ raise ConfigError(f"profile '{ctx.profile}' has no write corpus; pass --corpus")
63
+ c = ctx.select([name])[0]
64
+ variables = {}
65
+ for v in a.var or []:
66
+ if "=" not in v:
67
+ raise ConfigError(f"--var wants key=value, got '{v}'")
68
+ k, val = v.split("=", 1)
69
+ variables[k] = val
70
+ dest = new_entry(ctx, c, a.title, a.collection, a.dir, variables)
71
+ rel = dest.relative_to(c.root).as_posix()
72
+ col = c.cfg.first(rel)
73
+ if a.collection and (col is None or col.name != a.collection):
74
+ print(f"note: {rel} does not match the paths of collection '{a.collection}'", file=sys.stderr)
75
+ with ix.session(ctx, c):
76
+ pass
77
+ print(dest)
78
+ g = c.guide_file()
79
+ if g is not None:
80
+ print(f"guide: divan guide {c.name} ({g.relative_to(c.root).as_posix()})", file=sys.stderr)
81
+ return 0
82
+
83
+
84
+ def cmd_land(ctx: Context, a):
85
+ land(ctx, a.files, a.m, log=lambda s: print(s, file=sys.stderr))
86
+ return 0
87
+
88
+
89
+ def _locate(c, f):
90
+ """Corpus-relative path of f (cwd-relative or corpus-relative), or None if f is not inside c."""
91
+ cands = [Path(f).expanduser().absolute(), c.root / f]
92
+ for p in cands:
93
+ if os.path.lexists(p) and is_inside(c.root, p):
94
+ return os.path.relpath(os.path.realpath(p), c.root).replace(os.sep, "/")
95
+ return None
96
+
97
+
98
+ def cmd_check(ctx: Context, a):
99
+ corpora = ctx.select(a.corpus)
100
+ per = {}
101
+ for f in a.files:
102
+ homes = [(c, r) for c in corpora if (r := _locate(c, f)) is not None]
103
+ if not homes:
104
+ raise ConfigError(f"{f}: not an existing file inside a corpus of profile '{ctx.profile}'")
105
+ for c, r in homes:
106
+ per.setdefault(c.name, []).append(r)
107
+ if a.files:
108
+ corpora = [c for c in corpora if c.name in per]
109
+ allf, rows_all = [], []
110
+ for c in corpora:
111
+ fs, rows = check_corpus(ctx, c, per.get(c.name) if a.files else None, a.explain)
112
+ allf += fs
113
+ rows_all += [dict(r, corpus=c.name) for r in rows]
114
+ errors = sum(f.severity == "error" for f in allf)
115
+ if a.json:
116
+ _emit({"errors": errors, "warnings": len(allf) - errors, "findings": findings_json(allf),
117
+ **({"explain": rows_all} if a.explain else {})})
118
+ else:
119
+ if a.explain:
120
+ for r in rows_all:
121
+ extra = f" (also: {', '.join(r['all'][1:])})" if len(r["all"]) > 1 else ""
122
+ print(f"{r['corpus']}:{r['path']} -> {r['collection'] or '(no collection)'}{extra}")
123
+ for f in allf:
124
+ print(f"{f.severity}: {f.corpus}:{f.path}:{f.line}: {f.rule}: {f.message}")
125
+ print(f"{errors} error(s), {len(allf) - errors} warning(s)")
126
+ return 1 if errors else 0
127
+
128
+
129
+ def _matches(fm, k, v):
130
+ x = fm.get(k)
131
+ if isinstance(x, list):
132
+ return v in [str(i) for i in x]
133
+ return x is not None and str(x) == v
134
+
135
+
136
+ def _since(spec: str) -> datetime.date:
137
+ m = re.fullmatch(r"(\d+)([dwm])", spec.strip())
138
+ if not m:
139
+ raise ConfigError(f"--since wants a span like 7d, 2w or 3m, got '{spec}'")
140
+ days = int(m.group(1)) * {"d": 1, "w": 7, "m": 30}[m.group(2)]
141
+ return datetime.date.today() - datetime.timedelta(days=days)
142
+
143
+
144
+ def _entry_date(fm: dict, mtime_ns: int) -> datetime.date:
145
+ """Newest of the entry's date/updated/created fields; the file's mtime when it has none."""
146
+ found = []
147
+ for k in ("date", "updated", "created"):
148
+ try:
149
+ found.append(datetime.date.fromisoformat(str(fm.get(k))[:10]))
150
+ except ValueError:
151
+ pass
152
+ return max(found) if found else datetime.date.fromtimestamp(mtime_ns / 1e9)
153
+
154
+
155
+ def cmd_guide(ctx: Context, a):
156
+ if a.corpus:
157
+ c = ctx.select([a.corpus])[0]
158
+ elif ctx.write:
159
+ c = ctx.select([ctx.write])[0]
160
+ elif len(ctx.corpora) == 1:
161
+ c = next(iter(ctx.corpora.values()))
162
+ else:
163
+ raise ConfigError(f"name a corpus: {', '.join(ctx.corpora) or 'none in this profile'}")
164
+ f = c.guide_file()
165
+ if f is None:
166
+ raise ConfigError(f"corpus '{c.name}' has no guide (set [corpus] guide in divan.toml, "
167
+ "or add AGENTS.md, CLAUDE.md or README.md)")
168
+ sys.stdout.write(f.read_text(encoding="utf-8"))
169
+ return 0
170
+
171
+
172
+ _STOP = set("the a an and or of for to in on with from by is are as at be this that how what why when into over via vs not no".split())
173
+
174
+
175
+ def _tags(fm: dict) -> list[str]:
176
+ t = fm.get("tags")
177
+ if isinstance(t, str):
178
+ t = t.split(",")
179
+ return [str(x).strip().lower() for x in t or [] if str(x).strip()]
180
+
181
+
182
+ def _topics(ctx: Context, a) -> list[dict]:
183
+ """One row per top-level folder: entry count and the 3 commonest tags (else title words)."""
184
+ from collections import Counter
185
+ out = []
186
+ for c in ctx.select(a.corpus):
187
+ with ix.session(ctx, c) as db:
188
+ rows = ix.listing(db)
189
+ groups: dict[str, list] = {}
190
+ for path, title, fmj, col, mtime_ns in rows:
191
+ if a.collection and col != a.collection:
192
+ continue
193
+ top = path.split("/", 1)[0] if "/" in path else "(root)"
194
+ groups.setdefault(top, []).append((title, json.loads(fmj)))
195
+ for top, items in sorted(groups.items()):
196
+ tags = Counter(t for _, fm in items for t in set(_tags(fm)))
197
+ if not tags:
198
+ tags = Counter(w for title, _ in items for w in set(re.findall(r"[a-z][a-z0-9-]{3,}", title.lower()))
199
+ if w not in _STOP)
200
+ top3 = [k for k, _ in sorted(tags.items(), key=lambda kv: (-kv[1], kv[0]))[:3]]
201
+ out.append({"corpus": c.name, "folder": top, "entries": len(items), "keywords": top3})
202
+ return out
203
+
204
+
205
+ def cmd_list(ctx: Context, a):
206
+ if a.topics:
207
+ rows = _topics(ctx, a)
208
+ if a.json:
209
+ _emit(rows)
210
+ else:
211
+ for r in rows:
212
+ print(f"{r['corpus']}:{r['folder']} | {r['entries']} entries | {', '.join(r['keywords'])}")
213
+ return 0
214
+ where = []
215
+ for w in a.where or []:
216
+ if "=" not in w:
217
+ raise ConfigError(f"--where wants key=value, got '{w}'")
218
+ where.append(tuple(w.split("=", 1)))
219
+ fields = [f for f in (a.fields or "").split(",") if f]
220
+ cutoff = _since(a.since) if a.since else None
221
+ out = []
222
+ for c in ctx.select(a.corpus):
223
+ with ix.session(ctx, c) as db:
224
+ rows = ix.listing(db)
225
+ for path, title, fmj, col, mtime_ns in rows:
226
+ if a.collection and col != a.collection:
227
+ continue
228
+ fm = json.loads(fmj)
229
+ if cutoff and _entry_date(fm, mtime_ns) < cutoff:
230
+ continue
231
+ if all(_matches(fm, k, v) for k, v in where):
232
+ out.append({"corpus": c.name, "path": path, "title": title, "collection": col,
233
+ **{f: fm.get(f) for f in fields}})
234
+ if a.json:
235
+ _emit(out)
236
+ return 0
237
+ for e in out:
238
+ extra = "".join(f" | {f}={e[f]}" for f in fields if e[f] is not None)
239
+ print(f"{e['corpus']}:{e['path']} | {e['title']}{extra}")
240
+ return 0
241
+
242
+
243
+ def cmd_corpora(ctx: Context, a):
244
+ info = []
245
+ for c in ctx.corpora.values():
246
+ st = ix.status(ctx, c)
247
+ cfg = c.cfg
248
+ info.append({"name": c.name, "path": str(c.root), "remote": c.remote, "shared": cfg.shared,
249
+ "write": c.name == ctx.write,
250
+ "collections": [{"name": k.name, "path": k.paths, "weight": k.weight,
251
+ "search": k.search} for k in cfg.collections], **st})
252
+ if a.json:
253
+ _emit({"profile": ctx.profile, "write": ctx.write, "corpora": info})
254
+ return 0
255
+ print(f"profile: {ctx.profile} write: {ctx.write or '(none)'}")
256
+ for i in info:
257
+ flags = ", ".join(x for x in ("shared" if i["shared"] else "", "write" if i["write"] else "") if x)
258
+ print(f"- {i['name']} {i['path']}" + (f" [{flags}]" if flags else ""))
259
+ if i["remote"]:
260
+ print(f" remote: {i['remote']}")
261
+ for k in i["collections"]:
262
+ print(f" collection {k['name']}: {', '.join(k['path'])}"
263
+ + ("" if k["search"] else " (not in default search)"))
264
+ if i["updated"] is None:
265
+ print(" index: not built yet")
266
+ else:
267
+ when = datetime.datetime.fromtimestamp(i["updated"]).strftime("%Y-%m-%d %H:%M")
268
+ print(f" index: {i['indexed']} files, updated {when}, {i['stale']} stale")
269
+ return 0
270
+
271
+
272
+ def cmd_skill(ctx, a):
273
+ from importlib.resources import files
274
+ sys.stdout.write(files("divan").joinpath("SKILL.md").read_text(encoding="utf-8"))
275
+ return 0
276
+
277
+
278
+ def cmd_hook(ctx, a):
279
+ from . import hooks
280
+ return hooks.main(a.agent, a.event)
281
+
282
+
283
+ def cmd_join(ctx, a):
284
+ from .join import join
285
+ return join(a.url, a.path, a.name, a.author, allow_local=a.allow_local)
286
+
287
+
288
+ def cmd_agent_setup(ctx, a):
289
+ from .agent import setup
290
+ return setup(a.status, a.json, a.client, a.yes, a.remove)
291
+
292
+
293
+ def cmd_agent_config(ctx, a):
294
+ from . import settings
295
+ eff = settings.effective()
296
+ if a.json:
297
+ _emit({"config": str(settings.config_path()),
298
+ "settings": {k: {"value": v, "source": src} for k, (v, src) in eff.items()}})
299
+ return 0
300
+ print(f"config: {settings.config_path()} (DIVAN_AGENT=off turns every hook off)")
301
+ for k, (v, src) in eff.items():
302
+ shown = ("on" if v else "off") if isinstance(v, bool) else (v if v != "" else '""')
303
+ print(f"{k:17} {shown:11} {src:9} {settings.SPEC[k][2]}")
304
+ return 0
305
+
306
+
307
+ def cmd_agent_set(ctx, a):
308
+ from . import settings
309
+ value, cfg = settings.set_value(a.key, a.value)
310
+ print(f"{a.key} = {value if not isinstance(value, bool) else ('on' if value else 'off')} ({cfg})")
311
+ return 0
312
+
313
+
314
+ def build_parser():
315
+ ap = argparse.ArgumentParser(prog="divan", description="Search and write markdown knowledge-base repos.")
316
+ from . import __version__
317
+ ap.add_argument("--version", action="version", version=f"divan {__version__}")
318
+ sub = ap.add_subparsers(dest="cmd", required=True)
319
+ cm = _common()
320
+
321
+ p = sub.add_parser("find", parents=[cm], help="ranked full-text search, grouped per corpus")
322
+ p.add_argument("query", nargs="+")
323
+ p.add_argument("--corpus", action="append", help="limit to a corpus (repeatable)")
324
+ p.add_argument("--collection")
325
+ p.add_argument("--all", action="store_true", help="include collections with search = false")
326
+ p.add_argument("-n", type=int, default=8, help="hits per corpus (default 8)")
327
+ p.add_argument("--json", action="store_true")
328
+ p.add_argument("--rebuild", action="store_true", help="drop and rebuild the index")
329
+ p.set_defaults(fn=cmd_find)
330
+
331
+ p = sub.add_parser("new", parents=[cm], help="create an entry from a collection template")
332
+ p.add_argument("--corpus")
333
+ p.add_argument("--collection")
334
+ p.add_argument("--title", required=True)
335
+ p.add_argument("--dir", help="subfolder inside the collection folder (replaces the collection's dir pattern)")
336
+ p.add_argument("--var", action="append", metavar="KEY=VALUE", help="value for a {key} placeholder (repeatable)")
337
+ p.set_defaults(fn=cmd_new)
338
+
339
+ p = sub.add_parser("land", parents=[cm], help="commit exactly these files, pull --rebase, push")
340
+ p.add_argument("files", nargs="+")
341
+ p.add_argument("-m", required=True, help="commit message")
342
+ p.set_defaults(fn=cmd_land)
343
+
344
+ p = sub.add_parser("check", parents=[cm], help="frontmatter, required fields, leak rules")
345
+ p.add_argument("files", nargs="*")
346
+ p.add_argument("--corpus", action="append")
347
+ p.add_argument("--explain", action="store_true", help="show which collection each file resolved to")
348
+ p.add_argument("--json", action="store_true")
349
+ p.set_defaults(fn=cmd_check)
350
+
351
+ p = sub.add_parser("list", parents=[cm], help="list entries with frontmatter fields")
352
+ p.add_argument("--corpus", action="append")
353
+ p.add_argument("--collection")
354
+ p.add_argument("--where", action="append", metavar="KEY=VALUE")
355
+ p.add_argument("--topics", action="store_true",
356
+ help="one line per top-level folder: entry count and its top 3 tags (else title words)")
357
+ p.add_argument("--since", metavar="SPAN", help="only entries dated within a span such as 7d, 2w or 3m "
358
+ "(frontmatter date/updated/created, else file mtime)")
359
+ p.add_argument("--fields", help="comma-separated frontmatter fields to show")
360
+ p.add_argument("--json", action="store_true")
361
+ p.set_defaults(fn=cmd_list)
362
+
363
+ p = sub.add_parser("guide", parents=[cm], help="print a corpus's guide (how to write to it)")
364
+ p.add_argument("corpus", nargs="?")
365
+ p.set_defaults(fn=cmd_guide)
366
+
367
+ p = sub.add_parser("corpora", parents=[cm], help="show the active profile and its corpora")
368
+ p.add_argument("--json", action="store_true")
369
+ p.set_defaults(fn=cmd_corpora)
370
+ p = sub.add_parser("skill", help="print the agent skill (SKILL.md) to install in an agent harness")
371
+ p.set_defaults(fn=cmd_skill, needs_config=False)
372
+ p = sub.add_parser("join", help="clone a knowledge-base repo and register it in your config")
373
+ p.add_argument("url", help="git URL of the repo")
374
+ p.add_argument("--path", help="where to clone it (default: ~/divan/<name>)")
375
+ p.add_argument("--name", help="corpus name (default: the repo name)")
376
+ p.add_argument("--author", help="set [vars] author, used by `divan new`, if not already set")
377
+ p.add_argument("--allow-local", action="store_true",
378
+ help="also accept a local path or file:// URL (default: https and ssh only)")
379
+ p.set_defaults(fn=cmd_join, needs_config=False)
380
+
381
+ p = sub.add_parser("agent", help="set up your coding agents")
382
+ asub = p.add_subparsers(dest="agent_cmd", required=True)
383
+ p = asub.add_parser("setup", help="install the divan plugin into each detected agent (Claude Code, Codex, Antigravity)")
384
+ p.add_argument("--status", action="store_true", help="show what is installed, change nothing")
385
+ p.add_argument("--json", action="store_true", help="print the plan as JSON, change nothing")
386
+ p.add_argument("--client", action="append", choices=["claude", "codex", "antigravity"], help="only this agent (repeatable)")
387
+ p.add_argument("-y", "--yes", action="store_true", help="do not ask before running")
388
+ p.add_argument("--remove", action="store_true", help="uninstall the plugin instead")
389
+ p.set_defaults(fn=cmd_agent_setup, needs_config=False)
390
+
391
+ p = asub.add_parser("config", help="show the effective hook settings and where each came from")
392
+ p.add_argument("--json", action="store_true")
393
+ p.set_defaults(fn=cmd_agent_config, needs_config=False)
394
+ p = asub.add_parser("set", help="change one hook setting in your config (keeps the rest of the file)")
395
+ p.add_argument("key")
396
+ p.add_argument("value")
397
+ p.set_defaults(fn=cmd_agent_set, needs_config=False)
398
+
399
+ p = sub.add_parser("hook", help="agent hook entry point (called by the plugin; reads JSON on stdin)")
400
+ p.add_argument("agent", choices=["claude", "codex", "antigravity"])
401
+ p.add_argument("event", choices=["SessionStart", "PreToolUse", "PostToolUse", "PreCompact", "Stop"])
402
+ p.set_defaults(fn=cmd_hook, needs_config=False)
403
+ return ap
404
+
405
+
406
+ def main(argv=None):
407
+ a = build_parser().parse_args(argv)
408
+ try:
409
+ if not getattr(a, "needs_config", True):
410
+ return a.fn(None, a)
411
+ ctx = load_context(a.profile, a.path)
412
+ return a.fn(ctx, a)
413
+ except ConfigError as e:
414
+ print(f"divan: {e}", file=sys.stderr)
415
+ return 2