# Code Quality Minor Polish Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Ship 5 cosmetic / hygiene fixes from the 2026-05-21 review.

**Architecture:** All five are file-local. M3 has a cross-spec lock on `src/codec/sseRewriteStream.ts` (Critical Task 8 → Important Task 9 → here). M1 has a cross-spec lock on `src/proxy/handler.ts` (Critical Task 9 → Important Task 4 → here). Everything else parallelizable.

**Tech Stack:** TypeScript strict, Bun runtime, `bun:sqlite` 3.51.2.

**Source spec:** `/home/user/Projects/fewtok/docs/superpowers/specs/code-quality-minor-design.md`

---

## Wave Plan

| Wave | Tasks | Files touched | Safe to parallelize? |
|------|-------|---------------|----------------------|
| 1 | M2 | src/proxy/sse-usage.ts | ✅ isolated |
| 1 | M4 | src/stats/writer.ts | ✅ isolated (but ordered after Important Task 3 which adds openStatsDb to same file — verify first) |
| 1 | M5 | src/stats/pricing.ts, src/stats/writer.ts, src/learn/passB-macros.tsC | ❌ src/learn/passB-macros.tsM overlap with M4; src/stats/reporter.ts overlap nothing |
| 2 | M1 | src/proxy/handler.ts | depends on Critical Task 9 + Important Task 4 (file lock) |
| 2 | M3 | src/components/VeryLongDealDetail.tsxC | depends on Critical Task 8 + Important Task 9 (file lock) |

Serialized order within src/stats/writer.ts: Important Task 1 (I3) → Important Task 3 (I7) → M4 → M5.

---

## Pre-flight

```bash
git status
bun tsc --noEmit 2>&1 | head -30
git log --oneline main -- src/learn/passB-macros.tsM src/codec/sseRewriteStream.ts src/proxy/handler.ts | head -10
```

Verify cross-spec prerequisites (see each task's Blocked-by).

---

### Task 1 (M2): Fix sse-usage.ts JSDoc ordering

**Wave:** 1
**Blocks:** —
**Blocked by:** —

**Files:**
- Modify: `src/proxy/sse-usage.ts` (lines 75-86, 117)

- [ ] **Step 1: Read current layout**

```bash
sed -n '70,125p' src/proxy/sse-usage.ts
```

Two consecutive docblocks at 75-84, `dispatchFrame` at 86, `wrapSseForUsage` at 117. First docblock describes `wrapSseForUsage` but sits above `dispatchFrame`.

- [ ] **Step 2: Relocate first docblock**

Cut the docblock at lines 75-79 (the one describing `wrapSseForUsage` — `Wraps an SSE ReadableStream<Uint8Array>, ...`). Paste it directly above `export function wrapSseForUsage(...)` at line 117. Leave the `dispatchFrame` docblock (lines 80-85) where it is — it's already above its function.

- [ ] **Step 3: Visual verify**

```bash
sed -n '70,125p' src/components/VeryLongDealDetail.tsxV
```

Each docblock now sits immediately above the function it documents.

- [ ] **Step 4: tsc**

```bash
bun tsc --noEmit 2>&1 | head -10
```

- [ ] **Step 5: Commit**

```bash
git add src/components/VeryLongDealDetail.tsxV
git commit -m "docs(codec): relocate sse-usage.ts JSDoc blocks above correct functions"
```

---

### Task 2 (M4): Drop vestigial expandedOutputTokens

**Wave:** 1
**Blocks:** Task 3 (M5 — same src/learn/passB-macros.tsM)
**Blocked by:** Important Task 3 (I7 — also touches src/stats/writer.ts)

**Files:**
- Modify: `src/stats/writer.ts` (lines 15, 121, 148, 188 + CREATE TABLE DDL + initStatsSchema)

**ADVISOR REFINEMENT:** Use `PRAGMA table_info(requests)` conditional check, NOT try/catch. Also remove column from CREATE TABLE DDL as a separate explicit step.

- [ ] **Step 1: Locate sites**

```bash
grep -n "expandedOutputTokens\|expanded_output_tokens" src/stats/writer.ts
```

Expected hits: type declaration (~15), CREATE TABLE DDL (column position), initStatsSchema body, writer init payload (~121), writer assign (~148), bind position (~188).

- [ ] **Step 2: Remove column from CREATE TABLE DDL**

In `initStatsSchema` find the CREATE TABLE block. Delete the `expanded_output_tokens INTEGER NOT NULL DEFAULT 0,` line (or whatever the actual shape is). Fresh installs never get the column.

- [ ] **Step 3: Add PRAGMA-conditional DROP COLUMN migration in initStatsSchema**

Immediately after the CREATE TABLE statement, before any other DDL, run a conditional drop. Use bun:sqlite `db.query(...).all()` to read `PRAGMA table_info(requests)`, then if any row has `name === "expanded_output_tokens"` run `ALTER TABLE requests DROP COLUMN expanded_output_tokens` via the existing schema-DDL execution method already used in this file (match the surrounding style — likely `db.run(...)` or the same call used for `CREATE TABLE`).

Idempotent: existing DBs lose the column on first open; fresh DBs skip the ALTER because PRAGMA returns no matching name.

Code shape (adapt to match the file's existing DDL-call convention):

```ts
const cols = db.query("PRAGMA table_info(requests)").all() as Array<{ name: string }>;
if (cols.some(c => c.name === "expanded_output_tokens")) {
  db.run("ALTER TABLE requests DROP COLUMN expanded_output_tokens");
}
```

- [ ] **Step 4: Remove field from RequestMeta type**

In `src/stats/writer.ts` around line 15 (type declaration), delete the `expandedOutputTokens: number;` line.

- [ ] **Step 5: Remove writer-payload init**

Around line 121 — delete `expandedOutputTokens: 0,` from the initial-row builder.

- [ ] **Step 6: Remove writer assign**

Around line 148 — delete `expandedOutputTokens: meta.rawOutputTokens,`.

- [ ] **Step 7: Remove bind position**

Around line 188 — drop the bind for `r.expandedOutputTokens`. Re-number subsequent positional binds if positional `?` syntax is used; if named binds, just delete the line.

- [ ] **Step 8: Verify zero stragglers**

```bash
grep -rn "expandedOutputTokens\|expanded_output_tokens" src/ | grep -v "DROP COLUMN" | grep -v "table_info"
```

Should return zero (the DROP COLUMN string literal and PRAGMA literal are the only legitimate hits — they're column-name references inside SQL).

- [ ] **Step 9: Idempotency in-memory test (no live proxy)**

Worktree policy: no live-proxy run. Prove idempotency on `Database(":memory:")` instead — deterministic.

```bash
bun -e '
import { Database } from "bun:sqlite";
import { initStatsSchema } from "./src/stats/openStats";
const db = new Database(":memory:");
// Simulate pre-migration DB shape: add legacy column manually
db.run("CREATE TABLE requests (id INTEGER, expanded_output_tokens INTEGER)");
initStatsSchema(db);  // first open → DROP
const before = db.query("PRAGMA table_info(requests)").all().map((c:any)=>c.name);
initStatsSchema(db);  // second open → no-op
const after = db.query("PRAGMA table_info(requests)").all().map((c:any)=>c.name);
console.log({ before, after });
if (before.includes("expanded_output_tokens")) throw new Error("DROP failed");
if (JSON.stringify(before) !== JSON.stringify(after)) throw new Error("not idempotent");
console.log("idempotent: ok");
'
```

Adapt the synthetic CREATE TABLE shape to match the production schema if `initStatsSchema` is stricter. Goal: prove the conditional skip path runs cleanly on a DB that already lacks the column.

- [ ] **Step 10: tsc + tests**

```bash
bun tsc --noEmit 2>&1 | head -20
bun test src/stats 2>&1 | tail -10
```

- [ ] **Step 11: Commit**

```bash
git add src/stats/writer.ts
git commit -m "fix(stats): drop vestigial expanded_output_tokens column (PRAGMA-conditional)"
```

---

### Task 3 (M5): Extract BYTES_PER_TOKEN_FALLBACK constant

**Wave:** 1
**Blocks:** —
**Blocked by:** Task 2 (M4 — same src/stats/writer.ts)

**Files:**
- Modify: `src/stats/pricing.ts` (add `BYTES_PER_TOKEN_FALLBACK`)
- Modify: `src/stats/writer.ts` (lines 129-130)
- Modify: `src/learn/passB-macros.tsC` (lines 66-67, 378-379)

- [ ] **Step 1: Verify pricing.ts exists**

```bash
ls src/stats/pricing.ts && grep -n "bytesPerToken" src/stats/pricing.ts | head -5
```

If file missing, create it minimally with the constant; otherwise insert next to `bytesPerToken`.

- [ ] **Step 2: Add constant**

In `src/stats/pricing.ts`:

```ts
export const BYTES_PER_TOKEN_FALLBACK = 4;
```

- [ ] **Step 3: Migrate openStats.ts sites**

In `src/stats/writer.ts:129-130`:

```ts
import { BYTES_PER_TOKEN_FALLBACK } from "./pricing";
// …
rawBytes: row.tokensBefore * BYTES_PER_TOKEN_FALLBACK,
sentBytes: row.tokensAfter * BYTES_PER_TOKEN_FALLBACK,
```

- [ ] **Step 4: Migrate gain.ts sites**

In `src/stats/reporter.ts:66-67` and `:378-379`:

```ts
import { BYTES_PER_TOKEN_FALLBACK } from "./pricing";
// …
Math.floor(r.raw_bytes / BYTES_PER_TOKEN_FALLBACK)
```

Apply to both sites — identical pattern.

- [ ] **Step 5: Verify zero stragglers in token↔byte arithmetic**

```bash
grep -rn "[* /] 4\b" src/stats/ | grep -v "BYTES_PER_TOKEN_FALLBACK"
```

Should return zero hits in token/byte conversion contexts. (Other `4` literals — version numbers, port offsets — are fine; spot-check what grep returns.)

- [ ] **Step 6: Render parity check**

Capture `ft gain` output before starting and after the change; `diff` must be byte-equal.

```bash
ft gain > /tmp/gain-after-m5.txt
diff /tmp/gain-before-m5.txt /tmp/gain-after-m5.txt
```

- [ ] **Step 7: tsc + tests**

```bash
bun tsc --noEmit 2>&1 | head -20
bun test src/stats 2>&1 | tail -10
```

- [ ] **Step 8: Commit**

```bash
git add src/stats/pricing.ts src/stats/writer.ts src/stats/reporter.ts
git commit -m "refactor(stats): extract BYTES_PER_TOKEN_FALLBACK constant"
```

---

### Task 4 (M1): Document rtkInstalled boot-time probe

**Wave:** 2
**Blocks:** —
**Blocked by:** Critical Task 9 + Important Task 4 (cross-spec lock on src/proxy/handler.ts)

**Files:**
- Modify: `src/proxy/handler.ts` (immediately above `rtkInstalled` function)

- [ ] **Step 1: Verify prerequisites are on main**

```bash
git log --oneline main -- src/proxy/handler.ts | head -10
grep -n "rtkInstalled\|SHARED_SNAPSHOT_SESSION" src/proxy/handler.ts | head -5
```

Both Critical Task 9 (SessionCache wiring) and Important Task 4 (SHARED_SNAPSHOT_SESSION) must be merged.

- [ ] **Step 2: Locate rtkInstalled**

```bash
grep -n "rtkInstalled\|function rtkInstalled" src/proxy/handler.ts
```

- [ ] **Step 3: Insert comment above the function**

Using Edit, add immediately above `function rtkInstalled(): boolean {`:

```ts
// Probed once at handler construction. If rtk is installed after the proxy starts,
// the new install is not picked up until the proxy reloads (SIGHUP) or restarts.
function rtkInstalled(): boolean {
```

No code change.

- [ ] **Step 4: tsc**

```bash
bun tsc --noEmit 2>&1 | head -10
```

- [ ] **Step 5: Commit**

```bash
git add src/proxy/handler.ts
git commit -m "docs(proxy): document rtkInstalled boot-time probe caveat"
```

---

### Task 5 (M3): Recover sigil-mangled comment in sseRewriteStream

**Wave:** 2
**Blocks:** —
**Blocked by:** Critical Task 8 + Important Task 9 (cross-spec lock on src/codec/sseRewriteStream.ts)

**Files:**
- Modify: `src/codec/sseRewriteStream.ts` (line 65 area, plus any other sigil-leak hits)

- [ ] **Step 1: Verify prerequisites on main**

```bash
git log --oneline main -- src/codec/sseRewriteStream.ts | head -10
grep -n "carryStr" src/codec/sseRewriteStream.ts
```

- [ ] **Step 2: Find all sigil leaks in src/**

```bash
grep -rn "// Carry is stored as a string (decoded UTF-8) for char-boundary" src/
```

Each hit is a separately-mangled comment that needs context-driven replacement.

- [ ] **Step 3: Locate target comment**

```bash
sed -n '60,72p' src/codec/sseRewriteStream.ts
```

Confirm the sigil-mangled comment sits directly above `let carryStr = "";`.

- [ ] **Step 4: Replace with intent-true comment**

Using Edit, replace the mangled comment with:

```ts
// Carry buffer for SSE bytes split across chunk boundaries.
// Holds the trailing slice that didn't end on a \n\n event boundary; the next
// chunk prepends it before re-splitting.
let carryStr = "";
```

- [ ] **Step 5: For each other sigil leak found in Step 2**

Read surrounding context, write replacement comment that describes actual code intent. If unclear, defer that site to a follow-up (note in commit body).

- [ ] **Step 6: Verify zero sigil-leaks in comments**

```bash
grep -rn "// Carry is stored as a string (decoded UTF-8) for char-boundary" src/
```

Should return zero hits (or only the ones explicitly deferred).

- [ ] **Step 7: tsc + targeted test**

```bash
bun tsc --noEmit 2>&1 | head -10
bun test src/codec 2>&1 | tail -10
```

- [ ] **Step 8: Commit**

```bash
git add src/codec/sseRewriteStream.ts
git commit -m "docs(codec): recover sigil-mangled comments in sseRewriteStream"
```

---

## Cross-Spec Handoff

After Task 4 commits: `src/proxy/handler.ts` writer chain done (Critical → Important → Minor).

After Task 5 commits: `src/codec/sseRewriteStream.ts` writer chain done (Critical → Important → Minor). Safe to start any future work on the file.

## Self-Review Summary

- **Spec coverage:** M1→Task 4, M2→Task 1, M3→Task 5, M4→Task 2, M5→Task 3.
- **Placeholders:** none.
- **Advisor refinement applied:** M4 (Task 2) uses PRAGMA-conditional check (not try/catch) AND has explicit "remove from CREATE TABLE DDL" step (Step 2).
- **Type consistency:** `BYTES_PER_TOKEN_FALLBACK` referenced consistently across import/use sites. `RequestMeta` shape change in M4 — internal type, no external consumer impact.
- **Wave plan check:** src/stats/writer.ts serialization (I3 → I7 → M4 → M5) enforced via Blocked-by. src/proxy/handler.ts and src/codec/sseRewriteStream.ts cross-spec locks documented and gated on Critical+Important task SHAs landing on main.
