# Pockist — Agent Quick Context
**Pockist** is a local-first progressive web app (PWA) for todos and notes.
- **Live URL:** https://pockist.com
- **Stack:** Vanilla JS (frontend) + Go 1.25 + SQLite (backend)
- **Deployment:** Docker on an Ubuntu VPS
- **Philosophy:** Minimal dependencies. Vanilla everything. No build step for JS.
---
## What It Does
- Local-first todo lists and notes (all data stays on the user's device)
- No accounts, no tracking
- Temporary anonymous share links (backed by server-side SQLite)
- Weather widget + geocoding
- Archive / restore / search / drag-and-drop reordering
- Import / export JSON backups
---
## Architecture
| Layer | What It Is |
|-------|------------|
| **Frontend** | Single-page vanilla JS app. Web Components via custom elements. Custom event bus + event delegation. |
| **Data Store** | Browser `IndexedDB` with a single `items` object store. Notes, lists, and todos are all `item` records with a `type` field. |
| **Backend** | Go `net/http` mux. Serves static files and a handful of API endpoints. |
| **Database** | SQLite for share links only. Frontend data never touches the server. |
| **Caching** | Service Worker (`sw.js`) + in-memory Go cache (`pkg/cache`) for API responses. |
---
## Directory Structure
```
├── main.go # Go server entrypoint (routes, middleware, startup)
├── handlers/ # Go HTTP handlers
│ ├── ShareHandler.go # Create / read / delete share links (live)
│ ├── AccountHandlers.go # Auth handlers (dead code — not wired in main.go)
│ ├── weather_handler.go # Weather API proxy + caching
│ ├── geocode_handler.go # Geocode API proxy + caching
│ └── Database.go # SQLite init
├── pkg/cache/ # In-memory TTL cache for Go handlers
├── token/ # JWT creation / validation (used by dead auth code)
├── public/ # Static frontend assets
│ ├── index.html # Single HTML shell
│ ├── app.js # Boot: DB init → migrations → router → service worker
│ ├── sw.js # Service worker (caches static assets + API GETs)
│ ├── app.webmanifest # PWA manifest
│ ├── components/ # Custom element components
│ │ ├── ListBase.js # Shared list CRUD logic
│ │ ├── NoteBase.js # Shared note CRUD logic
│ │ ├── *Page.js # Route-level page components
│ │ └── weather/ # Weather sub-components
│ ├── services/ # Business-logic modules
│ │ ├── DBManager.js # IndexedDB wrapper, migrations, CRUD
│ │ ├── Router.js # Client-side router (event delegation)
│ │ ├── API.js # Fetch wrapper for backend APIs
│ │ ├── ShareService.js # Share link helpers
│ │ ├── ImportExportService.js
│ │ ├── DialogService.js
│ │ ├── DraggableList.js
│ │ └── WeatherService.js
│ └── styles/ # CSS files (one per feature area)
├── docs/ # Deep-dive documentation (see below)
├── Dockerfile # Multi-stage build (Go + alpine)
├── docker-compose.yml # Compose with persistent volume
└── .air.toml # Air live-reload config (Go only)
```
---
## Key Files to Know
| File | Why It Matters |
|------|--------------|
| `public/services/DBManager.js` | The heart of the app. IndexedDB schema, migrations, and all CRUD. |
| `public/app.js` | Boot sequence. Initializes DB, runs migrations, starts router, registers SW. |
| `public/services/Router.js` | Client-side routing. Uses `document`-level click delegation to intercept `` tags. |
| `public/components/ListBase.js` | Shared list logic: add, reorder, complete, archive, drag-drop, clear. |
| `public/components/NoteBase.js` | Shared note logic: load, sort, actions. |
| `main.go` | Go server. Serves static files, API routes, and catch-all fallback to `index.html`. |
| `handlers/ShareHandler.go` | Only live backend feature: temporary share links with rate limiting. |
| `handlers/AccountHandlers.go` | **Dead code.** Auth is not wired up. Do not treat as active. |
| `token/*.go` | JWT creation / validation — contains `log.Fatalf` crashes (only used by dead auth code). |
---
## Current State
Check **`docs/TODO.md`** for the canonical task list.
At a glance (as of 2026-07-14):
- **Active bugs (max 3):**
1. `_clearCompleted` saves list before archiving children — orphaned items on partial failure
2. `showError()` alert-modal missing from `index.html` — errors fall back to `alert()`
3. Add coordinate validation to weather_handler.go (invalid lat/lon cached 20min)
- **Major planned refactor:** v11 schema migration (move from `list.items[]` child refs to `parentId` + compound index in IndexedDB). **On hold** until active bugs are cleared.
- **Auth system:** Entirely dead code. Consolidated to backlog pending a decision to either wire it up or delete it.
- **Recently shipped (v0.1.29):** Parent list tracking for archive/restore, API.fetch error handling fix.
- **Recently fixed (2026-07-14):**
- Object URL revoke race — all downloads defer `URL.revokeObjectURL()` by 3 seconds.
- Router blob URL interception — `blob:` clicks from `ImportExportService` were being hijacked by the router and killed. Added `blob:` to Router exclusion list.
---
## Critical Context
### Database Version
- **Current:** `10`
- **Next (planned):** `11` — parentId + compound index to kill N+1 queries and retire `list.items[]`
- **Status:** v11 is on hold until Active bug backlog is cleared.
### LocalStorage Migration Flags
| Flag | Migration |
|------|-----------|
| `migrationComplete` | textAreaDB → pockist-db |
| `multiNoteMigrationComplete` | Number IDs → string IDs |
| `todoDBMigrationComplete` | TodoDB → lists |
| `itemsMigrationComplete` | notes + lists → unified items (v9) |
| `itemsArrayMigrationComplete` | `links[]` → `items[]` (v10) |
### Active Risks
1. **N+1 reads** — `DBManager.getListItems()` fetches children one-by-one. v11 migration is the fix.
2. **Unbounded SW cache** — `sw.js` caches every API GET (weather, geocode, shares) with no eviction.
3. **Auth decision pending** — All auth work moved to backlog. Need decision: wire up or delete.
4. **~~List reordering index mismatch~~** — Fixed 2026-07-08. `_archiveItem` now removes child refs from `listItem.items` before archiving. `_loadCurrentList` prunes legacy orphaned refs on load.
5. **`_clearCompleted` orphan risk** — Active bug #1. `saveItem` called before `archiveItem` loop.
---
## Session Notes
### 2026-07-08 — Legacy Code Cleanup (Quick Win)
- Removed 4 dead methods from `DBManager.js` with zero callers anywhere in the codebase:
1. `getNote(id)` — unreferenced externally
2. `getLists()` — unreferenced externally
3. `deleteList(listId)` — unreferenced externally
4. `#itemToLegacyNote(item)` — only called by `getNote`
- Migration chain remains intact. All 5 migration methods and their private helpers preserved.
- Adapter methods still referenced by `ImportExportService.js` (`saveNote`, `saveList`, `getList`, `createList`, `#itemToLegacyList`) kept in place.
- Net reduction: ~50 lines. Zero risk.
### 2026-06-30 — PM Handover
- Took over as PM from code-author mode.
- `TODO.md` read and understood. `AGENT_NOTES.md` created.
- Active bugs prioritized: SearchPopover entity corruption, WeatherPage listener leak, and one critical server bug next.
- v11 schema migration confirmed as post-bug-fix roadmap item.
### 2026-06-30 — SearchPopover Fix Applied
- Fixed `#highlightText` in `SearchPopover.js` to tokenize escaped text into HTML entities and plain-text runs before applying the highlight regex.
- Prevents queries like `amp` from breaking `&` entities.
- Entities are matched by regex `&(?:#\d+|#x[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);` and skipped during highlighting.
### 2026-06-30 — Router Event Delegation + Listener Leak Fix
- Replaced per-page `a.pwa` click interceptors in `WeatherPage.js`, `AboutPage.js`, `ListPage.js`, and `HomePage.js` with a single `document`-level event delegation handler in `Router.js`.
- `Router.init()` now uses `document.addEventListener("click", ...)` with `event.target.closest("a")` to catch all clicks on `` tags — static and dynamically added.
- Filters external links (`http://`, `tel:`, `mailto:`, `#`) to avoid intercepting non-app navigation.
- Removed dead `Router` imports from pages that no longer reference it directly.
- Also resolves TODO item: "Router not intercepting dynamically added `` tags after init".
### 2026-06-30 — PM Queue Maintenance
- Read `TODO.md` and `AGENT_NOTES.md`. Confirmed docs folder has 6 files.
- Moved completed SearchPopover and Router fixes from Active → Recently Completed (they were already there, but still checked in Active).
- Refilled Active queue to max 3:
1. `token/` `log.Fatalf` DoS vector (remains)
2. `ListBase._handleAdd` rollback bug (pulled from Next Up)
3. `API.js` `Authorization: null` header (pulled from Next Up)
- Next Up now has 1 item: weather coordinate validation.
- v11 schema migration remains on hold until Active bug backlog is cleared.
### 2026-06-30 — Auth Consolidated to Backlog
- User directed: move all auth stuff to backlog.
- Removed auth items from Active: `token/` `log.Fatalf`, `API.js` `Authorization: null`.
- Moved auth bugs from Backlog - Bugs: `AccountHandler.Register` name drop, `AccountHandler.Authenticate` empty name.
- Moved auth security: JWT in localStorage.
- Consolidated all under **Backlog - Auth Project (On Hold)**.
- Active queue refilled with non-auth bugs:
1. `ListBase._handleAdd` rollback
2. `API.fetch` swallowing errors
3. `ImportExportService` object URL revoke race
- Next Up: `showError()` missing, `_clearCompleted` orphan risk, weather coordinate validation.
### 2026-06-30 — ListBase._handleAdd Rollback Fix Verified
- User fixed `ListBase._handleAdd` catch block: `listItem.items.pop()` → `listItem.items.shift()`.
- Symmetry restored: `unshift` to index 0 on add, `shift` from index 0 on rollback.
- Prevents silent corruption where save failure would drop the wrong (last) item instead of the newly added (first) item.
- File: `public/components/ListBase.js`, line 218.
- Moved to Recently Completed; pulled `Fix showError() alert-modal missing` from Next Up into Active.
### 2026-06-30 — PM Task 1: API.fetch Error Swallowing (In Progress)
- Confirmed root cause: `response.json()` called unconditionally; 404/500 HTML bodies cause SyntaxError → caught → returns `undefined`.
- Plan provided to user: check `response.ok`, parse error body, re-throw after `app.showError()`.
- Bonus decision: fix `Authorization: null` header while editing `API.js`.
- Blast-radius mitigation: keep `try/catch` in `API.js` and re-throw, so `app.js` doesn't need immediate changes.
- Status: Awaiting user implementation and verification.
### 2026-07-08 — List Reordering Fix Applied (Revised: Option A)
- **Initial attempt (Option B):** Removed child refs from `listItem.items` in `_archiveItem`, added legacy cleanup in `_loadCurrentList`.
- **Problem discovered:** ArchivePage restore logic expects the ref to still exist in the parent list. Removing it broke restore — archived items became orphans with no way to know which list they belonged to.
- **Reverted to Option A:**
1. `_archiveItem`: reverted to old behavior — just calls `DBManager.archiveItem(itemId)`, ref stays in `listItem.items`. Restore behavior preserved.
2. Added `_pruneArchivedRefs(listItem)` helper that strips dead refs from `listItem.items` by checking `this._linkedItems` for `meta.archived`. Re-sequences remaining refs.
3. Called `_pruneArchivedRefs()` at the start of every reorder entry point: `_moveItem`, `_reorderItem`, `_moveItemToTop`, `_moveItemToBottom`, `_sortItems`, `_clearCompleted`.
4. Kept `_loadCurrentList` legacy cleanup from Option B — it prunes orphaned refs on page load anyway, so dead refs are cleaned up even if no reorder happens.
- **Problem discovered (second round):** `_archiveItem` refreshed `this._linkedItems` but not `this._currentListItem`, so the stale `listItem.items` still contained the dead ref. Any operation immediately after archive (add, duplicate, action menu) read the stale array and computed wrong indices / disabled wrong buttons.
- **Fix:** Added `_pruneArchivedRefs(listItem)` to 4 more entry points: `_archiveItem` (after refresh), `_showItemActions`, `_handleAdd`, `_doDuplicateItem`. Now `_currentListItem` is clean immediately after archive, no refresh needed.
- **Problem discovered (third round):** After archive, stale `_currentListItem` was cleaned in-memory by `_pruneArchivedRefs`, but navigating to the list page would trigger `_loadCurrentList` which saves the pruned array to IndexedDB. The DB permanently lost the archived ref. Restoring from ArchivePage had nowhere to put the item back — it became an orphan.
- **Root cause of root cause:** We wanted to keep refs in the list for restore (Option A), but our own pruning logic was saving those pruned arrays back to the DB. The ref was lost before restore could use it.
- **Fix (Path 2 — parent tracking):**
1. `DBManager.archiveItem(id, parentListId?)` — added optional `parentListId` parameter. Sets `item.meta.parentListId` before archiving. Single DB write.
2. `ListBase._archiveItem` — passes `listItem.id` as `parentListId`.
3. `ListBase._clearCompleted` — passes `listItem.id` for each archived item.
4. `ArchivePage.js` restore handler — reads `item.meta.parentListId`, loads the parent list, re-adds the item ref (appended at end with `order = items.length`), saves the list, then unarchives the item.
- **Edge cases handled:**
- Parent list deleted/archived → `getItem` returns null → skip re-adding, item restored as standalone orphan.
- Ref already exists in parent list (shouldn't happen, defensive) → skip duplicate.
- Notes archived without a parent list → `parentListId` is undefined → skip re-adding, note restored as standalone.
- Result: restore works correctly even if the list's `items[]` ref was pruned from the DB by later mutations. Items know where they came from.
- Moved list reordering bug from Active → Recently Completed.
- Pulled `_clearCompleted` orphan risk into Active (slot 1 of 3).
- Active queue now:
1. Fix _clearCompleted saving list before archiving items (orphaned items on failure)
2. Fix showError() alert-modal missing
3. Fix ImportExportService revoking object URL before download starts
### 2026-07-01 — API.fetch Fix Completed + List Reordering Bug Investigated
- User completed `API.fetch` error swallowing fix. Moved to Recently Completed.
- Active queue refilled to max 3:
1. List reordering index mismatch (investigated and detailed below)
2. `showError()` alert-modal missing (pulled from Next Up)
3. `ImportExportService` object URL revoke race (remains)
- **List reordering root cause identified:** `DBManager.archiveItem()` does not remove the child's ref from `listItem.items[]`. DOM renders only non-archived items (`_getLinkedItems()` filters them). `DraggableList` indices are DOM-based. `ListBase._reorderItem` applies DOM indices directly to `listItem.items`, which still contains archived refs. This causes the wrong item to move. `_moveItem` also swaps with invisible archived refs, appearing to do nothing. `ListWidget` pagination compounds the mismatch because `#offset` is computed on the filtered array but applied to the unfiltered `items[]`.
- **Suggested fix:** In `_reorderItem`, resolve item IDs from `_getLinkedItems()` before splicing `listItem.items`. In `_moveItem`, skip archived refs when finding swap targets. Optionally prune dead archived refs on list load.
- Next Up now has: `_clearCompleted` orphan risk, weather coordinate validation, ShareView 3-arg confirm.
### 2026-07-12 — PM Mode Handover + Active Bug Verification
- **Role change:** Switched from code-author to project manager mode per user direction.
- **Active bug verification (all 3 still present):**
1. **`_clearCompleted` orphan risk:** `ListBase.js:371` still calls `DBManager.saveItem(listItem)` (removing refs) BEFORE the `archiveItem` loop. If archive fails partway, items become orphaned.
2. **`showError()` alert-modal missing:** `index.html` has no `