kipp-memory 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.
kipp/cli.py ADDED
@@ -0,0 +1,753 @@
1
+ """CLI entry point for the memory command."""
2
+
3
+ import uuid
4
+ from collections import Counter
5
+ from datetime import datetime, timedelta, timezone
6
+ from pathlib import Path
7
+
8
+ import click
9
+ import httpx
10
+ from qdrant_client.models import FieldCondition, Filter, MatchValue
11
+
12
+ from kipp.backup import DEFAULT_KEEP, backup_all
13
+ from kipp.client import (
14
+ DOMAINS,
15
+ collection_name,
16
+ collection_stats,
17
+ delete_entity,
18
+ ensure_collections,
19
+ get_client,
20
+ get_entity,
21
+ list_children,
22
+ qdrant_connection,
23
+ scroll_entities,
24
+ store_event,
25
+ )
26
+ from kipp.extract import MATCH_THRESHOLD
27
+ from kipp.maintenance import compact_domain, expire_events, expire_facts, reindex_domain
28
+ from kipp.facts import write_entity
29
+ from kipp.merge import (
30
+ SPLIT_THRESHOLD,
31
+ current_fact_count,
32
+ long_fact_warning,
33
+ mark_superseded,
34
+ merge,
35
+ oversized_warning,
36
+ )
37
+ from kipp.models import Entity, Fact
38
+ from kipp.pipeline import DEFAULT_BATCH_SIZE, run_extraction
39
+
40
+
41
+ def _get_embedder():
42
+ """Lazy-load the embedder (avoids slow import on every CLI call)."""
43
+ from kipp.embedder import Embedder
44
+
45
+ return Embedder()
46
+
47
+
48
+ @click.group()
49
+ def main():
50
+ """KIPP: entity memory for AI agents."""
51
+ pass
52
+
53
+
54
+ _domain_option = click.option(
55
+ "--domain", type=click.Choice(DOMAINS), default="shared", show_default=True,
56
+ help="Domain to operate on.",
57
+ )
58
+
59
+
60
+ @main.command()
61
+ def init():
62
+ """Create collections and indexes if they don't exist."""
63
+ client = get_client()
64
+ created = ensure_collections(client)
65
+ if created:
66
+ click.echo(f"Created collections: {', '.join(created)}")
67
+ else:
68
+ click.echo("All collections already exist.")
69
+
70
+
71
+ @main.command()
72
+ def stats():
73
+ """Show collection sizes and health."""
74
+ client = get_client()
75
+ st = collection_stats(client)
76
+ for name, info in st.items():
77
+ if info.get("exists") is False:
78
+ click.echo(f"{name}: not created")
79
+ else:
80
+ click.echo(f"{name}: {info['points']} points")
81
+
82
+
83
+ @main.command()
84
+ @click.option("--type", "entity_type", required=True, help="Entity type: person|project|tool|preference|decision")
85
+ @click.option("--id", "entity_id", required=True, help="Entity key (e.g. alice, dashboard)")
86
+ @click.option("--content", required=True, help="Fact text to store")
87
+ @click.option(
88
+ "--supersedes", default=None,
89
+ help="Text of an existing current fact this replaces. "
90
+ "Marks it superseded (kept for --as-of queries, hidden from search).",
91
+ )
92
+ @click.option(
93
+ "--valid-from", "valid_from", default=None,
94
+ help="ISO date the new fact became true in the world, if not today.",
95
+ )
96
+ @click.option(
97
+ "--parent", default=None,
98
+ help="Full id of the entity this one was split from, e.g. person:alice.",
99
+ )
100
+ @_domain_option
101
+ def store(
102
+ entity_type: str, entity_id: str, content: str, supersedes: str | None,
103
+ valid_from: str | None, parent: str | None, domain: str,
104
+ ):
105
+ """Directly upsert an entity with a fact."""
106
+ client = get_client()
107
+ ensure_collections(client)
108
+ embedder = _get_embedder()
109
+
110
+ full_id = f"{entity_type}:{entity_id}" if ":" not in entity_id else entity_id
111
+ now = datetime.utcnow()
112
+ today = now.date().isoformat()
113
+
114
+ # Future-effective dating isn't supported yet (issue #24) — see memory_store.
115
+ if valid_from is not None and valid_from[:10] > today:
116
+ raise click.ClickException(
117
+ f"future valid_from {valid_from!r} is not supported yet (today is "
118
+ f"{today}); future-effective dating is tracked in issue #24"
119
+ )
120
+
121
+ if parent is not None:
122
+ from kipp.split import check_parent
123
+
124
+ try:
125
+ check_parent(client, full_id, parent, domain=domain)
126
+ except ValueError as exc:
127
+ raise click.ClickException(str(exc))
128
+
129
+ existing = get_entity(client, full_id, domain=domain)
130
+ if existing is None:
131
+ existing = Entity(id=full_id, type=entity_type)
132
+ if parent is not None:
133
+ existing.parent = parent
134
+
135
+ superseded = None
136
+ if supersedes:
137
+ # Close the old fact exactly when the replacement starts (its valid_from,
138
+ # falling back to today): a backdated replacement must end the old fact at
139
+ # the same date, or an as-of query in the gap sees both as valid (#21).
140
+ marked = mark_superseded(
141
+ existing, supersedes, by=content, on_date=valid_from or today,
142
+ )
143
+ superseded = marked.text if marked is not None else None
144
+
145
+ new_fact = Fact(text=content, added=today, source="cli:store", valid_from=valid_from)
146
+ merged = merge(existing, [new_fact], embedder, now=now)
147
+
148
+ write_entity(client, merged, embedder, domain=domain)
149
+
150
+ click.echo(f"Stored: {full_id} ({current_fact_count(merged)} current facts)")
151
+ if supersedes:
152
+ if superseded is not None:
153
+ click.echo(f" Superseded: {superseded!r}")
154
+ else:
155
+ click.echo(f" No current fact matched --supersedes {supersedes!r}")
156
+ warning = long_fact_warning(content)
157
+ if warning:
158
+ click.echo(f" Warning: {warning}", err=True)
159
+ oversized = oversized_warning(merged)
160
+ if oversized:
161
+ click.echo(f" Oversized: {oversized}", err=True)
162
+
163
+
164
+ @main.command()
165
+ @click.argument("entity_id")
166
+ @_domain_option
167
+ def get(entity_id: str, domain: str):
168
+ """Retrieve a single entity's full detail."""
169
+ client = get_client()
170
+ entity = get_entity(client, entity_id, domain=domain)
171
+ if entity is None:
172
+ click.echo(f"Not found: {entity_id}")
173
+ raise SystemExit(1)
174
+
175
+ click.echo(entity.id)
176
+ click.echo(f"Updated: {entity.last_updated}")
177
+ if entity.parent:
178
+ click.echo(f"Parent: {entity.parent}")
179
+ children = list_children(client, entity.id, domain=domain)
180
+ if children:
181
+ click.echo(f"Children: {', '.join(children)}")
182
+ click.echo(f"Facts ({len(entity.facts)}):")
183
+ for f in entity.facts:
184
+ expires = f" [expires {f.expires}]" if f.expires else ""
185
+ superseded = f" [superseded {f.superseded_at}]" if f.superseded_at else ""
186
+ click.echo(f" [{f.hit_count}x] {f.text} (since {f.added}, last seen {f.last_seen}){expires}{superseded}")
187
+
188
+
189
+ @main.command()
190
+ @click.argument("entity_id")
191
+ @click.option("--yes", "-y", is_flag=True, help="Skip confirmation")
192
+ @_domain_option
193
+ def delete(entity_id: str, yes: bool, domain: str):
194
+ """Delete an entity permanently."""
195
+ if not yes:
196
+ click.confirm(f"Delete {entity_id} from {domain}?", abort=True)
197
+
198
+ client = get_client()
199
+ if delete_entity(client, entity_id, domain=domain):
200
+ click.echo(f"Deleted: {entity_id} ({domain})")
201
+ else:
202
+ click.echo(f"Not found in {domain}: {entity_id}")
203
+ raise SystemExit(1)
204
+
205
+
206
+ @main.command(name="list")
207
+ @click.option("--type", "entity_type", default=None, help="Filter by type")
208
+ @_domain_option
209
+ def list_entities(entity_type: str | None, domain: str):
210
+ """List all known entities."""
211
+ client = get_client()
212
+ entities = scroll_entities(client, entity_type, domain=domain)
213
+ if not entities:
214
+ click.echo("No entities found.")
215
+ return
216
+ for e in entities:
217
+ updated = e.last_updated[:10] if e.last_updated else "unknown"
218
+ click.echo(f"{e.id} ({len(e.facts)} facts, updated {updated})")
219
+
220
+
221
+ @main.command()
222
+ @click.argument("query")
223
+ @click.option("--type", "entity_type", default=None, help="Filter by entity type")
224
+ @click.option("--limit", default=5, help="Max results to return")
225
+ @click.option(
226
+ "--as-of", "as_of", default=None,
227
+ help="ISO date: show each entity as it was then (superseded facts in effect "
228
+ "at that date are shown). Default hides superseded facts.",
229
+ )
230
+ @_domain_option
231
+ def search(query: str, entity_type: str | None, limit: int, as_of: str | None, domain: str):
232
+ """Semantic search across all entities."""
233
+ from kipp.search import search_entities, format_results
234
+
235
+ client = get_client()
236
+ embedder = _get_embedder()
237
+ results = search_entities(
238
+ client, query, embedder, entity_type=entity_type, limit=limit, as_of=as_of,
239
+ domain=domain,
240
+ )
241
+ click.echo(format_results(results))
242
+
243
+
244
+ @main.command(name="eval")
245
+ @click.argument(
246
+ "case_file", required=False, type=click.Path(dir_okay=False, exists=True, path_type=Path),
247
+ )
248
+ @click.option(
249
+ "--k", default=10, show_default=True, type=click.IntRange(min=5),
250
+ help="Results fetched per question (at least 5, so hit@5 is measurable)",
251
+ )
252
+ @click.option("--json", "as_json", is_flag=True, help="Machine-readable output")
253
+ def eval_cmd(case_file: Path | None, k: int, as_json: bool):
254
+ """Score search recall against known-answer questions. Read-only.
255
+
256
+ CASE_FILE is JSON Lines (default ~/.config/kipp/eval.jsonl). See
257
+ docs/operations.md#recall-evaluation for the format.
258
+ """
259
+ import json as json_mod
260
+ from kipp.evaluate import default_case_path, format_report, load_cases, report_json, run_case
261
+
262
+ path = case_file or default_case_path()
263
+ if not path.exists():
264
+ raise click.ClickException(f"No case file at {path}")
265
+ try:
266
+ cases = load_cases(path)
267
+ except ValueError as e:
268
+ raise click.ClickException(str(e)) from e
269
+ if not cases:
270
+ raise click.ClickException(f"{path} has no cases")
271
+
272
+ client = get_client()
273
+ embedder = _get_embedder()
274
+ results = [
275
+ run_case(client, embedder, c, k, embedder.count_tokens, embedder.window)
276
+ for c in cases
277
+ ]
278
+ if as_json:
279
+ click.echo(json_mod.dumps(report_json(results, k), indent=2))
280
+ else:
281
+ click.echo(format_report(results, k))
282
+
283
+
284
+ EVENT_TTL_DAYS = 30
285
+
286
+
287
+ @main.command()
288
+ @click.argument("text")
289
+ @click.option("--source", default="conversation", help="Event source: conversation|task|cron")
290
+ @click.option("--agent", default="main", help="Agent name")
291
+ @_domain_option
292
+ def event(text: str, source: str, agent: str, domain: str):
293
+ """Log a raw observation. No entity extraction happens immediately."""
294
+ client = get_client()
295
+ ensure_collections(client)
296
+ embedder = _get_embedder()
297
+
298
+ now = datetime.utcnow()
299
+ event_id = str(uuid.uuid4())
300
+ vector = embedder.embed(text)
301
+ expires = (now + timedelta(days=EVENT_TTL_DAYS)).isoformat()
302
+
303
+ store_event(
304
+ client, event_id=event_id, text=text, vector=vector,
305
+ timestamp=now.isoformat(), source=source, agent=agent, expires=expires,
306
+ domain=domain,
307
+ )
308
+ click.echo(f"Logged event: {event_id[:8]}...")
309
+
310
+
311
+ @main.command()
312
+ @click.option("--since", default=None, help="Process events from last N minutes (e.g. 55m)")
313
+ @click.option("--all", "process_all", is_flag=True, help="Process all unextracted events")
314
+ @click.option(
315
+ "--domain", type=click.Choice(DOMAINS), default="shared",
316
+ help="Domain to extract within: shared|dev|personal",
317
+ )
318
+ @click.option(
319
+ "--batch", "batch_size", default=DEFAULT_BATCH_SIZE, show_default=True,
320
+ help="Events per batch; each batch commits and reports progress before the next.",
321
+ )
322
+ @click.option(
323
+ "--threshold", default=MATCH_THRESHOLD, show_default=True, type=float,
324
+ help="Cosine gate for a sentence→fact match (with --match-untagged only).",
325
+ )
326
+ @click.option(
327
+ "--match-untagged", is_flag=True,
328
+ help="Also cosine-match events with no leading [type:id] tag. Off by "
329
+ "default: it misattributes most facts (issue #33).",
330
+ )
331
+ def extract(
332
+ since: str | None, process_all: bool, domain: str, batch_size: int,
333
+ threshold: float, match_untagged: bool,
334
+ ):
335
+ """Process unextracted events into entity upserts.
336
+
337
+ Events opening with a [type:id] tag attach to that entity when it exists.
338
+ Events are processed in batches so a large backlog makes visible,
339
+ kill-safe progress. Only events that enriched an existing entity are
340
+ marked extracted; fully-unmatched events stay as new-entity candidates.
341
+ """
342
+ client = get_client()
343
+ embedder = _get_embedder()
344
+
345
+ since_dt = None
346
+ if since and not process_all:
347
+ minutes = int(since.rstrip("m"))
348
+ since_dt = datetime.utcnow() - timedelta(minutes=minutes)
349
+
350
+ def _progress(info: dict) -> None:
351
+ click.echo(
352
+ f" batch {info['batch']}/{info['total_batches']}: "
353
+ f"{info['events_in_batch']} events, "
354
+ f"{info['matched_in_batch']} enriched "
355
+ f"({info['cumulative_events']}/{info['total_events']} done)"
356
+ )
357
+
358
+ summary = run_extraction(
359
+ client, embedder, domain=domain, since=since_dt,
360
+ batch_size=batch_size, threshold=threshold, progress=_progress,
361
+ match_untagged=match_untagged,
362
+ )
363
+
364
+ if summary["events_processed"] == 0:
365
+ click.echo("No unextracted events found.")
366
+ return
367
+
368
+ click.echo(f"Processed {summary['events_processed']} events:")
369
+ click.echo(f" {summary['matched']} sentences matched to entities")
370
+ click.echo(f" {summary['unmatched']} unmatched sentences")
371
+ for s in summary["unmatched_samples"]:
372
+ click.echo(f" UNMATCHED: \"{s}\"")
373
+
374
+
375
+ @main.command(name="dismiss")
376
+ @click.option(
377
+ "--source", "src", required=True,
378
+ help="Only dismiss unextracted events whose 'source' field equals this "
379
+ "(e.g. claude_ai_import_conversation).",
380
+ )
381
+ @click.option("--domain", default="shared", help="Domain: shared|dev|personal")
382
+ @click.option(
383
+ "--keep", "keep", multiple=True,
384
+ help="Event ID to exclude from dismissal. Repeatable.",
385
+ )
386
+ @click.option(
387
+ "--apply", "apply_changes", is_flag=True,
388
+ help="Actually mark matched events extracted. Without this flag the command "
389
+ "is a dry-run (prints count + sample, writes nothing).",
390
+ )
391
+ def dismiss(src: str, domain: str, keep: tuple[str, ...], apply_changes: bool):
392
+ """Bulk-dismiss unextracted events by source, marking them extracted.
393
+
394
+ Built for one-time cleanup of bulk imports (e.g. the Claude.ai conversation
395
+ import) whose events are not memory-worthy: it marks them extracted=True
396
+ with no entity created, so the extractor stops reconsidering them. Events
397
+ are NOT deleted — their existing 30-day TTL still applies. Dry-run by
398
+ default; pass --apply to commit.
399
+ """
400
+ client = get_client()
401
+ coll = collection_name(domain, "events")
402
+ if not client.collection_exists(coll):
403
+ click.echo(f"No events collection for domain {domain!r}.")
404
+ raise SystemExit(1)
405
+
406
+ keep_set = set(keep)
407
+ scroll_filter = Filter(
408
+ must=[
409
+ FieldCondition(key="extracted", match=MatchValue(value=False)),
410
+ FieldCondition(key="source", match=MatchValue(value=src)),
411
+ ]
412
+ )
413
+
414
+ matched_ids: list = []
415
+ sample: list[tuple[str, str]] = []
416
+ offset = None
417
+ while True:
418
+ points, offset = client.scroll(
419
+ collection_name=coll, scroll_filter=scroll_filter,
420
+ limit=256, offset=offset, with_payload=True,
421
+ )
422
+ for p in points:
423
+ if str(p.id) in keep_set:
424
+ continue
425
+ matched_ids.append(p.id)
426
+ if len(sample) < 5:
427
+ text = (p.payload or {}).get("text", "")
428
+ sample.append((str(p.id), text.replace("\n", " ")[:100]))
429
+ if offset is None:
430
+ break
431
+
432
+ click.echo(
433
+ f"Matched {len(matched_ids)} unextracted events "
434
+ f"(source={src!r}, domain={domain!r}, {len(keep_set)} excluded)."
435
+ )
436
+ for eid, snippet in sample:
437
+ click.echo(f" {eid} {snippet}")
438
+ if len(matched_ids) > len(sample):
439
+ click.echo(f" ... and {len(matched_ids) - len(sample)} more")
440
+
441
+ if not apply_changes:
442
+ click.echo("DRY-RUN: nothing written. Pass --apply to mark these extracted.")
443
+ return
444
+
445
+ if not matched_ids:
446
+ click.echo("Nothing to dismiss.")
447
+ return
448
+
449
+ batch = 500
450
+ for i in range(0, len(matched_ids), batch):
451
+ chunk = matched_ids[i : i + batch]
452
+ client.set_payload(
453
+ collection_name=coll, payload={"extracted": True}, points=chunk,
454
+ wait=True,
455
+ )
456
+ click.echo(f"Dismissed {len(matched_ids)} events (extracted=True).")
457
+
458
+
459
+ def _resolve_domains(domain: str) -> list[str]:
460
+ return list(DOMAINS) if domain == "all" else [domain]
461
+
462
+
463
+ # Maintenance commands default to `shared` (the pre-#32 behaviour) so existing
464
+ # callers keep their blast radius; `--domain all` opts in to every domain.
465
+ _maintenance_domain = click.option(
466
+ "--domain", type=click.Choice([*DOMAINS, "all"]), default="shared",
467
+ show_default=True, help="Domain to operate on, or 'all'.",
468
+ )
469
+
470
+
471
+ @main.command()
472
+ @click.option(
473
+ "--domain", type=click.Choice([*DOMAINS, "all"]), default="all",
474
+ show_default=True, help="Domain to check, or 'all'.",
475
+ )
476
+ @click.option(
477
+ "--threshold", type=click.IntRange(min=1), default=SPLIT_THRESHOLD,
478
+ show_default=True, help="Flag entities with more current facts than this.",
479
+ )
480
+ def oversized(domain: str, threshold: int):
481
+ """List entities that should be split into topic entities. Read-only."""
482
+ client = get_client()
483
+ rows = [
484
+ (current_fact_count(e), d, e.id)
485
+ for d in _resolve_domains(domain)
486
+ for e in scroll_entities(client, domain=d)
487
+ if current_fact_count(e) > threshold
488
+ ]
489
+ if not rows:
490
+ click.echo(f"No entities over {threshold} current facts.")
491
+ return
492
+ for n, d, eid in sorted(rows, key=lambda r: (-r[0], r[1], r[2])):
493
+ click.echo(f"{n:>5} {d:<9} {eid}")
494
+
495
+
496
+ @main.command(name="split-plan")
497
+ @click.argument("entity_id")
498
+ @click.option("--domain", type=click.Choice(DOMAINS), default="shared", show_default=True)
499
+ @click.option(
500
+ "--groups", type=click.IntRange(min=1), default=None,
501
+ help="Number of topic groups. Default: current facts / 12, between 2 and 12.",
502
+ )
503
+ @click.option(
504
+ "-o", "--output", type=click.Path(dir_okay=False, path_type=Path), default=None,
505
+ help="Write the plan here instead of stdout.",
506
+ )
507
+ def split_plan_cmd(entity_id: str, domain: str, groups: int | None, output: Path | None):
508
+ """Group an entity's facts by topic into an editable split plan. Read-only.
509
+
510
+ Edit the JSON: rename each group's target, move facts between groups or
511
+ into "keep" (they stay on the source), delete groups. Then run
512
+ `kipp split-apply`.
513
+ """
514
+ import json as json_mod
515
+
516
+ from kipp.split import plan_split
517
+
518
+ client = get_client()
519
+ entity = get_entity(client, entity_id, domain=domain)
520
+ if entity is None:
521
+ raise click.ClickException(f"{entity_id} not found in domain {domain!r}")
522
+ plan = plan_split(entity, _get_embedder(), domain=domain, now=datetime.utcnow(), groups=groups)
523
+ text = json_mod.dumps(plan, indent=2, ensure_ascii=False) + "\n"
524
+ if output is None:
525
+ click.echo(text, nl=False)
526
+ else:
527
+ output.write_text(text)
528
+ for g in plan["groups"]:
529
+ click.echo(f"{len(g['facts']):>4} {g['target']} ({', '.join(g['keywords'])})", err=True)
530
+ click.echo(f"{len(plan['keep']):>4} keep on {entity.id}", err=True)
531
+
532
+
533
+ @main.command(name="split-apply")
534
+ @click.argument("plan_file", type=click.Path(exists=True, dir_okay=False, path_type=Path))
535
+ @click.option("--apply", "apply_changes", is_flag=True, help="Move the facts. Default is a dry run.")
536
+ def split_apply_cmd(plan_file: Path, apply_changes: bool):
537
+ """Move facts into topic entities as a split plan says.
538
+
539
+ Dry run by default. Targets are written before facts leave the source, so
540
+ an interrupted run duplicates facts rather than losing them; re-run the
541
+ same plan to finish. Take a backup before --apply.
542
+ """
543
+ import json as json_mod
544
+
545
+ from kipp.split import apply_plan
546
+
547
+ plan = json_mod.loads(plan_file.read_text())
548
+ client = get_client()
549
+ embedder = _get_embedder() if apply_changes else None
550
+ try:
551
+ results = apply_plan(client, embedder, plan, now=datetime.utcnow(), apply=apply_changes)
552
+ except ValueError as exc:
553
+ raise click.ClickException(str(exc))
554
+ verb = "moved" if apply_changes else "would move"
555
+ for r in results:
556
+ new = " (new)" if r.created else ""
557
+ carried = f", {r.carried} superseded with them" if r.carried else ""
558
+ click.echo(f"{r.target}{new}: {verb} {len(r.moved)}{carried}")
559
+ if r.already:
560
+ click.echo(f" already moved: {len(r.already)}")
561
+ for text in r.unmatched:
562
+ click.echo(f" not found: {text[:100]}")
563
+ for text in r.left:
564
+ click.echo(f" left on the source (changed during the move; re-run): {text[:100]}")
565
+ if apply_changes:
566
+ remaining = results[-1].source_facts if results else None
567
+ if remaining is not None:
568
+ click.echo(f"{plan['source']} keeps {remaining} current facts.")
569
+ else:
570
+ click.echo("DRY-RUN: nothing written. Pass --apply to move facts.")
571
+
572
+
573
+ @main.command(name="compact")
574
+ @click.option("--max-facts", default=20, help="Max facts per entity")
575
+ @_maintenance_domain
576
+ def compact_cmd(max_facts: int, domain: str):
577
+ """Delete all but the top facts of every entity over the limit. Lossy.
578
+
579
+ Not scheduled anywhere: split oversized entities instead (see
580
+ ``kipp oversized``). Take a backup first.
581
+ """
582
+ client = get_client()
583
+ embedder = _get_embedder()
584
+ now = datetime.utcnow()
585
+
586
+ for d in _resolve_domains(domain):
587
+ compacted = compact_domain(client, embedder, d, now, max_facts=max_facts)
588
+ click.echo(f"[{d}] Compacted {compacted} entities (max_facts={max_facts}).")
589
+
590
+
591
+ @main.command()
592
+ @_maintenance_domain
593
+ def expire(domain: str):
594
+ """Garbage-collect expired events and entity facts."""
595
+ client = get_client()
596
+ embedder = _get_embedder()
597
+ now = datetime.utcnow()
598
+
599
+ for d in _resolve_domains(domain):
600
+ expired_events = expire_events(client, d, now)
601
+ updated_entities = expire_facts(client, embedder, d, now)
602
+ click.echo(
603
+ f"[{d}] Expired {expired_events} events, updated {updated_entities} entities."
604
+ )
605
+
606
+
607
+ @main.command()
608
+ @_maintenance_domain
609
+ def reindex(domain: str):
610
+ """Rebuild every entity's search vector from its current facts.
611
+
612
+ Run after upgrading to a version that changes how vectors are built.
613
+ Facts are not modified.
614
+ """
615
+ client = get_client()
616
+ embedder = _get_embedder()
617
+ now = datetime.utcnow()
618
+
619
+ for d in _resolve_domains(domain):
620
+ n = reindex_domain(client, embedder, d, now)
621
+ click.echo(f"[{d}] Re-embedded {n} entities.")
622
+
623
+
624
+ @main.command(name="export")
625
+ @click.option("--format", "fmt", type=click.Choice(["json", "md"]), default="json", help="Output format")
626
+ def export_cmd(fmt: str):
627
+ """Export all entities for backup or inspection."""
628
+ import sys
629
+ from kipp.export import export_json, export_markdown
630
+
631
+ client = get_client()
632
+ entities = scroll_entities(client)
633
+
634
+ if fmt == "json":
635
+ export_json(entities, sys.stdout)
636
+ else:
637
+ export_markdown(entities, sys.stdout)
638
+
639
+
640
+ @main.command(name="import")
641
+ @click.argument("file", type=click.Path(exists=True))
642
+ def import_cmd(file: str):
643
+ """Import entities from a JSON export. Runs merge logic (won't duplicate)."""
644
+ import json as json_mod
645
+ from kipp.export import import_json, reject_future_dated_facts
646
+
647
+ client = get_client()
648
+ ensure_collections(client)
649
+ embedder = _get_embedder()
650
+ now = datetime.utcnow()
651
+
652
+ with open(file) as f:
653
+ data = json_mod.load(f)
654
+
655
+ imported = import_json(data)
656
+ # Validate the whole backup before writing anything, so a bad fact aborts the
657
+ # import atomically rather than half-applying it (issue #24).
658
+ try:
659
+ reject_future_dated_facts(imported, now.date().isoformat())
660
+ except ValueError as exc:
661
+ raise click.ClickException(str(exc))
662
+
663
+ for entity in imported:
664
+ existing = get_entity(client, entity.id)
665
+ if existing is None:
666
+ existing = Entity(id=entity.id, type=entity.type)
667
+ if existing.parent is None:
668
+ existing.parent = entity.parent
669
+
670
+ merged = merge(existing, entity.facts, embedder, now=now)
671
+ write_entity(client, merged, embedder)
672
+
673
+ click.echo(f"Imported {len(imported)} entities.")
674
+
675
+
676
+ @main.command()
677
+ @click.option(
678
+ "--domain", type=click.Choice([*DOMAINS, "all"]), default="all",
679
+ show_default=True, help="Domain to repair, or 'all'.",
680
+ )
681
+ @click.option("--apply", "apply_changes", is_flag=True, help="Write the moves. Default is a dry run.")
682
+ def repair(domain: str, apply_changes: bool):
683
+ """Move extracted facts whose [type:id] tag names a different entity.
684
+
685
+ Dry run by default: prints the planned moves, tags whose entity doesn't
686
+ exist (left in place), and per-entity counts of untagged extracted facts
687
+ (no ground truth, so not moved). Take a backup before --apply.
688
+ """
689
+ from kipp.repair import apply_repair, plan_repair
690
+
691
+ client = get_client()
692
+ embedder = _get_embedder() if apply_changes else None
693
+ now = datetime.utcnow()
694
+
695
+ for d in DOMAINS if domain == "all" else [domain]:
696
+ entities = scroll_entities(client, domain=d)
697
+ plan = plan_repair(entities)
698
+ moves_by_pair = Counter((m.source_id, m.target_id) for m in plan.moves)
699
+ click.echo(
700
+ f"[{d}] {len(plan.moves)} facts to move, "
701
+ f"{sum(plan.missing_targets.values())} with a missing target, "
702
+ f"{sum(plan.untagged_extracted.values())} untagged extracted."
703
+ )
704
+ for (src, dst), n in moves_by_pair.most_common():
705
+ click.echo(f" move {n:>4} {src} -> {dst}")
706
+ for tag, n in plan.missing_targets.most_common():
707
+ click.echo(f" missing {n:>4} {tag}")
708
+ for eid, n in plan.untagged_extracted.most_common(10):
709
+ click.echo(f" untagged {n:>4} {eid}")
710
+ if apply_changes and plan.moves:
711
+ rewritten = apply_repair(client, embedder, d, entities, plan, now)
712
+ click.echo(f" applied: {rewritten} entities rewritten")
713
+
714
+ if not apply_changes:
715
+ click.echo("DRY-RUN: nothing written. Pass --apply to move facts.")
716
+
717
+
718
+ @main.command()
719
+ def mcp():
720
+ """Run the MCP stdio server (used by Endurance and other MCP clients)."""
721
+ from kipp.mcp_server import run
722
+
723
+ run()
724
+
725
+
726
+ BACKUP_TIMEOUT = 600 # seconds, for snapshot create + download
727
+
728
+
729
+ @main.command(name="backup")
730
+ @click.option(
731
+ "--dest", type=click.Path(file_okay=False, path_type=Path),
732
+ default=Path.home() / "backups" / "qdrant", show_default=True,
733
+ help="Directory holding one subdirectory per backup",
734
+ )
735
+ @click.option("--keep", default=DEFAULT_KEEP, show_default=True, help="Complete backups to retain")
736
+ def backup_cmd(dest: Path, keep: int):
737
+ """Snapshot every Qdrant collection to DEST/<stamp>/ (verified, pruned)."""
738
+ # Snapshot creation of a large collection can outlast the 5s default.
739
+ client = get_client(timeout=BACKUP_TIMEOUT)
740
+ _, api_key = qdrant_connection()
741
+ headers = {"api-key": api_key} if api_key else {}
742
+ # client.http.client.host is the endpoint qdrant-client resolved (default
743
+ # port filled in), so downloads hit the same server snapshots were made on.
744
+ with httpx.Client(base_url=client.http.client.host, headers=headers, timeout=BACKUP_TIMEOUT) as http:
745
+ result = backup_all(client, http, dest, datetime.now(timezone.utc), keep=keep)
746
+ for name, entry in result.collections.items():
747
+ click.echo(f" {name:20s} {entry['points']:6d} points {entry['bytes'] / 1e6:7.1f} MB")
748
+ click.echo(f"Backed up {len(result.collections)} collections to {result.path}"
749
+ f" ({len(result.pruned)} old backups pruned).")
750
+
751
+
752
+ if __name__ == "__main__":
753
+ main()