Files
ailed-docs-rp/.sdd/task-2-brief.md
T
chrnxandClaude Opus 5 8ed2944518 docs: design, plan, and the execution record
The thinking behind the organism, versioned alongside the three code repos rather than
living only on one machine.

- AILED_General_Specification.md, the authoritative design, and the implementation plan
  the code was built from
- AGENTS.md, the project-wide rules, including the two that were learned the hard way:
  this is not a performance benchmark, and a null recorded early beats a claim propped up
  later
- the nine superseded module specs, each carrying a banner naming what replaced it
- .sdd/, the execution ledger and every task brief and report: each ruling taken, what it
  would cost if wrong, every correction, and every number verified independently

The three code repos are siblings, each its own repository, and are git-ignored here so
nothing is nested.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
2026-09-02 13:17:39 -05:00

185 lines
6.1 KiB
Markdown

# Task 2: Affect (spec §5)
## Global constraints
- Root `ia-stuff/` is **not** a git repo; `ailed/`, `experiments/`, `paper/` each are. Commit inside the repo you touched.
- No hand-written backward passes. Autograd only (spec §1, §11).
- $\psi$ never carries gradient: it is built from `loss.item()` (spec §5).
- Every oracle is opt-in and must leave the non-oracle trajectory byte-identical (spec §7).
- $\kappa = 0$ must be a single flag that disables affect on the gate (spec §4).
- Affect axes are read by name (`valence`, `arousal`), never by position, outside `Organism.forward` (spec §5).
- Commit messages end with the attribution trailer of the session driving this plan:
```
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
```
Implementers use these two lines verbatim, not the attribution of their own subagent
session — the commits belong to one plan run.
**Files:**
- Create: `ailed/src/ailed/affect.py`
- Test: `ailed/tests/test_affect.py`
**Interfaces:**
- Produces:
- `AffectConfig(rho_fast=0.2, rho_slow=0.02, rho_a=0.5, rho_v=0.1, reward_scale=1.0, decay=0.2, eps=1e-6)` frozen dataclass
- `Affect(valence=0.0, arousal=0.0, fast=0.0, slow=0.0, steps=0)` frozen dataclass with `.axes -> tuple[float, float]` returning `(valence, arousal)`
- `update(state: Affect, loss: float, cfg: AffectConfig, reward: float = 0.0) -> Affect`
- `decay(state: Affect, cfg: AffectConfig) -> Affect`
- [ ] **Step 1: Write the failing tests**
`ailed/tests/test_affect.py`:
```python
from ailed.affect import Affect, AffectConfig, update, decay
CFG = AffectConfig()
def run(losses, rewards=None, cfg=CFG):
s = Affect()
rewards = rewards or [0.0] * len(losses)
out = []
for l, r in zip(losses, rewards):
s = update(s, l, cfg, reward=r)
out.append(s)
return out
def test_first_step_is_not_a_surprise():
s = update(Affect(), 5.0, CFG)
assert s.arousal == 0.0
assert s.fast == 5.0 and s.slow == 5.0
def test_constant_loss_settles_at_zero():
s = run([1.0] * 200)[-1]
assert abs(s.arousal) < 1e-6
assert abs(s.valence) < 1e-6
def test_spike_raises_arousal_then_decays():
hist = run([1.0] * 100 + [10.0] + [1.0] * 60)
assert hist[100].arousal > 0.4
assert hist[-1].arousal < 0.05
def test_decreasing_loss_gives_positive_valence():
losses = [1.0 - 0.004 * i for i in range(200)]
assert run(losses)[-1].valence > 0.05
def test_increasing_loss_gives_negative_valence():
losses = [0.2 + 0.004 * i for i in range(200)]
assert run(losses)[-1].valence < -0.05
def test_reward_moves_valence_with_flat_loss():
s = run([1.0] * 100, rewards=[0.0] * 50 + [1.0] * 50)[-1]
assert s.valence > 0.3
def test_decay_moves_toward_neutral():
s = Affect(valence=0.8, arousal=0.6, fast=1.0, slow=1.0, steps=10)
d = decay(s, CFG)
assert d.valence == 0.8 * (1 - CFG.decay)
assert d.arousal == 0.6 * (1 - CFG.decay)
assert d.fast == 1.0 and d.slow == 1.0
def test_update_is_pure():
s = Affect(valence=0.1, arousal=0.2, fast=1.0, slow=1.0, steps=5)
update(s, 3.0, CFG)
assert s == Affect(valence=0.1, arousal=0.2, fast=1.0, slow=1.0, steps=5)
def test_axes_by_name():
s = Affect(valence=0.3, arousal=0.7)
assert s.axes == (0.3, 0.7)
```
- [ ] **Step 2: Run to verify failure**
Run: `cd ailed && uv run pytest tests/test_affect.py -q`
Expected: `ImportError` / collection error on `ailed.affect`.
- [ ] **Step 3: Implement**
`ailed/src/ailed/affect.py`:
```python
"""Two-axis affect from the organism's own error stream. Spec §5.
Pure functions: state in, state out. No torch, no gradient by construction.
"""
from __future__ import annotations
import math
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class AffectConfig:
rho_fast: float = 0.2 # fast error baseline rate
rho_slow: float = 0.02 # slow error baseline rate, must be < rho_fast
rho_a: float = 0.5 # arousal reactivity
rho_v: float = 0.1 # valence reactivity
reward_scale: float = 1.0 # s_r
decay: float = 0.2 # between-episode decay toward neutral
eps: float = 1e-6
@dataclass(frozen=True)
class Affect:
valence: float = 0.0 # v in [-1, 1]
arousal: float = 0.0 # a in [0, 1]
fast: float = 0.0 # L̄_fast
slow: float = 0.0 # L̄_slow
steps: int = 0
@property
def axes(self) -> tuple[float, float]:
"""(valence, arousal). Consumers read by name; this is the only positional export."""
return (self.valence, self.arousal)
def update(state: Affect, loss: float, cfg: AffectConfig, reward: float = 0.0) -> Affect:
if state.steps == 0:
fast = slow = loss # baselines initialise to the first loss: step one is not a surprise
else:
fast = state.fast + cfg.rho_fast * (loss - state.fast)
slow = state.slow + cfg.rho_slow * (loss - state.slow)
denom = slow + cfg.eps
a_target = math.tanh(max(0.0, loss - slow) / denom)
v_target = math.tanh((slow - fast) / denom + reward / cfg.reward_scale)
return Affect(
valence=state.valence + cfg.rho_v * (v_target - state.valence),
arousal=state.arousal + cfg.rho_a * (a_target - state.arousal),
fast=fast,
slow=slow,
steps=state.steps + 1,
)
def decay(state: Affect, cfg: AffectConfig) -> Affect:
k = 1.0 - cfg.decay
return replace(state, valence=state.valence * k, arousal=state.arousal * k)
```
- [ ] **Step 4: Run to verify pass**
Run: `cd ailed && uv run pytest tests/test_affect.py -q`
Expected: `9 passed`. If `test_spike_raises_arousal_then_decays` fails on the second assert, the spike lifted `slow` and 60 steps is too short; raise the tail to 100 steps and note it in the commit, do not touch `rho_slow`.
- [ ] **Step 5: Commit**
```bash
cd ailed && git add -A && git commit -q -m "feat(affect): two-axis affect from the error stream (spec §5)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85"
```