-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
1582 lines (1355 loc) · 53.7 KB
/
install.py
File metadata and controls
1582 lines (1355 loc) · 53.7 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
"""
dotai — TUI + CLI Installer
Full-screen terminal application and non-interactive CLI for installing
standardized Claude Code configuration. No arguments launches the TUI.
Any flags run non-interactively for scripting and CI use.
Requirements: Python 3.8+, textual (pip install textual) for TUI mode
Platforms: macOS, Linux, Windows
"""
import json
import re
import sys
import shutil
from datetime import datetime
from pathlib import Path
# ---------------------------------------------------------------------------
# Dependency check (deferred — only needed for TUI mode)
# ---------------------------------------------------------------------------
try:
from textual.app import App, ComposeResult
from textual.screen import Screen
from textual.widgets import (
Static, Button, SelectionList,
RadioSet, RadioButton, Checkbox,
Rule, Footer, Header,
)
from textual.containers import Container, Horizontal, VerticalScroll
from textual.binding import Binding
from textual.widgets.selection_list import Selection
from textual import on
from rich.text import Text
_TEXTUAL_AVAILABLE = True
except ImportError:
_TEXTUAL_AVAILABLE = False
# Stubs so TUI class definitions don't crash at import time.
# These classes are never instantiated — CLI mode doesn't use them.
class _StubMeta(type):
def __getattr__(cls, name): return cls
class _Stub(metaclass=_StubMeta):
pass
App = Screen = _Stub
ComposeResult = None
def Binding(*a, **kw): return None
def Selection(*a, **kw): return None
Static = Button = SelectionList = RadioSet = RadioButton = Checkbox = _Stub
Rule = Footer = Header = _Stub
Container = Horizontal = VerticalScroll = _Stub
def on(*a, **kw):
return lambda f: f
class Text:
def __init__(self, *a, **kw): pass
def append(self, *a, **kw): pass
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
SCRIPT_DIR = Path(__file__).resolve().parent
HOME_DIR = SCRIPT_DIR / "standards" / "home"
HOME_CLAUDE_MD = HOME_DIR / "CLAUDE.md"
HOME_RULES_DIR = HOME_DIR / "rules"
AGENTS_DIR = SCRIPT_DIR / "standards" / "agents"
TASKS_DIR = SCRIPT_DIR / "standards" / "tasks"
CLAUDE_HOME = Path.home() / ".claude"
CLAUDE_MD = CLAUDE_HOME / "CLAUDE.md"
CLAUDE_RULES = CLAUDE_HOME / "rules"
CLAUDE_AGENTS = CLAUDE_HOME / "agents"
BACKUPS_DIR = CLAUDE_HOME / "backups"
MANDATORY_RULES = {"security.md"}
MANDATORY_AGENTS = {"security-auditor.md", "compliance-reviewer.md"}
HOME_SETTINGS_JSON = HOME_DIR / "settings.json"
HOME_STATUSLINE = HOME_DIR / "statusline.sh"
CLAUDE_SETTINGS = CLAUDE_HOME / "settings.json"
CLAUDE_STATUSLINE = CLAUDE_HOME / "statusline.sh"
AUTO_READ_PERMISSIONS = {
"permissions": {
"allow": [
"Read",
"Glob",
"Grep",
"Bash(ls:*)",
"Bash(git diff:*)",
"Bash(git log:*)",
"Bash(git status:*)",
]
}
}
# ---------------------------------------------------------------------------
# File helpers
# ---------------------------------------------------------------------------
def discover_files(directory: Path) -> list:
if not directory.exists():
return []
return sorted(
[(f.name, f) for f in directory.iterdir()
if f.suffix == ".md" and f.is_file() and not f.is_symlink()],
key=lambda x: x[0],
)
def is_git_repo(path: Path) -> bool:
current = path.resolve()
while True:
if (current / ".git").exists():
return True
parent = current.parent
if parent == current:
return False
current = parent
def get_repo_name(path: Path) -> str:
current = path.resolve()
while True:
if (current / ".git").exists():
return current.name
parent = current.parent
if parent == current:
return path.name
current = parent
def file_has_content(path: Path) -> bool:
if not path.exists():
return False
text = path.read_text(encoding="utf-8").strip()
text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
lines = [l for l in text.splitlines() if l.strip() and not l.strip().startswith("#")]
return len(lines) > 0
def get_heading(path: Path) -> str:
for line in path.read_text(encoding="utf-8").splitlines():
if line.startswith("#"):
return line.lstrip("#").strip()
return path.stem
def get_frontmatter_field(path: Path, field: str) -> str:
"""Extract a field from YAML frontmatter (between --- delimiters)."""
lines = path.read_text(encoding="utf-8").splitlines()
if not lines or lines[0].strip() != "---":
return ""
for line in lines[1:]:
if line.strip() == "---":
break
if line.startswith(f"{field}:"):
return line.split(":", 1)[1].strip()
return ""
def get_description(path: Path) -> str:
return get_frontmatter_field(path, "description")
def get_model(path: Path) -> str:
return get_frontmatter_field(path, "model")
def backup_file(path: Path) -> Path:
ts = datetime.now().strftime("%Y%m%d-%H%M%S")
try:
rel = path.resolve().relative_to(CLAUDE_HOME.resolve())
backup = BACKUPS_DIR / f"{rel}.bak.{ts}"
except ValueError:
backup = BACKUPS_DIR / f"{path.name}.bak.{ts}"
backup.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, backup)
return backup
def create_snapshot():
"""Snapshot managed files under ~/.claude/ before installing.
Only snapshots files we manage: CLAUDE.md, rules/, agents/, tasks/.
Returns the snapshot directory, or None if nothing to snapshot.
"""
if not CLAUDE_HOME.exists():
return None
# Collect only files we manage
files_to_snap = []
claude_md = CLAUDE_HOME / "CLAUDE.md"
if claude_md.exists():
files_to_snap.append(claude_md)
settings_json = CLAUDE_HOME / "settings.json"
if settings_json.exists():
files_to_snap.append(settings_json)
statusline_sh = CLAUDE_HOME / "statusline.sh"
if statusline_sh.exists():
files_to_snap.append(statusline_sh)
for subdir in ("rules", "agents", "tasks"):
d = CLAUDE_HOME / subdir
if d.exists():
for f in d.iterdir():
if f.is_file() and not f.is_symlink():
files_to_snap.append(f)
if not files_to_snap:
return None
ts = datetime.now().strftime("%Y%m%d-%H%M%S")
snap_dir = BACKUPS_DIR / ts
snap_dir.mkdir(parents=True, exist_ok=True)
for f in files_to_snap:
rel = f.relative_to(CLAUDE_HOME)
dest = snap_dir / rel
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(f, dest)
return snap_dir
def discover_snapshots() -> list:
"""Return list of (timestamp_str, path) for existing snapshots, newest first."""
if not BACKUPS_DIR.exists():
return []
snaps = []
for d in BACKUPS_DIR.iterdir():
if d.is_dir() and re.match(r'^\d{8}-\d{6}$', d.name):
snaps.append((d.name, d))
return sorted(snaps, key=lambda x: x[0], reverse=True)
def restore_snapshot(snap_dir: Path) -> list:
"""Restore files from a snapshot directory back to ~/.claude/.
Returns log entries.
"""
log = []
resolved_home = CLAUDE_HOME.resolve()
for item in snap_dir.rglob("*"):
if not item.is_file() or item.is_symlink():
continue
rel = item.relative_to(snap_dir)
dest = CLAUDE_HOME / rel
# Skip if destination is an existing symlink (could escape ~/.claude/)
if dest.exists() and dest.is_symlink():
continue
# Verify destination stays under ~/.claude/
try:
dest.resolve().relative_to(resolved_home)
except ValueError:
continue
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists():
if dest.read_bytes() == item.read_bytes():
log.append(("current", f"~/.claude/{rel}"))
continue
backup_file(dest)
shutil.copy2(item, dest)
log.append(("restored", f"~/.claude/{rel}"))
return log
# ---------------------------------------------------------------------------
# Status detection — compare source vs installed
# ---------------------------------------------------------------------------
def file_status(src: Path, dest: Path) -> str:
"""Compare source file with installed file.
Returns: 'new', 'installed', or 'update'
- new: source exists, not installed yet
- installed: installed and matches source (up to date)
- update: installed but differs from source (update available)
"""
if not dest.exists():
return "new"
src_bytes = src.read_bytes()
dest_bytes = dest.read_bytes()
return "installed" if src_bytes == dest_bytes else "update"
def is_fresh_install() -> bool:
"""True if no global CLAUDE.md exists yet (first-time install)."""
return not CLAUDE_MD.exists()
def build_file_info(source_files: list, install_dir: Path, mandatory: set) -> list:
"""Build a list of dicts with name, source, status, mandatory for each file.
Returns list of:
{name, src, heading, status, mandatory, description, model}
"""
items = []
for name, src in source_files:
dest = install_dir / name
status = file_status(src, dest)
items.append({
"name": name,
"src": src,
"status": status,
"mandatory": name in mandatory,
"heading": get_heading(src),
"description": get_description(src),
"model": get_model(src),
})
return items
STATUS_BADGE = {
"new": "NEW",
"installed": "UP TO DATE",
"update": "UPDATE",
}
STATUS_STYLE = {
"new": "cyan bold",
"installed": "green",
"update": "yellow bold",
}
def make_selection_label(item: dict, show_model: bool = False):
"""Build a Rich Text label with status badge for a SelectionList item."""
label = Text()
label.append(f"{item['heading']} ", style="bold")
label.append(f"({item['name']})", style="dim")
if show_model and item.get("model"):
label.append(f" [{item['model']}]", style="dim yellow")
if item["mandatory"]:
label.append(" MANDATORY", style="red bold")
badge = STATUS_BADGE[item["status"]]
style = STATUS_STYLE[item["status"]]
label.append(f" {badge}", style=style)
return label
# ---------------------------------------------------------------------------
# Smart install — install, update, remove, skip
# ---------------------------------------------------------------------------
def smart_install(src: Path, dest: Path, label: str, log: list) -> None:
"""Install or update a file, skipping if already up to date."""
dest.parent.mkdir(parents=True, exist_ok=True)
if not dest.exists():
shutil.copy2(src, dest)
log.append(("installed", label))
elif src.read_bytes() != dest.read_bytes():
bak = backup_file(dest)
shutil.copy2(src, dest)
log.append(("updated", f"{label} (backed up -> {bak.name})"))
else:
log.append(("current", label))
def remove_with_log(dest: Path, label: str, log: list) -> None:
"""Remove an installed file, backing up first."""
if dest.exists():
bak = backup_file(dest)
dest.unlink()
log.append(("removed", f"{label} (backed up -> {bak.name})"))
def install_auto_read(cwd: Path, log: list) -> None:
"""Create .claude/settings.json with auto-approve read permissions."""
settings_dir = cwd / ".claude"
settings_dir.mkdir(parents=True, exist_ok=True)
settings_file = settings_dir / "settings.json"
if settings_file.exists():
# Merge into existing settings
try:
existing = json.loads(settings_file.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
existing = {}
perms = existing.setdefault("permissions", {})
allow = perms.setdefault("allow", [])
added = []
for tool in AUTO_READ_PERMISSIONS["permissions"]["allow"]:
if tool not in allow:
allow.append(tool)
added.append(tool)
if added:
settings_file.write_text(
json.dumps(existing, indent=2) + "\n", encoding="utf-8"
)
log.append(("installed", f".claude/settings.json (added {len(added)} permissions)"))
else:
log.append(("current", ".claude/settings.json (permissions already present)"))
else:
settings_file.write_text(
json.dumps(AUTO_READ_PERMISSIONS, indent=2) + "\n", encoding="utf-8"
)
log.append(("installed", ".claude/settings.json (auto-approve read)"))
def deep_merge_settings(base: dict, overlay: dict) -> dict:
"""Recursively merge overlay into base. Lists append without dupes, scalars overlay wins."""
merged = dict(base)
for key, value in overlay.items():
if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
merged[key] = deep_merge_settings(merged[key], value)
elif key in merged and isinstance(merged[key], list) and isinstance(value, list):
for item in value:
if item not in merged[key]:
merged[key].append(item)
else:
merged[key] = value
return merged
def install_global_settings(log: list) -> None:
"""Install global ~/.claude/settings.json from template, merging with existing."""
CLAUDE_HOME.mkdir(parents=True, exist_ok=True)
# Load template
try:
template = json.loads(HOME_SETTINGS_JSON.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as e:
log.append(("warning", f"~/.claude/settings.json (failed to read template: {e})"))
return
# Load existing settings
existing = {}
if CLAUDE_SETTINGS.exists():
try:
existing = json.loads(CLAUDE_SETTINGS.read_text(encoding="utf-8"))
except json.JSONDecodeError:
bak = backup_file(CLAUDE_SETTINGS)
log.append(("warning", f"~/.claude/settings.json (malformed JSON, backed up -> {bak})"))
existing = {}
# Merge: template is the base, existing user customizations preserved on top
merged = deep_merge_settings(template, existing)
# But always update env vars and permissions from template (template wins for these)
if "env" in template:
merged["env"] = deep_merge_settings(
merged.get("env", {}), template["env"]
)
if "permissions" in template:
for perm_key in ("allow", "deny", "ask"):
if perm_key in template["permissions"]:
base_list = merged.setdefault("permissions", {}).setdefault(perm_key, [])
for item in template["permissions"][perm_key]:
if item not in base_list:
base_list.append(item)
# Scalars from template permissions
for scalar_key in ("defaultMode", "disableBypassPermissionsMode"):
if scalar_key in template.get("permissions", {}):
merged.setdefault("permissions", {})[scalar_key] = template["permissions"][scalar_key]
# Compare with existing to detect changes
if existing == merged:
log.append(("current", "~/.claude/settings.json"))
else:
if CLAUDE_SETTINGS.exists() and existing:
bak = backup_file(CLAUDE_SETTINGS)
CLAUDE_SETTINGS.write_text(
json.dumps(merged, indent=2) + "\n", encoding="utf-8"
)
log.append(("updated", f"~/.claude/settings.json (backed up -> {bak})"))
else:
CLAUDE_SETTINGS.write_text(
json.dumps(merged, indent=2) + "\n", encoding="utf-8"
)
log.append(("installed", "~/.claude/settings.json"))
# Install statusline script
if HOME_STATUSLINE.exists():
smart_install(HOME_STATUSLINE, CLAUDE_STATUSLINE, "~/.claude/statusline.sh", log)
# Ensure executable
import stat
CLAUDE_STATUSLINE.chmod(CLAUDE_STATUSLINE.stat().st_mode | stat.S_IXUSR)
def run_install(app) -> list:
"""Execute install based on app state. Returns log entries."""
log = []
# Snapshot existing files before making changes
if app.scope in ("global", "both"):
snap = create_snapshot()
if snap:
log.append(("snapshot", f"Backed up to {snap}"))
if app.scope in ("global", "both"):
# CLAUDE.md — always install/update
smart_install(HOME_CLAUDE_MD, CLAUDE_MD, "~/.claude/CLAUDE.md", log)
# Rules — install selected, remove deselected
CLAUDE_RULES.mkdir(parents=True, exist_ok=True)
for item in app.rule_info:
name = item["name"]
dest = CLAUDE_RULES / name
if name in app.selected_rules:
smart_install(item["src"], dest, f"~/.claude/rules/{name}", log)
else:
remove_with_log(dest, f"~/.claude/rules/{name}", log)
# Agents — install selected, remove deselected
CLAUDE_AGENTS.mkdir(parents=True, exist_ok=True)
for item in app.agent_info:
name = item["name"]
dest = CLAUDE_AGENTS / name
if name in app.selected_agents:
smart_install(item["src"], dest, f"~/.claude/agents/{name}", log)
else:
remove_with_log(dest, f"~/.claude/agents/{name}", log)
# Tasks
if app.create_global_tasks:
tasks_dir = CLAUDE_HOME / "tasks"
tasks_dir.mkdir(parents=True, exist_ok=True)
for tpl in ["lessons.md", "todo.md"]:
src = TASKS_DIR / tpl
dest = tasks_dir / tpl
if dest.exists() and file_has_content(dest):
log.append(("skipped", f"~/.claude/tasks/{tpl} (has content)"))
else:
shutil.copy2(src, dest)
log.append(("installed", f"~/.claude/tasks/{tpl}"))
# Global settings.json (permissions)
install_global_settings(log)
if app.scope in ("project", "both"):
cwd = app.cwd
if is_git_repo(cwd):
if app.create_project_tasks:
tasks_dir = cwd / "tasks"
tasks_dir.mkdir(parents=True, exist_ok=True)
for tpl in ["lessons.md", "todo.md"]:
src = TASKS_DIR / tpl
dest = tasks_dir / tpl
if dest.exists() and file_has_content(dest):
log.append(("skipped", f"tasks/{tpl} (has content)"))
else:
shutil.copy2(src, dest)
log.append(("installed", f"tasks/{tpl}"))
if app.auto_read:
install_auto_read(cwd, log)
else:
log.append(("skipped", "Project install (not in a git repo)"))
return log
# ---------------------------------------------------------------------------
# Textual CSS
# ---------------------------------------------------------------------------
INSTALLER_CSS = """
Screen {
align: center middle;
}
.wizard {
width: 90%;
max-width: 100;
height: auto;
max-height: 95%;
border: double $accent;
padding: 1 2;
background: $surface;
}
.title {
width: 100%;
text-align: center;
text-style: bold;
background: $accent;
color: $text;
padding: 0 2;
}
.subtitle {
text-align: center;
color: $text-muted;
margin: 1 0;
}
.info {
color: $text-muted;
}
.mandatory-note {
color: $error;
text-style: italic;
margin: 0 0 0 2;
}
.legend {
color: $text-muted;
margin: 0 0 0 2;
}
SelectionList {
height: auto;
max-height: 18;
margin: 1 0;
border: solid $primary;
& > .selection-list--button {
color: $panel;
background: $panel;
}
& > .selection-list--button-highlighted {
color: $panel;
background: $panel;
}
& > .selection-list--button-selected {
color: $success;
background: $panel;
text-style: bold;
}
& > .selection-list--button-selected-highlighted {
color: $success;
background: $panel;
text-style: bold;
}
}
.help-text {
color: $text-muted;
text-style: italic;
margin: 0 0 0 2;
}
RadioSet {
width: 100%;
margin: 1 0;
}
Checkbox {
margin: 1 2;
}
.buttons {
width: 100%;
height: auto;
align: center middle;
margin-top: 1;
}
.buttons Button {
margin: 0 1;
}
.log-box {
width: 100%;
height: auto;
max-height: 20;
border: solid $success;
padding: 1 2;
margin: 1 0;
}
.summary-box {
width: 100%;
height: auto;
border: double $success;
padding: 1 2;
margin: 1 0;
}
"""
# ---------------------------------------------------------------------------
# Screens
# ---------------------------------------------------------------------------
class ScopeScreen(Screen):
BINDINGS = [
Binding("enter", "next", "Next", priority=True),
Binding("q", "quit", "Quit"),
]
def compose(self) -> ComposeResult:
cwd = self.app.cwd
in_repo = self.app.in_repo
repo_info = f" (repo: {get_repo_name(cwd)})" if in_repo else ""
fresh = self.app.fresh_install
with Container(classes="wizard"):
yield Static("AI Coding Standards", classes="title")
yield Static(
"Standardized Claude Code configuration for your team",
classes="subtitle",
)
yield Rule()
yield Static(f" {cwd}{repo_info}", classes="info")
if not fresh:
yield Static(
" Existing installation detected — select items to add, update, or remove",
classes="info",
)
yield Static("")
with RadioSet(id="scope-radio"):
yield RadioButton(
"Global — CLAUDE.md + rules + agents to ~/.claude/",
value=True,
)
yield RadioButton(
f"Project — tasks + settings in current repo"
f"{'' if in_repo else ' (no repo detected)'}",
)
yield RadioButton("Both — global + project")
yield RadioButton("Restore — restore from a previous backup")
with Horizontal(classes="buttons"):
yield Button("Next", variant="primary", id="btn-next")
yield Button("Quit", variant="error", id="btn-quit")
yield Footer()
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "btn-next":
self.action_next()
elif event.button.id == "btn-quit":
self.action_quit()
def action_next(self) -> None:
radio = self.query_one("#scope-radio", RadioSet)
idx = radio.pressed_index if radio.pressed_index >= 0 else 0
self.app.scope = {0: "global", 1: "project", 2: "both", 3: "restore"}[idx]
if self.app.scope == "restore":
self.app.push_screen(RestoreScreen())
elif self.app.scope in ("global", "both"):
self.app.push_screen(RulesScreen())
else:
self.app.push_screen(ProjectScreen())
def action_quit(self) -> None:
self.app.exit()
class RulesScreen(Screen):
BINDINGS = [
Binding("enter", "next", "Next", priority=True),
Binding("escape", "back", "Back"),
Binding("q", "quit", "Quit"),
]
def compose(self) -> ComposeResult:
fresh = self.app.fresh_install
selections = []
for item in self.app.rule_info:
label = make_selection_label(item)
# Pre-select: fresh = all, re-install = only installed/update + mandatory
checked = fresh or item["status"] != "new" or item["mandatory"]
selections.append(Selection(label, item["name"], checked))
with Container(classes="wizard"):
yield Static("Select Rules", classes="title")
yield Static(
"Auto-loaded from ~/.claude/rules/ every session",
classes="subtitle",
)
yield Static("MANDATORY rules cannot be deselected", classes="mandatory-note")
yield Static(" Space = toggle selection | Arrow keys = navigate | Enter = next", classes="help-text")
legend = Text()
legend.append(" NEW", style="cyan bold")
legend.append(" = not yet installed ", style="dim")
legend.append("UP TO DATE", style="green")
legend.append(" = current ", style="dim")
legend.append("UPDATE", style="yellow bold")
legend.append(" = new version available", style="dim")
yield Static(legend, classes="legend")
yield SelectionList(*selections, id="rules-list")
with Horizontal(classes="buttons"):
yield Button("Back", id="btn-back")
yield Button("Next", variant="primary", id="btn-next")
yield Footer()
@on(SelectionList.SelectionToggled, "#rules-list")
def enforce_mandatory(self) -> None:
sl = self.query_one("#rules-list", SelectionList)
for name in MANDATORY_RULES:
if name not in sl.selected:
sl.select(name)
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "btn-next":
self.action_next()
elif event.button.id == "btn-back":
self.action_back()
def action_next(self) -> None:
sl = self.query_one("#rules-list", SelectionList)
self.app.selected_rules = set(sl.selected)
self.app.push_screen(AgentsScreen())
def action_back(self) -> None:
self.app.pop_screen()
def action_quit(self) -> None:
self.app.exit()
class AgentsScreen(Screen):
BINDINGS = [
Binding("enter", "next", "Next", priority=True),
Binding("escape", "back", "Back"),
Binding("q", "quit", "Quit"),
]
def compose(self) -> ComposeResult:
fresh = self.app.fresh_install
selections = []
for item in self.app.agent_info:
label = make_selection_label(item, show_model=True)
checked = fresh or item["status"] != "new" or item["mandatory"]
selections.append(Selection(label, item["name"], checked))
with Container(classes="wizard"):
yield Static("Select Agents", classes="title")
yield Static(
"Invoked via /agent-name in Claude Code",
classes="subtitle",
)
yield Static("MANDATORY agents cannot be deselected", classes="mandatory-note")
yield Static(" Space = toggle selection | Arrow keys = navigate | Enter = next", classes="help-text")
legend = Text()
legend.append(" NEW", style="cyan bold")
legend.append(" = not yet installed ", style="dim")
legend.append("UP TO DATE", style="green")
legend.append(" = current ", style="dim")
legend.append("UPDATE", style="yellow bold")
legend.append(" = new version available", style="dim")
yield Static(legend, classes="legend")
yield SelectionList(*selections, id="agents-list")
with Horizontal(classes="buttons"):
yield Button("Back", id="btn-back")
yield Button("Next", variant="primary", id="btn-next")
yield Footer()
@on(SelectionList.SelectionToggled, "#agents-list")
def enforce_mandatory(self) -> None:
sl = self.query_one("#agents-list", SelectionList)
for name in MANDATORY_AGENTS:
if name not in sl.selected:
sl.select(name)
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "btn-next":
self.action_next()
elif event.button.id == "btn-back":
self.action_back()
def action_next(self) -> None:
sl = self.query_one("#agents-list", SelectionList)
self.app.selected_agents = set(sl.selected)
self.app.push_screen(OptionsScreen())
def action_back(self) -> None:
self.app.pop_screen()
def action_quit(self) -> None:
self.app.exit()
class OptionsScreen(Screen):
BINDINGS = [
Binding("enter", "install", "Install", priority=True),
Binding("escape", "back", "Back"),
Binding("q", "quit", "Quit"),
]
def compose(self) -> ComposeResult:
show_project = self.app.scope in ("project", "both")
in_repo = self.app.in_repo
with Container(classes="wizard"):
yield Static("Options", classes="title")
yield Static("Final settings before installation", classes="subtitle")
yield Rule()
if self.app.scope in ("global", "both"):
yield Static(" Global:", classes="info")
yield Checkbox(
"Create ~/.claude/tasks/ (lessons + todo)",
True,
id="global-tasks",
)
if show_project and in_repo:
yield Static("")
yield Static(
f" Project: {get_repo_name(self.app.cwd)}",
classes="info",
)
yield Checkbox(
"Create ./tasks/ (lessons + todo)",
True,
id="project-tasks",
)
yield Checkbox(
"Auto-approve read operations for agents (creates .claude/settings.json)",
True,
id="auto-read",
)
yield Static(
" Tip: Use /init inside Claude Code to generate a project CLAUDE.md",
classes="help-text",
)
elif show_project and not in_repo:
yield Static("")
yield Static(
" Project install will be skipped — not in a git repo",
classes="mandatory-note",
)
yield Static("")
with Horizontal(classes="buttons"):
yield Button("Back", id="btn-back")
yield Button("Install", variant="success", id="btn-install")
yield Footer()
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "btn-install":
self.action_install()
elif event.button.id == "btn-back":
self.action_back()
def action_install(self) -> None:
try:
self.app.create_global_tasks = self.query_one(
"#global-tasks", Checkbox
).value
except Exception:
self.app.create_global_tasks = False
try:
self.app.create_project_tasks = self.query_one(
"#project-tasks", Checkbox
).value
except Exception:
self.app.create_project_tasks = False
try:
self.app.auto_read = self.query_one(
"#auto-read", Checkbox
).value
except Exception:
self.app.auto_read = False
self.app.push_screen(ResultScreen())
def action_back(self) -> None:
self.app.pop_screen()
def action_quit(self) -> None:
self.app.exit()
class ProjectScreen(Screen):
BINDINGS = [
Binding("enter", "install", "Install", priority=True),
Binding("escape", "back", "Back"),
Binding("q", "quit", "Quit"),
]
def compose(self) -> ComposeResult:
in_repo = self.app.in_repo
with Container(classes="wizard"):
yield Static("Project Setup", classes="title")
yield Static(
"Configure tasks and settings for your repository",
classes="subtitle",
)
yield Rule()
if in_repo:
yield Static(
f" Detected repo: {get_repo_name(self.app.cwd)}",
classes="info",
)
yield Static("")
yield Checkbox(
"Create ./tasks/ (lessons + todo)",
True,
id="project-tasks",
)
yield Checkbox(
"Auto-approve read operations for agents (creates .claude/settings.json)",
True,
id="auto-read",
)
yield Static(
" Tip: Use /init inside Claude Code to generate a project CLAUDE.md",
classes="help-text",
)
yield Static("")
with Horizontal(classes="buttons"):
yield Button("Back", id="btn-back")