-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsession-start.py
More file actions
1136 lines (936 loc) · 41.9 KB
/
Copy pathsession-start.py
File metadata and controls
1136 lines (936 loc) · 41.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
"""
CodingBuddy Session Start Hook — Bootstrap for global UserPromptSubmit.
This file is the **source of truth** for how the CodingBuddy plugin
installs its ``UserPromptSubmit`` hook into Claude Code.
Why this file exists
--------------------
CodingBuddy uses two distinct hook layers:
1. **Plugin-local** ``hooks/hooks.json`` — registers ``SessionStart``,
``PreToolUse``, ``PostToolUse``, and ``Stop`` hooks that Claude Code
loads directly from the plugin package at runtime.
2. **Global install** (this script) — at every session start, copies
``hooks/user-prompt-submit.py`` into ``~/.claude/hooks/`` and
registers a ``UserPromptSubmit`` hook in the user's global
``~/.claude/settings.json``.
``UserPromptSubmit`` is deliberately **not** in ``hooks/hooks.json``.
The global install is what actually wires up PLAN/ACT/EVAL/AUTO mode
detection today, and contributors reading ``hooks.json`` first have
repeatedly mistaken the missing entry for a bug (see #1380).
For the long-form rationale and migration options, see:
``packages/claude-code-plugin/docs/bootstrap-architecture.md``.
What this hook does on every session start
-------------------------------------------
1. Check whether the mode-detection hook file already exists at
``~/.claude/hooks/codingbuddy-mode-detect.py``.
2. If not, copy ``user-prompt-submit.py`` there (alongside its ``lib/``
dependencies).
3. Ensure ``~/.claude/settings.json`` has a ``UserPromptSubmit`` hook
entry pointing at that file, creating the settings file if needed
and using file locking on Unix to avoid concurrent writes.
4. Additionally installs the status line, ``~/.claude/mcp.json`` entry,
system-prompt injection, and briefing-recovery suggestions.
Invariant: any change that moves ``UserPromptSubmit`` registration into
``hooks/hooks.json`` **must** delete the corresponding install logic
below and update ``docs/bootstrap-architecture.md`` plus
``tests/test_bootstrap_architecture.py`` in the same change.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path
from typing import Dict, List, Optional, Tuple
# File locking (Unix only, optional on Windows)
try:
import fcntl
HAS_FCNTL = True
except ImportError:
HAS_FCNTL = False
# Constants
HOOK_FILENAME = "codingbuddy-mode-detect.py"
SOURCE_FILENAME = "user-prompt-submit.py"
HOOK_COMMAND = f'python3 "$HOME/.claude/hooks/{HOOK_FILENAME}"'
# i18n Messages
MESSAGES: Dict[str, Dict[str, str]] = {
"en": {
"installed": "CodingBuddy mode detection hook installed",
"patterns": " PLAN:/ACT:/EVAL:/AUTO: patterns will be auto-detected",
"restart_needed": " Restart Claude Code to activate PLAN/ACT/EVAL/AUTO mode detection.",
"source_not_found": "CodingBuddy: Could not find hook source file. Please reinstall the plugin or check the installation.",
"permission_error": "CodingBuddy: Permission error - {error}",
"permission_hint": "Try running: chmod +x ~/.claude/hooks/codingbuddy-mode-detect.py",
"setup_error": "CodingBuddy hook setup error: {error}",
"backup_corrupted": "Backed up corrupted settings to {path}",
},
"ko": {
"installed": "CodingBuddy 모드 감지 훅이 설치되었습니다",
"patterns": " PLAN:/ACT:/EVAL:/AUTO: 패턴이 자동 감지됩니다",
"restart_needed": " PLAN/ACT/EVAL/AUTO 모드 감지를 활성화하려면 Claude Code를 재시작하세요.",
"source_not_found": "CodingBuddy: 훅 소스 파일을 찾을 수 없습니다. 플러그인을 재설치하거나 설치를 확인하세요.",
"permission_error": "CodingBuddy: 권한 오류 - {error}",
"permission_hint": "실행: chmod +x ~/.claude/hooks/codingbuddy-mode-detect.py",
"setup_error": "CodingBuddy 훅 설정 오류: {error}",
"backup_corrupted": "손상된 설정을 {path}에 백업했습니다",
},
"ja": {
"installed": "CodingBuddyモード検出フックがインストールされました",
"patterns": " PLAN:/ACT:/EVAL:/AUTO: パターンが自動検出されます",
"restart_needed": " PLAN/ACT/EVAL/AUTOモード検出を有効にするには、Claude Codeを再起動してください。",
"source_not_found": "CodingBuddy: フックソースファイルが見つかりません。プラグインを再インストールするか、インストールを確認してください。",
"permission_error": "CodingBuddy: 権限エラー - {error}",
"permission_hint": "実行: chmod +x ~/.claude/hooks/codingbuddy-mode-detect.py",
"setup_error": "CodingBuddyフック設定エラー: {error}",
"backup_corrupted": "破損した設定を{path}にバックアップしました",
},
"zh": {
"installed": "CodingBuddy模式检测钩子已安装",
"patterns": " PLAN:/ACT:/EVAL:/AUTO: 模式将被自动检测",
"restart_needed": " 请重启Claude Code以激活PLAN/ACT/EVAL/AUTO模式检测。",
"source_not_found": "CodingBuddy: 找不到钩子源文件。请重新安装插件或检查安装。",
"permission_error": "CodingBuddy: 权限错误 - {error}",
"permission_hint": "执行: chmod +x ~/.claude/hooks/codingbuddy-mode-detect.py",
"setup_error": "CodingBuddy钩子设置错误: {error}",
"backup_corrupted": "已将损坏的设置备份到{path}",
},
"es": {
"installed": "Hook de detección de modo CodingBuddy instalado",
"patterns": " PLAN:/ACT:/EVAL:/AUTO: los patrones serán detectados automáticamente",
"restart_needed": " Reinicie Claude Code para activar la detección de modos PLAN/ACT/EVAL/AUTO.",
"source_not_found": "CodingBuddy: No se pudo encontrar el archivo fuente del hook. Por favor reinstale el plugin o verifique la instalación.",
"permission_error": "CodingBuddy: Error de permisos - {error}",
"permission_hint": "Ejecute: chmod +x ~/.claude/hooks/codingbuddy-mode-detect.py",
"setup_error": "Error de configuración del hook CodingBuddy: {error}",
"backup_corrupted": "Se respaldó la configuración corrupta en {path}",
},
}
# Language cache (module-level singleton)
_cached_language: Optional[str] = None
def get_system_language() -> str:
"""Get the system language code (en, ko, ja, zh, es)."""
try:
# Try environment variables first (most reliable, cross-version)
for env_var in ("LANG", "LC_ALL", "LC_MESSAGES", "LANGUAGE"):
lang = os.environ.get(env_var)
if lang:
lang_code = lang.split("_")[0].split(".")[0].lower()
if lang_code in MESSAGES:
return lang_code
return "en"
except Exception:
return "en"
def _get_cached_language() -> str:
"""Get cached language, computing once on first call."""
global _cached_language
if _cached_language is None:
_cached_language = get_system_language()
return _cached_language
def msg(key: str, **kwargs) -> str:
"""Get a localized message by key."""
lang = _get_cached_language()
lang_messages = MESSAGES.get(lang, MESSAGES["en"])
template = lang_messages.get(key) or MESSAGES["en"].get(key, key)
return template.format(**kwargs) if kwargs else template
def parse_version(version_str: str) -> Tuple[int, ...]:
"""
Parse a version string into a tuple of integers for comparison.
Handles formats like: "3.0.0", "3.1.0-beta", "v2.0.0"
Args:
version_str: Version string to parse
Returns:
Tuple of integers for comparison (e.g., (3, 1, 0))
"""
# Remove leading 'v' if present
version_str = version_str.lstrip('v')
# Extract numeric parts
match = re.match(r'^(\d+)(?:\.(\d+))?(?:\.(\d+))?', version_str)
if match:
parts = [int(p) if p else 0 for p in match.groups()]
return tuple(parts)
# Fallback: return (0, 0, 0) for unparseable versions
return (0, 0, 0)
def sort_version_dirs(dirs: List[Path]) -> List[Path]:
"""
Sort directory paths by semantic version (descending).
Args:
dirs: List of directory paths with version names
Returns:
Sorted list with highest version first
"""
return sorted(dirs, key=lambda d: parse_version(d.name), reverse=True)
def _find_source_from_env() -> Optional[Path]:
"""Check CLAUDE_PLUGIN_DIR environment variable for source.
Security: Validates that the path resolves to a real location
and the source file exists before returning.
"""
plugin_dir = os.environ.get("CLAUDE_PLUGIN_DIR")
if plugin_dir:
try:
# Resolve symlinks and normalize path for security
resolved_dir = Path(plugin_dir).resolve()
source = resolved_dir / "hooks" / SOURCE_FILENAME
# Verify file exists and is a regular file (not symlink to unexpected location)
if source.exists() and source.is_file():
return source.resolve()
except (OSError, ValueError):
# Invalid path - skip silently
pass
return None
def _find_source_from_cache(home: Path) -> Optional[Path]:
"""Check known plugin cache paths for source.
Security: Uses Path.resolve() to prevent symlink traversal attacks.
"""
cache_paths = [
home / ".claude/plugins/cache/jeremydev87/codingbuddy",
home / ".claude/plugins/cache/codingbuddy",
home / ".claude/plugins/codingbuddy",
]
for base_path in cache_paths:
try:
resolved_base = base_path.resolve()
if resolved_base.exists() and resolved_base.is_dir():
all_dirs = [d for d in resolved_base.iterdir() if d.is_dir()]
for version_dir in sort_version_dirs(all_dirs):
source = version_dir / "hooks" / SOURCE_FILENAME
resolved_source = source.resolve()
if resolved_source.exists() and resolved_source.is_file():
return resolved_source
except (OSError, ValueError):
# Invalid path - skip silently
continue
return None
def _find_source_from_dev(home: Path) -> Optional[Path]:
"""Check common development directory patterns for source.
Security: Uses Path.resolve() to prevent symlink traversal attacks.
"""
dev_patterns = [
"workspace/codingbuddy/packages/claude-code-plugin/hooks",
"dev/codingbuddy/packages/claude-code-plugin/hooks",
"projects/codingbuddy/packages/claude-code-plugin/hooks",
"code/codingbuddy/packages/claude-code-plugin/hooks",
]
for pattern in dev_patterns:
try:
source = home / pattern / SOURCE_FILENAME
resolved_source = source.resolve()
if resolved_source.exists() and resolved_source.is_file():
return resolved_source
except (OSError, ValueError):
# Invalid path - skip silently
continue
return None
def find_plugin_source() -> Optional[Path]:
"""
Find the source hook file from plugin installation.
Search order:
1. CLAUDE_PLUGIN_DIR environment variable
2. Known plugin cache paths (fallback)
3. Local development path
Returns:
Path to source file or None if not found
"""
# Try each source in priority order
source = _find_source_from_env()
if source:
return source
home = Path.home()
source = _find_source_from_cache(home)
if source:
return source
return _find_source_from_dev(home)
def is_hook_registered(settings_file: Path) -> bool:
"""Check if the hook is already registered in settings.json."""
if not settings_file.exists():
return False
try:
with open(settings_file, "r", encoding="utf-8") as f:
settings = json.load(f)
return _is_hook_in_settings(settings)
except (json.JSONDecodeError, KeyError):
return False
def _is_hook_in_settings(settings: dict) -> bool:
"""Check if our hook is already registered in settings dict."""
user_prompt_hooks = settings.get("hooks", {}).get("UserPromptSubmit", [])
for hook_group in user_prompt_hooks:
for hook in hook_group.get("hooks", []):
if HOOK_FILENAME in hook.get("command", ""):
return True
return False
def _create_hook_entry() -> dict:
"""Create the hook entry structure for UserPromptSubmit."""
return {
"hooks": [{
"type": "command",
"command": HOOK_COMMAND
}]
}
def _add_hook_to_settings(settings: dict) -> dict:
"""Add our hook to settings dict, return modified settings."""
hooks = settings.setdefault("hooks", {})
user_prompt_hooks = hooks.setdefault("UserPromptSubmit", [])
user_prompt_hooks.append(_create_hook_entry())
return settings
def _write_settings_file(settings_file: Path, settings: dict) -> None:
"""Write settings to file with optional file locking."""
with open(settings_file, "w", encoding="utf-8") as f:
if HAS_FCNTL:
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
json.dump(settings, f, indent=2, ensure_ascii=False)
def _read_settings_file(settings_file: Path) -> dict:
"""Read settings from file, backup if corrupted."""
try:
with open(settings_file, "r", encoding="utf-8") as f:
if HAS_FCNTL:
fcntl.flock(f.fileno(), fcntl.LOCK_SH)
return json.load(f)
except json.JSONDecodeError:
backup_path = settings_file.with_suffix(".json.bak")
shutil.copy(settings_file, backup_path)
print(msg("backup_corrupted", path=backup_path), file=sys.stderr)
return {}
def register_hook_in_settings(settings_file: Path) -> bool:
"""
Register the UserPromptSubmit hook in the user's global settings.json.
This is the **bootstrap source of truth** for CodingBuddy's
UserPromptSubmit registration. The plugin-local ``hooks/hooks.json``
intentionally does NOT declare UserPromptSubmit; instead, this
function writes the hook entry into ``~/.claude/settings.json`` so
it is active for *all* Claude Code sessions, not just sessions
inside the CodingBuddy project.
Why global, not plugin-local? PLAN/ACT/EVAL keyword detection is
meant to work from any working directory once the plugin is
installed. A plugin-local hook would only fire when
``CLAUDE_PLUGIN_ROOT`` resolves to this package, which is too
narrow. See ``docs/bootstrap-architecture.md`` and #1380.
Uses file locking on Unix systems to prevent concurrent write
issues when multiple Claude Code sessions start at the same time.
Args:
settings_file: Path to ``~/.claude/settings.json``.
Returns:
``True`` if the hook was newly registered, ``False`` if an
entry already existed (idempotent).
"""
settings_file.parent.mkdir(parents=True, exist_ok=True)
# Read existing settings or start fresh
settings = _read_settings_file(settings_file) if settings_file.exists() else {}
# Check if already registered
if _is_hook_in_settings(settings):
return False
# Add hook and write
settings = _add_hook_to_settings(settings)
_write_settings_file(settings_file, settings)
return True
# Asset sync ignore patterns shared by both installers (#1490).
# Why these patterns:
# __pycache__ / *.pyc / *.pyo — compiled artifacts; never needed at runtime
# .pytest_cache — local test runner state; can pollute sys.path
# test_*.py — test files must not enter the runtime lib
# *.egg-info — packaging metadata
_HUD_SYNC_IGNORE_PATTERNS: Tuple[str, ...] = (
"__pycache__",
"*.pyc",
"*.pyo",
".pytest_cache",
"test_*.py",
"*.egg-info",
)
def _atomic_sync_with_lib(
source_script: Path,
target_dir: Path,
extra_ignore: Optional[Tuple[str, ...]] = None,
) -> None:
"""Atomically install a script + its sibling ``lib/`` directory.
Replaces the prior pattern of ``shutil.copy`` (script-only) and
``shutil.copytree(dirs_exist_ok=True)`` (additive lib copy). Both
were vulnerable to the v5.6.0/v5.6.1 HUD installer regression
(#1490) where renamed/removed modules from prior plugin versions
remained in the target directory and caused import failures.
Behavior (3-phase, near-atomic lib swap):
1. ``mkdir -p target_dir``
2. Copy ``source_script`` to ``target_dir/<source_script.name>``
and ``chmod 0o755``.
3. If ``source_script.parent / "lib"`` exists:
a. Copy it into a staging directory ``.lib.staging-<uuid>``
b. Rename the existing ``lib`` aside to ``.lib.old-<uuid>``
c. Rename the staging directory to ``lib`` (POSIX ``rename``
is atomic, so the window during which importers see no
lib is bounded by two ``rename`` syscalls — microseconds)
d. ``rmtree`` the archived old lib
Why staging instead of rmtree-then-copytree:
The naive pattern ``rmtree(target_lib); copytree(source_lib, target_lib)``
leaves the target empty for the duration of ``copytree`` (which
can be hundreds of milliseconds for a multi-megabyte lib). Any
concurrent HUD subprocess that statted the script during that
window would see import failures and render the fallback face.
The staging/rename pattern shrinks the window from ``O(copytree)``
to ``O(rename)`` — effectively atomic. It also tolerates
concurrent installers from multiple simultaneous Claude Code
sessions because each uses a uuid-scoped staging directory.
Why not ``dirs_exist_ok=True`` on its own:
That mode only writes; it does not remove files that existed
before but are gone now. A renamed module
(e.g. ``hud_old.py`` → ``hud_new.py``) would remain in the
target lib and could be imported first, causing subtle
regressions. The staging pattern gives the same stale-safety
guarantees with atomicity on top.
Args:
source_script: Path to the script file to install. Its parent
directory is searched for a sibling ``lib/`` to mirror.
target_dir: Destination directory. Created if missing.
extra_ignore: Additional ignore-pattern tuple appended to the
shared :data:`_HUD_SYNC_IGNORE_PATTERNS` list. Reserved for
future wave-specific excludes; both production callers
currently pass ``None``. Runtime lib modules are assumed
to follow the ``hud_*`` / ``tiny_actor_*`` naming
convention — do NOT add runtime helpers named
``test_*.py`` or the ignore filter will drop them.
"""
import uuid
target_dir.mkdir(parents=True, exist_ok=True)
# 1. Script
target_script = target_dir / source_script.name
shutil.copy(source_script, target_script)
target_script.chmod(0o755)
# 2. Lib — staging/rename pattern for near-atomic swap
source_lib = source_script.parent / "lib"
if not source_lib.is_dir():
return
target_lib = target_dir / "lib"
ignore_patterns = _HUD_SYNC_IGNORE_PATTERNS
if extra_ignore:
ignore_patterns = ignore_patterns + tuple(extra_ignore)
suffix = uuid.uuid4().hex[:8]
staging_lib = target_dir / f".lib.staging-{suffix}"
archive_lib = target_dir / f".lib.old-{suffix}"
try:
shutil.copytree(
source_lib,
staging_lib,
ignore=shutil.ignore_patterns(*ignore_patterns),
)
# Atomic archive + promote. Each rename is a single syscall,
# so the window during which ``target_lib`` does not exist is
# bounded by one ``rename`` (~microseconds).
if target_lib.exists():
os.rename(str(target_lib), str(archive_lib))
os.rename(str(staging_lib), str(target_lib))
except Exception:
# Leave target_lib in the best recoverable state: prefer the
# old lib (from archive) over nothing. Staging is always
# disposable.
if staging_lib.exists():
shutil.rmtree(staging_lib, ignore_errors=True)
if archive_lib.exists() and not target_lib.exists():
try:
os.rename(str(archive_lib), str(target_lib))
except OSError:
pass
raise
finally:
if archive_lib.exists():
shutil.rmtree(archive_lib, ignore_errors=True)
def _install_hook_with_lib(
source_file: Path, hooks_dir: Path, target_file: Path
) -> None:
"""Copy hook file AND its lib/ dependencies to the target hooks directory.
v5.6.2 (#1490): now delegates to :func:`_atomic_sync_with_lib` so
renamed/removed modules from prior plugin versions are purged on
every sync. The hook script is then renamed in place to
``HOOK_FILENAME`` because Claude Code's settings.json points at
that canonical name (``codingbuddy-mode-detect.py``) rather than
the source name (``user-prompt-submit.py``).
Note on permission bits: ``_atomic_sync_with_lib`` has already
chmod'd the synced script to ``0o755`` before we rename it, and
POSIX ``rename`` preserves permission bits across the move. We
therefore do not re-chmod after the rename; a redundant ``chmod``
there would trigger an unnecessary silent failure path on
filesystems that reject mode changes (NFS, read-only mounts).
Args:
source_file: Path to the source hook script.
hooks_dir: Target directory (e.g. ``~/.claude/hooks/``).
target_file: Full target path for the hook script.
"""
_atomic_sync_with_lib(source_file, hooks_dir)
synced = hooks_dir / source_file.name
if synced != target_file:
if target_file.exists():
target_file.unlink()
synced.rename(target_file)
# No chmod here: _atomic_sync_with_lib already set 0o755 on
# ``synced`` and ``rename`` preserves mode.
CODINGBUDDY_MCP_ENTRY = {
"command": "codingbuddy",
"args": ["mcp"],
}
def _ensure_mcp_json(mcp_json_path: Path) -> None:
"""Ensure ~/.claude/mcp.json contains the codingbuddy MCP server entry (#1100).
Creates the file if missing, or merges the codingbuddy entry into an
existing file while preserving other MCP server configurations.
"""
mcp_json_path.parent.mkdir(parents=True, exist_ok=True)
if mcp_json_path.exists():
try:
with open(mcp_json_path, "r", encoding="utf-8") as f:
if HAS_FCNTL:
fcntl.flock(f.fileno(), fcntl.LOCK_SH)
existing = json.load(f)
except (json.JSONDecodeError, OSError):
existing = {}
else:
existing = {}
servers = existing.setdefault("mcpServers", {})
if "codingbuddy" in servers:
return # Already configured — don't overwrite user customizations
servers["codingbuddy"] = CODINGBUDDY_MCP_ENTRY
with open(mcp_json_path, "w", encoding="utf-8") as f:
if HAS_FCNTL:
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
json.dump(existing, f, indent=2, ensure_ascii=False)
HUD_FILENAME = "codingbuddy-hud.py"
def _get_plugin_version() -> str:
"""Read plugin version from .claude-plugin/plugin.json.
Falls back to '0.0.0' if not found.
"""
try:
this_dir = os.path.dirname(os.path.abspath(__file__))
plugin_json = os.path.join(this_dir, "..", ".claude-plugin", "plugin.json")
if os.path.isfile(plugin_json):
with open(plugin_json, "r", encoding="utf-8") as f:
return json.load(f).get("version", "0.0.0")
except Exception:
pass
# Try CLAUDE_PLUGIN_DIR
plugin_dir = os.environ.get("CLAUDE_PLUGIN_DIR")
if plugin_dir:
try:
pj = os.path.join(plugin_dir, ".claude-plugin", "plugin.json")
if os.path.isfile(pj):
with open(pj, "r", encoding="utf-8") as f:
return json.load(f).get("version", "0.0.0")
except Exception:
pass
return "0.0.0"
def _find_hud_source() -> Optional[Path]:
"""Find the codingbuddy-hud.py source file.
Same 3-tier search as find_plugin_source() but for the HUD script.
"""
# 1. CLAUDE_PLUGIN_DIR env
plugin_dir = os.environ.get("CLAUDE_PLUGIN_DIR")
if plugin_dir:
try:
source = Path(plugin_dir).resolve() / "hooks" / HUD_FILENAME
if source.exists() and source.is_file():
return source.resolve()
except (OSError, ValueError):
pass
home = Path.home()
# 2. Plugin cache paths
cache_paths = [
home / ".claude/plugins/cache/jeremydev87/codingbuddy",
home / ".claude/plugins/cache/codingbuddy",
home / ".claude/plugins/codingbuddy",
]
for base_path in cache_paths:
try:
resolved_base = base_path.resolve()
if resolved_base.exists() and resolved_base.is_dir():
all_dirs = [d for d in resolved_base.iterdir() if d.is_dir()]
for version_dir in sort_version_dirs(all_dirs):
source = version_dir / "hooks" / HUD_FILENAME
if source.resolve().exists():
return source.resolve()
except (OSError, ValueError):
continue
# 3. Dev paths
dev_patterns = [
"workspace/codingbuddy/packages/claude-code-plugin/hooks",
"dev/codingbuddy/packages/claude-code-plugin/hooks",
"projects/codingbuddy/packages/claude-code-plugin/hooks",
"code/codingbuddy/packages/claude-code-plugin/hooks",
]
for pattern in dev_patterns:
try:
source = home / pattern / HUD_FILENAME
if source.resolve().exists():
return source.resolve()
except (OSError, ValueError):
continue
return None
def _install_statusline(home: Path, settings_file: Path) -> None:
"""Install codingbuddy statusLine (#1089, fix #1490).
v5.6.2: now syncs ``hooks/lib`` alongside the script via
:func:`_atomic_sync_with_lib`. Previous versions only copied the
single ``codingbuddy-hud.py`` file, leaving ``~/.claude/hud/lib``
empty or stale. Once Wave 1/2/3 modules were extracted to
``hooks/lib`` in v5.6.0 every statusLine import failed and the
outer ``try/except`` in ``codingbuddy-hud.py`` rendered only
``◕‿◕ CodingBuddy``.
Set ``CODINGBUDDY_HUD_DEBUG=1`` to surface install errors on
stderr; without the env var, errors bubble to ``main()``'s outer
silent except so session start is never blocked.
"""
# 1. Find HUD source
source = _find_hud_source()
if not source:
if os.environ.get("CODINGBUDDY_HUD_DEBUG"):
print("[hud] _install_statusline: source not found", file=sys.stderr)
return
hud_dir = home / ".claude" / "hud"
# 2. Atomic sync (script + lib/) — replaces previous shutil.copy-only path
try:
_atomic_sync_with_lib(source, hud_dir)
except Exception as exc:
if os.environ.get("CODINGBUDDY_HUD_DEBUG"):
print(f"[hud] _atomic_sync_with_lib failed: {exc}", file=sys.stderr)
raise # bubble to main()'s outer except
# 3. Write version stamp for health_check / diagnostics
try:
version = _get_plugin_version()
(hud_dir / ".version").write_text(version, encoding="utf-8")
except Exception:
pass # stamp is best-effort
# 4. Update settings.json
settings = _read_settings_file(settings_file) if settings_file.exists() else {}
current_sl = settings.get("statusLine", {}).get("command", "")
if "codingbuddy-hud" in current_sl:
pass # already installed
elif "omc-hud" in current_sl or not current_sl:
settings["statusLine"] = {
"type": "command",
"command": f'python3 "{home}/.claude/hud/{HUD_FILENAME}"',
}
# else: custom statusLine — preserve
_write_settings_file(settings_file, settings)
def _ensure_lib_path():
"""Ensure hooks/lib is on sys.path (idempotent)."""
_hooks_dir = os.path.dirname(os.path.abspath(__file__))
_lib_dir = os.path.join(_hooks_dir, "lib")
if _lib_dir not in sys.path:
sys.path.insert(0, _lib_dir)
return _lib_dir
def load_agent_visuals(agents_dir: str) -> Dict[str, dict]:
"""Load agent definitions with visual fields from JSON files.
Args:
agents_dir: Path to agents directory containing *.json files.
Returns:
Dict mapping agent-id to {name, visual} data.
"""
agents: Dict[str, dict] = {}
if not os.path.isdir(agents_dir):
return agents
try:
for fname in os.listdir(agents_dir):
if not fname.endswith(".json"):
continue
agent_id = fname[:-5] # strip .json
fpath = os.path.join(agents_dir, fname)
try:
with open(fpath, "r", encoding="utf-8") as f:
data = json.load(f)
if "visual" in data:
agents[agent_id] = {
"name": data.get("name", agent_id),
"visual": data["visual"],
}
except (json.JSONDecodeError, OSError):
continue
except OSError:
pass
return agents
def _find_agents_dir() -> Optional[str]:
"""Find the .ai-rules/agents directory relative to plugin source."""
# Try CLAUDE_PLUGIN_DIR first
plugin_dir = os.environ.get("CLAUDE_PLUGIN_DIR", "")
if plugin_dir:
candidate = os.path.join(plugin_dir, "..", "rules", ".ai-rules", "agents")
resolved = os.path.realpath(candidate)
if os.path.isdir(resolved):
return resolved
# Try relative to this file (dev mode)
this_dir = os.path.dirname(os.path.abspath(__file__))
candidates = [
os.path.join(this_dir, "..", "..", "rules", ".ai-rules", "agents"),
os.path.join(this_dir, "..", "..", "..", "packages", "rules", ".ai-rules", "agents"),
]
for candidate in candidates:
resolved = os.path.realpath(candidate)
if os.path.isdir(resolved):
return resolved
return None
def _read_pending_context(cwd: str) -> Optional[Dict[str, str]]:
"""Read pending work context from docs/codingbuddy/context.md.
Parses the YAML-like frontmatter and last section to extract
the most recent mode, task, and status.
Args:
cwd: Project directory to search for context.md.
Returns:
Dict with mode, task, status keys or None if not found.
"""
context_path = os.path.join(cwd, "docs", "codingbuddy", "context.md")
if not os.path.isfile(context_path):
return None
try:
with open(context_path, "r", encoding="utf-8") as f:
content = f.read(8192) # Read first 8KB only
except OSError:
return None
if not content.strip():
return None
result: Dict[str, str] = {}
# Parse frontmatter for currentMode and status
if content.startswith("---"):
parts = content.split("---", 2)
if len(parts) >= 3:
for line in parts[1].strip().splitlines():
line = line.strip()
if line.startswith("currentMode:"):
result["mode"] = line.split(":", 1)[1].strip().strip('"')
elif line.startswith("status:"):
result["status"] = line.split(":", 1)[1].strip().strip('"')
# Find last section's task line
for line in content.splitlines():
line = line.strip()
if line.lower().startswith("task:"):
result["task"] = line.split(":", 1)[1].strip().strip('"')
return result if result.get("mode") else None
def _check_briefing_recovery() -> None:
"""Check for recent briefings and suggest recovery.
Scans docs/codingbuddy/briefings/ for .md files modified within the
last 24 hours. If any are found, prints a suggestion to stderr so
the user knows they can resume previous work.
This function never raises — all errors are silently swallowed to
avoid blocking session start.
"""
try:
briefings_dir = os.path.join(
os.environ.get("CLAUDE_PROJECT_DIR", os.getcwd()),
"docs", "codingbuddy", "briefings",
)
if not os.path.isdir(briefings_dir):
return
now = time.time()
recent: List[str] = []
for f in sorted(os.listdir(briefings_dir), reverse=True):
if f.endswith(".md"):
age = now - os.path.getmtime(os.path.join(briefings_dir, f))
if age < 86400: # 24 hours
recent.append(f)
if len(recent) >= 3:
break
if recent:
print(
f"\U0001f4cb Found {len(recent)} recent briefing(s). "
f"Use `resume_session` to continue previous work.",
file=sys.stderr,
)
except Exception:
pass # Never block session start
def main():
"""Main entry point for the session start hook."""
_ensure_lib_path()
from hook_runtime import time_hook
with time_hook("SessionStart"):
return _main_inner()
def _main_inner():
"""Core session-start logic, wrapped by time_hook."""
try:
home = Path.home()
hooks_dir = home / ".claude" / "hooks"
target_file = hooks_dir / HOOK_FILENAME
settings_file = home / ".claude" / "settings.json"
installed_hook = False
registered_settings = False
new_version = None
# Step 0.5: Auto-update marketplace clone (#1101)
try:
_ensure_lib_path()
from updater import auto_update_marketplace
new_version = auto_update_marketplace(home=home)
except Exception:
pass # Never block session start
# Step 1: Install hook file if not exists
if not target_file.exists():
source_file = find_plugin_source()
if source_file:
_install_hook_with_lib(source_file, hooks_dir, target_file)
installed_hook = True
else:
# Source not found - provide manual installation guide
print(msg("source_not_found"), file=sys.stderr)
# Step 2: Register in settings.json if not registered
if target_file.exists() and not is_hook_registered(settings_file):
registered_settings = register_hook_in_settings(settings_file)
# Output status message
if installed_hook or registered_settings:
print(msg("installed"))
print(msg("patterns"))
if installed_hook:
print(msg("restart_needed"))
# Step 2.5: Install codingbuddy statusLine (#1089, #1092)
try:
_install_statusline(home, settings_file)
except Exception:
pass # Never block session start
# Step 2.6: Ensure ~/.claude/mcp.json has codingbuddy entry (#1100)
try:
import shutil as _shutil
if _shutil.which("codingbuddy"):
_ensure_mcp_json(home / ".claude" / "mcp.json")
except Exception:
pass # Never block session start
# Step 3: System prompt injection (#828)
# SessionStart uses plain stdout for context injection (NOT JSON)
try:
_ensure_lib_path()
from prompt_injection import PromptInjector
from config import get_config
cwd = os.environ.get("CLAUDE_PROJECT_DIR", str(Path.cwd()))
cfg = get_config(cwd)
injector = PromptInjector()
system_msg = injector.build_system_prompt(cfg, cwd)
if system_msg:
print(system_msg)
except Exception:
pass # Never block session start
# Step 4: Initialize operational stats (#825)
try:
_ensure_lib_path()
from stats import SessionStats
from session_utils import get_session_id
session_id = get_session_id()
SessionStats(session_id=session_id)
SessionStats.cleanup_stale(
os.environ.get("CLAUDE_PLUGIN_DATA",
os.path.join(str(home), ".codingbuddy"))
)
except Exception:
pass # Never block session start
# Step 4.5: Initialize HUD state for statusLine (#1089)
_pending_ctx_for_hud = None
try:
_ensure_lib_path()
from hud_state import init_hud_state
from session_utils import get_session_id as _get_sid_hud
hud_version = _get_plugin_version()
init_hud_state(_get_sid_hud(), hud_version)
except Exception:
pass # Never block session start
# Step 4.5b: Enrich HUD baseline with pending context (#1324)
try:
cwd_hud = os.environ.get("CLAUDE_PROJECT_DIR", str(Path.cwd()))