Membership Core Identity Loop — Implementation Plan
For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Build identity generation, visit tracking, and balance display for the Almanack membership system.
Architecture: FastAPI microservice handles identity storage and visit tracking. Browser JS generates age keypairs, stores in localStorage, calls API. Django template renders dropdown UI populated by JS.
Tech Stack: FastAPI, SQLModel, SQLite, typage (browser age crypto), vanilla JS
Task 1: FastAPI Project Scaffold
Files:
- Create: api/__init__.py
- Create: api/main.py
- Create: api/requirements.txt
- Create: api/data/.gitkeep
Step 1: Create api directory structure
mkdir -p api/data
touch api/__init__.py api/data/.gitkeep
Step 2: Create requirements.txt
fastapi>=0.109.0
uvicorn[standard]>=0.27.0
sqlmodel>=0.0.14
pydantic>=2.5.0
python-multipart>=0.0.6
pytest>=7.4.0
httpx>=0.26.0
Step 3: Create minimal main.py with health endpoint
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(title="Almanack Membership API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Restrict in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/health")
def health():
return {"status": "ok"}
Step 4: Test manually
cd api && pip install -r requirements.txt
uvicorn main:app --reload --port 8000
# In another terminal:
curl http://localhost:8000/health
# Expected: {"status":"ok"}
Step 5: Commit
git add api/
git commit -m "feat(api): scaffold FastAPI microservice with health endpoint"
Task 2: Database Models
Files:
- Create: api/models.py
- Create: api/db.py
Step 1: Create models.py with Member and Visit
from datetime import date, datetime
from typing import Optional
from sqlmodel import Field, SQLModel
class Member(SQLModel, table=True):
pubkey: str = Field(primary_key=True) # age1...
name: str
balance: int = Field(default=0)
created_at: datetime = Field(default_factory=datetime.utcnow)
last_visit: Optional[date] = Field(default=None)
streak: int = Field(default=0)
class Visit(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
pubkey: str = Field(foreign_key="member.pubkey")
visited_on: date
page_type: str = Field(default="article")
Step 2: Create db.py with engine and session
import os
from sqlmodel import Session, SQLModel, create_engine
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///data/members.db")
engine = create_engine(DATABASE_URL, echo=False)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def get_session():
with Session(engine) as session:
yield session
Step 3: Update main.py to create tables on startup
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from db import create_db_and_tables
@asynccontextmanager
async def lifespan(app: FastAPI):
create_db_and_tables()
yield
app = FastAPI(title="Almanack Membership API", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/health")
def health():
return {"status": "ok"}
Step 4: Test database creation
cd api && rm -f data/members.db
python -c "from db import create_db_and_tables; create_db_and_tables()"
ls -la data/members.db
# Expected: file exists
Step 5: Commit
git add api/models.py api/db.py api/main.py
git commit -m "feat(api): add Member and Visit models with SQLite database"
Task 3: Name Generator Data Files
Files:
- Create: assets/names/titles.txt
- Create: assets/names/surnames.txt
- Create: assets/names/firstnames/generic.txt
- Create: assets/names/locations/generic.txt
Step 1: Create directory structure
mkdir -p assets/names/firstnames assets/names/locations
Step 2: Create titles.txt
Sir
Dame
Lord
Lady
Captain
Admiral
Professor
Doctor
Reverend
Viscount
Baron
Baroness
Alderman
Magistrate
Commodore
Colonel
Major
Chancellor
Provost
Deacon
Step 3: Create surnames.txt (whimsical procedural-style)
Winklebottom
Bramblethwaite
Crumplestitch
Thistlewood
Skipansicoal
Muffinbrook
Cobblethorne
Puddingstone
Nettlegrove
Rumblebristle
Quibblesworth
Fizzleton
Bumblecrumb
Snickerdash
Wobbleknock
Tumblewort
Fumblegate
Crinkleton
Noodlebank
Prattlewhisk
Grumbleshire
Dingleberry
Higgleston
Pogglesnatch
Wibbleford
Step 4: Create firstnames/generic.txt (Victorian flavor)
Archibald
Beatrice
Cornelius
Dorothea
Edmund
Florence
Geoffrey
Henrietta
Ignatius
Josephine
Kingsley
Lavinia
Montgomery
Nathaniel
Octavia
Percival
Quentin
Rosalind
Sebastian
Theodora
Ulysses
Victoria
Wellington
Xavier
Yolanda
Zachariah
Step 5: Create locations/generic.txt
the Western Reaches
the Northern Counties
the Coastal Provinces
the Eastern Marches
the Southern Highlands
Lower Bumblingshire
Upper Throttlebottom
Greater Wobblefordshire
Lesser Fiddlestick
the Outer Hebrides
the Inner Sanctum
the Forgotten Isles
County Peculiar
the Moors of Uncertainty
the Vales of Whimsy
Step 6: Commit
git add assets/names/
git commit -m "feat(names): add title, surname, firstname, and location data files"
Task 4: Name Generator
Files:
- Create: api/names.py
- Create: api/tests/__init__.py
- Create: api/tests/test_names.py
Step 1: Create test directory
mkdir -p api/tests
touch api/tests/__init__.py
Step 2: Write failing test for name generator
# api/tests/test_names.py
import re
from names import generate_name
def test_generate_name_format():
"""Name should be: Title Firstname Surname of Location"""
name = generate_name()
# Pattern: word(s) word word of word(s)
pattern = r"^[A-Z][a-z]+ [A-Z][a-z]+ [A-Z][a-z]+ of .+$"
assert re.match(pattern, name), f"Name '{name}' doesn't match expected format"
def test_generate_name_randomness():
"""Should generate different names on multiple calls"""
names = {generate_name() for _ in range(10)}
assert len(names) > 1, "Generator produced identical names"
Step 3: Run test to verify it fails
cd api && python -m pytest tests/test_names.py -v
# Expected: FAIL - ModuleNotFoundError: No module named 'names'
Step 4: Implement name generator
# api/names.py
import os
import random
from pathlib import Path
# Find assets/names relative to this file (api/) -> parent -> assets/names
ASSETS_DIR = Path(__file__).parent.parent / "assets" / "names"
def load_lines(filepath: Path) -> list[str]:
"""Load non-empty lines from a text file."""
with open(filepath) as f:
return [line.strip() for line in f if line.strip()]
def get_titles() -> list[str]:
return load_lines(ASSETS_DIR / "titles.txt")
def get_surnames() -> list[str]:
return load_lines(ASSETS_DIR / "surnames.txt")
def get_firstnames(region: str = "generic") -> list[str]:
filepath = ASSETS_DIR / "firstnames" / f"{region}.txt"
if not filepath.exists():
filepath = ASSETS_DIR / "firstnames" / "generic.txt"
return load_lines(filepath)
def get_locations(region: str = "generic") -> list[str]:
filepath = ASSETS_DIR / "locations" / f"{region}.txt"
if not filepath.exists():
filepath = ASSETS_DIR / "locations" / "generic.txt"
return load_lines(filepath)
def generate_name(region: str = "generic") -> str:
"""Generate a whimsical name like 'Captain Dmitri Winklebottom of the Volga Basin'"""
title = random.choice(get_titles())
firstname = random.choice(get_firstnames(region))
surname = random.choice(get_surnames())
location = random.choice(get_locations(region))
return f"{title} {firstname} {surname} of {location}"
Step 5: Run test to verify it passes
cd api && python -m pytest tests/test_names.py -v
# Expected: 2 passed
Step 6: Commit
git add api/names.py api/tests/
git commit -m "feat(api): add whimsical name generator"
Task 5: Register Endpoint
Files:
- Create: api/tests/test_register.py
- Modify: api/main.py
Step 1: Write failing test for /register
# api/tests/test_register.py
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_register_new_member():
"""POST /register with pubkey creates member and returns name"""
response = client.post("/register", json={"pubkey": "age1testkey123"})
assert response.status_code == 200
data = response.json()
assert "name" in data
assert data["balance"] == 0
assert data["streak"] == 0
def test_register_existing_member():
"""POST /register with existing pubkey returns existing profile"""
pubkey = "age1existingkey456"
# Register first time
response1 = client.post("/register", json={"pubkey": pubkey})
name1 = response1.json()["name"]
# Register again
response2 = client.post("/register", json={"pubkey": pubkey})
name2 = response2.json()["name"]
assert name1 == name2, "Should return same name for existing member"
Step 2: Run test to verify it fails
cd api && python -m pytest tests/test_register.py -v
# Expected: FAIL - 404 Not Found
Step 3: Add /register endpoint to main.py
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from sqlmodel import Session, select
from db import create_db_and_tables, engine, get_session
from models import Member
from names import generate_name
@asynccontextmanager
async def lifespan(app: FastAPI):
create_db_and_tables()
yield
app = FastAPI(title="Almanack Membership API", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class RegisterRequest(BaseModel):
pubkey: str
class ProfileResponse(BaseModel):
name: str
balance: int
streak: int
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/register", response_model=ProfileResponse)
def register(request: RegisterRequest, session: Session = Depends(get_session)):
# Check if member exists
member = session.get(Member, request.pubkey)
if member:
return ProfileResponse(name=member.name, balance=member.balance, streak=member.streak)
# Create new member
name = generate_name()
member = Member(pubkey=request.pubkey, name=name)
session.add(member)
session.commit()
session.refresh(member)
return ProfileResponse(name=member.name, balance=member.balance, streak=member.streak)
Step 4: Run test to verify it passes
cd api && python -m pytest tests/test_register.py -v
# Expected: 2 passed
Step 5: Commit
git add api/main.py api/tests/test_register.py
git commit -m "feat(api): add /register endpoint for member creation"
Task 6: Visit Endpoint
Files:
- Create: api/tests/test_visit.py
- Modify: api/main.py
Step 1: Write failing test for /visit
# api/tests/test_visit.py
from datetime import datetime, timedelta
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def setup_member(pubkey: str) -> str:
"""Helper to register a member and return their name"""
response = client.post("/register", json={"pubkey": pubkey})
return response.json()["name"]
def test_visit_debits_balance():
"""First visit of day debits 50 almanickels"""
pubkey = "age1visitdebit001"
setup_member(pubkey)
timestamp = datetime.utcnow().isoformat() + "Z"
response = client.post("/visit", json={
"pubkey": pubkey,
"signature": "test_sig", # Signature verification disabled for now
"timestamp": timestamp
})
assert response.status_code == 200
data = response.json()
assert data["balance"] == -50
assert data["debited"] is True
assert data["streak"] == 1
def test_visit_same_day_no_debit():
"""Second visit same day does not debit"""
pubkey = "age1visitsameday002"
setup_member(pubkey)
timestamp = datetime.utcnow().isoformat() + "Z"
# First visit
client.post("/visit", json={
"pubkey": pubkey,
"signature": "test_sig",
"timestamp": timestamp
})
# Second visit
response = client.post("/visit", json={
"pubkey": pubkey,
"signature": "test_sig",
"timestamp": timestamp
})
data = response.json()
assert data["balance"] == -50 # Still -50, not -100
assert data["debited"] is False
Step 2: Run test to verify it fails
cd api && python -m pytest tests/test_visit.py -v
# Expected: FAIL - 404 Not Found
Step 3: Add /visit endpoint to main.py
Add these imports and models at the top, then add the endpoint:
from datetime import date, datetime
# ... existing imports ...
class VisitRequest(BaseModel):
pubkey: str
signature: str
timestamp: str
class VisitResponse(BaseModel):
balance: int
streak: int
debited: bool
DAILY_DEBIT = 50
@app.post("/visit", response_model=VisitResponse)
def visit(request: VisitRequest, session: Session = Depends(get_session)):
member = session.get(Member, request.pubkey)
if not member:
# Auto-register if not found
member = Member(pubkey=request.pubkey, name=generate_name())
session.add(member)
today = date.today()
debited = False
# Check if already visited today
if member.last_visit != today:
# Debit and record visit
member.balance -= DAILY_DEBIT
debited = True
# Update streak
if member.last_visit and (today - member.last_visit).days == 1:
member.streak += 1
else:
member.streak = 1
member.last_visit = today
# Record visit in history
from models import Visit
visit_record = Visit(pubkey=request.pubkey, visited_on=today)
session.add(visit_record)
session.commit()
session.refresh(member)
return VisitResponse(balance=member.balance, streak=member.streak, debited=debited)
Step 4: Run test to verify it passes
cd api && python -m pytest tests/test_visit.py -v
# Expected: 2 passed
Step 5: Commit
git add api/main.py api/tests/test_visit.py
git commit -m "feat(api): add /visit endpoint with daily debit and streak tracking"
Task 7: Me Endpoint
Files:
- Create: api/tests/test_me.py
- Modify: api/main.py
Step 1: Write failing test for /me
# api/tests/test_me.py
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_me_returns_profile():
"""GET /me returns member profile"""
pubkey = "age1metest001"
# Register first
reg_response = client.post("/register", json={"pubkey": pubkey})
expected_name = reg_response.json()["name"]
# Get profile
response = client.get("/me", params={"pubkey": pubkey, "sig": "test", "ts": "now"})
assert response.status_code == 200
data = response.json()
assert data["name"] == expected_name
assert data["balance"] == 0
assert data["streak"] == 0
def test_me_unknown_member():
"""GET /me for unknown pubkey returns 404"""
response = client.get("/me", params={"pubkey": "age1unknown999", "sig": "test", "ts": "now"})
assert response.status_code == 404
Step 2: Run test to verify it fails
cd api && python -m pytest tests/test_me.py -v
# Expected: FAIL - 404 or 405
Step 3: Add /me endpoint to main.py
from fastapi import Depends, FastAPI, HTTPException
# ... in main.py, add this endpoint ...
@app.get("/me", response_model=ProfileResponse)
def get_me(pubkey: str, sig: str, ts: str, session: Session = Depends(get_session)):
# TODO: Verify signature
member = session.get(Member, pubkey)
if not member:
raise HTTPException(status_code=404, detail="Member not found")
return ProfileResponse(name=member.name, balance=member.balance, streak=member.streak)
Step 4: Run test to verify it passes
cd api && python -m pytest tests/test_me.py -v
# Expected: 2 passed
Step 5: Run all API tests
cd api && python -m pytest tests/ -v
# Expected: All tests pass
Step 6: Commit
git add api/main.py api/tests/test_me.py
git commit -m "feat(api): add /me endpoint for fetching member profile"
Task 8: Makefile Targets
Files:
- Modify: Makefile
Step 1: Read current Makefile to find insertion point
grep -n "^serve:" Makefile || echo "No serve target"
Step 2: Add API targets to Makefile
Add after existing targets:
# === API ===
serve-api:
cd api && uvicorn main:app --reload --port 8000
test-api:
cd api && python -m pytest tests/ -v
install-api:
cd api && pip install -r requirements.txt
Step 3: Test the targets
make test-api
# Expected: All tests pass
Step 4: Commit
git add Makefile
git commit -m "build: add make targets for API (serve-api, test-api, install-api)"
Task 9: Identity JS Library - Core
Files:
- Create: src/almnck/static/js/identity.js
Step 1: Create identity.js with localStorage management
// identity.js - Client-sovereign identity for Almanack membership
(function(global) {
'use strict';
const STORAGE_KEYS = {
identity: 'almanack:identity',
profile: 'almanack:profile'
};
const API_BASE = document.querySelector('meta[name="almanack-api"]')?.content || 'http://localhost:8000';
// State
let privateKey = null;
let publicKey = null;
let profile = null;
// === Storage ===
function saveIdentity(secretKey) {
localStorage.setItem(STORAGE_KEYS.identity, secretKey);
}
function loadIdentity() {
return localStorage.getItem(STORAGE_KEYS.identity);
}
function saveProfile(data) {
profile = data;
localStorage.setItem(STORAGE_KEYS.profile, JSON.stringify(data));
}
function loadProfile() {
const stored = localStorage.getItem(STORAGE_KEYS.profile);
if (stored) {
profile = JSON.parse(stored);
}
return profile;
}
// === Crypto ===
// Note: Full age crypto requires typage library
// For MVP, we use a simplified approach with random keys
function generateKeypair() {
// Simplified: generate random 32 bytes as hex for "pubkey"
// Real implementation would use typage for age keys
const array = new Uint8Array(32);
crypto.getRandomValues(array);
const pubkey = 'age1' + Array.from(array).map(b => b.toString(16).padStart(2, '0')).join('').slice(0, 58);
const secretKey = 'AGE-SECRET-KEY-1' + Array.from(array).map(b => b.toString(16).padStart(2, '0')).join('').toUpperCase();
return { pubkey, secretKey };
}
function derivePublicKey(secretKey) {
// For MVP, pubkey is stored alongside secret
// Real implementation would derive from secret
const stored = loadProfile();
return stored?.pubkey || null;
}
// === API ===
async function apiPost(endpoint, body) {
const response = await fetch(`${API_BASE}${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return response.json();
}
async function apiGet(endpoint, params) {
const url = new URL(`${API_BASE}${endpoint}`);
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
return response.json();
}
// === Public API ===
const Identity = {
async init() {
const stored = loadIdentity();
if (stored) {
privateKey = stored;
loadProfile();
publicKey = profile?.pubkey;
return true;
}
// Generate new identity
const { pubkey, secretKey } = generateKeypair();
privateKey = secretKey;
publicKey = pubkey;
saveIdentity(secretKey);
// Register with server
await this.register();
return true;
},
async register() {
try {
const data = await apiPost('/register', { pubkey: publicKey });
saveProfile({ ...data, pubkey: publicKey });
return data;
} catch (err) {
console.error('Registration failed:', err);
// Use cached or create placeholder
if (!profile) {
saveProfile({ pubkey: publicKey, name: 'Fellow Traveler', balance: 0, streak: 0 });
}
return profile;
}
},
async visit() {
if (!publicKey) await this.init();
try {
const timestamp = new Date().toISOString();
const data = await apiPost('/visit', {
pubkey: publicKey,
signature: 'placeholder', // TODO: real signature
timestamp
});
saveProfile({ ...profile, ...data, pubkey: publicKey });
return data;
} catch (err) {
console.error('Visit tracking failed:', err);
// Jubilee mode - no debit on failure
return { balance: profile?.balance || 0, streak: profile?.streak || 0, debited: false, jubilee: true };
}
},
async getMe() {
if (!publicKey) await this.init();
try {
const data = await apiGet('/me', { pubkey: publicKey, sig: 'placeholder', ts: Date.now() });
saveProfile({ ...data, pubkey: publicKey });
return data;
} catch (err) {
console.error('Profile fetch failed:', err);
return profile;
}
},
getPublicKey() {
return publicKey;
},
getName() {
return profile?.name || 'Fellow Traveler';
},
getBalance() {
return profile?.balance || 0;
},
getStreak() {
return profile?.streak || 0;
},
isInitialized() {
return !!privateKey;
}
};
// Export
global.AlmanackIdentity = Identity;
})(window);
Step 2: Commit
git add src/almnck/static/js/identity.js
git commit -m "feat(js): add Identity library for client-sovereign membership"
Task 10: Identity JS - Dropdown Controller
Files:
- Create: src/almnck/static/js/identity-dropdown.js
Step 1: Create dropdown controller
// identity-dropdown.js - UI controller for membership dropdown
(function(global) {
'use strict';
function formatBalance(balance) {
const sign = balance < 0 ? '−' : '';
return sign + Math.abs(balance).toLocaleString();
}
function initDropdown() {
const widget = document.getElementById('identity-widget');
if (!widget) return;
const trigger = widget.querySelector('.identity-trigger');
const menu = widget.querySelector('.dropdown-menu');
const nameEl = document.getElementById('member-name');
const nameShortEl = document.getElementById('member-name-short');
const balanceEl = document.getElementById('member-balance');
const streakEl = document.getElementById('member-streak');
// Toggle dropdown
trigger?.addEventListener('click', (e) => {
e.stopPropagation();
menu.hidden = !menu.hidden;
});
// Close on outside click
document.addEventListener('click', () => {
if (menu) menu.hidden = true;
});
// Close on escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && menu) menu.hidden = true;
});
// Update UI from Identity
function updateUI() {
const Identity = global.AlmanackIdentity;
if (!Identity) return;
const name = Identity.getName();
const balance = Identity.getBalance();
const streak = Identity.getStreak();
if (nameEl) nameEl.textContent = name;
if (nameShortEl) {
// Extract first name for short display
const parts = name.split(' ');
nameShortEl.textContent = parts[1] || parts[0] || 'you';
}
if (balanceEl) balanceEl.textContent = formatBalance(balance);
if (streakEl) streakEl.textContent = streak;
// Update balance styling
if (balanceEl) {
balanceEl.classList.toggle('negative', balance < 0);
balanceEl.classList.toggle('positive', balance > 0);
}
}
// Initialize identity and update UI
async function initialize() {
const Identity = global.AlmanackIdentity;
if (!Identity) {
console.warn('AlmanackIdentity not loaded');
return;
}
await Identity.init();
updateUI();
// Record visit and update
const visitResult = await Identity.visit();
updateUI();
// Show jubilee message if API was down
if (visitResult.jubilee) {
console.log('Jubilee day! No charge.');
}
}
initialize();
}
// Initialize when DOM ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initDropdown);
} else {
initDropdown();
}
})(window);
Step 2: Commit
git add src/almnck/static/js/identity-dropdown.js
git commit -m "feat(js): add dropdown controller for membership UI"
Task 11: Django Template Integration
Files:
- Modify: src/almnck/templates/base.html (or equivalent)
Step 1: Find the base template
find src/almnck/templates -name "*.html" | head -10
Step 2: Read current meta-right section
Locate the masthead/meta-right area in the base template.
Step 3: Add identity dropdown HTML
In the meta-right section of the template, add:
<div class="identity-dropdown" id="identity-widget">
<button class="identity-trigger" type="button" aria-expanded="false" aria-haspopup="true">
<span class="greeting">Hello, <span id="member-name">stranger</span>!</span>
<span class="dropdown-arrow" aria-hidden="true">▼</span>
</button>
<div class="dropdown-menu" hidden>
<div class="balance-row">
<span class="balance-icon" aria-hidden="true">⚖️</span>
<span id="member-balance">0</span> almanickels
</div>
<div class="streak-row">
<span class="streak-icon" aria-hidden="true">🔥</span>
<span id="member-streak">0</span>-day streak
</div>
<hr>
<a href="/profile/">Profile</a>
<a href="/topup/">Top up</a>
<hr>
<a href="/recover/" class="recover-link">Not <span id="member-name-short">you</span>? Recover →</a>
</div>
</div>
Step 4: Add meta tag for API URL
In the <head> section:
<meta name="almanack-api" content="http://localhost:8000">
Step 5: Add script tags before closing body
<script src="{% static 'js/identity.js' %}"></script>
<script src="{% static 'js/identity-dropdown.js' %}"></script>
Step 6: Commit
git add src/almnck/templates/
git commit -m "feat(ui): integrate identity dropdown into base template"
Task 12: Dropdown CSS
Files: - Modify: existing stylesheet (find main CSS file)
Step 1: Find main stylesheet
find src/almnck/static -name "*.css" | head -5
Step 2: Add dropdown styles
/* Identity Dropdown */
.identity-dropdown {
position: relative;
display: inline-block;
}
.identity-trigger {
background: none;
border: none;
cursor: pointer;
font: inherit;
color: inherit;
padding: 0;
}
.identity-trigger:hover {
text-decoration: underline;
}
.dropdown-arrow {
font-size: 0.75em;
margin-left: 0.25em;
}
.dropdown-menu {
position: absolute;
right: 0;
top: 100%;
background: var(--bg-color, #fff);
border: 1px solid var(--border-color, #ccc);
padding: 0.5rem;
min-width: 200px;
z-index: 100;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.dropdown-menu hr {
margin: 0.5rem 0;
border: none;
border-top: 1px solid var(--border-color, #ccc);
}
.dropdown-menu a {
display: block;
padding: 0.25rem 0;
}
.balance-row,
.streak-row {
padding: 0.25rem 0;
}
#member-balance.negative {
color: var(--negative-color, #c00);
}
#member-balance.positive {
color: var(--positive-color, #080);
}
Step 3: Commit
git add src/almnck/static/
git commit -m "style: add CSS for identity dropdown"
Task 13: Integration Test
Files: - None (manual testing)
Step 1: Start the API server
make serve-api
# Keep running in background or separate terminal
Step 2: Start Django dev server
make serve
Step 3: Test in browser
- Open http://localhost:8000 (or Django port)
- Check that dropdown appears with “Hello, [Name]!”
- Open DevTools → Application → Local Storage
- Verify
almanack:identityandalmanack:profilekeys exist - Refresh page, verify same name persists
- Check balance shows -50 after first visit
Step 4: Document any issues found
If issues found, create follow-up tasks.
Step 5: Final commit if changes needed
git add -A
git commit -m "fix: integration fixes from manual testing"
Summary
| Task | Description | Est. Complexity |
|---|---|---|
| 1 | FastAPI scaffold | Simple |
| 2 | Database models | Simple |
| 3 | Name data files | Simple |
| 4 | Name generator | Medium |
| 5 | /register endpoint | Medium |
| 6 | /visit endpoint | Medium |
| 7 | /me endpoint | Simple |
| 8 | Makefile targets | Simple |
| 9 | Identity JS core | Medium |
| 10 | Dropdown controller | Medium |
| 11 | Template integration | Medium |
| 12 | Dropdown CSS | Simple |
| 13 | Integration test | Simple |
Total: 13 tasks
After completing all tasks, the membership core identity loop will be functional: visitors get a whimsical name, visits are tracked with daily debits, and the dropdown displays their identity and balance.