rotless 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.
rotless/cli.py ADDED
@@ -0,0 +1,775 @@
1
+ """Command-line interface for rotless with lazy subcommand imports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from . import __version__
11
+ from .config import load_config
12
+
13
+
14
+ def _warn(msg: str) -> None:
15
+ print(f"[rotless] WARN: {msg}", file=sys.stderr)
16
+
17
+
18
+ def _cmd_warmup(args: argparse.Namespace) -> int:
19
+ from .warmup import emit_warmup_output, resolve_warmup_cwd, run_warmup
20
+
21
+ cfg = load_config(args.home, quiet=True)
22
+ cwd = resolve_warmup_cwd(args.cwd)
23
+ res = run_warmup(cfg, cwd=cwd, budget=args.budget, explain=args.explain)
24
+ return emit_warmup_output(res, fmt=args.format, explain=args.explain)
25
+
26
+
27
+ def _cmd_init(args: argparse.Namespace) -> int:
28
+ from .integrations import run_init
29
+
30
+ cfg = load_config(args.home)
31
+ agents = [a.strip() for a in args.agents.split(",") if a.strip()] if args.agents else None
32
+ try:
33
+ return run_init(
34
+ cfg,
35
+ agents=agents,
36
+ bin_path=args.bin_path,
37
+ dry_run=args.dry_run,
38
+ uninstall=args.uninstall,
39
+ yes=args.yes,
40
+ no_scan=args.no_scan,
41
+ as_json=args.json,
42
+ )
43
+ except ValueError as exc:
44
+ print(f"Error: {exc}", file=sys.stderr)
45
+ return 2
46
+
47
+
48
+ def _cmd_sync(args: argparse.Namespace) -> int:
49
+ from .sync import run_sync
50
+
51
+ cfg = load_config(args.home)
52
+ res = run_sync(cfg, scope=args.scope, dry_run=args.dry_run, force=args.force, warn=_warn)
53
+ if args.json:
54
+ import json
55
+
56
+ print(json.dumps(res, ensure_ascii=False, indent=2))
57
+ return 0
58
+ prefix = "[dry-run] " if args.dry_run else ""
59
+ for sc, info in res["scopes"].items():
60
+ print(
61
+ f"{prefix}Synced {sc}: updated={info['updated']}, skipped={info['skipped']}, "
62
+ f"removed={info['removed']}"
63
+ )
64
+ return 0
65
+
66
+
67
+ def _cmd_add(args: argparse.Namespace) -> int:
68
+ import json
69
+
70
+ from .vault import DuplicateCardError, add_card
71
+
72
+ cfg = load_config(args.home)
73
+ raw_content = sys.stdin.read() if args.content == "-" else args.content
74
+ try:
75
+ res = add_card(
76
+ cfg,
77
+ raw_content,
78
+ tags=args.tags or "",
79
+ title=args.title,
80
+ card_type=args.type,
81
+ local=args.local,
82
+ stale_after=args.stale_after,
83
+ verified=args.verified,
84
+ source_session=args.source_session,
85
+ source_ref=args.source_ref,
86
+ force=args.force,
87
+ allow_redacted=args.allow_redacted,
88
+ auto_project_tag=not args.no_project_tag,
89
+ )
90
+ except DuplicateCardError as exc:
91
+ print(f"Duplicate warning ({exc.report['create_safety']}): similar active memory found.", file=sys.stderr)
92
+ for m in exc.report["matches"]:
93
+ print(f" - {m['doc_id']} | {m['title']} ({m['reason']})", file=sys.stderr)
94
+ print("Pass --force to create anyway, or use `rotless supersede`.", file=sys.stderr)
95
+ return 1
96
+ except (ValueError, OSError) as exc:
97
+ print(f"Error: {exc}", file=sys.stderr)
98
+ return 2
99
+
100
+ if args.json:
101
+ print(json.dumps(res, ensure_ascii=False, indent=2))
102
+ else:
103
+ print(f"Added {res['id']} ({res['origin']}) -> {res['path']}")
104
+ return 0
105
+
106
+
107
+ def _cmd_search(args: argparse.Namespace) -> int:
108
+ import json
109
+ import secrets
110
+ import time
111
+
112
+ from .fs_atomic import find_git_context, sha256_text
113
+ from .store import connect_ro, expand_doc_context, search_by_tags, search_fts
114
+ from .sync import maybe_auto_sync
115
+ from .text_utils import fence_untrusted, normalize_tags
116
+
117
+ t0 = time.monotonic()
118
+ cfg = load_config(args.home)
119
+ query = (args.query_pos or args.query or "").strip()
120
+ req_tags = normalize_tags(args.tags or "")
121
+ if not query and not req_tags:
122
+ print("Error: provide a search query or --tags", file=sys.stderr)
123
+ return 2
124
+
125
+ if not args.no_sync:
126
+ sync_scope = "all" if args.scope in ("all", "session") else "memory"
127
+ maybe_auto_sync(cfg, scope=sync_scope, warn=_warn)
128
+
129
+ git_ctx = find_git_context()
130
+ repo_key = sha256_text(str(git_ctx[1].resolve()))[:8] if git_ctx else ""
131
+
132
+ conn = connect_ro(cfg.db_path, busy_timeout_ms=1000)
133
+ if conn is None:
134
+ hits: list[dict[str, Any]] = []
135
+ else:
136
+ try:
137
+ if not query:
138
+ hits = search_by_tags(conn, args.scope, req_tags, limit=args.limit, current_repo_key=repo_key)
139
+ else:
140
+ hits = search_fts(
141
+ conn,
142
+ query,
143
+ scope=args.scope,
144
+ tags=req_tags,
145
+ limit=args.limit,
146
+ current_repo_key=repo_key,
147
+ collapse_docs=not args.all_chunks,
148
+ )
149
+ if args.expand:
150
+ for hit in hits:
151
+ hit["expanded_text"] = expand_doc_context(conn, hit["doc_id"], hit.get("chunk_idx", 0))
152
+ finally:
153
+ conn.close()
154
+
155
+ elapsed_ms = round((time.monotonic() - t0) * 1000, 1)
156
+ if args.json:
157
+ print(json.dumps({"total": len(hits), "elapsed_ms": elapsed_ms, "results": hits}, ensure_ascii=False, indent=2))
158
+ return 0
159
+
160
+ print(f"Found {len(hits)} result(s) ({elapsed_ms} ms)")
161
+ nonce = secrets.token_hex(6)
162
+ for idx, h in enumerate(hits, 1):
163
+ tags_str = ", ".join(h["tags"]) if h["tags"] else "-"
164
+ badges: list[str] = []
165
+ status = str(h.get("status") or "stable").lower()
166
+ if status in ("superseded", "deprecated", "archived"):
167
+ sup = h.get("superseded_by")
168
+ badges.append(f"{status.upper()} -> {sup}" if sup else status.upper())
169
+ if h.get("is_stale"):
170
+ badges.append("STALE")
171
+ badge_str = f" [{' | '.join(badges)}]" if badges else ""
172
+ print(f"\n[{idx}] ({h['scope']}/{h['origin']}) {h['title']}{badge_str} | score={h['score']}")
173
+ print(f" id: {h['doc_id']} | tags: {tags_str}")
174
+ if h["source_session"]:
175
+ print(f" session: {h['source_session']}")
176
+ body = h.get("expanded_text") or h.get("text") or ""
177
+ snippet = body if args.expand else (body[:320] + ("..." if len(body) > 320 else ""))
178
+ if not args.raw_output:
179
+ trust = "project-repo" if h["origin"] == "project" else ("session-log" if h["scope"] == "session" else "global-user")
180
+ snippet = fence_untrusted(str(h["doc_id"]), snippet, trust=trust, nonce=nonce)
181
+ for line in snippet.splitlines():
182
+ print(f" | {line}")
183
+ return 0
184
+
185
+
186
+ def _cmd_supersede(args: argparse.Namespace) -> int:
187
+ import json
188
+
189
+ from .vault import supersede_card
190
+
191
+ cfg = load_config(args.home)
192
+ new_content = args.new_content
193
+ if new_content == "-":
194
+ new_content = sys.stdin.read()
195
+ try:
196
+ res = supersede_card(
197
+ cfg,
198
+ args.old_id,
199
+ by_id=args.by or None,
200
+ new_content=new_content,
201
+ tags=args.tags or "",
202
+ title=args.title,
203
+ apply=args.apply,
204
+ )
205
+ except (LookupError, ValueError, OSError) as exc:
206
+ print(f"Error: {exc}", file=sys.stderr)
207
+ return 1 if isinstance(exc, LookupError) else 2
208
+
209
+ if args.json:
210
+ print(json.dumps(res, ensure_ascii=False, indent=2))
211
+ return 0
212
+ if not res["applied"]:
213
+ print(f"[dry-run] Would supersede {res['old_doc_id']} -> {res['new_doc_id']} (pass --apply to write)")
214
+ print(res["diff"])
215
+ return 0
216
+ print(f"Superseded {res['old_doc_id']} -> {res['new_doc_id']}")
217
+ return 0
218
+
219
+
220
+ def _cmd_trust(args: argparse.Namespace) -> int:
221
+ import json
222
+
223
+ from .fs_atomic import find_git_context, safe_iter_markdown, sha256_text
224
+ from .store import connect_ro, connect_rw, list_registered_projects, trust_project
225
+
226
+ cfg = load_config(args.home)
227
+ if args.list:
228
+ conn = connect_ro(cfg.db_path, busy_timeout_ms=500)
229
+ items = list_registered_projects(conn, trusted_only=True) if conn else []
230
+ if conn:
231
+ conn.close()
232
+ if args.json:
233
+ print(json.dumps({"trusted_projects": items}, ensure_ascii=False, indent=2))
234
+ return 0
235
+ if not items:
236
+ print("No trusted project overlays.")
237
+ return 0
238
+ for p in items:
239
+ print(f"- {p['repo_name']} ({p['project_root']}) | trusted_at={p['trusted_at']}")
240
+ return 0
241
+
242
+ target = Path(args.path).expanduser() if args.path else Path.cwd()
243
+ git_ctx = find_git_context(target)
244
+ if git_ctx is None:
245
+ print(f"Error: {target} is not inside a git repository.", file=sys.stderr)
246
+ return 2
247
+ project_root, common_dir, repo_name = git_ctx
248
+ mem_dir = project_root / ".rotless" / "memories"
249
+ files = safe_iter_markdown(mem_dir, max_files=200, max_bytes=65536) if mem_dir.is_dir() else []
250
+
251
+ conn = connect_rw(cfg.db_path)
252
+ try:
253
+ repo_key = sha256_text(str(common_dir.resolve()))[:8]
254
+ ts = trust_project(conn, project_root, repo_key, repo_name)
255
+ conn.commit()
256
+ finally:
257
+ conn.close()
258
+
259
+ from .sync import maybe_auto_sync
260
+
261
+ maybe_auto_sync(cfg, scope="memory", cwd=project_root, warn=_warn)
262
+ if args.json:
263
+ print(
264
+ json.dumps(
265
+ {
266
+ "trusted": True,
267
+ "repo_name": repo_name,
268
+ "project_root": str(project_root),
269
+ "memory_files": len(files),
270
+ "trusted_at": ts,
271
+ },
272
+ ensure_ascii=False,
273
+ indent=2,
274
+ )
275
+ )
276
+ return 0
277
+ print(f"Trusted {repo_name} ({project_root}) [{len(files)} memory file(s)].")
278
+ return 0
279
+
280
+
281
+ def _cmd_untrust(args: argparse.Namespace) -> int:
282
+ import json
283
+
284
+ from .fs_atomic import find_git_context
285
+ from .store import connect_rw, untrust_project
286
+
287
+ cfg = load_config(args.home)
288
+ target = Path(args.path).expanduser() if args.path else Path.cwd()
289
+ git_ctx = find_git_context(target)
290
+ proj_root = git_ctx[0] if git_ctx else target.resolve()
291
+
292
+ conn = connect_rw(cfg.db_path)
293
+ try:
294
+ changed = untrust_project(conn, proj_root)
295
+ conn.commit()
296
+ finally:
297
+ conn.close()
298
+
299
+ if args.json:
300
+ print(json.dumps({"untrusted": changed, "project_root": str(proj_root)}, ensure_ascii=False, indent=2))
301
+ return 0
302
+ print(f"Untrusted {proj_root}." if changed else f"Not trusted: {proj_root}")
303
+ return 0
304
+
305
+
306
+ def _cmd_lint(args: argparse.Namespace) -> int:
307
+ import json
308
+
309
+ from .lint import fix_lint_issues, run_lint
310
+ from .sync import maybe_auto_sync
311
+
312
+ if args.apply and not args.fix:
313
+ print("Error: --apply requires --fix.", file=sys.stderr)
314
+ return 2
315
+
316
+ cfg = load_config(args.home)
317
+ if not args.local and not args.no_sync:
318
+ maybe_auto_sync(cfg, scope="memory", warn=_warn)
319
+
320
+ if args.fix:
321
+ try:
322
+ res = fix_lint_issues(cfg, local_only=args.local, apply=args.apply)
323
+ except (ValueError, OSError) as exc:
324
+ print(f"Error: {exc}", file=sys.stderr)
325
+ return 2
326
+ if args.json:
327
+ print(json.dumps(res, ensure_ascii=False, indent=2))
328
+ return 0 if res["report"]["is_healthy"] else 1
329
+ mode_tag = "[applied]" if res["applied"] else "[dry-run]"
330
+ print(f"rotless lint --fix {mode_tag}: fixes={res['fix_count']}")
331
+ for fix in res["fixes"]:
332
+ if fix["kind"] == "permission":
333
+ print(f" - chmod {fix['from_mode']} -> {fix['to_mode']}: {fix['path']}")
334
+ else:
335
+ reasons = ", ".join(fix["reasons"])
336
+ print(f" - patch ({reasons}): {fix['path']}")
337
+ if fix.get("diff"):
338
+ print(fix["diff"].rstrip())
339
+ if not res["applied"] and res["fix_count"] > 0:
340
+ print("\nPass --apply to write deterministic fixes.")
341
+ rep = res["report"]
342
+ print(f"Health: memories={rep['total_memories']}, issues={rep['issue_count']}, healthy={rep['is_healthy']}")
343
+ return 0 if rep["is_healthy"] else 1
344
+
345
+ try:
346
+ report = run_lint(cfg, local_only=args.local)
347
+ except ValueError as exc:
348
+ print(f"Error: {exc}", file=sys.stderr)
349
+ return 2
350
+
351
+ if args.json:
352
+ print(json.dumps(report, ensure_ascii=False, indent=2))
353
+ return 0 if report["is_healthy"] else 1
354
+
355
+ print(
356
+ f"rotless lint: memories={report['total_memories']}, "
357
+ f"issues={report['issue_count']}, healthy={report['is_healthy']}"
358
+ )
359
+ labels = (
360
+ ("stale_notes", "Stale notes"),
361
+ ("stale_verifications", "Stale verifications"),
362
+ ("broken_supersedes", "Broken superseded_by links"),
363
+ ("status_mismatches", "Status mismatches"),
364
+ ("invisible_unicode", "Security: invisible Unicode detected"),
365
+ ("insecure_permissions", "Security: overly permissive file modes"),
366
+ ("duplicate_candidates", "Potential duplicate memories"),
367
+ )
368
+ for key, label in labels:
369
+ items = report[key]
370
+ if items:
371
+ print(f"\n[{label}] ({len(items)})")
372
+ for item in items:
373
+ print(f" - {json.dumps(item, ensure_ascii=False)}")
374
+ return 0 if report["is_healthy"] else 1
375
+
376
+
377
+ def _cmd_verify(args: argparse.Namespace) -> int:
378
+ import json
379
+
380
+ from .vault import verify_card
381
+
382
+ cfg = load_config(args.home)
383
+ try:
384
+ res = verify_card(
385
+ cfg,
386
+ args.id,
387
+ stale_after=args.stale_after,
388
+ extend_days=args.extend,
389
+ clear_stale=args.clear_stale,
390
+ )
391
+ except (LookupError, ValueError, OSError) as exc:
392
+ print(f"Error: {exc}", file=sys.stderr)
393
+ return 1 if isinstance(exc, LookupError) else 2
394
+
395
+ if args.json:
396
+ print(json.dumps(res, ensure_ascii=False, indent=2))
397
+ return 0
398
+ stale_info = f" (stale_after={res['stale_after']})" if res["stale_after"] else ""
399
+ print(f"Verified {res['doc_id']} at {res['verified_at']}{stale_info}")
400
+ return 0
401
+
402
+
403
+ def _cmd_promote(args: argparse.Namespace) -> int:
404
+ import json
405
+
406
+ from .fs_atomic import CASConflictError
407
+ from .vault import promote_card
408
+
409
+ cfg = load_config(args.home)
410
+ try:
411
+ res = promote_card(
412
+ cfg,
413
+ args.id,
414
+ keep_global=args.keep_global,
415
+ allow_redacted=args.allow_redacted,
416
+ force=args.force,
417
+ apply=args.apply,
418
+ )
419
+ except (LookupError, ValueError, OSError, CASConflictError) as exc:
420
+ print(f"Error: {exc}", file=sys.stderr)
421
+ return 1 if isinstance(exc, LookupError) else 2
422
+
423
+ if args.json:
424
+ print(json.dumps(res, ensure_ascii=False, indent=2))
425
+ return 0
426
+ if not res["applied"]:
427
+ print(
428
+ f"[dry-run] Would promote {res['old_doc_id']} -> {res['target_path']} "
429
+ f"(mode={res['mode']}, pass --apply to write)"
430
+ )
431
+ print(res["preview"].rstrip())
432
+ if res.get("old_diff"):
433
+ print("\n" + res["old_diff"].rstrip())
434
+ return 0
435
+ print(f"Promoted {res['old_doc_id']} -> {res['new_doc_id']} ({res['target_path']}, mode={res['mode']})")
436
+ return 0
437
+
438
+
439
+ def _cmd_review(args: argparse.Namespace) -> int:
440
+ from .review import run_review
441
+
442
+ cfg = load_config(args.home)
443
+ return run_review(
444
+ cfg,
445
+ days=args.days,
446
+ limit=args.limit,
447
+ no_sync=args.no_sync,
448
+ as_json=args.json,
449
+ )
450
+
451
+
452
+ def _cmd_handoff(args: argparse.Namespace) -> int:
453
+ from .handoff import run_handoff_list, run_handoff_search, run_handoff_show
454
+
455
+ if args.handoff_cmd == "list":
456
+ return run_handoff_list(source=args.source, limit=args.limit, as_json=args.json)
457
+ if args.handoff_cmd == "search":
458
+ return run_handoff_search(args.query, source=args.source, limit=args.limit, as_json=args.json)
459
+ if args.handoff_cmd == "show":
460
+ return run_handoff_show(
461
+ args.session_id,
462
+ source=args.source,
463
+ mode=args.mode,
464
+ tail=args.tail,
465
+ turn_range=args.range,
466
+ max_chars=args.max_chars,
467
+ include_tools=args.include_tools,
468
+ raw_mode=args.raw,
469
+ as_json=args.json,
470
+ )
471
+ return 2
472
+
473
+
474
+ def _cmd_show(args: argparse.Namespace) -> int:
475
+ from .store import connect_ro, resolve_document
476
+
477
+ cfg = load_config(args.home)
478
+ conn = connect_ro(cfg.db_path, busy_timeout_ms=500)
479
+ if conn is None:
480
+ print(f"Not found: {args.id}", file=sys.stderr)
481
+ return 1
482
+ try:
483
+ row = resolve_document(conn, args.id)
484
+ if row is None:
485
+ print(f"Not found: {args.id}", file=sys.stderr)
486
+ return 1
487
+ p = Path(str(row["path"]))
488
+ if str(row["scope"]) == "memory" and p.is_file() and not p.is_symlink():
489
+ print(p.read_text(encoding="utf-8"))
490
+ return 0
491
+ chunks = conn.execute(
492
+ "SELECT raw_text FROM chunks WHERE doc_id = ? ORDER BY chunk_idx ASC",
493
+ (row["doc_id"],),
494
+ ).fetchall()
495
+ print(f"# {row['title']} ({row['doc_id']})\n")
496
+ print("\n---\n".join(str(c["raw_text"]) for c in chunks))
497
+ return 0
498
+ finally:
499
+ conn.close()
500
+
501
+
502
+ def _cmd_ls(args: argparse.Namespace) -> int:
503
+ import json
504
+
505
+ from .store import connect_ro, search_by_tags
506
+ from .text_utils import normalize_tags
507
+
508
+ cfg = load_config(args.home)
509
+ req_tags = normalize_tags(args.tags or "")
510
+ conn = connect_ro(cfg.db_path, busy_timeout_ms=500)
511
+ hits = search_by_tags(conn, args.scope, req_tags, limit=args.limit) if conn else []
512
+ if conn:
513
+ conn.close()
514
+ if args.json:
515
+ print(json.dumps({"total": len(hits), "items": hits}, ensure_ascii=False, indent=2))
516
+ return 0
517
+ for h in hits:
518
+ print(f"{h['doc_id']} | [{','.join(h['tags'])}] | {h['title']}")
519
+ print(f"Shown: {len(hits)}")
520
+ return 0
521
+
522
+
523
+ def _cmd_rm(args: argparse.Namespace) -> int:
524
+ from .vault import delete_card
525
+
526
+ cfg = load_config(args.home)
527
+ try:
528
+ res = delete_card(cfg, args.id)
529
+ print(f"Deleted {res['deleted']} ({Path(res['path']).name})")
530
+ return 0
531
+ except (LookupError, ValueError, OSError) as exc:
532
+ print(f"Error: {exc}", file=sys.stderr)
533
+ return 1 if isinstance(exc, LookupError) else 2
534
+
535
+
536
+ def _cmd_status(args: argparse.Namespace) -> int:
537
+ import json
538
+
539
+ from .fs_atomic import find_git_context
540
+ from .integrations import build_adapters
541
+ from .lint import run_lint
542
+ from .store import connect_ro, get_sync_meta, is_project_trusted, list_registered_projects
543
+
544
+ cfg = load_config(args.home)
545
+ db_size_mb = round(cfg.db_path.stat().st_size / (1024 * 1024), 3) if cfg.db_path.is_file() else 0.0
546
+ counts: dict[str, int] = {"memory": 0, "session": 0}
547
+ last_sync: dict[str, str] = {"memory": "never", "session": "never"}
548
+ trusted_projs: list[dict[str, Any]] = []
549
+ cur_trusted = False
550
+ git_ctx = find_git_context()
551
+
552
+ conn = connect_ro(cfg.db_path, busy_timeout_ms=500)
553
+ if conn is not None:
554
+ try:
555
+ for sc in ("memory", "session"):
556
+ counts[sc] = int(conn.execute("SELECT COUNT(*) FROM documents WHERE scope = ?", (sc,)).fetchone()[0])
557
+ last_sync[sc] = get_sync_meta(conn, f"last_sync:{sc}") or "never"
558
+ trusted_projs = list_registered_projects(conn, trusted_only=True)
559
+ if git_ctx is not None:
560
+ cur_trusted = is_project_trusted(conn, git_ctx[0])
561
+ finally:
562
+ conn.close()
563
+
564
+ lint_report = run_lint(cfg)
565
+ agents_status = {a.name: a.plan_install().status for a in build_adapters()}
566
+ payload = {
567
+ "version": __version__,
568
+ "data_dir": str(cfg.data_dir),
569
+ "db_path": str(cfg.db_path),
570
+ "db_size_mb": db_size_mb,
571
+ "counts": counts,
572
+ "last_sync": last_sync,
573
+ "trusted_projects": len(trusted_projs),
574
+ "current_repo": git_ctx[2] if git_ctx else None,
575
+ "current_repo_trusted": cur_trusted,
576
+ "lint_healthy": lint_report["is_healthy"],
577
+ "lint_issues": lint_report["issue_count"],
578
+ "agents": agents_status,
579
+ }
580
+ if args.json:
581
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
582
+ return 0
583
+
584
+ print(f"rotless v{__version__} | data={cfg.data_dir} | db={db_size_mb:.2f} MB")
585
+ print(f" memories : {counts['memory']} (last_sync={last_sync['memory']})")
586
+ print(f" sessions : {counts['session']} (last_sync={last_sync['session']})")
587
+ print(f" trusted : {len(trusted_projs)} repo(s)")
588
+ if git_ctx:
589
+ print(f" cwd repo : {git_ctx[2]} (trusted={cur_trusted})")
590
+ print(f" lint : healthy={lint_report['is_healthy']} (issues={lint_report['issue_count']})")
591
+ agent_line = ", ".join(f"{k}={v}" for k, v in agents_status.items())
592
+ print(f" agents : {agent_line}")
593
+ return 0
594
+
595
+
596
+ def build_parser() -> argparse.ArgumentParser:
597
+ epilog = (
598
+ "Command groups:\n"
599
+ " Core: init, review, add (create), search, handoff, status (stats)\n"
600
+ " Hygiene & Trust: lint, verify, supersede, promote, trust, untrust, show (get), ls (list), rm (delete)\n"
601
+ " Hook & Indexing: warmup, sync"
602
+ )
603
+ p = argparse.ArgumentParser(
604
+ prog="rotless",
605
+ description="Zero-key, anti-rot local memory and cross-agent handoff CLI.",
606
+ epilog=epilog,
607
+ formatter_class=argparse.RawDescriptionHelpFormatter,
608
+ )
609
+ p.add_argument("--version", action="version", version=f"rotless {__version__}")
610
+ p.add_argument("--home", default="", help="Override ROTLESS_HOME directory.")
611
+ sub = p.add_subparsers(dest="cmd", required=True)
612
+
613
+ # Core
614
+ s_init = sub.add_parser("init", help="Initialize rotless and install Tier 1 agent hooks/skills.")
615
+ s_init.add_argument("--agents", default="", help="Comma-separated agent list (claude,codex,antigravity,cursor).")
616
+ s_init.add_argument("--bin-path", default=None, help="Explicit rotless executable path for generated hooks.")
617
+ s_init.add_argument("--dry-run", action="store_true")
618
+ s_init.add_argument("--uninstall", action="store_true")
619
+ s_init.add_argument("-y", "--yes", action="store_true", help="Skip confirmation prompt.")
620
+ s_init.add_argument("--no-scan", action="store_true", help="Skip Day-0 local session discovery scan.")
621
+ s_init.add_argument("--json", action="store_true")
622
+ s_init.set_defaults(func=_cmd_init)
623
+
624
+ s_rev = sub.add_parser("review", help="30-second memory inbox over recent agent sessions.")
625
+ s_rev.add_argument("--days", type=int, default=None)
626
+ s_rev.add_argument("-l", "--limit", type=int, default=None)
627
+ s_rev.add_argument("--no-sync", action="store_true")
628
+ s_rev.add_argument("--json", action="store_true")
629
+ s_rev.set_defaults(func=_cmd_review)
630
+
631
+ s_add = sub.add_parser("add", aliases=["create"], help="Add a verified memory card to global or --local vault.")
632
+ s_add.add_argument("content", help="Markdown content or '-' for stdin.")
633
+ s_add.add_argument("--tags", default="")
634
+ s_add.add_argument("--title", default="")
635
+ s_add.add_argument("--type", default="learning")
636
+ s_add.add_argument("--local", action="store_true", help="Write into <repo>/.rotless/memories/ (fail-closed).")
637
+ s_add.add_argument("--allow-redacted", action="store_true", help="Redact secrets instead of failing with --local.")
638
+ s_add.add_argument("--no-project-tag", action="store_true")
639
+ s_add.add_argument("--source-session", default="")
640
+ s_add.add_argument("--source-ref", default="")
641
+ s_add.add_argument("--stale-after", default="")
642
+ s_add.add_argument("--verified", action="store_true")
643
+ s_add.add_argument("--force", action="store_true", help="Bypass pre-create duplicate guard.")
644
+ s_add.add_argument("--json", action="store_true")
645
+ s_add.set_defaults(func=_cmd_add)
646
+
647
+ s_search = sub.add_parser("search", help="Search memories and sessions via local FTS5 + anti-rot demotion.")
648
+ s_search.add_argument("query_pos", nargs="?", default="", help="Search query string.")
649
+ s_search.add_argument("-q", "--query", default="", help="Alias for positional search query.")
650
+ s_search.add_argument("--scope", choices=["memory", "session", "all"], default="all")
651
+ s_search.add_argument("--tags", default="")
652
+ s_search.add_argument("-l", "--limit", type=int, default=10)
653
+ s_search.add_argument("--expand", action="store_true")
654
+ s_search.add_argument("--all-chunks", action="store_true", help="Show all matching chunks instead of collapsing per doc.")
655
+ s_search.add_argument("--no-sync", action="store_true")
656
+ s_search.add_argument("--raw-output", action="store_true")
657
+ s_search.add_argument("--json", action="store_true")
658
+ s_search.set_defaults(func=_cmd_search)
659
+
660
+ s_ho = sub.add_parser("handoff", help="Read-only cross-agent session list, search, and show.")
661
+ ho_sub = s_ho.add_subparsers(dest="handoff_cmd", required=True)
662
+ ho_src_choices = ["all", "hermes", "antigravity", "antigravity-cli", "claude-code", "openclaw", "opencode", "codex"]
663
+
664
+ ho_list = ho_sub.add_parser("list", help="List recent sessions across coding agents.")
665
+ ho_list.add_argument("--source", choices=ho_src_choices, default="all")
666
+ ho_list.add_argument("-l", "--limit", type=int, default=20)
667
+ ho_list.add_argument("--json", action="store_true")
668
+
669
+ ho_search = ho_sub.add_parser("search", help="Search sessions by keyword.")
670
+ ho_search.add_argument("query")
671
+ ho_search.add_argument("--source", choices=ho_src_choices, default="all")
672
+ ho_search.add_argument("-l", "--limit", type=int, default=20)
673
+ ho_search.add_argument("--json", action="store_true")
674
+
675
+ ho_show = ho_sub.add_parser("show", help="Render a session summary or turn range.")
676
+ ho_show.add_argument("session_id")
677
+ ho_show.add_argument("--source", choices=ho_src_choices, default="all")
678
+ ho_show.add_argument("--mode", choices=["auto", "full", "summary"], default="auto")
679
+ ho_show.add_argument("--tail", type=int, default=8)
680
+ ho_show.add_argument("--range", default="")
681
+ ho_show.add_argument("--max-chars", type=int, default=12000)
682
+ ho_show.add_argument("--include-tools", action="store_true")
683
+ ho_show.add_argument("--raw", action="store_true", help="Disable secret redaction in output.")
684
+ ho_show.add_argument("--json", action="store_true")
685
+ s_ho.set_defaults(func=_cmd_handoff)
686
+
687
+ s_status = sub.add_parser("status", aliases=["stats"], help="Show vault, trust, lint, and agent integration status.")
688
+ s_status.add_argument("--json", action="store_true")
689
+ s_status.set_defaults(func=_cmd_status)
690
+
691
+ # Hygiene & Trust
692
+ s_lint = sub.add_parser("lint", help="Audit staleness, broken links, Unicode security, and permissions.")
693
+ s_lint.add_argument("--local", action="store_true", help="Audit only current repository .rotless/memories/.")
694
+ s_lint.add_argument("--fix", action="store_true", help="Preview deterministic fixes (pass --apply to write).")
695
+ s_lint.add_argument("--apply", action="store_true", help="Apply fixes planned by --fix atomically.")
696
+ s_lint.add_argument("--no-sync", action="store_true")
697
+ s_lint.add_argument("--json", action="store_true")
698
+ s_lint.set_defaults(func=_cmd_lint)
699
+
700
+ s_ver = sub.add_parser("verify", help="Refresh verified_at timestamp on a memory card via CAS.")
701
+ s_ver.add_argument("id")
702
+ s_ver.add_argument("--stale-after", default="", help="Set new future YYYY-MM-DD or RFC3339 stale_after.")
703
+ s_ver.add_argument("--extend", type=int, default=None, help="Extend stale_after N days from today.")
704
+ s_ver.add_argument("--clear-stale", action="store_true", help="Remove stale_after from the card.")
705
+ s_ver.add_argument("--json", action="store_true")
706
+ s_ver.set_defaults(func=_cmd_verify)
707
+
708
+ s_sup = sub.add_parser("supersede", help="Mark an older card superseded by an existing ID or new content.")
709
+ s_sup.add_argument("old_id")
710
+ s_sup.add_argument("new_content", nargs="?", default=None, help="Optional inline replacement text (or '-').")
711
+ s_sup.add_argument("--by", default="", help="Existing replacement card id/prefix.")
712
+ s_sup.add_argument("--tags", default="")
713
+ s_sup.add_argument("--title", default="")
714
+ s_sup.add_argument("--apply", action="store_true", help="Apply atomic CAS update (default is dry-run diff).")
715
+ s_sup.add_argument("--json", action="store_true")
716
+ s_sup.set_defaults(func=_cmd_supersede)
717
+
718
+ s_prom = sub.add_parser("promote", help="Graduate a global card into <repo>/.rotless/memories/ (dry-run by default).")
719
+ s_prom.add_argument("id")
720
+ s_prom.add_argument("--keep-global", action="store_true", help="Keep global card and mark it superseded.")
721
+ s_prom.add_argument("--allow-redacted", action="store_true", help="Allow redacting secrets/paths instead of blocking.")
722
+ s_prom.add_argument("--force", action="store_true", help="Overwrite if target project file already exists.")
723
+ s_prom.add_argument("--apply", action="store_true", help="Apply promotion to disk (default is dry-run).")
724
+ s_prom.add_argument("--json", action="store_true")
725
+ s_prom.set_defaults(func=_cmd_promote)
726
+
727
+ s_trust = sub.add_parser("trust", help="Explicitly trust a repository's .rotless/memories/ directory.")
728
+ s_trust.add_argument("path", nargs="?", default="")
729
+ s_trust.add_argument("--list", action="store_true")
730
+ s_trust.add_argument("--json", action="store_true")
731
+ s_trust.set_defaults(func=_cmd_trust)
732
+
733
+ s_untrust = sub.add_parser("untrust", help="Revoke trust for a repository's .rotless/memories/ directory.")
734
+ s_untrust.add_argument("path", nargs="?", default="")
735
+ s_untrust.add_argument("--json", action="store_true")
736
+ s_untrust.set_defaults(func=_cmd_untrust)
737
+
738
+ s_show = sub.add_parser("show", aliases=["get"], help="Print full card or session document by ID or prefix.")
739
+ s_show.add_argument("id")
740
+ s_show.set_defaults(func=_cmd_show)
741
+
742
+ s_ls = sub.add_parser("ls", aliases=["list"], help="List indexed memories or sessions by scope/tags.")
743
+ s_ls.add_argument("--scope", choices=["memory", "session", "all"], default="memory")
744
+ s_ls.add_argument("--tags", default="")
745
+ s_ls.add_argument("-l", "--limit", type=int, default=20)
746
+ s_ls.add_argument("--json", action="store_true")
747
+ s_ls.set_defaults(func=_cmd_ls)
748
+
749
+ s_rm = sub.add_parser("rm", aliases=["delete"], help="Delete a memory card and clean its SQLite index rows.")
750
+ s_rm.add_argument("id")
751
+ s_rm.set_defaults(func=_cmd_rm)
752
+
753
+ # Agent Hook & Indexing
754
+ s_warm = sub.add_parser("warmup", help="Fast-path SessionStart context warmup (hook & human preview).")
755
+ s_warm.add_argument("--cwd", default=None)
756
+ s_warm.add_argument("--budget", type=int, default=None)
757
+ s_warm.add_argument("--format", choices=["text", "claude-hook", "codex-hook", "agy-hook"], default="text")
758
+ s_warm.add_argument("--explain", action="store_true")
759
+ s_warm.set_defaults(func=_cmd_warmup)
760
+
761
+ s_sync = sub.add_parser("sync", help="Incrementally index global/trusted memories and sessions.")
762
+ s_sync.add_argument("--scope", choices=["memory", "session", "all"], default="all")
763
+ s_sync.add_argument("--dry-run", action="store_true")
764
+ s_sync.add_argument("--force", action="store_true")
765
+ s_sync.add_argument("--json", action="store_true")
766
+ s_sync.set_defaults(func=_cmd_sync)
767
+
768
+ return p
769
+
770
+
771
+ def main(argv: list[str] | None = None) -> int:
772
+ """CLI entrypoint."""
773
+ parser = build_parser()
774
+ args = parser.parse_args(argv)
775
+ return int(args.func(args))