-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·1311 lines (1135 loc) · 45.9 KB
/
Copy pathcli.py
File metadata and controls
executable file
·1311 lines (1135 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""icontext CLI — encrypted AI context vault for Claude Code, Codex, Cursor, and OpenCode."""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from pathlib import Path
__version__ = "0.4.0"
# ---------------------------------------------------------------------------
# Color helpers
# ---------------------------------------------------------------------------
class C:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
GREEN = "\033[32m"
CYAN = "\033[36m"
YELLOW = "\033[33m"
RED = "\033[31m"
WHITE = "\033[97m"
def _c(color: str, text: str) -> str:
return f"{color}{text}{C.RESET}"
def _ok(msg: str) -> str: return f" {_c(C.GREEN, '✓')} {msg}"
def _info(msg: str) -> str: return f" {_c(C.CYAN, '→')} {msg}"
def _warn(msg: str) -> str: return f" {_c(C.YELLOW, '!')} {msg}"
def _err(msg: str) -> str: return f" {_c(C.RED, '✗')} {msg}"
def _hr() -> str: return f" {_c(C.DIM, '─' * 44)}"
def _strip_ansi(text: str) -> str:
return re.sub(r'\033\[[0-9;]*m', '', text)
def _print(msg: str = "", **kwargs) -> None:
if not sys.stdout.isatty():
print(_strip_ansi(msg), **kwargs)
else:
print(msg, **kwargs)
def _header(cmd: str) -> None:
_print("")
_print(_hr())
_print(f" {_c(C.BOLD, f'icontext · {cmd}')}")
_print(_hr())
# ---------------------------------------------------------------------------
# Vault helpers
# ---------------------------------------------------------------------------
def _resolve_vault(vault_arg: str | None) -> Path:
if vault_arg:
return Path(vault_arg).expanduser().resolve()
env = os.environ.get("ICONTEXT_VAULT")
if env:
return Path(env).expanduser().resolve()
default = Path("~/context").expanduser().resolve()
if default.exists():
return default
sys.exit(
"\n"
+ _err("Vault not found.")
+ "\n\n"
+ _info("Run 'icontext init' to create your vault, or specify the path:")
+ "\n"
+ " icontext --vault /path/to/vault <command>\n"
+ " ICONTEXT_VAULT=/path/to/vault icontext <command>\n"
)
def _add_scripts_to_path() -> None:
"""Add the scripts/ directory (relative to cli.py) to sys.path."""
cli_dir = Path(__file__).resolve().parent
scripts_dir = cli_dir / "scripts"
if scripts_dir.is_dir() and str(scripts_dir) not in sys.path:
sys.path.insert(0, str(scripts_dir))
# Also support running from inside .icontext/
parent_scripts = cli_dir.parent / "scripts"
if parent_scripts.is_dir() and str(parent_scripts) not in sys.path:
sys.path.insert(0, str(parent_scripts))
def _get_connector(source: str):
"""Import and return a connector instance by name."""
cli_dir = Path(__file__).resolve().parent
# Support running from inside .icontext/ (installed) or repo root
connectors_dir = cli_dir / "connectors"
if not connectors_dir.is_dir():
connectors_dir = cli_dir.parent / "connectors"
if str(connectors_dir.parent) not in sys.path:
sys.path.insert(0, str(connectors_dir.parent))
if source == "gmail":
from connectors.gmail import GmailConnector
return GmailConnector()
if source == "linkedin":
from connectors.linkedin import LinkedInConnector
return LinkedInConnector()
sys.exit(_err(f"unknown source '{source}'. Valid: gmail, linkedin"))
# ---------------------------------------------------------------------------
# Relative time helper
# ---------------------------------------------------------------------------
def _relative_time(iso: str | None) -> str:
"""Convert an ISO timestamp to a human-readable relative string."""
if not iso:
return "never"
try:
from datetime import UTC, datetime
ts = datetime.fromisoformat(iso.replace("Z", "+00:00"))
delta = datetime.now(UTC) - ts
secs = int(delta.total_seconds())
if secs < 60:
return "just now"
if secs < 3600:
m = secs // 60
return f"{m}m ago"
if secs < 86400:
h = secs // 3600
return f"{h}h ago"
d = secs // 86400
return f"{d}d ago"
except Exception:
return iso
# ---------------------------------------------------------------------------
# Command handlers
# ---------------------------------------------------------------------------
def cmd_status(args: argparse.Namespace) -> int:
vault = _resolve_vault(args.vault)
_add_scripts_to_path()
if not vault.exists():
_print(_err(f"Vault not found: {vault}"))
_print(_info("Run 'icontext init' to create a vault, or check the path."))
return 1
_header("status")
_print("")
# Vault path
home = str(Path("~").expanduser())
vault_display = str(vault).replace(home, "~")
_print(f" {'vault':<12}{_c(C.WHITE, vault_display)}")
# Connector statuses
sources = ["gmail", "linkedin"]
for source in sources:
try:
connector = _get_connector(source)
st = connector.status(vault)
connected = st["connected"]
last_sync = _relative_time(st.get("last_sync"))
summary = st.get("summary", "")
# Extract display value from summary
if source == "gmail" and connected:
accounts_str = summary.replace(f"{summary.split(':')[0]}: ", "") if ":" in summary else summary
# Show first address only for brevity
first_addr = accounts_str.split(",")[0].strip()
val = f"{first_addr} {_c(C.DIM, '·')} synced {last_sync}"
elif source == "linkedin" and connected:
pdf_name = summary.replace("pdf: ", "") if summary.startswith("pdf: ") else summary
val = f"{pdf_name} {_c(C.DIM, '·')} synced {last_sync}"
else:
val = _c(C.DIM, "not connected")
_print(f" {source:<12}{val}")
except Exception as exc:
_print(f" {source:<12}{_c(C.RED, str(exc))}")
# Profile file
profile_path = vault / "internal" / "profile" / "user.md"
if profile_path.exists():
size_kb = profile_path.stat().st_size / 1024
home = str(Path("~").expanduser())
rel = str(profile_path).replace(home, "~")
_print(f" {'profile':<12}{rel} {_c(C.DIM, f'· {size_kb:.1f}KB')}")
else:
_print(f" {'profile':<12}{_c(C.DIM, 'not generated yet')}")
# Context card
card_path = vault / "shareable" / "profile" / "context-card.md"
if card_path.exists():
home = str(Path("~").expanduser())
rel = str(card_path).replace(home, "~")
_print(f" {'card':<12}{rel}")
else:
_print(f" {'card':<12}{_c(C.DIM, 'not generated yet')}")
_print(_hr())
return 0
def cmd_connect(args: argparse.Namespace) -> int:
try:
vault = _resolve_vault(args.vault)
connector = _get_connector(args.source)
if args.source == "linkedin":
pdf_path = getattr(args, "pdf", None)
connector.connect(vault, pdf_path=pdf_path)
else:
connector.connect(vault)
return 0
except KeyboardInterrupt:
_print(_warn("cancelled"))
return 1
except Exception as e:
_print(_err(str(e)))
return 1
def cmd_sync(args: argparse.Namespace) -> int:
vault = _resolve_vault(args.vault)
sources_to_sync: list[str] = []
if args.source:
sources_to_sync = [args.source]
else:
# Sync all connected sources
cfg_path = vault / ".icontext" / "connectors.json"
if cfg_path.exists():
import json
cfg = json.loads(cfg_path.read_text())
sources_to_sync = list(cfg.keys())
if not sources_to_sync:
_header("sync")
_print("")
_print(_warn("No sources configured yet."))
_print("")
_print(_info("Connect a source first:"))
_print(" icontext connect gmail")
_print(" icontext connect linkedin --pdf ~/Downloads/Profile.pdf")
_print("")
return 1
_header("sync")
_print("")
exit_code = 0
for source in sources_to_sync:
_print(_info(source))
try:
connector = _get_connector(source)
connector.sync(vault)
except Exception as exc:
_print(_err(str(exc)))
exit_code = 1
_print("")
if exit_code == 0 and sources_to_sync:
home = str(Path("~").expanduser())
profile_path = vault / "internal" / "profile" / "user.md"
profile_display = str(profile_path).replace(home, "~")
_print(_ok("context card ready"))
_print(_hr())
_print(_ok(f"done {_c(C.DIM, profile_display)}"))
_print("")
_print(" Open Claude Code and ask:")
_print(f' {_c(C.DIM, chr(34) + "What do you know about me?" + chr(34))}')
_print(_hr())
_print(_info("run `icontext doctor` to verify Claude Code has your profile"))
_print("")
return exit_code
def cmd_search(args: argparse.Namespace) -> int:
vault = _resolve_vault(args.vault)
_add_scripts_to_path()
try:
from indexlib import search
except ImportError:
sys.exit(_err("indexlib not found. Run from icontext repo root or after install."))
results = search(vault, args.query, limit=args.limit, tier=args.tier or None)
if not results:
_print(_warn("No results."))
return 0
for r in results:
_print(f" {_c(C.CYAN, r.tier)} {r.path} {_c(C.DIM, f'score: {r.score:.2f}')}")
_print(f" {_c(C.DIM, r.snippet)}")
_print("")
return 0
def cmd_rebuild(args: argparse.Namespace) -> int:
vault = _resolve_vault(args.vault)
_add_scripts_to_path()
try:
from indexlib import rebuild
except ImportError:
sys.exit(_err("indexlib not found. Run from icontext repo root or after install."))
_print(_info(f"Rebuilding index for {vault}..."))
count = rebuild(vault)
_print(_ok(f"Indexed {count} file(s)."))
return 0
def cmd_init(args: argparse.Namespace) -> int:
import subprocess as _sp
vault_path = args.vault or str(Path("~/context").expanduser())
vault = Path(vault_path).expanduser().resolve()
home = str(Path("~").expanduser())
vault_display = str(vault).replace(home, "~")
_header("init")
_print("")
# 1. Create vault directory structure
_print(_info(f"creating vault at {vault_display}"))
for subdir in ("shareable/profile", "internal/profile", "vault"):
(vault / subdir).mkdir(parents=True, exist_ok=True)
_print(_ok("shareable/ internal/ vault/ ready"))
# 2. Git init if needed
git_dir = vault / ".git"
if not git_dir.exists():
_sp.run(["git", "init", str(vault)], check=True, capture_output=True)
# Check git identity; set a temporary default if not configured
result = _sp.run(
["git", "config", "user.email"],
capture_output=True, text=True, cwd=str(vault),
)
if not result.stdout.strip():
_sp.run(
["git", "config", "user.email", "icontext@local"],
cwd=str(vault), capture_output=True,
)
_sp.run(
["git", "config", "user.name", "icontext"],
cwd=str(vault), capture_output=True,
)
_sp.run(
["git", "-C", str(vault), "commit", "--allow-empty", "-m", "init: icontext vault"],
check=True,
capture_output=True,
)
_print(_ok("git repo initialised"))
# 3. Install skills (Claude Code + Cursor)
skills_installed, skills_msgs = _install_skills()
for msg in skills_msgs:
_print(msg)
# 4. Insert CLAUDE.md snippet
_install_claude_md_snippet(vault)
_print(_hr())
_print("")
_print(" Next: open Claude Code in this directory and paste:")
_print("")
_print(f" {_c(C.BOLD, 'Populate my icontext profile from Gmail.')}")
_print("")
_print(f" {_c(C.DIM, 'That is it. Claude will use its Gmail MCP to build your profile.')}")
_print("")
_print(f" {_c(C.DIM, 'or, for headless setups (requires GEMINI_API_KEY):')}")
_print(" icontext connect gmail")
_print(" icontext sync")
_print("")
return 0
def _install_skills() -> tuple[int, list[str]]:
"""Install icontext skill files into ~/.claude/skills/ and ~/.cursor/rules/.
Returns (count_installed, list_of_status_messages).
"""
msgs: list[str] = []
cli_dir = Path(__file__).resolve().parent
skills_src = cli_dir / "skills"
if not skills_src.is_dir():
# Try repo-root layout when cli is symlinked
skills_src = cli_dir.parent / "skills"
if not skills_src.is_dir():
msgs.append(_warn("skills/ source dir not found — skipping skill install"))
return 0, msgs
skill_names = [
"icontext-populate-profile",
"icontext-refresh-profile",
"icontext-share-card",
"icontext-write-fact",
]
claude_skills_dir = Path("~/.claude/skills").expanduser()
cursor_rules_dir = Path("~/.cursor/rules").expanduser()
claude_skills_dir.mkdir(parents=True, exist_ok=True)
cursor_rules_dir.mkdir(parents=True, exist_ok=True)
count = 0
for name in skill_names:
src = skills_src / name / "SKILL.md"
if not src.exists():
msgs.append(_warn(f"missing skill source: {src}"))
continue
# Claude Code: ~/.claude/skills/<name>/SKILL.md
dest_claude = claude_skills_dir / name / "SKILL.md"
dest_claude.parent.mkdir(parents=True, exist_ok=True)
dest_claude.write_text(src.read_text())
# Cursor: ~/.cursor/rules/<name>.mdc (single-file equivalent)
dest_cursor = cursor_rules_dir / f"{name}.mdc"
dest_cursor.write_text(src.read_text())
count += 1
if count > 0:
msgs.append(_ok(f"{count} skill(s) installed (Claude Code + Cursor)"))
return count, msgs
def _install_claude_md_snippet(vault: Path) -> None:
"""Write or update the icontext snippet in ~/.claude/CLAUDE.md."""
claude_md = Path("~/.claude/CLAUDE.md").expanduser()
home = str(Path("~").expanduser())
vault_short = str(vault).replace(home, "~")
snippet = (
"<!-- icontext -->\n"
"## iContext (your context vault)\n\n"
f"Your context vault is at {vault_short} with this structure:\n\n"
" internal/profile/ — private synthesized profile\n"
" user.md — full profile (identity, relationships, projects)\n"
" relationships.md — key contacts table\n"
" projects.md — active projects\n"
" shareable/profile/ — shareable summaries\n"
" context-card.md — sendable to collaborators\n\n"
"ALWAYS read internal/profile/user.md at session start before answering personal\n"
"or work questions about the user.\n\n"
"If files are missing or older than 7 days, offer to populate/refresh.\n"
"To populate, invoke the icontext-populate-profile skill.\n\n"
"Available skills:\n"
"- icontext-populate-profile (build profile from Gmail/LinkedIn/chat)\n"
"- icontext-refresh-profile (update stale profile)\n"
"- icontext-share-card (regenerate shareable summary)\n"
"- icontext-write-fact (route a fact to the correct vault location)\n\n"
"Multi-device sync: at session start, run `icontext pull` to fetch any updates\n"
"from other machines. The user-prompt-submit hook does this automatically if a\n"
"remote is configured.\n"
"<!-- /icontext -->"
)
if claude_md.exists():
existing = claude_md.read_text()
else:
claude_md.parent.mkdir(parents=True, exist_ok=True)
existing = ""
pattern = re.compile(r"<!-- icontext -->.*?<!-- /icontext -->", re.DOTALL)
if pattern.search(existing):
new_text = pattern.sub(snippet, existing)
if new_text != existing:
claude_md.write_text(new_text)
_print(_ok("CLAUDE.md updated (skill references refreshed)"))
else:
_print(_ok("CLAUDE.md already up to date"))
else:
sep = "\n\n" if existing and not existing.endswith("\n\n") else ""
claude_md.write_text(existing + sep + snippet + "\n")
_print(_ok("CLAUDE.md updated — skills wired in"))
def cmd_share(args: argparse.Namespace) -> int:
vault = _resolve_vault(args.vault)
card_path = vault / "shareable" / "profile" / "context-card.md"
home = str(Path("~").expanduser())
card_display = str(card_path).replace(home, "~")
if not card_path.exists():
_header("share")
_print("")
_print(_warn("No context card found yet."))
_print("")
_print(" The card is generated automatically during your first Gmail sync.")
_print("")
_print(_info("icontext connect gmail # if not done yet"))
_print(_info("icontext sync # generates the card"))
_print("")
return 1
_header("your context card")
_print("")
# Print card content (no color, it's markdown)
content = card_path.read_text()
for line in content.splitlines():
print(f" {line}")
_print("")
_print(_hr())
_print(f" file: {_c(C.DIM, card_display)}")
_print(" share: email it, paste it into a new AI session,")
_print(" or drop it into a collaborator's vault")
_print(_hr())
_print("")
return 0
def cmd_skills(args: argparse.Namespace) -> int:
"""List or update installed icontext skills."""
import subprocess as _sp
action = getattr(args, "skills_action", None) or "list"
claude_skills_dir = Path("~/.claude/skills").expanduser()
cursor_rules_dir = Path("~/.cursor/rules").expanduser()
skill_names = [
"icontext-populate-profile",
"icontext-refresh-profile",
"icontext-share-card",
"icontext-write-fact",
]
if action == "list":
_header("skills")
_print("")
for name in skill_names:
claude_path = claude_skills_dir / name / "SKILL.md"
cursor_path = cursor_rules_dir / f"{name}.mdc"
claude_status = _c(C.GREEN, "✓") if claude_path.exists() else _c(C.DIM, "—")
cursor_status = _c(C.GREEN, "✓") if cursor_path.exists() else _c(C.DIM, "—")
_print(f" {name:<32} claude {claude_status} cursor {cursor_status}")
_print("")
_print(_hr())
return 0
if action == "update":
_header("skills · update")
_print("")
# Pull latest skill files from the icontext repo
icontext_dir = Path("~/icontext").expanduser()
if (icontext_dir / ".git").exists():
_print(_info("pulling latest from floomhq/icontext..."))
result = _sp.run(
["git", "-C", str(icontext_dir), "pull", "--ff-only", "--quiet"],
capture_output=True, text=True,
)
if result.returncode != 0:
_print(_warn(f"git pull failed: {result.stderr.strip()}"))
else:
_print(_warn(f"no icontext repo at {icontext_dir} — using bundled skills"))
count, msgs = _install_skills()
for msg in msgs:
_print(msg)
_print("")
_print(_hr())
return 0 if count > 0 else 1
_print(_err(f"unknown skills action: {action}"))
return 1
def _git_has_origin(vault: Path) -> bool:
result = subprocess.run(
["git", "-C", str(vault), "remote", "get-url", "origin"],
capture_output=True, text=True,
)
return result.returncode == 0 and bool(result.stdout.strip())
def _gh_repo_create_hint() -> str:
return (
"First time? Set up a private remote:\n"
" cd <vault> && gh repo create <user>/context --private --source=. --push\n"
" or, if you already have a repo:\n"
" cd <vault> && git remote add origin git@github.com:<user>/context.git && git push -u origin main"
)
def cmd_push(args: argparse.Namespace) -> int:
vault = _resolve_vault(args.vault)
if not vault.exists():
_print(_err(f"Vault not found: {vault}"))
return 1
if not (vault / ".git").exists():
_print(_err(f"Vault is not a git repo: {vault}"))
_print(_info("Run 'icontext init' first."))
return 1
_header("push")
_print("")
# Stage all
subprocess.run(
["git", "-C", str(vault), "add", "-A"],
check=False, capture_output=True,
)
# Check if anything is staged or already-committed-but-not-pushed
status = subprocess.run(
["git", "-C", str(vault), "status", "--porcelain"],
capture_output=True, text=True,
)
changed_lines = [ln for ln in status.stdout.splitlines() if ln.strip()]
n_changed = len(changed_lines)
if n_changed > 0:
# Commit
from datetime import datetime
msg = f"icontext: sync {datetime.now().strftime('%Y-%m-%d %H:%M')}"
commit = subprocess.run(
["git", "-C", str(vault), "commit", "-m", msg],
capture_output=True, text=True,
)
if commit.returncode != 0:
_print(_warn(f"commit failed: {commit.stderr.strip() or commit.stdout.strip()}"))
else:
_print(_ok(f"committed: {msg} ({n_changed} file(s) changed)"))
else:
_print(_info("no local changes to commit"))
# Push
if not _git_has_origin(vault):
_print("")
_print(_warn("no 'origin' remote configured"))
_print("")
for line in _gh_repo_create_hint().splitlines():
_print(f" {line}")
_print("")
return 1
push = subprocess.run(
["git", "-C", str(vault), "push"],
capture_output=True, text=True,
)
if push.returncode != 0:
err = (push.stderr or push.stdout).strip()
_print(_err(f"push failed: {err}"))
if "no upstream" in err.lower() or "set-upstream" in err.lower():
_print(_info("retrying with --set-upstream origin main..."))
push2 = subprocess.run(
["git", "-C", str(vault), "push", "--set-upstream", "origin", "HEAD"],
capture_output=True, text=True,
)
if push2.returncode != 0:
_print(_err((push2.stderr or push2.stdout).strip()))
return 1
_print(_ok("pushed (upstream set)"))
return 0
return 1
_print(_ok(f"pushed to origin"))
if push.stdout.strip():
for line in push.stdout.strip().splitlines()[:3]:
_print(_c(C.DIM, f" {line}"))
if push.stderr.strip():
for line in push.stderr.strip().splitlines()[:3]:
_print(_c(C.DIM, f" {line}"))
return 0
def cmd_pull(args: argparse.Namespace) -> int:
vault = _resolve_vault(args.vault)
if not vault.exists():
_print(_err(f"Vault not found: {vault}"))
return 1
if not (vault / ".git").exists():
_print(_err(f"Vault is not a git repo: {vault}"))
return 1
_header("pull")
_print("")
if not _git_has_origin(vault):
_print(_warn("no 'origin' remote configured — nothing to pull"))
_print("")
for line in _gh_repo_create_hint().splitlines():
_print(f" {line}")
_print("")
return 1
pull = subprocess.run(
["git", "-C", str(vault), "pull", "--rebase", "--autostash"],
capture_output=True, text=True,
)
out = (pull.stdout + pull.stderr).strip()
if pull.returncode != 0:
_print(_err("pull failed"))
for line in out.splitlines()[:10]:
_print(f" {line}")
if "conflict" in out.lower() or "CONFLICT" in out:
_print("")
_print(_warn("merge conflict — resolve manually:"))
_print(f" cd {vault}")
_print(" git status # see conflicted files")
_print(" # edit files to resolve")
_print(" git add <files>")
_print(" git rebase --continue")
return 1
if "Already up to date" in out or "up-to-date" in out.lower():
_print(_ok("already up to date"))
else:
_print(_ok("pulled latest from origin"))
for line in out.splitlines()[:6]:
_print(_c(C.DIM, f" {line}"))
return 0
# ---------------------------------------------------------------------------
# autosync
# ---------------------------------------------------------------------------
LAUNCHD_LABEL = "dev.icontext.autosync"
SYSTEMD_SERVICE = "icontext-autosync.service"
SYSTEMD_TIMER = "icontext-autosync.timer"
def _launchd_plist_path() -> Path:
return Path("~/Library/LaunchAgents/dev.icontext.autosync.plist").expanduser()
def _launchd_log_path() -> Path:
return Path("~/Library/Logs/icontext.log").expanduser()
def _systemd_unit_dir() -> Path:
return Path("~/.config/systemd/user").expanduser()
def _icontext_bin() -> str:
"""Best-effort path to the icontext executable for use in service files."""
import shutil as _sh
found = _sh.which("icontext")
if found:
return found
# Fall back to invoking cli.py directly via the current python
return f"{sys.executable} {Path(__file__).resolve()}"
def _autosync_start_macos(vault: Path) -> int:
plist = _launchd_plist_path()
plist.parent.mkdir(parents=True, exist_ok=True)
log_path = _launchd_log_path()
log_path.parent.mkdir(parents=True, exist_ok=True)
icontext = _icontext_bin()
# icontext might be "<python> <path>/cli.py"; split it.
program_args_xml = ""
parts = icontext.split()
for part in parts:
program_args_xml += f" <string>{part}</string>\n"
program_args_xml += " <string>push</string>\n"
program_args_xml += " <string>--vault</string>\n"
program_args_xml += f" <string>{vault}</string>\n"
plist_xml = f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{LAUNCHD_LABEL}</string>
<key>ProgramArguments</key>
<array>
{program_args_xml.rstrip()}
</array>
<key>StartInterval</key>
<integer>60</integer>
<key>KeepAlive</key>
<false/>
<key>RunAtLoad</key>
<true/>
<key>StandardOutPath</key>
<string>{log_path}</string>
<key>StandardErrorPath</key>
<string>{log_path}</string>
</dict>
</plist>
"""
plist.write_text(plist_xml)
_print(_ok(f"wrote {plist}"))
# Unload first if already loaded (idempotent), then load
subprocess.run(
["launchctl", "unload", str(plist)],
capture_output=True,
)
load = subprocess.run(
["launchctl", "load", str(plist)],
capture_output=True, text=True,
)
if load.returncode != 0:
_print(_err(f"launchctl load failed: {(load.stderr or load.stdout).strip()}"))
return 1
_print(_ok(f"launchd agent loaded ({LAUNCHD_LABEL})"))
_print(_info(f"runs every 60s; logs at {log_path}"))
return 0
def _systemctl_user_env() -> dict:
"""Return os.environ + XDG_RUNTIME_DIR/DBUS_SESSION_BUS_ADDRESS so systemctl
--user works in headless SSH sessions where the user's bus is set up via
`loginctl enable-linger`. No-op if already set in env."""
env = os.environ.copy()
if "XDG_RUNTIME_DIR" not in env:
uid = os.getuid()
runtime_dir = f"/run/user/{uid}"
if Path(runtime_dir).is_dir():
env["XDG_RUNTIME_DIR"] = runtime_dir
if "DBUS_SESSION_BUS_ADDRESS" not in env:
runtime_dir = env.get("XDG_RUNTIME_DIR", "")
bus_path = f"{runtime_dir}/bus" if runtime_dir else ""
if bus_path and Path(bus_path).exists():
env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={bus_path}"
return env
def _autosync_start_linux(vault: Path) -> int:
unit_dir = _systemd_unit_dir()
unit_dir.mkdir(parents=True, exist_ok=True)
icontext = _icontext_bin()
service_path = unit_dir / SYSTEMD_SERVICE
timer_path = unit_dir / SYSTEMD_TIMER
service_path.write_text(
f"""[Unit]
Description=iContext autosync (push vault to origin)
[Service]
Type=oneshot
ExecStart={icontext} push --vault {vault}
"""
)
timer_path.write_text(
f"""[Unit]
Description=iContext autosync timer
[Timer]
OnBootSec=2min
OnUnitActiveSec=60s
Unit={SYSTEMD_SERVICE}
[Install]
WantedBy=timers.target
"""
)
_print(_ok(f"wrote {service_path}"))
_print(_ok(f"wrote {timer_path}"))
sysenv = _systemctl_user_env()
# systemctl --user daemon-reload + enable --now
subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True, env=sysenv)
enable = subprocess.run(
["systemctl", "--user", "enable", "--now", SYSTEMD_TIMER],
capture_output=True, text=True, env=sysenv,
)
if enable.returncode != 0:
err = (enable.stderr or enable.stdout).strip()
_print(_err(f"systemctl enable failed: {err}"))
if "Failed to connect to bus" in err or "no medium" in err.lower():
_print(_warn("systemd --user not reachable from this shell"))
_print(_info("If you are in a headless SSH session, ensure linger is enabled:"))
_print(" loginctl enable-linger $(whoami)")
_print(_info("Then re-run with the user bus exported:"))
_print(' XDG_RUNTIME_DIR=/run/user/$(id -u) \\')
_print(' DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus \\')
_print(' icontext autosync start --vault ' + str(vault))
return 1
_print(_ok(f"timer enabled ({SYSTEMD_TIMER}; runs every 60s)"))
return 0
def _autosync_stop_macos() -> int:
plist = _launchd_plist_path()
if not plist.exists():
_print(_warn("autosync not configured (no plist)"))
return 0
subprocess.run(["launchctl", "unload", str(plist)], capture_output=True)
plist.unlink()
_print(_ok(f"unloaded and removed {plist}"))
return 0
def _autosync_stop_linux() -> int:
timer_path = _systemd_unit_dir() / SYSTEMD_TIMER
service_path = _systemd_unit_dir() / SYSTEMD_SERVICE
if not timer_path.exists() and not service_path.exists():
_print(_warn("autosync not configured (no unit files)"))
return 0
sysenv = _systemctl_user_env()
subprocess.run(
["systemctl", "--user", "disable", "--now", SYSTEMD_TIMER],
capture_output=True, env=sysenv,
)
for p in (timer_path, service_path):
if p.exists():
p.unlink()
_print(_ok(f"removed {p}"))
subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True, env=sysenv)
return 0
def _autosync_status_macos() -> int:
plist = _launchd_plist_path()
log_path = _launchd_log_path()
if not plist.exists():
_print(_c(C.DIM, " status: not running (no plist installed)"))
return 0
list_out = subprocess.run(
["launchctl", "list", LAUNCHD_LABEL],
capture_output=True, text=True,
)
if list_out.returncode == 0:
_print(_ok(f"status: running ({LAUNCHD_LABEL})"))
else:
_print(_warn(f"status: plist installed but not loaded — run 'icontext autosync start'"))
if log_path.exists():
mtime = log_path.stat().st_mtime
from datetime import datetime
last = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S")
_print(_info(f"last log: {last} ({log_path})"))
else:
_print(_c(C.DIM, " last log: no log file yet"))
return 0
def _autosync_status_linux() -> int:
timer_path = _systemd_unit_dir() / SYSTEMD_TIMER
if not timer_path.exists():
_print(_c(C.DIM, " status: not running (no timer installed)"))
return 0
sysenv = _systemctl_user_env()
is_active = subprocess.run(
["systemctl", "--user", "is-active", SYSTEMD_TIMER],
capture_output=True, text=True, env=sysenv,
)
state = is_active.stdout.strip() or is_active.stderr.strip()
if state == "active":
_print(_ok(f"status: active ({SYSTEMD_TIMER})"))
else:
_print(_warn(f"status: {state}"))
# Last run time
show = subprocess.run(
["systemctl", "--user", "show", SYSTEMD_SERVICE,
"--property=ExecMainExitTimestamp", "--property=Result"],
capture_output=True, text=True, env=sysenv,
)
for line in show.stdout.splitlines():
if line.strip():
_print(_info(line.strip()))
return 0
def cmd_autosync(args: argparse.Namespace) -> int:
import platform
action = getattr(args, "autosync_action", None)
if not action:
_print(_err("autosync requires an action: start | stop | status"))
return 1
is_mac = platform.system() == "Darwin"
_header(f"autosync · {action}")
_print("")
if action == "start":
vault = _resolve_vault(args.vault)
if not vault.exists():
_print(_err(f"Vault not found: {vault}"))
return 1
return _autosync_start_macos(vault) if is_mac else _autosync_start_linux(vault)
if action == "stop":
return _autosync_stop_macos() if is_mac else _autosync_stop_linux()
if action == "status":
return _autosync_status_macos() if is_mac else _autosync_status_linux()
_print(_err(f"unknown autosync action: {action}"))
return 1
def cmd_doctor(args: argparse.Namespace) -> int:
vault = _resolve_vault(args.vault)
_add_scripts_to_path()
# Find doctor.py relative to cli.py
cli_dir = Path(__file__).resolve().parent
candidates = [
cli_dir / "scripts" / "doctor.py",