-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.sh
More file actions
executable file
·623 lines (490 loc) · 17 KB
/
init.sh
File metadata and controls
executable file
·623 lines (490 loc) · 17 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
#!/bin/bash
# init.sh — Connect Claude Code and Obsidian to the second-brain tooling.
#
# What this does:
# 1. Check required dependencies (jq, python3)
# 2. Create settings.json from example if missing (SECOND_BRAIN_VAULT_PATH only)
# 3. Ensure script permissions (chmod +x)
# 4. Validate hooks config
# 5. Validate vault path and directory structure
# 6. Sync Templates/ to the vault (idempotent — skips existing files)
# 7. Print a status summary with pass/fail for each check
#
# Note: CLAUDE_PLUGIN_ROOT is auto-provided by the Claude Code plugin system.
# Only SECOND_BRAIN_VAULT_PATH needs user configuration.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
# Optional: vault path override from first argument
VAULT_PATH_ARG="${1:-}"
PASS="[ok]"
FAIL="[fail]"
SKIP="[skip]"
WARN="[warn]"
errors=0
log() { printf '%s %s\n' "$1" "$2"; }
ok() { log "$PASS" "$1"; }
fail() { log "$FAIL" "$1"; errors=$((errors + 1)); }
warn() { log "$WARN" "$1"; }
skip() { log "$SKIP" "$1"; }
echo ""
echo "=== second-brain init ==="
echo ""
# ── 1. Dependencies ────────────────────────────────────────────────────────────
echo "-- Dependencies"
if command -v jq >/dev/null 2>&1; then
ok "jq $(jq --version)"
else
fail "jq not found — install via: brew install jq"
fi
if command -v python3 >/dev/null 2>&1; then
ok "python3 $(python3 --version 2>&1)"
else
fail "python3 not found"
fi
echo ""
# ── 2. .claude/settings.local.json — canonical vault path config ──────────────
#
# Canonical location for SECOND_BRAIN_VAULT_PATH is .claude/settings.local.json
# (machine-specific / user-local, never committed).
# repo-root settings.json is kept as a legacy fallback for now.
echo "-- .claude/settings.local.json"
LOCAL_SETTINGS="$REPO_ROOT/.claude/settings.local.json"
PLACEHOLDER="/path/to/your/obsidian/vault"
_set_vault_path_in_settings() {
local path="$1" vault="$2"
python3 - "$path" "$vault" <<'PY'
import json, sys, pathlib
path, vault = sys.argv[1], sys.argv[2]
p = pathlib.Path(path)
try:
d = json.loads(p.read_text()) if p.exists() else {}
except Exception:
d = {}
d.setdefault("env", {})["SECOND_BRAIN_VAULT_PATH"] = vault
p.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as f:
json.dump(d, f, indent=4, ensure_ascii=False)
f.write("\n")
PY
}
_read_vault_path_from_settings() {
local path="$1"
python3 -c "
import json, sys
try:
d = json.load(open('$path'))
print(d.get('env', {}).get('SECOND_BRAIN_VAULT_PATH', ''))
except Exception:
pass
" 2>/dev/null || true
}
CURRENT_VAULT=$(_read_vault_path_from_settings "$LOCAL_SETTINGS")
if [[ -n "$CURRENT_VAULT" && "$CURRENT_VAULT" != "$PLACEHOLDER" && -d "$CURRENT_VAULT" ]]; then
# Valid path already configured — do not overwrite, even if an argument was passed
ok "SECOND_BRAIN_VAULT_PATH = $CURRENT_VAULT"
elif [[ -n "$VAULT_PATH_ARG" ]]; then
_set_vault_path_in_settings "$LOCAL_SETTINGS" "$VAULT_PATH_ARG"
CURRENT_VAULT="$VAULT_PATH_ARG"
ok "SECOND_BRAIN_VAULT_PATH set to: $VAULT_PATH_ARG"
else
fail "SECOND_BRAIN_VAULT_PATH not configured — run: second-brain:init /your/vault/path"
fi
# ── 2b. Sync vault path into CLAUDE.md ────────────────────────────────────────
# CLAUDE.md is loaded as project instructions by Claude Code, so the Location:
# line must reflect THIS user's vault — not the repo author's path.
# init.sh patches it idempotently whenever a valid vault path is known.
if [[ -n "$CURRENT_VAULT" && -d "$CURRENT_VAULT" ]]; then
CLAUDE_MD="$REPO_ROOT/CLAUDE.md"
if grep -q "^- Location:" "$CLAUDE_MD" 2>/dev/null; then
current_loc=$(grep "^- Location:" "$CLAUDE_MD" | sed "s|^- Location: \`\(.*\)\`|\1|")
if [[ "$current_loc" != "$CURRENT_VAULT" ]]; then
sed -i.bak "s|^- Location: \`.*\`|- Location: \`$CURRENT_VAULT\`|" "$CLAUDE_MD" && rm -f "${CLAUDE_MD}.bak"
ok "CLAUDE.md Location updated → $CURRENT_VAULT"
else
ok "CLAUDE.md Location already correct"
fi
else
warn "CLAUDE.md: Location: line not found — skipping"
fi
fi
echo ""
# ── 3. Script permissions ──────────────────────────────────────────────────────
echo "-- Script permissions"
fixed=0
for f in "$REPO_ROOT/scripts/"*.sh "$REPO_ROOT/scripts/"*.py; do
[[ -f "$f" ]] || continue
if [[ ! -x "$f" ]]; then
chmod +x "$f"
ok "chmod +x $(basename "$f")"
fixed=$((fixed + 1))
fi
done
if [[ $fixed -eq 0 ]]; then
ok "all scripts already executable"
fi
echo ""
# ── 3b. Pre-commit hook install ────────────────────────────────────────────────
# Install a symlink from .git/hooks/pre-commit → hooks/pre-commit (tracked).
# This ensures the guard survives across clones when init.sh is re-run.
echo "-- Pre-commit hook"
HOOK_SRC="$REPO_ROOT/hooks/pre-commit"
HOOK_DST="$REPO_ROOT/.git/hooks/pre-commit"
if [[ ! -f "$HOOK_SRC" ]]; then
warn "hooks/pre-commit not found — skipping"
else
chmod +x "$HOOK_SRC"
if [[ -L "$HOOK_DST" && "$(readlink "$HOOK_DST")" == "../../hooks/pre-commit" ]]; then
ok "pre-commit symlink already installed"
else
ln -sf "../../hooks/pre-commit" "$HOOK_DST"
ok "installed .git/hooks/pre-commit → hooks/pre-commit"
fi
fi
echo ""
# ── 3. Plugin hooks install ────────────────────────────────────────────────────
# Register hooks/hooks.json into .claude/settings.local.json so Claude Code
# actually fires them. Also sets CLAUDE_PLUGIN_ROOT in env.
# Idempotent: existing identical commands are not duplicated.
echo "-- Plugin hooks install"
HOOKS_FILE="$REPO_ROOT/hooks/hooks.json"
if [[ ! -f "$HOOKS_FILE" ]]; then
fail "hooks/hooks.json not found — cannot install hooks"
else
install_out=$(python3 - "$LOCAL_SETTINGS" "$HOOKS_FILE" "$REPO_ROOT" <<'PY'
import json, sys, pathlib
settings_path = pathlib.Path(sys.argv[1])
hooks_path = pathlib.Path(sys.argv[2])
plugin_root = sys.argv[3]
try:
settings = json.loads(settings_path.read_text()) if settings_path.exists() else {}
except Exception:
settings = {}
settings.setdefault("env", {})["CLAUDE_PLUGIN_ROOT"] = plugin_root
raw = hooks_path.read_text().replace("${CLAUDE_PLUGIN_ROOT}", plugin_root)
plugin_hooks = json.loads(raw).get("hooks", {})
dest_hooks = settings.setdefault("hooks", {})
added = 0
skipped = 0
for event, matchers in plugin_hooks.items():
dest_matchers = dest_hooks.setdefault(event, [])
for matcher_block in matchers:
for new_hook in matcher_block.get("hooks", []):
cmd = new_hook.get("command", "")
already = any(
h.get("command") == cmd
for m in dest_matchers
for h in m.get("hooks", [])
)
if already:
skipped += 1
continue
matcher_val = matcher_block.get("matcher")
target = next(
(m for m in dest_matchers if m.get("matcher") == matcher_val),
None,
)
if target is None:
target = {}
if matcher_val is not None:
target["matcher"] = matcher_val
target["hooks"] = []
dest_matchers.append(target)
target["hooks"].append(new_hook)
added += 1
settings_path.parent.mkdir(parents=True, exist_ok=True)
settings_path.write_text(json.dumps(settings, indent=4, ensure_ascii=False) + "\n")
print(f"added={added} skipped={skipped}")
PY
)
if [[ $? -eq 0 ]]; then
ok "hooks installed: $install_out (CLAUDE_PLUGIN_ROOT=$REPO_ROOT)"
else
fail "hook install failed"
fi
fi
echo ""
# ── 4. Hooks config validation ─────────────────────────────────────────────────
echo "-- Hooks"
HOOKS_FILE="$REPO_ROOT/hooks/hooks.json"
if [[ -f "$HOOKS_FILE" ]]; then
if jq empty "$HOOKS_FILE" 2>/dev/null; then
hook_count=$(jq '[.hooks | to_entries[] | .value[] | .hooks[]] | length' "$HOOKS_FILE" 2>/dev/null || echo "?")
ok "hooks/hooks.json valid ($hook_count hooks)"
else
fail "hooks/hooks.json is not valid JSON"
fi
else
fail "hooks/hooks.json not found"
fi
echo ""
# ── 4. Vault path ──────────────────────────────────────────────────────────────
echo "-- Vault"
# Resolve vault path: argument → env var → .claude/settings.local.json → settings.json (legacy) → CLAUDE.md
VAULT_PATH="${VAULT_PATH_ARG:-${SECOND_BRAIN_VAULT_PATH:-}}"
if [[ -z "$VAULT_PATH" ]] && [[ -f "$LOCAL_SETTINGS" ]]; then
VAULT_PATH=$(_read_vault_path_from_settings "$LOCAL_SETTINGS")
fi
if [[ -z "$VAULT_PATH" ]] && [[ -f "$REPO_ROOT/settings.json" ]]; then
VAULT_PATH=$(_read_vault_path_from_settings "$REPO_ROOT/settings.json")
fi
if [[ -z "$VAULT_PATH" ]] && [[ -f "$REPO_ROOT/CLAUDE.md" ]]; then
VAULT_PATH=$(sed -n 's/^- Location: `\(.*\)`/\1/p' "$REPO_ROOT/CLAUDE.md" | head -n 1)
fi
if [[ -z "$VAULT_PATH" ]]; then
fail "vault path not found — set SECOND_BRAIN_VAULT_PATH in .claude/settings.local.json"
echo ""
echo "=== Result: $errors error(s) ==="
exit 1
fi
VAULT_PATH="${VAULT_PATH%/}"
if [[ -d "$VAULT_PATH" ]]; then
ok "vault found: $VAULT_PATH"
else
fail "vault directory does not exist: $VAULT_PATH"
echo ""
echo "=== Result: $errors error(s) ==="
exit 1
fi
echo ""
# ── 5. Vault directory structure ───────────────────────────────────────────────
echo "-- Vault structure"
REQUIRED_DIRS=(Daily Weekly Monthly Projects Ideas References Clippings Meta Bases)
for d in "${REQUIRED_DIRS[@]}"; do
if [[ -d "$VAULT_PATH/$d" ]]; then
ok "$d/"
else
warn "$d/ missing — will be created on first use by hooks"
fi
done
echo ""
# ── 6. Sync Templates/ to vault ────────────────────────────────────────────────
echo "-- Templates sync"
VAULT_TEMPLATES="$VAULT_PATH/Templates"
mkdir -p "$VAULT_TEMPLATES"
synced=0
skipped=0
sync_template() {
local fname="$1"
local target="$VAULT_TEMPLATES/$fname"
if [[ -f "$target" ]]; then
skip "$fname (already exists)"
skipped=$((skipped + 1))
else
# Content is passed via stdin
cat > "$target"
ok "created Templates/$fname"
synced=$((synced + 1))
fi
}
sync_template "daily.md" <<'TMPL'
---
title: {{date:YYYY-MM-DD}}
type: daily
date: {{date:YYYY-MM-DD}}
tags:
- journal
---
## 今日のフォーカス
## メモ
> [!note] 振り返り
## フォローアップ
- [ ]
## 関連ノート
## AI Session
TMPL
sync_template "weekly.md" <<'TMPL'
---
title: {{date:YYYY-[W]WW}}
type: weekly
week: {{date:YYYY-[W]WW}}
reviewed: {{date:YYYY-MM-DD}}
tags:
- planning
- review
---
## 進行中プロジェクト
## 昇格候補アイデア
## ブロッカー
> [!tip] 週次の要約
> 重要度の高い項目だけ Projects に昇格し、残りは保留または整理する。
## 来週の重点
## 関連ノート
TMPL
sync_template "monthly.md" <<'TMPL'
---
title: {{date:YYYY-MM}}
type: monthly
period: {{date:YYYY-MM}}
tags:
- monthly
- strategy
---
## 優先事項
## うまくいったこと
## 改善点
> [!warning] 月次判断
> 実行可能な項目は Projects に移し、原則は References に残す。
## 来月の焦点
## 関連ノート
TMPL
sync_template "project.md" <<'TMPL'
---
title:
type: project
status: active
review: {{date:YYYY-MM-DD}}
tags: []
---
## ゴール
## 次のアクション
- [ ]
## 添付
## 関連ノート
TMPL
sync_template "idea.md" <<'TMPL'
---
title:
type: idea
status: incubating
created: {{date:YYYY-MM-DD}}
tags: []
---
## プロジェクト化の条件
- 今月実装したい
- 複数ステップが必要
- 他フォルダへ影響がある
> [!note] 次の扱い
## 下書き素材
TMPL
sync_template "reference.md" <<'TMPL'
---
title:
type: reference
topic:
---
## 目的
## 手順
> [!warning] 再利用ルール
## 関連資料
TMPL
sync_template "clipping.md" <<'TMPL'
---
title:
type: clipping
source:
captured: {{date:YYYY-MM-DD}}
---
## メモ
-
TMPL
echo ""
echo "-- Summary"
echo " Templates synced: $synced, skipped: $skipped"
echo ""
# ── 6b. Meta/Profile/ — cognitive profile starter files (human-maintained) ───────────────────
echo "-- Meta/Profile/"
PROFILE_DIR="$VAULT_PATH/Meta/Profile"
mkdir -p "$PROFILE_DIR"
_sync_profile() {
local fname="$1"
local target="$PROFILE_DIR/$fname"
if [[ -f "$target" ]]; then
skip "$fname (already exists)"
else
cat > "$target"
ok "created Meta/Profile/$fname"
fi
}
_sync_profile "preferences.md" <<'PROF'
---
title: Capture Preferences
type: profile
topic: capture-preferences
---
## キャプチャ対象
<!-- harvest.py が重要とみなすトピック・キーワードを記述してください -->
<!-- 例: second-brain, obsidian, claude-code, 設計決定, アーキテクチャ -->
## キャプチャ除外
<!-- 誤検知しやすいトピック・用語を記述してください -->
<!-- 例: デバッグ中の一時的なコード, テスト用のダミーデータ -->
PROF
_sync_profile "working-style.md" <<'PROF'
---
title: Working Style
type: profile
topic: working-style
---
## 作業パターン
<!-- 典型的な作業セッションの流れを記述してください -->
<!-- 例: 問題定義 → 実装 → 検証 → ドキュメント化 -->
## フォーカス領域
<!-- 現在注力しているプロジェクト・技術領域 -->
## 思考スタイル
<!-- ノートに残したい粒度・形式の好み -->
<!-- 例: 決定の理由を残したい / 手順よりも原則を残したい -->
PROF
_sync_profile "review-policy.md" <<'PROF'
---
title: Review Policy
type: profile
topic: review-policy
---
## Meta/Promotions/ レビュー方針
<!-- ドラフトを承認するかどうかの判断基準 -->
<!-- 例: 同じトピックが 2 セッション以上現れたら昇格 -->
## 昇格頻度
<!-- どのくらいの頻度で /promote を実行するか -->
<!-- 例: 週次レビュー時にまとめて処理 -->
PROF
_sync_profile "promotion-policy.md" <<'PROF'
---
title: Promotion Policy
type: profile
topic: promotion-policy
---
## 昇格先の判断基準
<!-- References/ vs Ideas/ の判断基準 -->
<!-- 例: 再利用可能な手順・決定 → References/ / まだ検討中 → Ideas/ -->
## スコアしきい値の調整
<!-- harvest.py のデフォルト (L1=3, L2=6, L3=9) を変えたい場合はここに記録 -->
<!-- 変更には harvest.py の定数を直接編集してください -->
PROF
echo ""
# ── 7. Vault CI (opt-in only: set SECOND_BRAIN_INSTALL_VAULT_CI=1 or pass --install-vault-ci) ──
echo "-- Vault CI"
INSTALL_VAULT_CI="${SECOND_BRAIN_INSTALL_VAULT_CI:-0}"
for _arg in "$@"; do
[[ "$_arg" == "--install-vault-ci" ]] && INSTALL_VAULT_CI=1
done
VAULT_WORKFLOWS="$VAULT_PATH/.github/workflows"
EXAMPLE_CI="$REPO_ROOT/docs/examples/vault-ci.yml"
VAULT_CI_TARGET="$VAULT_WORKFLOWS/vault-ci.yml"
if [[ "$INSTALL_VAULT_CI" != "1" ]]; then
skip "vault CI not requested — pass --install-vault-ci or set SECOND_BRAIN_INSTALL_VAULT_CI=1 to opt in"
elif ! git -C "$VAULT_PATH" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
skip "vault is not a git repo — skipping vault CI setup"
elif [[ ! -f "$EXAMPLE_CI" ]]; then
warn "docs/examples/vault-ci.yml not found — skipping vault CI setup"
elif [[ -f "$VAULT_CI_TARGET" ]]; then
skip "vault-ci.yml already exists in vault repo"
else
mkdir -p "$VAULT_WORKFLOWS"
cp "$EXAMPLE_CI" "$VAULT_CI_TARGET"
ok "created .github/workflows/vault-ci.yml in vault repo"
warn "Review $VAULT_CI_TARGET before committing to your vault repo"
fi
echo ""
# ── Result ─────────────────────────────────────────────────────────────────────
if [[ $errors -eq 0 ]]; then
echo "=== Result: all checks passed ==="
echo ""
echo "Next steps:"
echo " 1. Open Obsidian → Settings → Core plugins → enable Templates, Daily notes, Bases"
echo " 2. Templates plugin: set folder location to 'Templates'"
echo " 3. Daily notes plugin: set date format to 'YYYY-MM-DD', folder to 'Daily'"
echo " 4. Start a new Claude Code session in this directory — hooks will fire automatically"
else
echo "=== Result: $errors error(s) — fix the above before using second-brain ==="
exit 1
fi