lorexplore 0.1.0a1__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.
lorexplore/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ """lorexplore — Local-first codebase intelligence & git narrative engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError
6
+ from importlib.metadata import version as _dist_version
7
+ from typing import Any
8
+
9
+ __all__ = ["LoreEngine", "RequestContext", "__version__"]
10
+
11
+
12
+ def _resolve_version() -> str:
13
+ try:
14
+ return _dist_version("lorexplore")
15
+ except PackageNotFoundError:
16
+ return "0.0.0.dev0"
17
+
18
+
19
+ __version__: str = _resolve_version()
20
+
21
+
22
+ def __getattr__(name: str) -> Any:
23
+ """Lazy package exports (PEP 562) to preserve <50 ms CLI & hook cold starts."""
24
+ if name == "LoreEngine":
25
+ from .engine import LoreEngine
26
+
27
+ return LoreEngine
28
+ if name == "RequestContext":
29
+ from .models import RequestContext
30
+
31
+ return RequestContext
32
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
lorexplore/cli.py ADDED
@@ -0,0 +1,465 @@
1
+ """1:1 CLI parity for lorexplore (`lorexplore` / `lxp`).
2
+
3
+ Tier-0 import boundary: keep top-level imports restricted to `click` and stdlib
4
+ so `lxp --help`, `lxp --version`, `--json` piping, and synchronous `post-commit`
5
+ hooks stay under the 50 ms cold-start budget. Heavy modules (`mcp`, `LoreEngine`)
6
+ are imported strictly on demand via `LazyGroup` and function-scoped imports.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib
12
+ import json
13
+ import stat
14
+ import sys
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Any
17
+
18
+ import click
19
+
20
+ from . import __version__
21
+ from .cli_format import (
22
+ fmt_draft_lore,
23
+ fmt_history,
24
+ fmt_impact,
25
+ fmt_locate,
26
+ fmt_read,
27
+ fmt_stale,
28
+ fmt_sync,
29
+ fmt_timeline,
30
+ fmt_trace,
31
+ fmt_why,
32
+ meta_footer,
33
+ )
34
+
35
+ if TYPE_CHECKING:
36
+ from .engine import LoreEngine
37
+ from .models import RequestContext
38
+
39
+
40
+ class LazyGroup(click.Group):
41
+ """Click Group that defers importing heavy subcommands (e.g., `serve`) until invoked."""
42
+
43
+ def __init__(
44
+ self,
45
+ *args: Any,
46
+ lazy_subcommands: dict[str, tuple[str, str]] | None = None,
47
+ **kwargs: Any,
48
+ ) -> None:
49
+ super().__init__(*args, **kwargs)
50
+ self.lazy_subcommands: dict[str, tuple[str, str]] = lazy_subcommands or {}
51
+
52
+ def list_commands(self, ctx: click.Context) -> list[str]:
53
+ base = super().list_commands(ctx)
54
+ return sorted(set(base) | set(self.lazy_subcommands))
55
+
56
+ def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:
57
+ if cmd_name in self.lazy_subcommands:
58
+ import_path, _ = self.lazy_subcommands[cmd_name]
59
+ mod_name, attr_name = import_path.split(":", 1)
60
+ mod = importlib.import_module(mod_name)
61
+ cmd = getattr(mod, attr_name)
62
+ if not isinstance(cmd, click.Command):
63
+ raise TypeError(f"Lazy command {import_path!r} is not a click.Command")
64
+ return cmd
65
+ return super().get_command(ctx, cmd_name)
66
+
67
+ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
68
+ """Render help text without eagerly importing lazy_subcommands."""
69
+ commands: list[tuple[str, str]] = []
70
+ for subcommand in self.list_commands(ctx):
71
+ if subcommand in self.lazy_subcommands:
72
+ commands.append((subcommand, self.lazy_subcommands[subcommand][1]))
73
+ continue
74
+ cmd = super().get_command(ctx, subcommand)
75
+ if cmd is not None and not cmd.hidden:
76
+ commands.append((subcommand, cmd.get_short_help_str(limit=formatter.width)))
77
+
78
+ if commands:
79
+ limit = formatter.width - 6 - max(len(c[0]) for c in commands)
80
+ rows = [
81
+ (name, (help_str[: limit - 3] + "...") if len(help_str) > limit > 3 else help_str)
82
+ for name, help_str in commands
83
+ ]
84
+ with formatter.section("Commands"):
85
+ formatter.write_dl(rows)
86
+
87
+
88
+ def _emit(res: dict[str, Any], as_json: bool, markdown_renderer: Any = None) -> None:
89
+ if as_json:
90
+ click.echo(json.dumps(res, indent=2))
91
+ return
92
+ status = res.get("status")
93
+ if status == "error":
94
+ click.echo(f"ERROR [{res.get('error_code')}]: {res.get('hint', '')}", err=True)
95
+ sys.exit(1)
96
+ if status == "empty":
97
+ click.echo(f"(empty) {res.get('hint', 'No results.')}")
98
+ return
99
+ click.echo(markdown_renderer(res) if markdown_renderer is not None else json.dumps(res, indent=2))
100
+
101
+
102
+ @click.group(
103
+ cls=LazyGroup,
104
+ lazy_subcommands={
105
+ "serve": (
106
+ "lorexplore.mcp_server:serve_command",
107
+ "Start the progressive-disclosure MCP server (official mcp SDK).",
108
+ ),
109
+ },
110
+ )
111
+ @click.version_option(version=__version__, prog_name="lorexplore")
112
+ @click.option("--repo", default=".", type=click.Path(file_okay=False), help="Target repository root")
113
+ @click.option("--db", default=None, type=click.Path(dir_okay=False), help="Custom SQLite DB path")
114
+ @click.option("--json", "as_json", is_flag=True, help="Emit compact structured JSON")
115
+ @click.option("--read-only", is_flag=True, help="Open DB strictly read-only")
116
+ @click.pass_context
117
+ def main(ctx: click.Context, repo: str, db: str | None, as_json: bool, read_only: bool) -> None:
118
+ """lorexplore (lxp) — Local-first codebase intelligence & git archaeology CLI."""
119
+ ctx.ensure_object(dict)
120
+ ctx.obj["repo"] = str(Path(repo).expanduser().resolve())
121
+ ctx.obj["db"] = db
122
+ ctx.obj["as_json"] = as_json
123
+ ctx.obj["read_only"] = read_only
124
+
125
+
126
+ def _open_engine(ctx: click.Context) -> tuple[LoreEngine, RequestContext]:
127
+ from .engine import LoreEngine
128
+ from .models import RequestContext
129
+
130
+ ro = bool(ctx.obj["read_only"])
131
+ return LoreEngine(ctx.obj["repo"], db_path=ctx.obj["db"], read_only=ro), RequestContext(
132
+ actor="cli", read_only=ro
133
+ )
134
+
135
+
136
+ @main.command()
137
+ @click.option("--full", is_flag=True, help="Force full re-index instead of incremental sync")
138
+ @click.option(
139
+ "--max-cochange-files", default=30, show_default=True, help="Skip bulk commits > N files from co-change"
140
+ )
141
+ @click.option("--quiet", is_flag=True, help="Suppress output (for git hooks)")
142
+ @click.pass_context
143
+ def sync(ctx: click.Context, full: bool, max_cochange_files: int, quiet: bool) -> None:
144
+ """Build or incrementally refresh the SQLite WAL + FTS5 index."""
145
+ eng, rctx = _open_engine(ctx)
146
+ with eng:
147
+ res = eng.sync(rctx, incremental=not full, max_cochange_files=max_cochange_files)
148
+ if not quiet:
149
+ _emit(res, ctx.obj["as_json"], fmt_sync)
150
+
151
+
152
+ @main.command()
153
+ @click.pass_context
154
+ def status(ctx: click.Context) -> None:
155
+ """Show index health, stats, and DB location."""
156
+ eng, rctx = _open_engine(ctx)
157
+ with eng:
158
+ stats = eng.store.get_stats(rctx.repo_id)
159
+ if ctx.obj["as_json"]:
160
+ click.echo(json.dumps(stats, indent=2))
161
+ return
162
+ click.echo(
163
+ f"lorexplore index @ {stats['db_path']} ({stats['db_size_kb']} KB)\n"
164
+ f" HEAD indexed : {stats['last_indexed_sha'] or 'never'}\n"
165
+ f" Updated UTC : {stats['indexed_at_utc'] or 'never'}\n"
166
+ f" Counts : files={stats['files']}, symbols={stats['symbols']}, "
167
+ f"edges={stats['code_edges']}, commits={stats['commits']}, "
168
+ f"co_change={stats['co_change']}, docs={stats['docs']}"
169
+ )
170
+
171
+
172
+ @main.command("map")
173
+ @click.option(
174
+ "--focus", "focus_paths", multiple=True, help="Path prefix(es) to boost via Personalized PageRank"
175
+ )
176
+ @click.option("--query", default=None, help="Optional topic query to seed PageRank")
177
+ @click.option("--max-tokens", default=1024, show_default=True)
178
+ @click.pass_context
179
+ def cmd_map(ctx: click.Context, focus_paths: tuple[str, ...], query: str | None, max_tokens: int) -> None:
180
+ """Generate a Personalized PageRank skeleton map of the repository."""
181
+ eng, rctx = _open_engine(ctx)
182
+ with eng:
183
+ res = eng.repo_map(rctx, focus_paths=list(focus_paths) or None, query=query, max_tokens=max_tokens)
184
+ _emit(res, ctx.obj["as_json"], lambda r: r["data"]["markdown"] + meta_footer(r))
185
+
186
+
187
+ @main.command()
188
+ @click.argument("query")
189
+ @click.option(
190
+ "--scope", type=click.Choice(["all", "code", "history", "docs"]), default="all", show_default=True
191
+ )
192
+ @click.option("--max-tokens", default=800, show_default=True)
193
+ @click.option("--cursor", default=None)
194
+ @click.pass_context
195
+ def locate(ctx: click.Context, query: str, scope: str, max_tokens: int, cursor: str | None) -> None:
196
+ """Unified progressive-disclosure search across symbols, commits, and ADRs."""
197
+ eng, rctx = _open_engine(ctx)
198
+ with eng:
199
+ res = eng.locate(rctx, query=query, scope=scope, max_tokens=max_tokens, cursor=cursor)
200
+ _emit(res, ctx.obj["as_json"], lambda r: fmt_locate(query, scope, r))
201
+
202
+
203
+ @main.command()
204
+ @click.argument("targets", nargs=-1, required=True)
205
+ @click.option("--mode", type=click.Choice(["skeleton", "body"]), default="skeleton", show_default=True)
206
+ @click.option("--context", "context_lines", default=0, show_default=True)
207
+ @click.option("--max-tokens", default=2000, show_default=True)
208
+ @click.pass_context
209
+ def read(
210
+ ctx: click.Context, targets: tuple[str, ...], mode: str, context_lines: int, max_tokens: int
211
+ ) -> None:
212
+ """Batch-read AST skeletons or exact symbol/line-range bodies."""
213
+ eng, rctx = _open_engine(ctx)
214
+ with eng:
215
+ res = eng.read_symbol(
216
+ rctx, targets=list(targets), mode=mode, context_lines=context_lines, max_tokens=max_tokens
217
+ )
218
+ _emit(res, ctx.obj["as_json"], fmt_read)
219
+
220
+
221
+ @main.command()
222
+ @click.argument("target")
223
+ @click.option(
224
+ "--direction",
225
+ type=click.Choice(["callers", "callees", "both", "tests"]),
226
+ default="both",
227
+ show_default=True,
228
+ )
229
+ @click.option("--depth", default=2, show_default=True)
230
+ @click.option("--max-tokens", default=1200, show_default=True)
231
+ @click.pass_context
232
+ def trace(ctx: click.Context, target: str, direction: str, depth: int, max_tokens: int) -> None:
233
+ """Trace N-hop static callers, callees, imports, or tests."""
234
+ eng, rctx = _open_engine(ctx)
235
+ with eng:
236
+ res = eng.trace_graph(rctx, target=target, direction=direction, depth=depth, max_tokens=max_tokens)
237
+ _emit(res, ctx.obj["as_json"], lambda r: fmt_trace(target, direction, depth, r))
238
+
239
+
240
+ @main.command()
241
+ @click.argument("target")
242
+ @click.option("--max-commits", default=8, show_default=True)
243
+ @click.option("--max-tokens", default=1500, show_default=True)
244
+ @click.pass_context
245
+ def why(ctx: click.Context, target: str, max_commits: int, max_tokens: int) -> None:
246
+ """Git archaeology narrative card: commits, Lore trailers, ADRs/Plans, and co-changed files."""
247
+ eng, rctx = _open_engine(ctx)
248
+ with eng:
249
+ res = eng.explain_why(rctx, target=target, max_commits=max_commits, max_tokens=max_tokens)
250
+ _emit(res, ctx.obj["as_json"], fmt_why)
251
+
252
+
253
+ @main.command()
254
+ @click.argument("target", default="working_tree")
255
+ @click.option("--depth", default=2, show_default=True)
256
+ @click.option("--max-tokens", default=1500, show_default=True)
257
+ @click.pass_context
258
+ def impact(ctx: click.Context, target: str, depth: int, max_tokens: int) -> None:
259
+ """Unified static blast radius + historical temporal co-change coupling."""
260
+ eng, rctx = _open_engine(ctx)
261
+ with eng:
262
+ res = eng.co_change_impact(rctx, target=target, depth=depth, max_tokens=max_tokens)
263
+ _emit(res, ctx.obj["as_json"], fmt_impact)
264
+
265
+
266
+ @main.command()
267
+ @click.argument("query")
268
+ @click.option("--path", "path_glob", default=None, help="Optional glob filter on changed file paths")
269
+ @click.option("--fixes-only", is_flag=True, help="Restrict to fix/revert commits")
270
+ @click.option("--since", default=None, help="ISO date or shorthand (e.g., 30d, 12w)")
271
+ @click.option("--max-tokens", default=1200, show_default=True)
272
+ @click.pass_context
273
+ def history(
274
+ ctx: click.Context,
275
+ query: str,
276
+ path_glob: str | None,
277
+ fixes_only: bool,
278
+ since: str | None,
279
+ max_tokens: int,
280
+ ) -> None:
281
+ """Search commits, Lore trailers, and ADRs/Plans via FTS5."""
282
+ eng, rctx = _open_engine(ctx)
283
+ with eng:
284
+ res = eng.search_history(
285
+ rctx,
286
+ query=query,
287
+ path_glob=path_glob,
288
+ only_fixes_or_reverts=fixes_only,
289
+ since=since,
290
+ max_tokens=max_tokens,
291
+ )
292
+ _emit(res, ctx.obj["as_json"], lambda r: fmt_history(query, r))
293
+
294
+
295
+ @main.command()
296
+ @click.option(
297
+ "--min-churn",
298
+ default=3,
299
+ show_default=True,
300
+ help="Minimum post-doc commits on a referenced file to flag drift",
301
+ )
302
+ @click.option("--max-tokens", default=1500, show_default=True)
303
+ @click.pass_context
304
+ def stale(ctx: click.Context, min_churn: int, max_tokens: int) -> None:
305
+ """Audit ACTIVE Plans/ADRs for deleted file references or heavy post-doc code churn."""
306
+ eng, rctx = _open_engine(ctx)
307
+ with eng:
308
+ res = eng.audit_stale_docs(rctx, min_churn=min_churn, max_tokens=max_tokens)
309
+ _emit(res, ctx.obj["as_json"], lambda r: fmt_stale(min_churn, r))
310
+
311
+
312
+ @main.command("draft-lore")
313
+ @click.option(
314
+ "--working-tree", is_flag=True, help="Inspect full working-tree diff vs HEAD instead of staged diff"
315
+ )
316
+ @click.option(
317
+ "--commit", "commit_sha", default=None, help="Inspect a specific commit SHA instead of staged diff"
318
+ )
319
+ @click.option("--max-tokens", default=1200, show_default=True)
320
+ @click.pass_context
321
+ def draft_lore(ctx: click.Context, working_tree: bool, commit_sha: str | None, max_tokens: int) -> None:
322
+ """Draft Lore commit trailers + pre-commit invariant/co-change checklist from a diff."""
323
+ eng, rctx = _open_engine(ctx)
324
+ with eng:
325
+ res = eng.draft_lore(rctx, staged=not working_tree, commit_sha=commit_sha, max_tokens=max_tokens)
326
+ _emit(res, ctx.obj["as_json"], fmt_draft_lore)
327
+
328
+
329
+ @main.command()
330
+ @click.option("--target", default=None, help="Optional file or directory prefix to scope the timeline")
331
+ @click.option("--since", default=None, help="Start window (ISO date or shorthand e.g. 14d, 30d, 12w)")
332
+ @click.option("--max-commits", default=25, show_default=True)
333
+ @click.option("--max-tokens", default=1800, show_default=True)
334
+ @click.pass_context
335
+ def timeline(
336
+ ctx: click.Context, target: str | None, since: str | None, max_commits: int, max_tokens: int
337
+ ) -> None:
338
+ """Chronological SHA-anchored narrative feed for onboarding or milestone synthesis."""
339
+ eng, rctx = _open_engine(ctx)
340
+ with eng:
341
+ res = eng.build_timeline(
342
+ rctx, target=target, since=since, max_commits=max_commits, max_tokens=max_tokens
343
+ )
344
+ _emit(res, ctx.obj["as_json"], fmt_timeline)
345
+
346
+
347
+ @main.command("import-prs")
348
+ @click.argument("json_file", type=click.Path(exists=True, dir_okay=False))
349
+ @click.pass_context
350
+ def import_prs(ctx: click.Context, json_file: str) -> None:
351
+ """Import offline GitHub PR & review thread JSON (from `gh pr list --json ...`)."""
352
+ eng, rctx = _open_engine(ctx)
353
+ with eng:
354
+ res = eng.import_prs(rctx, json_path=json_file)
355
+ _emit(
356
+ res,
357
+ ctx.obj["as_json"],
358
+ lambda r: (
359
+ f"Imported {r['data']['imported']} PR record(s) with "
360
+ f"{r['data']['file_links']} file link(s) from {r['data']['source']}"
361
+ ),
362
+ )
363
+
364
+
365
+ @main.command()
366
+ @click.option("--title", required=True, help="Short decision title")
367
+ @click.option("--rationale", required=True, help="Why this decision was made")
368
+ @click.option("--target", "targets", multiple=True, required=True, help="Affected file/symbol path(s)")
369
+ @click.option("--rejected", multiple=True, help="Rejected alternative(s)")
370
+ @click.option(
371
+ "--supersedes", "supersedes_path", default=None, help="Prior ADR/plan path superseded by this decision"
372
+ )
373
+ @click.option("--write-file", is_flag=True, help="Also write Markdown ADR under .lore/decisions/")
374
+ @click.pass_context
375
+ def decide(
376
+ ctx: click.Context,
377
+ title: str,
378
+ rationale: str,
379
+ targets: tuple[str, ...],
380
+ rejected: tuple[str, ...],
381
+ supersedes_path: str | None,
382
+ write_file: bool,
383
+ ) -> None:
384
+ """Record a bi-temporal decision & print ready-to-paste Lore trailers."""
385
+ eng, rctx = _open_engine(ctx)
386
+ with eng:
387
+ res = eng.record_decision(
388
+ rctx,
389
+ title=title,
390
+ rationale=rationale,
391
+ affected_targets=list(targets),
392
+ rejected_alternatives=list(rejected) or None,
393
+ supersedes_path=supersedes_path,
394
+ write_adr_file=write_file,
395
+ )
396
+ _emit(
397
+ res,
398
+ ctx.obj["as_json"],
399
+ lambda r: (
400
+ f"Recorded decision: {r['data']['decision_path']} (wrote_file={r['data']['wrote_file']})\n\n"
401
+ f"Paste into your git commit message:\n```\n{r['data']['lore_trailers']}\n```"
402
+ ),
403
+ )
404
+
405
+
406
+ def _strip_existing_hook_block(content: str, start_marker: str, end_marker: str) -> str:
407
+ new_lines: list[str] = []
408
+ skipping = False
409
+ for ln in content.splitlines(keepends=True):
410
+ if ln.strip() == start_marker:
411
+ skipping = True
412
+ continue
413
+ if skipping:
414
+ if ln.strip() == end_marker or "sync --quiet" in ln:
415
+ skipping = False
416
+ continue
417
+ new_lines.append(ln)
418
+ return "".join(new_lines).rstrip()
419
+
420
+
421
+ def _upsert_hook_file(hook_path: Path, start_marker: str, end_marker: str, block: str) -> None:
422
+ if not hook_path.exists():
423
+ hook_path.write_text("#!/bin/sh\n\n" + block, encoding="utf-8")
424
+ else:
425
+ content = hook_path.read_text(encoding="utf-8", errors="ignore")
426
+ if start_marker in content:
427
+ base = _strip_existing_hook_block(content, start_marker, end_marker)
428
+ prefix = base + "\n\n" if base else "#!/bin/sh\n\n"
429
+ hook_path.write_text(prefix + block, encoding="utf-8")
430
+ else:
431
+ hook_path.write_text(content.rstrip() + "\n\n" + block, encoding="utf-8")
432
+ hook_path.chmod(hook_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
433
+
434
+
435
+ @main.command("install-hooks")
436
+ @click.option(
437
+ "--async",
438
+ "async_mode",
439
+ is_flag=True,
440
+ help="Run sync detached in background via nohup (for very large monorepos); default is synchronous with `|| true`.",
441
+ )
442
+ @click.pass_context
443
+ def install_hooks(ctx: click.Context, async_mode: bool) -> None:
444
+ """Install portable POSIX git hooks for automatic incremental sync on commit/merge/checkout."""
445
+ repo = Path(ctx.obj["repo"])
446
+ hooks_dir = repo / ".git" / "hooks"
447
+ if not hooks_dir.is_dir():
448
+ click.echo(f"ERROR: Not a git repository with .git/hooks: {repo}", err=True)
449
+ sys.exit(1)
450
+
451
+ lxp_bin = Path(sys.argv[0]).resolve()
452
+ start_marker = "# lorexplore-incremental-sync"
453
+ end_marker = "# end-lorexplore-incremental-sync"
454
+ cmd = (
455
+ f'nohup "{lxp_bin}" --repo "{repo}" sync --quiet </dev/null >/dev/null 2>&1 &'
456
+ if async_mode
457
+ else f'"{lxp_bin}" --repo "{repo}" sync --quiet >/dev/null 2>&1 || true'
458
+ )
459
+ block = f"{start_marker}\n{cmd}\n{end_marker}\n"
460
+ updated = ["post-commit", "post-merge", "post-checkout"]
461
+ for hook_name in updated:
462
+ _upsert_hook_file(hooks_dir / hook_name, start_marker, end_marker, block)
463
+
464
+ mode_label = "async (nohup)" if async_mode else "sync (|| true)"
465
+ click.echo(f"Installed lorexplore incremental hooks [{mode_label}]: {', '.join(updated)}")