Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions .claude/hooks/guard_pytest_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""PreToolUse(Bash) hook: 本番DBを巻き込むpytest実行をブロックする。

tests/unit/test_migrations.py は全テーブルを drop/再作成し、
tests/integration/ は実データを書き込む。`.env.test`(テスト専用DB)が
無い状態でpytestを走らせると、`.env`の日常用DB(Neon)がそのまま使われ、
データが消える(過去に実際に起きかけた事故)。

次のいずれかを満たす場合のみpytestの実行を許可する:
- プロジェクト直下に `.env.test` がある(conftest.pyがテスト用DBへ上書きする)
- コマンド内で DATABASE_URL を localhost / 127.0.0.1 へ上書きしている
(/check スキルはこの形で実行する)
"""

from __future__ import annotations

import json
import os
import re
import sys
from pathlib import Path

# pytestを「コマンドとして」起動している箇所だけを検出する
# (`grep pytest pyproject.toml` のような引数中の出現は対象外)。
_PYTEST_INVOCATION = re.compile(
r"(?:^|[;&|(\n]|\bthen\b|\bdo\b)\s*"
r"(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*"
r"(?:env\s+(?:(?:-u|--unset)\s+\S+\s+|-\S+\s+)*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*)?"
r"(?:(?:uv|poetry)\s+run\s+)?"
r"(?:\S*/)?(?:pytest|py\.test|python3?(?:\.\d+)?\s+-m\s+pytest)\b"
)
_SAFE_DB_OVERRIDE = re.compile(r"DATABASE_URL=\S*@(?:127\.0\.0\.1|localhost)[:/]")


def main() -> int:
payload = json.load(sys.stdin)
command = payload.get("tool_input", {}).get("command", "")
if not _PYTEST_INVOCATION.search(command):
return 0

project_dir = Path(os.environ.get("CLAUDE_PROJECT_DIR", Path(__file__).resolve().parents[2]))
if (project_dir / ".env.test").exists() or _SAFE_DB_OVERRIDE.search(command):
return 0

print(
"Blocked: .env.test が無い状態で pytest を実行すると、.env の本番DB(Neon)に対して"
" test_migrations.py が全テーブルを drop/再作成します。\n"
"代わりに /check スキル(.claude/skills/check/check.sh)を使うか、"
"DATABASE_URL=postgresql+psycopg://safe:safe@127.0.0.1:1/unreachable を"
"コマンドの先頭に付けて実行してください。",
file=sys.stderr,
)
return 2


if __name__ == "__main__":
sys.exit(main())
16 changes: 16 additions & 0 deletions .claude/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/guard_pytest_db.py\"",
"timeout": 10
}
]
}
]
}
}
26 changes: 26 additions & 0 deletions .claude/skills/check/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
name: check
description: Run this project's full quality gate (ruff lint, ruff format, mypy, i18n duplicate-key check, unit tests against a safe dummy DB). Use after code changes and before committing, instead of running pytest directly — plain pytest can wipe the production Neon DB.
---

# /check

Run the bundled script from the repository root:

```bash
.claude/skills/check/check.sh
```

It runs, in order, and reports every failure (it does not stop at the first):

1. `ruff check app src tests`
2. `ruff format --check app src tests`
3. `mypy src`
4. Duplicate keys in `TRANSLATIONS` (`app/i18n.py`)
5. `pytest tests/unit` with `DATABASE_URL` pointed at an unreachable localhost and `tests/unit/test_migrations.py` excluded

## Rules

- Never run `pytest` directly against the default environment. Without `.env.test`, `tests/unit/test_migrations.py` drops and recreates every table in the `.env` production DB, and `tests/integration/` writes to it. A PreToolUse hook (`.claude/hooks/guard_pytest_db.py`) blocks such runs.
- If ruff format fails, fix with `.venv/bin/ruff format app src tests` and re-run.
- Report the final `ALL PASSED` / `FAILED: ...` line to the user; on failure include the failing step's output.
45 changes: 45 additions & 0 deletions .claude/skills/check/check.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env bash
# lint / format / 型 / i18n / ユニットテストを一括で実行する。
# テストは本番DB(.envのNeon)に触れないよう、DATABASE_URLを到達不能な
# localhostへ差し替え、DBを破壊するtest_migrations.pyを除外して実行する
# (.env.testがある場合はconftest.pyがそちらで上書きする)。
set -uo pipefail
cd "$(git rev-parse --show-toplevel)"

SAFE_DB_URL="postgresql+psycopg://safe:safe@127.0.0.1:1/unreachable"
failed=()

step() {
local name="$1"
shift
echo "== ${name}"
if "$@"; then echo " OK"; else echo " FAILED"; failed+=("$name"); fi
}

check_i18n() {
.venv/bin/python - <<'PY'
import collections
import re
import sys

keys = re.findall(r'^ "(.+?)":', open("app/i18n.py", encoding="utf-8").read(), re.M)
dups = [k for k, n in collections.Counter(keys).items() if n > 1]
if dups:
print(" duplicate TRANSLATIONS keys:", dups)
sys.exit(1)
PY
}

step "ruff check" .venv/bin/ruff check app src tests
step "ruff format" .venv/bin/ruff format --check app src tests
step "mypy" .venv/bin/mypy src
step "i18n duplicate keys" check_i18n
step "pytest (unit, safe DB)" env DATABASE_URL="$SAFE_DB_URL" \
.venv/bin/pytest tests/unit --ignore=tests/unit/test_migrations.py -q -p no:cacheprovider

echo
if ((${#failed[@]})); then
echo "FAILED: ${failed[*]}"
exit 1
fi
echo "ALL PASSED"
28 changes: 28 additions & 0 deletions .claude/skills/db-health/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
name: db-health
description: Read-only health check of the production Neon DB — per-user log counts, content-duplicate records (e.g. double CSV imports), latest record date per log type, and orphaned workout exercises/sets. Use when dashboard charts look empty, inflated, or wrong, or after bulk CSV imports.
---

# /db-health

Run from the repository root:

```bash
.venv/bin/python .claude/skills/db-health/db_health.py
```

The script connects with `postgresql_readonly` (Postgres rejects any write with `ReadOnlySqlTransaction`), so it is safe to run against production. It takes a few seconds because the DB is remote.

## Reading the output

- **重複**: records whose content matches another record exactly (all fields except the ID). Same rule as the CSV import dedupe (`content_key` in `app/components/csv_import.py`). Non-zero usually means a CSV was imported more than once, which multiplies dashboard totals.
- **最終記録日**: if it is more than 7 days ago, the dashboard's default "last 7 days" view is empty for that log type. That is expected, not a bug.
- **Orphans**: workout exercises or sets with no parent row.

## Fixing problems

This skill only diagnoses. Deleting duplicates is destructive and irreversible, so:

1. Show the user the counts and ask for explicit confirmation first.
2. Dry-run, then delete through the repositories (`uow.<logs>.delete(user_id, id)`, keeping one record per `content_key`) in a single transaction, so workout exercises and sets cascade and a failure rolls everything back.
3. Re-run `/db-health` to confirm, and tell the user to restart Streamlit: the app caches reads for up to 10 minutes and does not see changes made outside the app.
104 changes: 104 additions & 0 deletions .claude/skills/db-health/db_health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""本番DB(.envのDATABASE_URL)の健全性を読み取り専用で点検する。

- ログ種別ごとの件数・重複件数(内容が完全一致するレコード。CSVインポートの
二重取り込み判定 `content_key` と同じ基準)・最終記録日(JST)
- 運動ログの子テーブル(種目・セット)の孤児行

接続は `postgresql_readonly` を指定したトランザクションで行うため、
このスクリプトからDBへ書き込むことはできない。

使い方(リポジトリ直下から):
.venv/bin/python .claude/skills/db-health/db_health.py
"""

from __future__ import annotations

import os
import sys
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "app"))

from components.csv_import import content_key # noqa: E402
from components.formatting import jst_date_of # noqa: E402
from sqlalchemy import create_engine, text # noqa: E402
from sqlalchemy.orm import sessionmaker # noqa: E402

from health_intelligence.config import load_environment # noqa: E402
from health_intelligence.repositories.sqlalchemy.unit_of_work import ( # noqa: E402
SqlAlchemyUnitOfWork,
)

# (UoWの属性名, 表示名, 記録日時の属性名)
_LOGS = [
("meal_logs", "食事", "consumed_at"),
("workout_logs", "運動", "performed_at"),
("sleep_logs", "睡眠", "bedtime"),
("weight_logs", "体重", "recorded_at"),
("health_logs", "体調", "recorded_at"),
("learning_logs", "学習", "started_at"),
]
_STALE_DAYS = 7
_ORPHAN_QUERIES = {
"workout_exercises(親の運動ログなし)": (
"select count(*) from workout_exercises e"
" where not exists (select 1 from workout_logs w where w.id = e.workout_log_id)"
),
"workout_sets(親の種目なし)": (
"select count(*) from workout_sets s"
" where not exists (select 1 from workout_exercises e where e.id = s.workout_exercise_id)"
),
}


def main() -> int:
load_environment()
engine = create_engine(
os.environ["DATABASE_URL"],
pool_pre_ping=True,
execution_options={"postgresql_readonly": True},
)
today = jst_date_of(datetime.now(UTC))
problems: list[str] = []

with SqlAlchemyUnitOfWork(sessionmaker(bind=engine)) as uow:
session = uow._session
assert session is not None
users = session.execute(text("select id, email from users order by email")).all()

for user_id, email in users:
print(f"# {email}")
print(f" {'種別':<4} {'件数':>6} {'重複':>6} {'最終記録日(JST)':>16}")
for attr, label, at_field in _LOGS:
logs = getattr(uow, attr).list_by_user(user_id)
counts = Counter(content_key(log) for log in logs)
duplicates = sum(n - 1 for n in counts.values())
latest = max((jst_date_of(getattr(log, at_field)) for log in logs), default=None)
latest_text = latest.isoformat() if latest else "-"
print(f" {label:<4} {len(logs):>6} {duplicates:>6} {latest_text:>16}")

if duplicates:
problems.append(f"{email} {label}: 内容が同一の重複 {duplicates}件")
if latest is not None and (today - latest).days > _STALE_DAYS:
problems.append(
f"{email} {label}: 最終記録が{(today - latest).days}日前"
f"({latest.isoformat()}) → ダッシュボードの直近{_STALE_DAYS}日間は空"
)
print()

for label, sql in _ORPHAN_QUERIES.items():
orphans = session.execute(text(sql)).scalar_one()
if orphans:
problems.append(f"{label}: {orphans}行")

print("## 検出事項")
for problem in problems or ["なし"]:
print(f"- {problem}")
return 0


if __name__ == "__main__":
sys.exit(main())
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,6 @@ Thumbs.db

kiroku
data

# Claude Code personal settings
.claude/settings.local.json
Loading
Loading