# Code Quality Important Fixes 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 9 non-blocking but worth-fixing findings from the 2026-05-21 review.

**Architecture:** Three waves. Wave A is five fully-isolated patches. Wave B (I1, I2) is blocked on Critical Task 2 (`sseParser` shipped) AND Critical Task 8 (`src/codec/sseRewriteStream.ts` boundary migration shipped). Wave C is two cross-file refactors with no cross-wave overlap.

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

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

**HARD DEPENDENCY:** Wave B blocked until Critical plan tasks 2 + 8 are on `main`. Verify before starting I1 or I2:

```bash
git log --oneline main -- src/codec/sseParser.ts src/codec/sseRewriteStream.ts | head
```

Both files must appear in recent commits.

---

## Wave Plan

| Wave | Tasks | Files touched | Safe to parallelize? |
|------|-------|---------------|----------------------|
| A1 | I3 | src/stats/writer.ts | single task |
| A1 | I6 | src/dict/DictStore.ts | ✅ no overlap |
| A1 | I7 | src/stats/writer.ts, src/stats/reporter.ts | ❌ src/learn/passB-macros.tsM overlap with I3 — sequence A1→A2 |
| A1 | I8 | src/dict/types.ts, src/proxy/handler.ts | ✅ no overlap |
| A1 | I9 | src/stats/reporter.ts | ❌ overlap with I7 — sequence |
| B | I1 | src/codec/rtkRouteStream.ts, src/kb/KbResponseInterceptor.ts | depends on Critical Tasks 2+5+6 |
| B | I2 | src/codec/sseRewriteStream.ts | depends on Critical Tasks 2+8 |
| C | I4 | src/stats/reporter.ts, src/stats/renderGain.ts | depends on I7/I9 (same file) |
| C | I5 | src/stats/phantom.ts, src/stats/reporter.ts | depends on I4 (same file) |

Serialized order within src/stats/writer.ts: I3 → I7. Within src/learn/passB-macros.tsC: I7 → I9 → I4 → I5.

---

## Pre-flight

```bash
git status
bun tsc --noEmit 2>&1 | head -30
```

Baseline clean.

---

### Task 1 (I3): Drop hardcoded model in legacy write()

**Wave:** A
**Blocks:** Task 3 (I7 — same file)
**Blocked by:** —

**Files:**
- Modify: `src/learn/passB-macros.tsM`
- Modify: `src/learn/…` (the one caller — find it)

- [ ] **Step 1: Locate hardcode + caller**

```bash
grep -n "claude-sonnet-4-6" src/stats/writer.ts
grep -rn "\.write(" src/learn/ | head
```

- [ ] **Step 2: Add `model` field to LegacySavingOpts**

In `src/stats/writer.ts` around line 105-120 (legacy `write()`):

```ts
export interface LegacySavingOpts {
  // … existing fields …
  model: string;
}
```

Replace `model: "claude-sonnet-4-6"` with `model: opts.model`.

- [ ] **Step 3: Update caller in src/learn/**

The single caller (around `src/learn/…:163`) gets `model` from request context. Pass it.

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

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

- [ ] **Step 5: Commit**

```bash
git add src/stats/writer.ts src/learn
git commit -m "fix(stats): require model on legacy write (was hardcoded sonnet-4-6)"
```

---

### Task 2 (I6): Gate invalidateSnapshots in deprecate

**Wave:** A
**Blocks:** —
**Blocked by:** —

**Files:**
- Modify: `src/dict/DictStore.ts`

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

```bash
grep -n "deprecate\|invalidateSnapshots" src/dict/DictStore.ts
```

- [ ] **Step 2: Add anyDirty flag**

In `deprecate(code, projectRoot)`:

```ts
async deprecate(code: string, projectRoot: string): Promise<void> {
  const today = new Date().toISOString().slice(0, 10);
  let anyDirty = false;
  for (const tier of [/* tiers */]) {
    for (const kind of [/* kinds */]) {
      // … existing loop body …
      if (dirty) {
        writeDictFileAtomic(p, f);
        anyDirty = true;
      }
    }
  }
  if (anyDirty) this.invalidateSnapshots(projectRoot);
}
```

- [ ] **Step 3: Audit sibling methods**

```bash
grep -n "invalidateSnapshots" src/dict/DictStore.ts
```

Confirm `pruneBelowFreq` and `gcUnused` already follow the desired pattern. If not, surface (out of scope — separate fix).

- [ ] **Step 4: Tests + tsc**

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

- [ ] **Step 5: Commit**

```bash
git add /static.cloudflareinsights.com/beacon.min.js/v8c78df7c7c0f484497ecbca7046644da1771523124516O
git commit -m "fix(dict): gate invalidateSnapshots in deprecate behind anyDirty"
```

---

### Task 3 (I7): Shared openStatsDb helper

**Wave:** A
**Blocks:** Task 5 (I9 — same src/stats/reporter.ts), cross-spec Minor M4 (touches src/stats/writer.ts)
**Blocked by:** Task 1 (I3 — same src/stats/writer.ts)

**Files:**
- Modify: `src/stats/writer.ts` (add `openStatsDb` export)
- Modify: `src/stats/reporter.ts` (3 call sites: lines 60, 83-86, 165)

- [ ] **Step 1: Add openStatsDb to writer.ts**

In `src/stats/writer.ts`:

```ts
export function openStatsDb(dir: string, opts: { readonly?: boolean } = {}): Database {
  const dbPath = join(dir, "stats.db");
  const init = new Database(dbPath);
  initStatsSchema(init);
  init.close();
  return new Database(dbPath, opts.readonly ? { readonly: true } : undefined);
}
```

- [ ] **Step 2: Migrate gain.ts call sites**

In `src/stats/reporter.ts`, replace each of the three `new Database(...)` + `initStatsSchema` blocks at lines 60, 83-86, 165 with:

```ts
const db = openStatsDb(statsDir, { readonly: true });
try {
  // … existing SELECT queries …
} finally {
  db.close();
}
```

Import: `import { openStatsDb } from "./writer";` (use the actual relative import).

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

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

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

```bash
grep -n "new Database" src/stats/reporter.ts
grep -n "initStatsSchema" src/stats/reporter.ts
```

Both must return zero.

- [ ] **Step 5: Commit**

```bash
git add src/stats/writer.ts src/stats/reporter.ts
git commit -m "refactor(stats): centralize stats.db open via openStatsDb (readonly)"
```

---

### Task 4 (I8): SHARED_SNAPSHOT_SESSION constant

**Wave:** A
**Blocks:** cross-spec Minor M1 (also touches src/proxy/handler.ts)
**Blocked by:** —

**Files:**
- Modify: `src/dict/types.ts` (add export)
- Modify: `src/proxy/handler.ts` (use import)

- [ ] **Step 1: Add constant to types.ts**

In `src/dict/types.ts` near the `SessionId` brand declaration:

```ts
export const SHARED_SNAPSHOT_SESSION: SessionId = "__shared__" as SessionId;
```

- [ ] **Step 2: Replace inline cast in handler.ts**

In `src/proxy/handler.ts:138` replace `store.snapshotLocal("__shared__" as SessionId)` with `store.snapshotLocal(SHARED_SNAPSHOT_SESSION)`. Add import.

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

```bash
grep -rn '"__shared__"' src/ | grep -v "SHARED_SNAPSHOT_SESSION"
```

Should return zero hits.

- [ ] **Step 4: tsc**

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

- [ ] **Step 5: Commit**

```bash
git add src/dict/types.ts src/proxy/handler.ts
git commit -m "refactor(proxy): extract SHARED_SNAPSHOT_SESSION constant"
```

---

### Task 5 (I9): buildAliasSourceMap(projectRoot)

**Wave:** A
**Blocks:** Task 6 (I4 — same src/learn/passB-macros.tsC)
**Blocked by:** Task 3 (I7 — same src/stats/reporter.ts)

**Files:**
- Modify: `src/stats/reporter.ts` (lines 296-320)

- [ ] **Step 1: Change signature**

```ts
function buildAliasSourceMap(projectRoot: string): Map<string, string> {
  // … existing body, but replace `paths.root()` with `projectRoot`
  const candidates = [join(projectRoot, "project-path.json"), /* …other entries… */];
  // …
}
```

- [ ] **Step 2: Update caller (gain.ts:320 area)**

```ts
const projectRoot = opts.project ?? paths.root();
const aliasSrc = buildAliasSourceMap(projectRoot);
```

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

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

- [ ] **Step 4: Commit**

```bash
git add src/stats/reporter.ts
git commit -m "fix(stats): thread projectRoot into buildAliasSourceMap"
```

---

### Task 6 (I4): GainTotals canonical names

**Wave:** C
**Blocks:** Task 7 (I5 — same src/learn/passB-macros.tsC)
**Blocked by:** Task 5 (I9 — same src/stats/reporter.ts)

**Files:**
- Modify: `src/learn/passB-macros.tsC` (lines 121-145, 240-250)
- Modify: `src/stats/renderGain.ts` (lines 154-155)

- [ ] **Step 1: Risk audit**

```bash
grep -rn "cacheHitTokens\b\|cacheCreationTokens\b\|\boutputTokens\b" src/
```

Confirm internal-only (no JSON consumer leaking the alias names). If any external consumer exists (CLI raw dump shape), STOP — escalate to user about deprecation shim.

- [ ] **Step 2: Delete alias fields from GainTotals**

In `src/learn/passB-macros.tsC:121-145`, remove:

```ts
cacheHitTokens: number;          // DELETE
cacheCreationTokens: number;     // DELETE
outputTokens: number;            // DELETE
```

Keep canonical:

```ts
cacheHitInputTokens: number;
cacheCreationInputTokens: number;
rawOutputTokens: number;
```

- [ ] **Step 3: Update aggregateTotals builder**

In `src/stats/reporter.ts:240-250`, remove the three alias assignments. Only canonical fields emitted.

- [ ] **Step 4: Update renderGain consumer**

In `src/stats/renderGain.ts:154-155`, swap:

```ts
totals.cacheHitTokens      → totals.cacheHitInputTokens
totals.cacheCreationTokens → totals.cacheCreationInputTokens
totals.outputTokens        → totals.rawOutputTokens
```

UI label text ("cache hits:") unchanged.

- [ ] **Step 5: tsc — let it find stragglers**

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

Fix every reported error by renaming to canonical.

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

```bash
ft gain > /tmp/gain-after.txt
diff /tmp/gain-before.txt /tmp/gain-after.txt  # capture /tmp/gain-before.txt before starting
```

Byte-equal required.

- [ ] **Step 7: Commit**

```bash
git add src/stats/reporter.ts src/stats/renderGain.ts
git commit -m "refactor(stats): drop GainTotals alias fields, use canonical *InputTokens"
```

---

### Task 7 (I5): phantomFilterSqlFor

**Wave:** C
**Blocks:** —
**Blocked by:** Task 6 (I4 — same src/stats/reporter.ts)

**Files:**
- Modify: `src/stats/phantom.ts` (add `phantomFilterSqlFor`)
- Modify: `src/stats/reporter.ts` (delete `qualifiedPhantomFilterSql`, update callers)

- [ ] **Step 1: Add generator to phantom.ts**

```ts
export function phantomFilterSqlFor(alias = ""): string {
  const a = alias ? `${alias}.` : "";
  const predicate = [
    `(${a}compressed_input_tokens = 0 AND ${a}raw_output_tokens = 0)`,
    `${a}raw_input_tokens = 0`,
    `${a}compressed_input_tokens < (${a}cache_hit_input_tokens + ${a}cache_creation_input_tokens)`,
  ].join(" OR ");
  return `NOT (${predicate})`;
}

export const phantomFilterSql = phantomFilterSqlFor();
```

- [ ] **Step 2: Delete qualifiedPhantomFilterSql in gain.ts**

In `src/stats/reporter.ts:11-17`, delete the function. Update callers:

```bash
grep -n "qualifiedPhantomFilterSql" src/stats/reporter.ts
```

Each call site becomes `phantomFilterSqlFor("r")` (or whatever alias was passed).

- [ ] **Step 3: Add unit test (not committed)**

`tests/stats/phantomFilterSqlFor.test.ts`:

```ts
import { describe, it, expect } from "bun:test";
import { phantomFilterSqlFor, phantomFilterSql } from "../../src/stats/phantom";

describe("phantomFilterSqlFor", () => {
  it("empty alias returns same SQL as phantomFilterSql", () => {
    expect(phantomFilterSqlFor("")).toBe(phantomFilterSql);
  });
  it("alias prefixes every column", () => {
    const sql = phantomFilterSqlFor("r");
    expect(sql).toContain("r.compressed_input_tokens");
    expect(sql).toContain("r.raw_input_tokens");
    expect(sql).toContain("r.cache_hit_input_tokens");
  });
});
```

- [ ] **Step 4: Tests + tsc**

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

- [ ] **Step 5: Commit**

```bash
git add src/stats/phantom.ts src/stats/reporter.ts
git commit -m "refactor(stats): replace string-surgery qualifiedPhantomFilterSql with generator"
```

---

### Task 8 (I1): Delete duplicate encodeSseEvent

**Wave:** B
**Blocks:** —
**Blocked by:** Critical Task 2 (sseParser), Critical Tasks 5+6 (rtkRouteStream + KbResponseInterceptor migrated)

**Files:**
- Modify: `src/codec/rtkRouteStream.ts` (if not already gone after Critical Task 5)
- Modify: `src/kb/KbResponseInterceptor.ts` (if not already gone after Critical Task 6)

- [ ] **Step 1: Verify Critical Tasks 5+6 are on main**

```bash
git log --oneline main -- src/codec/rtkRouteStream.ts src/kb/KbResponseInterceptor.ts | head -10
grep -rn "encodeSseEvent" src/
```

If grep returns zero hits, Critical Tasks 5+6 cleared this fully — mark task done, no commit needed. If hits remain, continue.

- [ ] **Step 2: Delete remaining local copies**

For each hit, replace with `encodeEvent` import from `sseParser`.

- [ ] **Step 3: tsc + relevant tests**

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

- [ ] **Step 4: Commit (only if changes)**

```bash
git add src/codec/rtkRouteStream.ts src/kb/KbResponseInterceptor.ts
git commit -m "chore(codec): remove residual encodeSseEvent duplicates"
```

---

### Task 9 (I2): Unify sorted-keys in sseRewriteStream

**Wave:** B
**Blocks:** Minor M3 (same file)
**Blocked by:** Critical Task 8 (sseRewriteStream boundary migration)

**CROSS-SPEC FILE LOCK:** `src/codec/sseRewriteStream.ts` — verify Critical Task 8 is on main before starting. After this task, Minor M3 may run.

**Files:**
- Modify: `src/codec/sseRewriteStream.ts` (lines 48, 76)

- [ ] **Step 1: Verify file state**

```bash
git log --oneline main -- src/codec/sseRewriteStream.ts | head -5
grep -n "_sortedKeys\|SORTED_KEYS\|_escaped\|_sigilRe" src/components/VeryLongDealDetail.tsxC
```

- [ ] **Step 2: Add one sorted list at factory top**

Locate the factory function. Above the first usage:

```ts
const sortedKeys = [...table.keys()].sort((a, b) => b.length - a.length);
const escapedKeys = sortedKeys.map(k => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
const sigilRe = escapedKeys.length > 0
  ? new RegExp(`§{4,}|(?:${escapedKeys.join("|")})`, "g")
  : /§{4,}/g;
```

Adjust the sigil prefix regex to match the existing pattern in the file — read it first, do not guess.

- [ ] **Step 3: Replace all later references**

`_sortedKeys`, `_escaped`, `_sigilRe`, `SORTED_KEYS` → use the new `sortedKeys` / `escapedKeys` / `sigilRe`. Delete the duplicate sort and regex compile at line 76.

- [ ] **Step 4: Add regression test for duplicate computation**

`tests/codec/sseRewriteStream.sortedKeys.test.ts` (not committed):

```ts
import { describe, it, expect } from "bun:test";
// import the factory + a way to inspect compiled regex (may need test export)

describe("sseRewriteStream sortedKeys", () => {
  it("factory called twice with same table produces byte-equal regex source", () => {
    // construct two instances, compare exposed regex .source
  });
});
```

- [ ] **Step 5: Run full sseRewriteStream test suite + tsc**

```bash
bun test src/codec 2>&1 | tail -20
bun tsc --noEmit 2>&1 | head -20
grep -c "sort" src/components/VeryLongDealDetail.tsxC
```

`grep -c "sort"` should return 1 (one sort call inside the factory).

- [ ] **Step 6: Defer E2E smoke**

E2E + dist rebuild gated on user approval per worktree policy. This task's verification is `bun tsc --noEmit` + `bun test src/codec` only (already in Step 5). Do NOT exercise live proxy here.

- [ ] **Step 7: Commit**

```bash
git add src/codec/sseRewriteStream.ts
git commit -m "refactor(codec): unify sortedKeys in sseRewriteStream (was computed twice)"
```

---

## Cross-Spec Handoff

After Task 9 commits: Minor M3 (sseRewriteStream comment recovery) is the last writer on `src/codec/sseRewriteStream.ts` — safe to start.

After Task 4 commits: Minor M1 (rtkInstalled comment) shares `src/proxy/handler.ts` — coordinate with Critical Task 9.

## Self-Review Summary

- **Spec coverage:** I1→Task 8, I2→Task 9, I3→Task 1, I4→Task 6, I5→Task 7, I6→Task 2, I7→Task 3, I8→Task 4, I9→Task 5.
- **Placeholders:** none.
- **Type consistency:** `LegacySavingOpts.model`, `openStatsDb`, `SHARED_SNAPSHOT_SESSION`, `phantomFilterSqlFor`, `GainTotals` canonical field names — consistent.
- **Wave plan check:** src/stats/writer.ts serialization (I3 → I7) and src/learn/passB-macros.tsC serialization (I7 → I9 → I4 → I5) enforced via Blocks/Blocked-by. Wave B hard-gated on Critical commits.
