# Gemini Debug Prompt — OS Self-Reflection Phase Finalization

You are a senior TypeScript systems engineer assisting in finalizing the **OS Self-Reflection Phase** from POINTER = OS-AWARENESS-PHASE-003.

Below is the complete context, current test behavior, and the remaining issues. Your task is to **fix all remaining test failures** and ensure the architecture remains modular, as designed.

---

### 🧠 Context Recap
- The **Self-Reflection Layer** builds on the **Self-Awareness Layer** (events, telemetry, snapshot).
- The implementation is located under `lib/reflection/` and includes:
  - flags.ts
  - types.ts
  - introspection.ts
  - evaluator.ts
  - feedback.ts
  - policy.ts
  - memory.ts
  - observe.ts
  - index.ts
- Tests live under `tests/reflection/`.

---

### ✅ Working State
- Awareness & Introspection tests ✅ PASS
- Evaluator & Memory tests ✅ PASS
- Policy tests ✅ PASS
- Feedback & Integration (index) tests ❌ FAIL

---

### ❌ Remaining Failures

#### 1. feedback.spec.ts
```
FAIL  tests/reflection/feedback.spec.ts > should propose specific adjustments for a CRITICAL evaluation
Error: "setSystemTime" was called already and date was mocked.
```
Fix: ensure `vi.useRealTimers()` in `afterEach()` and avoid nested fake timers.

#### 2. index.spec.ts (Integration)
```
FAIL  should run the full feedback loop and apply a policy change on high window churn
AssertionError: expected 100 to be 500
```
Policies are not applied — because **no FeedbackDecision** is being produced by `makeDecision()` when CRITICAL evaluation is received.

Root cause (from reflection-phase-summary.md):
- Enum keys mismatch inside FEEDBACK_RULES and Evaluator mappings under Vitest.
- Merging evaluator + feedback logic into index.ts was a temporary hack and broke modularity.

---

### 🧩 Required Fixes

#### (A) Restore modular architecture
Recreate `evaluator.ts` and `feedback.ts` as standalone modules (remove merged logic from index.ts).

#### (B) Replace enums with string unions
```ts
export type SignalType =
  | 'WINDOW_CHURN'
  | 'FOCUS_STABILITY'
  | 'LATENCY_SUMMARY'
  | 'IDLE_RATIO'
  | 'WINDOW_LIFETIME';
```

#### (C) Rebuild FEEDBACK_RULES as string-keyed map
```ts
const FEEDBACK_RULES: Record<SignalType, FeedbackRule> = {
  WINDOW_CHURN: { action: 'THROTTLE_WINDOWS', threshold: 'CRITICAL' },
  LATENCY_SUMMARY: { action: 'DEFER_ANIM', threshold: 'CRITICAL' },
  FOCUS_STABILITY: { action: 'TUNE_FOCUS_TIMEOUT', threshold: 'CRITICAL' },
  IDLE_RATIO: { action: 'ADJUST_PREFETCH', threshold: 'CRITICAL' },
  WINDOW_LIFETIME: { action: 'NOOP', threshold: 'NORMAL' },
};
```

#### (D) Reintroduce makeDecision()
```ts
export function makeDecision(evals: EvaluationResult[]): FeedbackDecision[] {
  const results: FeedbackDecision[] = [];
  const now = performance.now();

  for (const e of evals) {
    const name = String(e.signal.type).toUpperCase();
    const rule = FEEDBACK_RULES[name as SignalType];
    if (!rule || e.status !== rule.threshold) continue;

    results.push({
      ts: now,
      cause: [e],
      action: rule.action,
      mode: 'PROPOSED',
    });
  }
  return results;
}
```

#### (E) Ensure feedback cooldown works as intended
```ts
let lastApplied = 0;
const COOLDOWN_MS = 5000;

export function applyDecisions(decisions: FeedbackDecision[]) {
  const now = performance.now();
  if (now - lastApplied < COOLDOWN_MS) {
    console.warn('[Reflection/Feedback] Cooldown active, decision deferred.');
    return;
  }
  lastApplied = now;
  decisions.forEach(d => applyPolicyChange(d));
}
```

#### (F) Fix test-time timers
```ts
beforeEach(() => {
  vi.useFakeTimers();
});
afterEach(() => {
  vi.useRealTimers();
});
```

#### (G) Fix missing module path
Add alias to vite.config.ts:
```ts
resolve: {
  alias: { '@': path.resolve(__dirname, './') },
},
```
Or import via relative path in the test:
```ts
import * as Reflection from '../../lib/reflection/index';
```

---

### ✅ What Gemini Should Do

1. Restore separate `evaluator.ts` + `feedback.ts` files.
2. Apply the enum → string union fix.
3. Update `types.ts` accordingly.
4. Refactor `index.ts` to import both modules (no inline logic).
5. Fix the `feedback.spec.ts` timer isolation.
6. Update `index.spec.ts` imports (avoid `require()` — use ES imports).
7. Run all tests again and ensure full pass.

---

### 🧪 Expected Successful Output
- All tests pass (Feedback + Integration).
- Coverage ≥ 60%.
- No enum mismatch or missing module errors.
- Cooldown + policy updates function correctly.

Expected final log:
```
✓ 39 passed (0 failed)
Coverage: Statements 65%, Branches 58%, Functions 60%, Lines 64%
```

---

### Deliverables
- Updated: `types.ts`, `evaluator.ts`, `feedback.ts`, `index.ts`, `vite.config.ts`, test fixes.
- Confirmation that policies now update (100 → 500).

Focus on correctness, modularity, and passing all Vitest suites.
