summaryrefslogtreecommitdiff
path: root/DESIGN.md
blob: e0cf8675aece48330c3b6806a5eed8d243ee0a69 (plain)
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
# Task Dashboard - Design Document

## Overview

Task Dashboard is a personal productivity web application that aggregates tasks, meals, calendar events, and shopping lists from multiple external services into a unified, mobile-friendly interface. Built with Go backend, HTMX frontend, Tailwind CSS styling, and SQLite storage.

**Stack:** Go 1.21+ | chi router | HTMX 1.x | Tailwind CSS | SQLite (WAL mode)

---

## Project Intent

The dashboard serves as a **personal consolidation hub** designed to:

1. **Aggregate multiple data sources** into one view (Trello, Todoist, PlanToEat, Google Calendar, Google Tasks)
2. **Prioritize reliability** over speed - graceful degradation when APIs fail
3. **Support mobile-first usage** - optimized for phone/tablet in-store or on-the-go
4. **Minimize context switching** - complete tasks from any source without opening multiple apps
5. **Provide live monitoring** - volcano webcams and weather for Hawaii location

---

## Architecture

### Directory Structure

```
task-dashboard/
├── cmd/dashboard/
│   └── main.go                 # Application entry point, route registration
├── internal/
│   ├── api/                    # External API clients
│   │   ├── interfaces.go       # API client contracts (interfaces)
│   │   ├── http.go             # BaseClient HTTP utilities
│   │   ├── trello.go           # Trello API client
│   │   ├── todoist.go          # Todoist API (REST v2 + Sync v9)
│   │   ├── plantoeat.go        # PlanToEat web scraper
│   │   ├── google_calendar.go  # Google Calendar integration
│   │   └── google_tasks.go     # Google Tasks integration
│   ├── auth/
│   │   ├── auth.go             # Authentication service (bcrypt)
│   │   ├── handlers.go         # Login/logout handlers
│   │   └── middleware.go       # Session + CSRF protection
│   ├── config/
│   │   ├── config.go           # Environment configuration
│   │   ├── constants.go        # App constants (timeouts, limits)
│   │   └── timezone.go         # Display timezone helpers
│   ├── handlers/
│   │   ├── handlers.go         # Main HTTP handlers (~2000 LOC)
│   │   ├── response.go         # JSON/HTML response utilities
│   │   ├── cache.go            # Generic cache fetcher pattern
│   │   ├── atoms.go            # Unified task aggregation
│   │   ├── timeline.go         # Timeline view handler
│   │   └── timeline_logic.go   # Timeline data processing
│   ├── middleware/
│   │   └── security.go         # Security headers + rate limiting
│   ├── models/
│   │   ├── types.go            # Data models (Task, Card, Meal, etc.)
│   │   ├── atom.go             # Unified Atom model + converters
│   │   └── timeline.go         # TimelineItem + DaySection models
│   └── store/
│       └── sqlite.go           # SQLite database layer (~700 LOC)
├── migrations/                 # SQL migration files (001-009)
├── web/
│   ├── templates/
│   │   ├── index.html          # Main dashboard shell
│   │   ├── login.html          # Authentication page
│   │   ├── conditions.html     # Standalone live feeds page
│   │   ├── shopping-mode.html  # Full-screen shopping mode
│   │   └── partials/           # HTMX partial templates
│   └── static/
│       ├── css/input.css       # Tailwind source
│       ├── css/output.css      # Compiled CSS
│       └── js/app.js           # Client-side logic
└── tailwind.config.js
```

### Request Flow

```
Browser (HTMX request)
    ↓
chi Router (middleware stack)
    ├── Logger, Recoverer, Timeout
    ├── SecurityHeaders
    ├── Session (LoadAndSave)
    └── CSRFProtect
    ↓
Handler Function
    ├── API Client (fetch from external service)
    │   └── BaseClient.Get/Post (HTTP with context)
    └── Store (SQLite cache)
        └── Get*/Save* methods
    ↓
Template Rendering
    ├── Full page: ExecuteTemplate(w, "filename.html", data)
    └── Partial: ExecuteTemplate(w, "partial-name", data)
    ↓
HTML Response → HTMX swap
```

### Data Flow Patterns

**Cache-First with Fallback:**
```go
// internal/handlers/cache.go pattern
1. Check IsCacheValid(key) - TTL-based
2. If valid, return cached data from SQLite
3. If expired, fetch from API
4. If API fails, return stale cache (graceful degradation)
5. On success, save to cache + update metadata
```

**Unified Atom Model:**
```go
// internal/models/atom.go
// Normalizes Todoist tasks, Trello cards, bugs → single Atom struct
TaskToAtom(Task)  → Atom{Source: "todoist", SourceIcon: "🔴", ...}
CardToAtom(Card)  → Atom{Source: "trello",  SourceIcon: "📋", ...}
BugToAtom(Bug)    → Atom{Source: "bug",     SourceIcon: "🐛", ...}
```

**Timeline Aggregation:**
```go
// internal/handlers/timeline_logic.go
BuildTimeline(ctx, store, calendarClient, tasksClient, start, end)
├── Fetch tasks with due dates (Todoist)
├── Fetch cards with due dates (Trello)
├── Fetch meals (PlanToEat) → apply default times
├── Fetch events (Google Calendar)
├── Fetch tasks (Google Tasks)
├── Convert all to TimelineItem
├── Compute DaySection (today/tomorrow/later)
└── Sort by Time
```

---

## Visual Design

### Color Palette

| Usage | Value | Tailwind |
|-------|-------|----------|
| Panel background | `rgba(0,0,0,0.4)` | `bg-black/40` |
| Card background | `rgba(0,0,0,0.5)` | `bg-black/50` |
| Card hover | `rgba(0,0,0,0.6)` | `bg-black/60` |
| Primary text | `#ffffff` | `text-white` |
| Secondary text | `rgba(255,255,255,0.7)` | `text-white/70` |
| Muted text | `rgba(255,255,255,0.5)` | `text-white/50` |
| Border subtle | `rgba(255,255,255,0.1)` | `border-white/10` |
| Border accent | `rgba(255,255,255,0.2)` | `border-white/20` |
| Todoist accent | `#e44332` | `border-red-500` |
| Trello accent | `#0079bf` | `border-blue-500` |
| PlanToEat accent | `#10b981` | `border-green-500` |

### Component Patterns

**Card Container:**
```html
<div class="bg-card bg-card-hover transition-colors rounded-lg border border-white/5">
    <div class="flex items-start gap-3 p-3">
        <!-- checkbox → icon → content → link -->
    </div>
</div>
```

**Tab Button:**
```html
<button class="tab-button {{if .IsActive}}tab-button-active{{end}}">
    <span>🗓️</span> Timeline
</button>
```

**Badge:**
```html
<span class="text-xs px-2 py-0.5 rounded bg-blue-900/50 text-blue-300">
    trello
</span>
```

**Glass Morphism:**
- `bg-black/40 backdrop-blur-sm` for panels
- `bg-black/60 backdrop-blur-lg` for modals
- `box-shadow: 0 0 12px black` for depth

**Z-Index Hierarchy:**
| Layer | z-index | Element |
|-------|---------|---------|
| Content | default | Page content |
| Sticky headers | z-10 | Timeline section headers |
| FAB button | z-50 | Floating action button |
| Modals | z-50 | Action modal, edit modal |
| Dropdowns/Popups | z-100 | Navigation dropdown, context menus |

### Typography

- **Font:** Inter (300, 400, 500, 600 weights)
- **Headings:** `font-light tracking-wide text-white`
- **Labels:** `text-xs font-medium tracking-wider uppercase`
- **Body:** `text-sm text-white/70`

### Quick Add UX Pattern

All quick-add forms (shopping, tasks, etc.) must follow these behaviors for rapid data entry:

**On Successful Submission:**
1. **Clear input** - Reset the form/input field immediately
2. **Refocus input** - Return focus to the text input for the next entry
3. **Visual feedback** - Brief flash (green background, 300ms) to confirm success
4. **Update list** - New item appears in the list immediately

**On Error:**
1. **Preserve input** - Do not clear the input so user can retry
2. **Show error** - Display error message near the input
3. **Maintain focus** - Keep focus on the input

**Checked/Completed Items:**
- Completed items are immediately removed from view (not just crossed out)
- User items: Deleted from database
- External items (Trello, PlanToEat): Marked as checked, filtered from display

---

## API Integrations

### Summary Table

| Service | Auth Method | Config Var | Read | Write | Notes |
|---------|-------------|------------|------|-------|-------|
| Todoist | Bearer token | `TODOIST_API_KEY` | ✓ Tasks, Projects | ✓ Create, Complete | Incremental sync available |
| Trello | Key + Token | `TRELLO_API_KEY`, `TRELLO_TOKEN` | ✓ Boards, Cards, Lists | ✓ Create, Archive | Concurrent board fetching |
| PlanToEat | Session cookie | `PLANTOEAT_SESSION` | ✓ Meals, Shopping | ✗ | Web scraping (brittle) |
| Google Calendar | OAuth file | `GOOGLE_CREDENTIALS_FILE` | ✓ Events | ✗ | Multi-calendar support |
| Google Tasks | OAuth file | `GOOGLE_CREDENTIALS_FILE` | ✓ Tasks | ✓ Complete | Shared credentials with Calendar |

### Interface Pattern

All API clients implement interfaces (in `internal/api/interfaces.go`):

```go
type TodoistAPI interface {
    GetTasks(ctx context.Context) ([]models.Task, error)
    GetProjects(ctx context.Context) ([]models.Project, error)
    CreateTask(ctx context.Context, content, projectID string, dueDate *time.Time, priority int) (*models.Task, error)
    CompleteTask(ctx context.Context, taskID string) error
    ReopenTask(ctx context.Context, taskID string) error
    // ...
}
```

Compile-time enforcement:
```go
var _ TodoistAPI = (*TodoistClient)(nil)
```

### Timezone Handling

All times normalized to display timezone:
```go
config.SetDisplayTimezone("Pacific/Honolulu")  // Set at startup
config.Now()                                    // Current time in display TZ
config.Today()                                  // Current date in display TZ
config.ToDisplayTZ(t)                           // Convert any time
config.ParseDateInDisplayTZ("2026-01-27")       // Parse in display TZ
```

---

## Features

### Timeline View (`/tabs/timeline`)

Chronological view of all upcoming items grouped by day section.

**Data Sources:** Todoist, Trello, PlanToEat, Google Calendar, Google Tasks

**Organization:**
- **Today** (expanded, collapsible) - Items due today
- **Tomorrow** (expanded, collapsible) - Items due tomorrow
- **Later** (collapsed) - Items 2+ days out

**Item Display:**
- Color-coded dot (blue=event, orange=meal, green=task, yellow=gtask)
- Time display (hidden for all-day items at midnight)
- Checkbox for completable items
- Title + description (2-line clamp)
- External link icon

### Tasks View (`/tabs/tasks`)

Unified task grid showing Atoms (normalized tasks from all sources).

**Layout:** 3-column responsive grid

**Features:**
- Priority sorting (overdue → today → future → no date)
- Source icons (🔴 Todoist, 📋 Trello, 🐛 Bug)
- Expandable descriptions
- Collapsible "Future" section

### Shopping View (`/tabs/shopping`)

Aggregated shopping lists from Trello + PlanToEat + user items.

**Tab Mode:** Store sections with items, quick-add form

**Shopping Mode (`/shopping/mode/{store}`):** Full-screen mobile-optimized view
- Store switcher (horizontal tabs)
- Large touch targets
- Fixed bottom quick-add

### Meals View (`/tabs/meals`)

PlanToEat meal schedule for the next 7 days.

**Features:**
- Meals grouped by date + meal type (breakfast/lunch/dinner)
- Multiple recipes for same slot combined with " + " separator
- Sorted by date, then meal type order

### Conditions Page (`/conditions`)

**Public route** - no authentication required.

Standalone live feeds page with:
- 3 Kilauea volcano webcams (USGS)
- 2 Hawaii weather maps (Windy.com)
- 1 National weather map

Auto-refresh webcam images every 60 seconds.

---

## Database Schema

**Engine:** SQLite with WAL mode (concurrent reads)

**Key Tables:**

| Table | Purpose | Key Columns |
|-------|---------|-------------|
| `tasks` | Todoist cache | id, content, due_date, priority, completed |
| `boards` | Trello boards | id, name |
| `cards` | Trello cards | id, name, board_id, list_id, due_date |
| `meals` | PlanToEat meals | id, recipe_name, date, meal_type |
| `users` | Authentication | id, username, password_hash |
| `sessions` | SCS sessions | token, data, expiry |
| `bugs` | Bug reports | id, description, resolved_at |
| `user_shopping_items` | User-added items | id, name, store, checked |
| `shopping_item_checks` | External item state | source, item_id, checked |
| `cache_metadata` | Cache timestamps | key, last_fetch, ttl_minutes |
| `sync_tokens` | Incremental sync | service, token |

---

## Development Guide for Claude Code

### Getting Started

1. **Read this file first** - Understand architecture and patterns
2. **Check `CLAUDE.md`** - Project-specific instructions
3. **Run tests before changes:** `go test ./...`
4. **Run after changes:** `go test ./...` then `go build`

### Key Principles

1. **Cache-First, Fail-Soft:** Never hard-fail if an API is down. Return cached data.
2. **Minimal Changes:** Surgical edits only. Don't refactor unrelated code.
3. **Interface-Driven:** API clients implement interfaces for testability.
4. **HTMX for Updates:** Use partials and `hx-swap` for reactive UI.

### Common Patterns

**Adding a new handler:**
```go
// internal/handlers/handlers.go
func (h *Handler) HandleNewFeature(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()

    // 1. Parse input
    if err := r.ParseForm(); err != nil {
        JSONError(w, http.StatusBadRequest, "Parse failed", err)
        return
    }

    // 2. Validate
    value := r.FormValue("key")
    if value == "" {
        JSONError(w, http.StatusBadRequest, "Missing key", nil)
        return
    }

    // 3. Business logic
    result, err := h.apiClient.DoSomething(ctx, value)
    if err != nil {
        JSONError(w, http.StatusInternalServerError, "Failed", err)
        return
    }

    // 4. Save to cache (best-effort)
    _ = h.store.SaveResult(result)

    // 5. Respond
    HTMLResponse(w, h.templates, "partial-name", result)
}
```

**Adding a new API method:**
```go
// 1. Add to interface (internal/api/interfaces.go)
type MyAPI interface {
    NewMethod(ctx context.Context, param string) (Result, error)
}

// 2. Implement in client (internal/api/myclient.go)
func (c *MyClient) NewMethod(ctx context.Context, param string) (Result, error) {
    var result Result
    if err := c.Get(ctx, "/endpoint/"+param, c.authHeaders(), &result); err != nil {
        return Result{}, fmt.Errorf("failed to fetch: %w", err)
    }
    return result, nil
}
```

**Adding a new template:**
```html
<!-- web/templates/partials/new-feature.html -->
{{define "new-feature"}}
<div class="space-y-4">
    {{range .Items}}
    <div class="bg-card rounded-lg p-4">
        <h3 class="text-white font-medium">{{.Title}}</h3>
    </div>
    {{end}}
</div>
{{end}}
```

**Adding a new route:**
```go
// cmd/dashboard/main.go inside protected routes group
r.Get("/tabs/newfeature", h.HandleNewFeature)
r.Post("/newfeature/action", h.HandleNewAction)
```

### Template Naming Convention

| Type | Location | Reference |
|------|----------|-----------|
| Standalone page | `web/templates/name.html` | `"name.html"` |
| Partial | `web/templates/partials/name.html` | `"name"` (define name) |

**Example:**
```go
// Standalone page - use filename
h.templates.ExecuteTemplate(w, "shopping-mode.html", data)

// Partial - use define name
HTMLResponse(w, h.templates, "shopping-tab", data)
```

### HTMX Patterns

**Tab content loading:**
```html
<div id="tab-content"
     hx-get="/tabs/{{.ActiveTab}}"
     hx-trigger="load"
     hx-swap="innerHTML">
</div>
```

**Form submission with swap:**
```html
<form hx-post="/complete-atom"
      hx-vals='{"id": "{{.ID}}", "source": "{{.Source}}"}'
      hx-target="closest div.rounded-lg"
      hx-swap="outerHTML">
```

**Refresh trigger:**
```javascript
// After action completes
htmx.trigger(document.body, 'refresh-tasks')
```

### Test Patterns

**Unit test for store:**
```go
func TestStore_SaveTasks(t *testing.T) {
    db := setupTestStore(t)
    defer db.Close()

    tasks := []models.Task{{ID: "1", Content: "Test"}}
    err := db.SaveTasks(tasks)
    require.NoError(t, err)

    result, err := db.GetTasks()
    require.NoError(t, err)
    assert.Len(t, result, 1)
}
```

**Handler test:**
```go
func TestHandler_HandleDashboard(t *testing.T) {
    h := setupTestHandler(t)

    req := httptest.NewRequest(http.MethodGet, "/", nil)
    w := httptest.NewRecorder()

    h.HandleDashboard(w, req)

    assert.Equal(t, http.StatusOK, w.Code)
}
```

### Debugging Tips

1. **Check logs:** All errors logged with `log.Printf`
2. **Cache issues:** Check `cache_metadata` table for stale timestamps
3. **API failures:** Look for `"Warning:"` or `"ERROR:"` prefixes
4. **Template errors:** Check for `html/template: "name" is undefined`
5. **HTMX issues:** Browser DevTools Network tab shows all requests

### Files You'll Modify Most

| Task | Primary Files |
|------|--------------|
| New feature | `handlers.go`, `main.go`, new template |
| Bug fix | Usually `handlers.go` or specific API client |
| UI change | Template in `partials/`, maybe `input.css` |
| API integration | New file in `internal/api/`, update `interfaces.go` |
| Database change | New migration, update `sqlite.go` |

### Configuration Reference

**Required:**
- `TODOIST_API_KEY` - Todoist API key
- `TRELLO_API_KEY` - Trello API key
- `TRELLO_TOKEN` - Trello token
- `DEFAULT_PASS` - Admin password (must be set)

**Optional:**
- `DEFAULT_USER` (default: "admin")
- `PLANTOEAT_SESSION` - PlanToEat session cookie
- `GOOGLE_CREDENTIALS_FILE` - OAuth credentials JSON path
- `GOOGLE_CALENDAR_ID` (default: "primary")
- `GOOGLE_TASKS_LIST_ID` (default: "@default")
- `DATABASE_PATH` (default: "./dashboard.db")
- `PORT` (default: "8080")
- `CACHE_TTL_MINUTES` (default: 5)
- `TIMEZONE` (default: "Pacific/Honolulu")
- `DEBUG` (default: false)

### Common Mistakes to Avoid

1. **Don't use `"name"` for standalone pages** - Use `"name.html"`
2. **Don't forget context propagation** - All handlers should use `r.Context()`
3. **Don't panic on API errors** - Return cached data or empty slice
4. **Don't modify tests without running them** - `go test ./...`
5. **Don't add unnecessary comments** - Code should be self-explanatory
6. **Don't create new files unless necessary** - Prefer editing existing
7. **Don't refactor working code** - Only touch what's needed
8. **Don't alter git history** - Never amend, rebase, or force push. Keep a clean, linear history with new commits only.

### Feature Toggles

Feature toggles allow gradual rollout of new features and easy rollback if issues arise.

**When to use feature toggles:**
- New features that may need adjustment after deployment
- Experimental features being tested
- Features that depend on external services that may be unreliable
- Any change that could break existing functionality

**Creating a feature toggle:**

1. Add a migration or use the Settings UI at `/settings`
2. Check the toggle in your handler:
```go
if h.store.IsFeatureEnabled("my_feature") {
    // New behavior
} else {
    // Old behavior or disabled state
}
```

3. Document the toggle in this file under "Active Feature Toggles"

**Managing feature toggles:**
- Access the Settings page at `/settings` to view/toggle/create features
- Store methods: `IsFeatureEnabled()`, `SetFeatureEnabled()`, `CreateFeatureToggle()`
- Toggles are stored in the `feature_toggles` table

**Lifecycle:**
1. **Create** toggle (disabled by default) before deploying feature
2. **Enable** after deployment if tests pass
3. **Monitor** for issues
4. **Remove** toggle and conditional code once feature is stable (usually after 1-2 weeks)

**Active Feature Toggles:**
| Name | Description | Status |
|------|-------------|--------|
| `source_config` | Configure which boards/lists/calendars to fetch | Disabled |
| `calendar_timeline` | Show timeline as a calendar view with time slots | Disabled |
| `completed_log` | Track and display completed tasks log | Enabled |

### Git Practices

**Clean history principles:**
- **Never amend commits** - Create new commits for fixes instead
- **Never rebase** - Use merge to integrate changes
- **Never force push** - All pushes should be fast-forward only
- **One logical change per commit** - Keep commits focused and atomic

**Commit message format:**
```
Short summary (50 chars or less)

Optional longer description explaining the why, not the what.
Reference bug numbers with #N format.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
```

**If history diverges:** Use `git pull --rebase=false` to merge, never force push.

### Bug Management Workflow

Use the bug tracking system to report and resolve issues:

**Viewing bugs (production):**
```bash
./scripts/bugs
# Lists all bugs from production database with ID, description, and created_at
```

**Resolving a bug:**
```bash
./scripts/resolve-bug <bug_id>
# Shows bug description, then deletes it from the database
```

**Workflow:**
1. Bugs are reported via the dashboard UI (🐛 tab in quick-add modal)
2. Run `./scripts/bugs` to see current issues
3. Fix the bug with tests
4. Deploy the fix
5. Run `./scripts/resolve-bug <id>` to close it

Bugs appear as atoms in the Tasks view (🐛 icon) until resolved.

### Test-Driven Development (TDD)

**Required approach for all changes:**

1. **Write failing test first** - Define expected behavior before implementation
2. **Make it pass** - Write minimal code to pass the test
3. **Refactor** - Clean up while tests stay green

**Test locations:**
| Component | Test File |
|-----------|-----------|
| Store methods | `internal/store/sqlite_test.go` |
| Handlers | `internal/handlers/*_test.go` |
| API clients | `internal/api/*_test.go` |
| Integration | `test/acceptance_test.go` |

**Running tests:**
```bash
# All tests
go test ./...

# Specific package
go test ./internal/handlers/...

# Verbose with coverage
go test -v -cover ./...

# Single test
go test -run TestBuildTimeline ./internal/handlers/...
```

**Test patterns:**
```go
func TestFeature_Behavior(t *testing.T) {
    // Arrange
    db := setupTestStore(t)
    defer db.Close()

    // Act
    result, err := db.SomeMethod(input)

    // Assert
    require.NoError(t, err)
    assert.Equal(t, expected, result)
}
```

**Before submitting any change:**
- `go test ./...` must pass
- Add tests for new functionality
- Update tests for changed behavior

### Design Documents and ADRs

**When to update DESIGN.md:**
- Adding new features or views
- Changing data flow patterns
- Modifying API integrations
- Updating database schema

**When to create an ADR (Architecture Decision Record):**
- Choosing between multiple implementation approaches
- Adding new external dependencies
- Changing authentication/security model
- Significant refactoring decisions

**ADR location:** `docs/adr/NNN-title.md`

**ADR template:**
```markdown
# ADR NNN: Title

## Status
Proposed | Accepted | Deprecated | Superseded

## Context
What is the issue or decision we need to make?

## Decision
What did we decide and why?

### Technical Details:
- Implementation specifics
- Key code locations

## Consequences
- **Pros:** Benefits of this approach
- **Cons:** Tradeoffs and limitations

## Alternatives Considered
- Option A: Why rejected
- Option B: Why rejected
```

**Numbering:** Use sequential 3-digit numbers (001, 002, etc.)

**Example ADRs to consider:**
- API client retry strategy
- Caching invalidation approach
- New data source integration
- UI framework changes

---

## Quick Reference

### Commands

```bash
# Run application
go run cmd/dashboard/main.go

# Run tests
go test ./...

# Build binary
go build -o dashboard cmd/dashboard/main.go

# Rebuild Tailwind CSS
npx tailwindcss -i web/static/css/input.css -o web/static/css/output.css --watch
```

### Key Endpoints

| Method | Path | Purpose |
|--------|------|---------|
| GET | `/` | Main dashboard |
| GET | `/tabs/timeline` | Timeline partial |
| GET | `/tabs/tasks` | Tasks partial |
| GET | `/tabs/shopping` | Shopping partial |
| GET | `/conditions` | Live feeds page |
| POST | `/complete-atom` | Complete task/card |
| POST | `/uncomplete-atom` | Reopen task/card |
| POST | `/unified-add` | Quick add task |
| POST | `/shopping/add` | Add shopping item |
| GET | `/shopping/mode/{store}` | Shopping mode |

### Handler Signature

```go
func (h *Handler) HandleName(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    // ... implementation
}
```

### Response Helpers

```go
JSONResponse(w, data)                           // 200 + JSON
JSONError(w, status, "message", err)            // Error + log
HTMLResponse(w, h.templates, "name", data)      // Partial render
HTMLString(w, "<html>...</html>")               // Raw HTML
```