diff --git a/docs/superpowers/plans/2026-05-10-v032-cleanup.md b/docs/superpowers/plans/2026-05-10-v032-cleanup.md new file mode 100644 index 0000000..1a2d1a0 --- /dev/null +++ b/docs/superpowers/plans/2026-05-10-v032-cleanup.md @@ -0,0 +1,1039 @@ +# v0.3.2 Cleanup Cut Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** v024-backlog 잔여 23건 중 잠재 bug 4 + cosmetic 6 + 기록 정리 2 = 12건 일괄 처리 + time-dependent test flake fix. dogfood baseline 정리. + +**Architecture:** 기능 추가 X. 기존 production 코드 수정 + 단위 테스트 보강. canonical helper 재활용 (`src/shared/util/kstDate.ts`). 8 task = 8 commit (TDD per task). 단일 PR. + +**Tech Stack:** TypeScript 5 / Electron 41 / vitest / better-sqlite3 / undici / zod / RTL + +**Spec:** [docs/superpowers/specs/2026-05-10-v032-cleanup-design.md](../specs/2026-05-10-v032-cleanup-design.md) + +--- + +## File Structure + +| File | Task | 변경 | +|---|---|---| +| `src/main/repository/NoteRepository.ts` | 1, 4 | `create(input, now?: Date)` signature + KST import | +| `src/main/repository/ftsHelpers.ts` | 4 | KST import | +| `src/main/services/BackupService.ts` | 4 | KST import | +| `src/main/services/ContinuityService.ts` | 4 | KST import | +| `src/renderer/inbox/components/NoteCard.tsx` | 4 | KST import | +| `src/main/ai/AiWorker.ts` | 2, 6 | vocabSet COLLATE + per-tag Promise.all | +| `src/main/ai/LocalOllamaProvider.ts` | 3 | classifyFetchError + reason mask | +| `src/renderer/inbox/App.tsx` | 5 | 탭 `role="tab"` + `aria-selected` | +| `src/renderer/inbox/store.ts` | 5 | `loadExpired` action 제거 | +| `src/main/ipc/inboxApi.ts` | 7 | recall handle→on | +| `src/preload/index.ts` | 7 | recall ipcRenderer.send | +| `src/shared/types.ts` | 7 | recall return `void` (Promise X) | +| `src/main/services/CaptureService.ts` | 7 | telemetry `.catch` → debug log | +| `tests/unit/NoteRevisions.test.ts` | 1 | v1 capture 시간 주입 | +| `tests/unit/NoteRepository.upsertFromSync.test.ts` | 1 | 동 | +| `tests/unit/NoteRepository.test.ts` | 1 | create now param 단위 | +| `tests/unit/AiWorker.test.ts` | 2, 6 | vocabSet 3 + Promise.all 회귀 | +| `tests/unit/LocalOllamaProvider.test.ts` | 3 | classifyFetchError 4 | +| `tests/unit/App.test.tsx` | 5 | aria-selected assertion | +| `tests/unit/store.expired.test.ts` | 5 | `loadExpired` test 제거 | +| `tests/unit/recall-ipc.test.ts` (신규) | 7 | ipcRenderer.send 검증 | +| `package.json` | 8 | 0.3.1 → 0.3.2 | +| `docs/superpowers/v024-backlog.md` | 8 | 처리 이력 갱신 | +| `~/.claude/projects/.../memory/project_v022_feedback.md` | 8 | 삭제 | +| `~/.claude/projects/.../memory/MEMORY.md` | 8 | 라인 제거 | + +--- + +## Task 1: Time-dependent test flake fix + +**Files:** + +- Modify: `src/main/repository/NoteRepository.ts:82-105` (create signature) +- Modify: `tests/unit/NoteRevisions.test.ts:22-105` (v1 capture 시간 주입 4 testcase) +- Modify: `tests/unit/NoteRepository.upsertFromSync.test.ts:10-93` (v1 capture 시간 주입 2 testcase) +- Test: `tests/unit/NoteRepository.test.ts` (now param 단위 +2) + +### Step 1: Write the failing test (create now param) + +Add to `tests/unit/NoteRepository.test.ts` end of describe block: + +```ts +it('create accepts explicit now param', () => { + const fixed = new Date('2026-05-09T10:00:00.000Z'); + const { id } = repo.create({ rawText: 'hello' }, fixed); + const note = repo.findById(id)!; + expect(note.createdAt).toBe('2026-05-09T10:00:00.000Z'); + expect(note.updatedAt).toBe('2026-05-09T10:00:00.000Z'); +}); + +it('create defaults now to new Date when omitted', () => { + const before = Date.now(); + const { id } = repo.create({ rawText: 'hello' }); + const after = Date.now(); + const note = repo.findById(id)!; + const ts = new Date(note.createdAt).getTime(); + expect(ts).toBeGreaterThanOrEqual(before); + expect(ts).toBeLessThanOrEqual(after); +}); +``` + +### Step 2: Run test to verify it fails + +``` +npx vitest run tests/unit/NoteRepository.test.ts -t "create accepts explicit now param" +``` + +Expected: FAIL with `Expected 1 arguments, but got 2` typecheck error or runtime ignore of 2nd arg. + +### Step 3: Update `NoteRepository.create` signature + +Modify `src/main/repository/NoteRepository.ts:82-105`: + +```ts +create(input: CreateNoteInput, now: Date = new Date()): { id: string } { + const id = uuidv7(); + const ts = now.toISOString(); + const aiStatus: AiStatus = input.aiStatus ?? 'pending'; + const tx = this.db.transaction(() => { + this.db + .prepare(`INSERT INTO notes (id, raw_text, ai_status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?)`) + .run(id, input.rawText, aiStatus, ts, ts); + this.db + .prepare(`INSERT INTO note_revisions (note_id, raw_text, edited_at, edited_by) + VALUES (?, ?, ?, 'capture')`) + .run(id, input.rawText, ts); + if (aiStatus === 'pending') { + this.db + .prepare(`INSERT INTO pending_jobs (note_id, attempts, next_run_at) + VALUES (?, 0, ?)`) + .run(id, ts); + } + }); + tx(); + return { id }; +} +``` + +### Step 4: Run new tests to verify they pass + +``` +npx vitest run tests/unit/NoteRepository.test.ts -t "create accepts explicit now param" +npx vitest run tests/unit/NoteRepository.test.ts -t "create defaults now" +``` + +Expected: PASS + +### Step 5: Update flake testcases — `NoteRevisions.test.ts` + +Modify `tests/unit/NoteRevisions.test.ts` — find every `repo.create(...)` followed by a `repo.updateRawText(..., new Date('2026-05-10T00:00:00Z'))` and pass v1 capture time `new Date('2026-05-09T00:00:00Z')` (a day before v2): + +Change all of these patterns: + +```ts +const { id } = repo.create({ rawText: 'v1' }); +// ... +repo.updateRawText(id, 'v2', new Date('2026-05-10T00:00:00Z')); +``` + +To: + +```ts +const v1At = new Date('2026-05-09T00:00:00Z'); +const { id } = repo.create({ rawText: 'v1' }, v1At); +// ... +repo.updateRawText(id, 'v2', new Date('2026-05-10T00:00:00Z')); +``` + +Also fix line 30 expectation if it's checking v1 timestamp — change to `'2026-05-09T00:00:00.000Z'` if comparing `notes.updated_at` after `updateRawText`. Actually `updated_at` after `updateRawText` should be the v2 time. Keep `'2026-05-10T00:00:00.000Z'` as-is. + +Find line 40: `expect(revs.at(1)!.edited_at).toBe('2026-05-10T00:00:00.000Z');` — `revs.at(1)` (second element, DESC ordered) should be the OLDER revision = v1 capture. Change expected to `'2026-05-09T00:00:00.000Z'`. + +Apply same pattern to all 4 testcases (lines 22, 45, 57, 77, 105 cluster). + +### Step 6: Update flake testcases — `upsertFromSync.test.ts` + +Modify `tests/unit/NoteRepository.upsertFromSync.test.ts:10-93` — locate the `created = repo.create(...)` calls. Pass explicit time `new Date('2026-05-09T00:00:00Z')`: + +```ts +const created = repo.create({ rawText: 'baseline' }, new Date('2026-05-09T00:00:00Z')); +``` + +This ensures `created.updatedAt = '2026-05-09T00:00:00.000Z'` < `'2026-05-10T00:00:00Z'` (sync input) → sync wins consistently regardless of system clock. + +### Step 7: Run full suite to verify all pass + +``` +npx vitest run tests/unit/NoteRevisions.test.ts tests/unit/NoteRepository.upsertFromSync.test.ts tests/unit/NoteRepository.test.ts +``` + +Expected: PASS — flake testcases now deterministic. + +### Step 8: Commit + +```bash +git add src/main/repository/NoteRepository.ts tests/unit/NoteRepository.test.ts tests/unit/NoteRevisions.test.ts tests/unit/NoteRepository.upsertFromSync.test.ts +git commit -m "$(cat <<'EOF' +fix(v032): NoteRepository.create now param + time-dep test flake fix + +- create(input, now?: Date) signature 추가 (기존 setStatus/updateRawText 패턴 정합) +- NoteRevisions.test.ts 4 testcase v1 capture 시간 명시 주입 (2026-05-09T00:00:00Z) +- upsertFromSync.test.ts 2 testcase v1 capture 시간 명시 주입 +- 시스템 시계가 2026-05-10T00:00:00Z 초과 시 DESC ordering 깨지던 회귀 회복 + +backlog: time-dependent flake (Cut F audit 발견) +EOF +)" +``` + +--- + +## Task 2: vocabSet COLLATE NOCASE 정합 (#31) + +**Files:** + +- Modify: `src/main/ai/AiWorker.ts:189-191` +- Test: `tests/unit/AiWorker.test.ts` (+3) + +### Step 1: Write 3 failing tests + +Add to `tests/unit/AiWorker.test.ts` (end of vocab describe block, or add new describe): + +```ts +describe('vocab COLLATE NOCASE', () => { + it('hits when vocab has lowercase and AI returns capital', async () => { + // existing test setup pattern: mock repo.getTopUsedTags returns ['design'] + // mock provider returns tags: ['Design'] + // assert telemetry emit kind === 'tag_vocab_hit' (not miss) + // ... follow existing AiWorker.test.ts test setup ... + }); + + it('hits when vocab has capital and AI returns lowercase', async () => { + // repo.getTopUsedTags returns ['Design'] + // provider returns tags: ['design'] + // assert tag_vocab_hit + }); + + it('still hits when both vocab and AI tag are same lowercase (regression)', async () => { + // repo.getTopUsedTags returns ['design'] + // provider returns tags: ['design'] + // assert tag_vocab_hit + }); +}); +``` + +Use the existing `AiWorker.test.ts` test setup — mock `repo`, `holder`, `telemetry`. Spy on `telemetry.emit` and assert kinds. + +### Step 2: Run tests to verify they fail + +``` +npx vitest run tests/unit/AiWorker.test.ts -t "COLLATE" +``` + +Expected: FAIL — first 2 tests assert `tag_vocab_hit` but current code emits `tag_vocab_miss` due to strict-eq. + +### Step 3: Implement vocabSet lowercase normalize + +Modify `src/main/ai/AiWorker.ts:189-191`: + +```ts +const vocabSet = new Set(vocab.map((v) => v.toLowerCase())); +for (const tagName of new Set(res.tags)) { + if (vocabSet.has(tagName.toLowerCase())) { + const tagId = this.repo.getTagIdByName(tagName); + if (tagId !== null) { + await this.telemetry.emit({ + kind: 'tag_vocab_hit', + payload: { tagId, vocabSize: vocab.length } + }).catch(() => {}); + } + } else { + await this.telemetry.emit({ + kind: 'tag_vocab_miss', + payload: { vocabSize: vocab.length } + }).catch(() => {}); + } +} +``` + +### Step 4: Run tests to verify pass + +``` +npx vitest run tests/unit/AiWorker.test.ts -t "COLLATE" +``` + +Expected: PASS — all 3 tests green. + +### Step 5: Run full AiWorker.test.ts to verify no regression + +``` +npx vitest run tests/unit/AiWorker.test.ts +``` + +Expected: All existing tests still PASS. + +### Step 6: Commit + +```bash +git add src/main/ai/AiWorker.ts tests/unit/AiWorker.test.ts +git commit -m "$(cat <<'EOF' +fix(v032): AiWorker vocabSet COLLATE NOCASE 정합 (#31) + +DB tags.name 가 COLLATE NOCASE 인데 vocabSet 은 strict-eq 였음 → +대문자/소문자 vocab 과 AI tag 가 다를 때 silently skip. + +vocab.toLowerCase() + tagName.toLowerCase() 양쪽 normalize 로 정합. +EOF +)" +``` + +--- + +## Task 3: PII reason 마스킹 (#39) + +**Files:** + +- Modify: `src/main/ai/LocalOllamaProvider.ts:113-124` +- Test: `tests/unit/LocalOllamaProvider.test.ts` (+4) + +### Step 1: Write 4 failing tests + +Add to `tests/unit/LocalOllamaProvider.test.ts`: + +```ts +describe('healthCheck PII reason masking', () => { + it('classifies ECONNREFUSED as network', async () => { + const provider = new LocalOllamaProvider({ endpoint: 'http://192.168.1.5:11434' }); + // mock undici request to throw Error('connect ECONNREFUSED 192.168.1.5:11434') + vi.spyOn(undici, 'request').mockRejectedValueOnce(new Error('connect ECONNREFUSED 192.168.1.5:11434')); + const r = await provider.healthCheck(); + expect(r).toEqual({ ok: false, reason: 'unreachable:network' }); + }); + + it('classifies AbortError/timeout as timeout', async () => { + const provider = new LocalOllamaProvider({ endpoint: 'http://localhost:11434' }); + vi.spyOn(undici, 'request').mockRejectedValueOnce(new Error('The operation was aborted due to timeout')); + const r = await provider.healthCheck(); + expect(r).toEqual({ ok: false, reason: 'unreachable:timeout' }); + }); + + it('classifies ENOTFOUND as dns', async () => { + const provider = new LocalOllamaProvider({ endpoint: 'http://nonexistent.local:11434' }); + vi.spyOn(undici, 'request').mockRejectedValueOnce(new Error('getaddrinfo ENOTFOUND nonexistent.local')); + const r = await provider.healthCheck(); + expect(r).toEqual({ ok: false, reason: 'unreachable:dns' }); + }); + + it('falls back to other for unknown errors', async () => { + const provider = new LocalOllamaProvider({ endpoint: 'http://localhost:11434' }); + vi.spyOn(undici, 'request').mockRejectedValueOnce(new Error('something weird happened')); + const r = await provider.healthCheck(); + expect(r).toEqual({ ok: false, reason: 'unreachable:other' }); + }); +}); +``` + +(Adjust `vi.spyOn` based on existing `LocalOllamaProvider.test.ts` mock pattern — likely `vi.mock('undici')` at top with `request: vi.fn()`.) + +### Step 2: Run tests to verify they fail + +``` +npx vitest run tests/unit/LocalOllamaProvider.test.ts -t "PII reason masking" +``` + +Expected: FAIL — current code returns `unreachable: connect ECONNREFUSED 192.168.1.5:11434` (full message including IP). + +### Step 3: Add `classifyFetchError` helper + apply + +Modify `src/main/ai/LocalOllamaProvider.ts` — add helper at module top (after imports, line 7-ish): + +```ts +function classifyFetchError(e: unknown): 'network' | 'timeout' | 'dns' | 'other' { + const msg = ((e as Error)?.message ?? '').toLowerCase(); + if (msg.includes('aborted') || msg.includes('timeout')) return 'timeout'; + if (msg.includes('econnrefused') || msg.includes('econnreset')) return 'network'; + if (msg.includes('enotfound') || msg.includes('eai_again')) return 'dns'; + return 'other'; +} +``` + +Modify `healthCheck()` line 121-123: + +```ts +} catch (err) { + const cls = classifyFetchError(err); + return { ok: false, reason: `unreachable:${cls}` }; +} +``` + +### Step 4: Run tests to verify pass + +``` +npx vitest run tests/unit/LocalOllamaProvider.test.ts -t "PII reason masking" +``` + +Expected: PASS — all 4 tests green. + +### Step 5: Run full LocalOllamaProvider.test.ts to verify no regression + +``` +npx vitest run tests/unit/LocalOllamaProvider.test.ts +``` + +Expected: existing tests still PASS. Existing tests checking `reason: 'unreachable: ...'` may break — update them to match new format `unreachable:other` or `unreachable:network`. + +### Step 6: Commit + +```bash +git add src/main/ai/LocalOllamaProvider.ts tests/unit/LocalOllamaProvider.test.ts +git commit -m "$(cat <<'EOF' +fix(v032): healthCheck reason PII 마스킹 (#39) + +err.message 안에 LAN endpoint URL (예: 192.168.x.x:11434) 이 포함될 수 +있어 telemetry 파일에 PII 우회 노출. v0.2.3.1 in-app endpoint UI 가 LAN +사용을 흔하게 만들어 노출 경로 확대. + +classifyFetchError 로 error class 분류 (network/timeout/dns/other) 후 +reason: 'unreachable:{class}' 형태만 emit. host/IP 노출 0. +EOF +)" +``` + +--- + +## Task 4: KST inline 5 callsite migration (#19) + +**Files:** + +- Modify: `src/main/repository/NoteRepository.ts:1042-1047` (delete inline + import) +- Modify: `src/main/repository/ftsHelpers.ts:18-29` +- Modify: `src/main/services/BackupService.ts:6-10` +- Modify: `src/main/services/ContinuityService.ts:4-15` +- Modify: `src/renderer/inbox/components/NoteCard.tsx:30-31` + +### Step 1: NoteRepository.ts migration + +Replace `src/main/repository/NoteRepository.ts:1042-1047`: + +Before: +```ts +const KST_OFFSET_MS = 9 * 60 * 60 * 1000; +const kstNow = new Date(now.getTime() + KST_OFFSET_MS); +const kstYear = kstNow.getUTCFullYear(); +const kstMonth = kstNow.getUTCMonth(); +const kstDate = kstNow.getUTCDate(); +const kstMidnightUtc = Date.UTC(kstYear, kstMonth, kstDate) - KST_OFFSET_MS; +``` + +After: +```ts +const kstNow = new Date(now.getTime() + KST_OFFSET_MS); +const kstYear = kstNow.getUTCFullYear(); +const kstMonth = kstNow.getUTCMonth(); +const kstDate = kstNow.getUTCDate(); +const kstMidnightUtc = Date.UTC(kstYear, kstMonth, kstDate) - KST_OFFSET_MS; +``` + +Add at top of file (with other imports): +```ts +import { KST_OFFSET_MS } from '../../shared/util/kstDate.js'; +``` + +### Step 2: ftsHelpers.ts migration + +Modify `src/main/repository/ftsHelpers.ts:18`: + +Before: +```ts +const KST_OFFSET_MS = 9 * 60 * 60 * 1000; +``` + +Replace with import: +```ts +import { KST_OFFSET_MS } from '../../shared/util/kstDate.js'; +``` + +(Remove the `const` line.) + +### Step 3: BackupService.ts migration + +Modify `src/main/services/BackupService.ts:6`: + +Before: +```ts +const KST_OFFSET_MS = 9 * 60 * 60 * 1000; +``` + +Replace with import (added to imports at top): +```ts +import { KST_OFFSET_MS } from '../../shared/util/kstDate.js'; +``` + +### Step 4: ContinuityService.ts migration + +Modify `src/main/services/ContinuityService.ts:4`: + +Same pattern — replace local const with import. + +### Step 5: NoteCard.tsx migration + +Modify `src/renderer/inbox/components/NoteCard.tsx:30-31`: + +Before: +```tsx +const KST_OFFSET_MS = 9 * 60 * 60 * 1000; +const k = new Date(Date.now() + KST_OFFSET_MS); +``` + +After: +```tsx +const k = new Date(Date.now() + KST_OFFSET_MS); +``` + +Add import at top: +```tsx +import { KST_OFFSET_MS } from '@shared/util/kstDate.js'; +``` + +(Use the renderer alias `@shared/...` as already used elsewhere in renderer.) + +### Step 6: Verify no other inline duplicates remain + +``` +git grep -n "KST_OFFSET_MS = 9" -- src/ +``` + +Expected: only `src/shared/util/kstDate.ts:6` (canonical export) — no inline duplicates. + +### Step 7: Run full suite to verify regression + +``` +npm run typecheck +npm test +``` + +Expected: typecheck 0 errors, all existing tests PASS (algorithm identical, just import path). + +### Step 8: Commit + +```bash +git add src/main/repository/NoteRepository.ts src/main/repository/ftsHelpers.ts src/main/services/BackupService.ts src/main/services/ContinuityService.ts src/renderer/inbox/components/NoteCard.tsx +git commit -m "$(cat <<'EOF' +refactor(v032): KST_OFFSET_MS inline → @shared/util/kstDate import (#19) + +5 callsite (NoteRepository, ftsHelpers, BackupService, ContinuityService, +NoteCard) 모두 canonical export 로 정리. 알고리즘 동일 (9 * 60 * 60 * 1000), +회귀 PASS 검증. + +v0.2.6 commit 3cfa60b 가 4 callsite migrate 했지만 5 callsite 잔여. +Cut F audit 에서 발견. +EOF +)" +``` + +--- + +## Task 5: 탭 ARIA + loadExpired 제거 (#14, #18) + +**Files:** + +- Modify: `src/renderer/inbox/App.tsx:107-115` (탭 button → role="tab" + aria-selected) +- Modify: `src/renderer/inbox/store.ts:61, 238-241` (loadExpired 제거) +- Modify: `tests/unit/App.test.tsx` (+1 aria-selected assertion) +- Modify: `tests/unit/store.expired.test.ts:55-58` (loadExpired test 제거) + +### Step 1: Write failing test for aria-selected + +Add to `tests/unit/App.test.tsx` (end of describe — find existing tab navigation tests): + +```ts +it('inbox tab has aria-selected="true" when active', async () => { + // existing render setup ... + const inboxTab = screen.getByRole('tab', { name: /Inbox/ }); + expect(inboxTab).toHaveAttribute('aria-selected', 'true'); +}); +``` + +If existing test was using `aria-pressed`, update those references too — they should query by `role="tab"` going forward. + +### Step 2: Run test to verify it fails + +``` +npx vitest run tests/unit/App.test.tsx -t "aria-selected" +``` + +Expected: FAIL — current `aria-pressed` doesn't expose `role="tab"`. + +### Step 3: Update App.tsx tab buttons + +Modify `src/renderer/inbox/App.tsx:107-115`: + +Before: +```tsx +