diff options
| author | Danilo M. <danix@danix.xyz> | 2026-11-16 13:10:50 +0100 |
|---|---|---|
| committer | Danilo M. <danix@danix.xyz> | 2026-11-16 13:10:50 +0100 |
| commit | dbdc91f7d4fcf77aa2fadb306dad13fd47bcfe40 (patch) | |
| tree | 9f6ec5ba471de7208f35fe072cb5224c82ec9c0c /docs/superpowers/plans/2026-11-16-agent-lamp.md | |
| parent | e13880480330fc7421fd1b06a5669b118c59f2bb (diff) | |
| download | agent-lamp-dbdc91f7d4fcf77aa2fadb306dad13fd47bcfe40.tar.gz agent-lamp-dbdc91f7d4fcf77aa2fadb306dad13fd47bcfe40.zip | |
plan: agent-lamp implementation plan
Nine tasks: the script in three TDD steps, a real-bulb check, Claude Code
hooks, quickshell's nolamp mode and notify-sound forward, the opencode
notifier, retiring udt-bulb across repos, and the global AGENTS.md entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'docs/superpowers/plans/2026-11-16-agent-lamp.md')
| -rw-r--r-- | docs/superpowers/plans/2026-11-16-agent-lamp.md | 1072 |
1 files changed, 1072 insertions, 0 deletions
diff --git a/docs/superpowers/plans/2026-11-16-agent-lamp.md b/docs/superpowers/plans/2026-11-16-agent-lamp.md new file mode 100644 index 0000000..4450397 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-agent-lamp.md @@ -0,0 +1,1072 @@ +# agent-lamp 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:** Drive the IKEA TRADFRI colour bulb as a notification light for Claude Code and opencode, and retire `udt-bulb`. + +**Architecture:** One Python script, `agent-lamp`, stdlib only, calling libcoap's `coap-client`. Event commands record per-session states in a JSON file under `$XDG_RUNTIME_DIR/agent-lamp/` and spawn a detached renderer (`--run`), single-instance through `flock`, that snapshots the bulb, shows steady / breathing / cycling colour, and restores the snapshot when nothing is left. Hooks in Claude Code and the opencode notifier feed it; quickshell gets a `nolamp` mode. + +**Tech Stack:** Python 3 stdlib, libcoap `coap-client`, bash, QML. + +**Spec:** `docs/superpowers/specs/2026-11-16-agent-lamp-design.md` + +**House rules for every task:** commits are GPG-signed by default (never disable signing, check `git log -1 --format=%G?` shows `G`); commit messages end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`; no em dashes; no personal data (a pre-commit hook enforces it). Only edit live repos, never `~/Programming/GIT/my-dotfiles`. + +## Files + +| Path | Change | +|------|--------| +| `agent-lamp/agent-lamp` | create: the whole tool | +| `~/bin/agent-lamp` | symlink to the above | +| `~/.config/agent-lamp/tradfri.json` | copied from `~/.config/udt/tradfri.json` | +| `~/.claude/settings.json` | add hooks | +| `~/.config/opencode/opencode-notifier.json` | command args | +| `quickshell/desktop/modules/status/{statusctl,notify-sound,StatusPage.qml,README.md,test-statusctl.sh,test-notify-sound.sh}`, `quickshell/shared/Status.qml` | `nolamp` mode, forward to agent-lamp | +| `unified-desktop-theme/{bin/udt-bulb,bin/udt-accent,install.sh,AGENTS.md}` | retire udt-bulb | +| `rofi-scripts/bin/udt-powermenu.sh` | `agent-lamp reset` | +| `hypr-theme/{hypridle.conf,sections/autostart.lua}` | `agent-lamp reset` | +| `~/.config/opencode/AGENTS.md` | operational entry | + +--- + +### Task 1: Event words and Claude hook mapping + +**Files:** +- Create: `~/Programming/GIT/agent-lamp/agent-lamp` + +- [ ] **Step 1: Write the skeleton with the failing selftest** + +Create `agent-lamp` with this content, then `chmod +x agent-lamp`: + +```python +#!/usr/bin/env python3 +# agent-lamp - IKEA TRADFRI bulb as a notification light for coding agents +# Copyright (C) 2026 Danilo M. <danix@danix.xyz> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License version 2 as +# published by the Free Software Foundation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +"""Light an IKEA TRADFRI colour bulb when a coding agent needs you. + +Usage: agent-lamp STATE SESSION permission|question|error|complete|clear + agent-lamp claude a Claude Code hook payload on stdin + agent-lamp reset clear every session, restore the bulb + agent-lamp --pair HOST CODE pair with the gateway, list its bulbs + agent-lamp --selftest + +Purple: a permission waits. Amber: a question waits. Red: an agent failed. +Green: an agent finished. A permission or question left waiting starts to +breathe; several agents wanting different things cycle through their +colours. When nothing is left the bulb goes back to how it was. Unknown +state words do nothing, so hook callers never break. Without a paired +gateway or without coap-client, every command does nothing. +""" +import json +import sys + +# Colours are tuned on the real bulb; only the hue survives the saturation +# floor, so they are effectively hue picks. +COLOURS = {"permission": "#a000ff", "question": "#ffa000", + "error": "#ff0000", "complete": "#00ff40"} +CLEARS = ("clear", "user_message", "user_cancelled") + + +def word(w): + """The state a CLI or opencode-notifier event word means, or None.""" + if w in COLOURS: + return w + return "clear" if w in CLEARS else None + + +def from_claude(payload): + """(state, session) for a Claude Code hook payload, or None to ignore.""" + raise NotImplementedError + + +def selftest(): + assert word("permission") == "permission" + assert word("complete") == "complete" + assert word("user_message") == "clear" + assert word("user_cancelled") == "clear" + assert word("session_started") is None + assert word("reset") is None + + def hook(event, **kw): + return from_claude({"hook_event_name": event, "session_id": "s", **kw}) + assert hook("Notification", notification_type="permission_prompt") == ("permission", "s") + assert hook("Notification", notification_type="elicitation_dialog") == ("question", "s") + assert hook("Notification", notification_type="idle_prompt") is None + assert hook("PreToolUse", tool_name="AskUserQuestion") == ("question", "s") + assert hook("PreToolUse", tool_name="Bash") is None + assert hook("Stop") == ("complete", "s") + assert hook("StopFailure") == ("error", "s") + for clearing in ("PostToolUse", "UserPromptSubmit", "SessionEnd"): + assert hook(clearing) == ("clear", "s") + assert hook("SubagentStop") is None + assert from_claude({"hook_event_name": "Stop"}) is None + assert from_claude([]) is None + print("ok") + + +def main(): + args = sys.argv[1:] + if args == ["--selftest"]: + return selftest() + sys.exit(__doc__.split("\n\n")[1]) + + +if __name__ == "__main__": + main() +``` + +- [ ] **Step 2: Run it, expect failure** + +Run: `./agent-lamp --selftest` +Expected: `NotImplementedError` traceback from `from_claude`. + +- [ ] **Step 3: Implement `from_claude`** + +Replace the `from_claude` body: + +```python +def from_claude(payload): + """(state, session) for a Claude Code hook payload, or None to ignore.""" + if not isinstance(payload, dict) or not payload.get("session_id"): + return None + event = payload.get("hook_event_name") + if event == "Notification": + state = {"permission_prompt": "permission", + "elicitation_dialog": "question"}.get(payload.get("notification_type")) + elif event == "PreToolUse": + state = "question" if payload.get("tool_name") == "AskUserQuestion" else None + else: + state = {"Stop": "complete", "StopFailure": "error", "PostToolUse": "clear", + "UserPromptSubmit": "clear", "SessionEnd": "clear"}.get(event) + return (state, payload["session_id"]) if state else None +``` + +- [ ] **Step 4: Run it, expect pass** + +Run: `./agent-lamp --selftest` +Expected: `ok` + +- [ ] **Step 5: Commit** + +```bash +git add agent-lamp +git commit -m "feat: event words and Claude Code hook mapping + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +--- + +### Task 2: Session state and the display rule + +**Files:** +- Modify: `~/Programming/GIT/agent-lamp/agent-lamp` + +- [ ] **Step 1: Add the failing tests** + +Add at the end of `selftest()`, before `print("ok")`: + +```python + # apply: a session holds one state; the same state again keeps its + # start time, so repeated notifications do not reset the escalation. + s = {} + assert apply(s, "a", "permission", 10) and s == {"a": {"state": "permission", "since": 10}} + assert not apply(s, "a", "permission", 20) and s["a"]["since"] == 10 + assert apply(s, "a", "complete", 30) and s["a"] == {"state": "complete", "since": 30} + assert apply(s, "b", "error", 30) + assert apply(s, "a", "clear", 40) and list(s) == ["b"] + assert not apply(s, "a", "clear", 40) + assert apply(s, None, "reset", 50) and s == {} + assert not apply(s, None, "reset", 50) + + # frame: what the bulb shows at a moment, (colour, brightness) or None. + def st(state, since=0): + return {"state": state, "since": since} + assert frame({}, 0) is None + assert frame({"a": st("complete")}, 500) == (COLOURS["complete"], BRIGHT) + assert frame({"a": st("error"), "b": st("error")}, 5) == (COLOURS["error"], BRIGHT) + # Waiting past ESCALATE breathes; a finished agent never does. + waiting = ESCALATE + BREATHE + dim_at = waiting if int(waiting // BREATHE) % 2 else waiting + BREATHE + assert frame({"a": st("permission")}, dim_at) == (COLOURS["permission"], DIM) + assert frame({"a": st("permission")}, dim_at + BREATHE) == (COLOURS["permission"], BRIGHT) + assert frame({"a": st("question")}, dim_at) == (COLOURS["question"], DIM) + assert frame({"a": st("question", dim_at - 1)}, dim_at) == (COLOURS["question"], BRIGHT) + assert frame({"a": st("complete")}, dim_at) == (COLOURS["complete"], BRIGHT) + # Several colours cycle in priority order, at full brightness. + two = {"a": st("error"), "b": st("permission")} + assert frame(two, 0) == (COLOURS["permission"], BRIGHT) + assert frame(two, CYCLE) == (COLOURS["error"], BRIGHT) + assert frame(two, 2 * CYCLE) == (COLOURS["permission"], BRIGHT) + assert frame(two, dim_at)[1] == BRIGHT +``` + +- [ ] **Step 2: Run it, expect failure** + +Run: `./agent-lamp --selftest` +Expected: `NameError: name 'apply' is not defined` + +- [ ] **Step 3: Implement `apply`, `frame` and their constants** + +Below `CLEARS` add: + +```python +# Highest first: the order a multi-colour cycle walks. +PRIORITY = ("permission", "question", "error", "complete") +WAITING = ("permission", "question") + +# Calibration. Brightness 0..254. Times in seconds. +BRIGHT = 254 +DIM = 60 +ESCALATE = 120 # a wait this long starts to breathe +BREATHE = 2 # each half of a breath +CYCLE = 4 # each colour of a multi-colour cycle +``` + +Below `from_claude` add: + +```python +def apply(sessions, session, state, now): + """Record one event in sessions, in place. True if anything changed.""" + if state == "reset": + changed = bool(sessions) + sessions.clear() + return changed + if state == "clear": + return sessions.pop(session, None) is not None + if sessions.get(session, {}).get("state") == state: + return False + sessions[session] = {"state": state, "since": now} + return True + + +def frame(sessions, now): + """(colour, brightness) the bulb shows at `now`, or None for nothing.""" + active = [p for p in PRIORITY if any(v["state"] == p for v in sessions.values())] + if not active: + return None + if len(active) > 1: + return COLOURS[active[int(now // CYCLE) % len(active)]], BRIGHT + state = active[0] + since = min(v["since"] for v in sessions.values() if v["state"] == state) + if state in WAITING and now - since > ESCALATE and int(now // BREATHE) % 2: + return COLOURS[state], DIM + return COLOURS[state], BRIGHT +``` + +- [ ] **Step 4: Run it, expect pass** + +Run: `./agent-lamp --selftest` +Expected: `ok` + +- [ ] **Step 5: Commit** + +```bash +git add agent-lamp +git commit -m "feat: per-session state and the steady, breathe, cycle rule + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +--- + +### Task 3: Gateway, renderer, CLI and pairing + +**Files:** +- Modify: `~/Programming/GIT/agent-lamp/agent-lamp` + +- [ ] **Step 1: Add the failing tests** + +Add at the end of `selftest()`, before `print("ok")`: + +```python + # colour_state: hue from #rrggbb, saturation floored to full. + assert colour_state("#ff0000") == {"5707": 0, "5708": HUE_MAX, "5712": FADE} + pale = colour_state("#8080ff") + assert (pale["5707"], pale["5708"]) == (round(HUE_MAX * 2 / 3), HUE_MAX) + + # show and restore against a fake gateway that records every request. + global coap + real, sent = coap, [] + + def fake(method, url, ident, key, payload=None): + sent.append((method, url, payload)) + return json.dumps({LIGHT: [{"5850": 0, "5851": 120, "5709": 1, "5710": 2}]}) + coap = fake + try: + auth, urls = ("i", "k"), ["u1"] + shown = show(urls, auth, ("#ff0000", BRIGHT), (None, None)) + assert shown == ("#ff0000", BRIGHT) + # Colour first, brightness after, in requests of their own. + assert [p[LIGHT][0] for _, _, p in sent] == [ + colour_state("#ff0000"), {"5850": 1, "5851": BRIGHT, "5712": FADE}] + sent.clear() + assert show(urls, auth, ("#ff0000", BRIGHT), shown) == shown and sent == [] + show(urls, auth, ("#ff0000", DIM), shown) + assert [p[LIGHT][0] for _, _, p in sent] == [{"5850": 1, "5851": DIM, "5712": FADE}] + sent.clear() + snap = snapshot(urls, auth) + assert snap == [{"5850": 0, "5851": 120, "5709": 1, "5710": 2}] + sent.clear() + restore(urls, auth, snap) + # An off bulb gets its colour back, then is switched off. + assert [p[LIGHT][0] for _, _, p in sent] == [ + {"5709": 1, "5710": 2, "5712": FADE}, {"5850": 0}] + coap = lambda *a, **k: None + assert snapshot(urls, auth) is None + assert show(urls, auth, ("#ff0000", BRIGHT), (None, None)) == (None, None) + finally: + coap = real +``` + +- [ ] **Step 2: Run it, expect failure** + +Run: `./agent-lamp --selftest` +Expected: `NameError: name 'colour_state' is not defined` + +- [ ] **Step 3: Implement the gateway, renderer, CLI and pairing** + +Replace the import block with: + +```python +import colorsys +import contextlib +import fcntl +import json +import os +import secrets +import shutil +import subprocess +import sys +import time +from pathlib import Path +``` + +Below the calibration constants add: + +```python +TICK = 1 # renderer loop period +FADE = 20 # transition, tenths of a second +TIMEOUT = 5 # per gateway request + +CONFIG = Path.home() / ".config/agent-lamp/tradfri.json" +RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") +DIR = RUNTIME / "agent-lamp" +# quickshell's statusctl mode file; read directly so the shell need not run. +NOLAMP = RUNTIME / "status.nolamp" + +# IPSO object ids the gateway uses: 15001 devices, 3311 light control, +# 5850 on/off, 5851 brightness, 5707 hue, 5708 saturation, 5709/5710 colour +# xy, 5712 transition. Hue and saturation run 0..65279. +DEVICES, LIGHT = "15001", "3311" +HUE_MAX = 65279 +``` + +Below `frame` add: + +```python +def coap(method, url, ident, key, payload=None): + """The response body of one coaps request, or None on any failure.""" + cmd = ["coap-client", "-m", method, "-u", ident, "-k", key, "-B", str(TIMEOUT)] + if payload is not None: + cmd += ["-e", json.dumps(payload, separators=(",", ":"))] + try: + out = subprocess.run(cmd + [url], capture_output=True, text=True, + timeout=TIMEOUT + 2, check=True).stdout + except (subprocess.SubprocessError, OSError): + return None + return out.strip() + + +def put(url, auth, state): + return coap("put", url, *auth, {LIGHT: [state]}) is not None + + +def colour_state(colour): + """The 3311 state fading to #rrggbb. Pastels wash out to white on the + bulb, so saturation is floored to full and only the hue counts.""" + h, _, _ = colorsys.rgb_to_hsv(*(int(colour[i:i + 2], 16) / 255 for i in (1, 3, 5))) + return {"5707": round(h * HUE_MAX), "5708": HUE_MAX, "5712": FADE} + + +def show(urls, auth, target, shown): + """Move the bulbs from `shown` to `target`; the new shown state. + + The gateway drops part of a request setting colour and brightness at + once, so they go separately, colour first, and only what changed is sent. + On a failed request the old state is returned, so the next tick retries. + """ + colour, level = target + ok = True + for url in urls: + if colour != shown[0]: + ok &= put(url, auth, colour_state(colour)) + if level != shown[1]: + ok &= put(url, auth, {"5850": 1, "5851": level, "5712": FADE}) + return target if ok else shown + + +def snapshot(urls, auth): + """Each bulb's on/off, brightness and colour, or None if one is silent.""" + snap = [] + for url in urls: + try: + light = json.loads(coap("get", url, *auth))[LIGHT][0] + snap.append({k: light[k] for k in ("5850", "5851", "5709", "5710")}) + except (TypeError, ValueError, KeyError, IndexError): + return None + return snap + + +def restore(urls, auth, snap): + """Put the bulbs back as snapshot. Any colour change switches a bulb on, + so an off bulb gets its colour first and is switched off after.""" + for url, s in zip(urls, snap): + put(url, auth, {"5709": s["5709"], "5710": s["5710"], "5712": FADE}) + put(url, auth, {"5850": 1, "5851": s["5851"], "5712": FADE} if s["5850"] + else {"5850": 0}) + + +def configured(): + """The gateway config, or None when there is nothing to drive.""" + try: + cfg = json.loads(CONFIG.read_text()) + except (OSError, ValueError): + return None + if not cfg.get("bulbs") or not shutil.which("coap-client"): + return None + return cfg + + +@contextlib.contextmanager +def locked(): + """Hold the state lock: every read-modify-write of the state is inside.""" + DIR.mkdir(parents=True, exist_ok=True) + with open(DIR / "state.lock", "w") as f: + fcntl.flock(f, fcntl.LOCK_EX) + yield + + +def load(): + try: + return json.loads((DIR / "state.json").read_text()) + except (OSError, ValueError): + return {} + + +def save(sessions): + tmp = DIR / "state.json.tmp" + tmp.write_text(json.dumps(sessions)) + tmp.replace(DIR / "state.json") + + +def nolamp(): + try: + return NOLAMP.read_text().strip() == "1" + except OSError: + return False + + +def update(session, state): + """Record one event and wake the renderer if the state changed.""" + if not configured(): + return + with locked(): + sessions = load() + changed = apply(sessions, session, state, time.time()) + if changed: + save(sessions) + if changed and state != "reset": + subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "--run"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + + +def wait_renderer(seconds): + """Return once no renderer holds the run lock, or after `seconds`. + + `reset` runs right before logout, suspend or poweroff; waiting lets the + renderer restore the bulb before the network goes. + """ + DIR.mkdir(parents=True, exist_ok=True) + end = time.monotonic() + seconds + with open(DIR / "run.lock", "w") as f: + while time.monotonic() < end: + try: + fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) + return + except BlockingIOError: + time.sleep(0.2) + + +def run(): + """The renderer: one at a time, by the run lock; a late one waits its + turn and exits at once if nothing is left by then. The exit decision and + the restore happen under the state lock, so no event slips between them. + """ + cfg = configured() + if not cfg: + return + auth = cfg["identity"], cfg["key"] + urls = [f"coaps://{cfg['host']}:5684/{DEVICES}/{b}" for b in cfg["bulbs"]] + DIR.mkdir(parents=True, exist_ok=True) + with open(DIR / "run.lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + snap, shown = None, (None, None) + while True: + with locked(): + target = frame(load(), time.time()) + paused = nolamp() + if (target is None or paused) and snap: + restore(urls, auth, snap) + snap, shown = None, (None, None) + if target is None: + return + if not paused: + # ponytail: a silent gateway (just after resume) is retried + # every tick, no backoff; add one if it ever floods the log. + if snap is None: + snap = snapshot(urls, auth) + if snap is not None: + shown = show(urls, auth, target, shown) + time.sleep(TICK) + + +def pair(host, code): + ident = "agent-lamp-" + secrets.token_hex(4) + base = f"coaps://{host}:5684" + reply = coap("post", f"{base}/15011/9063", "Client_identity", code, {"9090": ident}) + try: + key = json.loads(reply)["9091"] + except (TypeError, ValueError, KeyError): + sys.exit(f"agent-lamp: pairing with {host} failed: {reply or 'no reply'}") + bulbs = [] + for dev in json.loads(coap("get", f"{base}/{DEVICES}", ident, key) or "[]"): + info = json.loads(coap("get", f"{base}/{DEVICES}/{dev}", ident, key) or "{}") + # Colour bulbs report a hue; white-spectrum ones only a colour temperature. + if "5707" in (info.get(LIGHT) or [{}])[0]: + bulbs.append(str(dev)) + print(f"{dev}: {info.get('9001', '?')}") + CONFIG.parent.mkdir(parents=True, exist_ok=True) + CONFIG.write_text(json.dumps({"host": host, "identity": ident, "key": key, + "bulbs": bulbs})) + CONFIG.chmod(0o600) + print(f"{len(bulbs)} colour bulb(s) recorded in {CONFIG}") +``` + +Replace `main()` with: + +```python +def main(): + args = sys.argv[1:] + if args == ["--selftest"]: + return selftest() + if args == ["--run"]: + return run() + if len(args) == 3 and args[0] == "--pair": + return pair(*args[1:]) + if args == ["reset"]: + update(None, "reset") + return wait_renderer(15) + if args == ["claude"]: + try: + event = from_claude(json.load(sys.stdin)) + except ValueError: + return + if event: + update(event[1], event[0]) + return + if len(args) == 2: + state = word(args[0]) + if state: + update(args[1], state) + return + sys.exit(__doc__.split("\n\n")[1]) +``` + +- [ ] **Step 4: Run it, expect pass** + +Run: `./agent-lamp --selftest` +Expected: `ok` + +- [ ] **Step 5: Check the no-config path is silent** + +Run: `HOME=$(mktemp -d) ./agent-lamp permission s; echo "exit $?"; ./agent-lamp bogus s; echo "exit $?"; ./agent-lamp; echo "exit $?"` +Expected: `exit 0`, `exit 0`, then the usage block and `exit 1`. + +- [ ] **Step 6: Commit** + +```bash +git add agent-lamp +git commit -m "feat: gateway, renderer, CLI and pairing + +The renderer snapshots the bulb, shows the frame each tick and restores +the snapshot when no state is left or the nolamp mode is on. + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +--- + +### Task 4: Install and verify on the real bulb + +**Files:** +- Create: `~/bin/agent-lamp` (symlink), `~/.config/agent-lamp/tradfri.json` (copy) + +- [ ] **Step 1: Install** + +```bash +ln -s ~/Programming/GIT/agent-lamp/agent-lamp ~/bin/agent-lamp +mkdir -p ~/.config/agent-lamp +install -m 600 ~/.config/udt/tradfri.json ~/.config/agent-lamp/tradfri.json +``` + +- [ ] **Step 2: Walk the states with the user watching the bulb** + +Run each, one at a time, asking the user what the bulb shows: + +```bash +agent-lamp permission t1 # purple, steady +agent-lamp question t1 # amber, steady (t1 replaced) +agent-lamp error t2 # cycle amber / red, ~4 s each +agent-lamp clear t1 # red, steady +agent-lamp complete t2 # green, steady +agent-lamp clear t2 # back to the pre-test state +``` + +Then escalation: `agent-lamp permission t3`, wait 2+ minutes, expect purple breathing; `agent-lamp reset` restores the bulb and returns once it has. + +Then restore-to-off: switch the bulb off with its remote, `agent-lamp complete t4`, expect green; `agent-lamp clear t4`, expect off. + +Then nolamp: `agent-lamp error t5`; `printf '1\n' > "$XDG_RUNTIME_DIR/status.nolamp"`, expect the pre-test state within a second; `printf '0\n' > "$XDG_RUNTIME_DIR/status.nolamp"`, expect red; `agent-lamp reset`. + +Check `pgrep -f 'agent-lamp --run'` prints nothing after each final clear. + +- [ ] **Step 3: Tune** + +If a colour reads wrong, adjust `COLOURS` (or `DIM`, `CYCLE`, `BREATHE`) per the user, re-run `./agent-lamp --selftest`, and commit: + +```bash +git add agent-lamp +git commit -m "tune: colours on the real bulb + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +Skip the commit if nothing changed. + +--- + +### Task 5: Claude Code hooks + +**Files:** +- Modify: `~/.claude/settings.json` (not a repo) + +- [ ] **Step 1: Add the hooks** + +Use the `update-config` skill, or edit with a short Python script, to add these entries under `hooks`, keeping the existing Notification (`notify-sound claude`) and UserPromptSubmit (`ponytail-reinject.sh`) hooks as they are. Each event gets one more group: + +```json +"Notification": [{"hooks": [{"type": "command", "command": "~/bin/agent-lamp claude", "async": true}]}], +"PreToolUse": [{"matcher": "AskUserQuestion", "hooks": [{"type": "command", "command": "~/bin/agent-lamp claude", "async": true}]}], +"PostToolUse": [{"hooks": [{"type": "command", "command": "~/bin/agent-lamp claude", "async": true}]}], +"Stop": [{"hooks": [{"type": "command", "command": "~/bin/agent-lamp claude", "async": true}]}], +"StopFailure": [{"hooks": [{"type": "command", "command": "~/bin/agent-lamp claude", "async": true}]}], +"UserPromptSubmit": [{"hooks": [{"type": "command", "command": "~/bin/agent-lamp claude", "async": true}]}], +"SessionEnd": [{"hooks": [{"type": "command", "command": "~/bin/agent-lamp claude", "async": true}]}] +``` + +(These are appended groups: for Notification and UserPromptSubmit the list then holds two groups.) + +- [ ] **Step 2: Validate** + +Run: `python3 -m json.tool ~/.claude/settings.json >/dev/null && echo valid` +Expected: `valid` + +- [ ] **Step 3: Verify live** + +In a new Claude Code session, ask it to run a command that needs permission: bulb turns purple; approve: bulb clears (PostToolUse); at the end of its turn: green; send a prompt: back to the pre-test state. + +--- + +### Task 6: quickshell `nolamp` mode and the notify-sound forward + +**Files:** +- Modify: `quickshell/desktop/modules/status/statusctl:28` +- Modify: `quickshell/shared/Status.qml` (property, count, setMode, toggleMode, ModeFile) +- Modify: `quickshell/desktop/modules/status/StatusPage.qml` (row after Quiet) +- Modify: `quickshell/desktop/modules/status/notify-sound` +- Modify: `quickshell/desktop/modules/status/test-statusctl.sh`, `test-notify-sound.sh`, `README.md` + +All paths below are under `~/Programming/GIT/quickshell`. + +- [ ] **Step 1: Failing statusctl test** + +In `desktop/modules/status/test-statusctl.sh`, after the `quiet toggle from 1` check, add: + +```bash +# nolamp keeps agent-lamp's bulb dark; a plain mode like quiet. +"$ctl" nolamp set 1 +check "nolamp set 1" "1" "$("$ctl" nolamp get)" +"$ctl" nolamp toggle +check "nolamp toggle from 1" "0" "$("$ctl" nolamp get)" +``` + +Run: `desktop/modules/status/test-statusctl.sh` +Expected: FAIL lines for both nolamp checks (`unknown mode: nolamp`). + +- [ ] **Step 2: Add the mode to statusctl** + +In `desktop/modules/status/statusctl` change: + +```bash +MODES="dnd presentation nolock quiet" +``` +to +```bash +MODES="dnd presentation nolock quiet nolamp" +``` + +Run: `desktop/modules/status/test-statusctl.sh` +Expected: all `ok`, exit 0. + +- [ ] **Step 3: Failing notify-sound test** + +Read `desktop/modules/status/test-notify-sound.sh` to the end first. It fakes `paplay` in `$tmp/bin`; add a fake `agent-lamp` the same way, right after the `paplay` fake: + +```bash +printf '#!/bin/sh\nprintf "%%s %%s\\n" "$1" "$2" >> "%s/lamp"\n' "$tmp" > "$tmp/bin/agent-lamp" +chmod +x "$tmp/bin/agent-lamp" +``` + +and before the final pass/fail summary add: + +```bash +# Two arguments (opencode's event and session) are forwarded to agent-lamp, +# even in quiet mode; Claude's single argument never is. +rm -f "$tmp/lamp" +"$here/notify-sound" claude +"$here/notify-sound" permission ses1 +"$here/statusctl" quiet set 1 +"$here/notify-sound" complete ses2 +sleep 0.2 +check "lamp forward" "permission ses1|complete ses2" "$(paste -sd'|' "$tmp/lamp" 2>/dev/null)" +``` + +Run: `desktop/modules/status/test-notify-sound.sh` +Expected: FAIL `lamp forward`. + +- [ ] **Step 4: Forward in notify-sound** + +In `desktop/modules/status/notify-sound`, directly after `here=...` and before the quiet check, add: + +```bash +# opencode's notifier passes its event and session id: forward them to the +# agent lamp, before the quiet check, since quiet mutes sound and not light. +# Claude Code passes one argument and has hooks of its own for the lamp. +if [[ $# -eq 2 ]] && command -v agent-lamp >/dev/null; then + agent-lamp "$1" "$2" </dev/null >/dev/null 2>&1 & +fi +``` + +Also extend the header usage comment line for opencode to `notify-sound <event> <session>`. + +Run: `desktop/modules/status/test-notify-sound.sh` +Expected: all `ok`, exit 0. + +- [ ] **Step 5: Status singleton** + +In `shared/Status.qml`: + +After the `quiet` property add: + +```qml + // Keeps agent-lamp's bulb dark; agent-lamp reads the file itself, so + // this is only the drawer's view of it. + readonly property bool nolamp: nolampFile.value +``` + +Change `activeCount` to add `+ (root.nolamp ? 1 : 0)`: + +```qml + readonly property int activeCount: (root.dnd ? 1 : 0) + (root.presentation ? 1 : 0) + + (root.nolock ? 1 : 0) + (root.quiet ? 1 : 0) + + (root.nolamp ? 1 : 0) +``` + +In `setMode`, after the `quiet` branch: + +```qml + } else if (name === "nolamp") { + nolampFile.write(on); +``` + +In `toggleMode` add: + +```qml + else if (name === "nolamp") root.setMode("nolamp", !root.nolamp); +``` + +After the `quietFile` ModeFile: + +```qml + ModeFile { id: nolampFile; path: root.dir + "/status.nolamp" } +``` + +- [ ] **Step 6: Drawer row** + +In `desktop/modules/status/StatusPage.qml`, after the Quiet `StatusRow` add: + +```qml + Rectangle { + width: page.width + height: 1 + color: Qt.alpha(Theme.text, 0.08) + } + + StatusRow { + width: page.width + mode: "nolamp" + label: "No lamp" + description: "Keeps the agent lamp dark, for a film. Agents still notify on screen." + value: Status.nolamp + } +``` + +- [ ] **Step 7: README** + +In `desktop/modules/status/README.md`: add `nolamp` to the mode list in the first paragraph, add `$XDG_RUNTIME_DIR/status.nolamp` to the files block, and after the `quiet` paragraph add: + +```markdown +`nolamp` keeps the agent lamp (the sibling agent-lamp repo) dark. The shell +does nothing with it: agent-lamp's renderer reads the file each second and +restores the bulb while it is 1, keeping the agents' states for when it +turns off. `notify-sound` forwards the opencode notifier's two arguments +(`<event> <session>`) to `agent-lamp`, before the quiet check. +``` + +- [ ] **Step 8: See it** + +Reload quickshell, open the drawer's status page, screenshot (`grim -o DP-1 <scratchpad>/status.png`, path in the session scratchpad) and check the No lamp row renders and toggles `statusctl nolamp get`. + +- [ ] **Step 9: Commit** + +```bash +git add desktop/modules/status shared/Status.qml +git commit -m "status: nolamp mode and the agent-lamp forward + +nolamp keeps agent-lamp's bulb dark; notify-sound forwards opencode's +event and session to agent-lamp before the quiet check. + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +--- + +### Task 7: opencode notifier args + +**Files:** +- Modify: `~/.config/opencode/opencode-notifier.json` (not a repo) + +- [ ] **Step 1: Edit** + +Change `"args": ["{event}"]` to: + +```json + "args": [ + "{event}", + "{sessionID}" + ] +``` + +Run: `python3 -m json.tool ~/.config/opencode/opencode-notifier.json >/dev/null && echo valid` +Expected: `valid` + +- [ ] **Step 2: Verify live** + +Restart opencode, trigger a permission prompt: purple; answer and send a message: restored. + +--- + +### Task 8: Retire udt-bulb + +**Files:** +- Delete: `unified-desktop-theme/bin/udt-bulb`, `~/bin/udt-bulb` symlink +- Modify: `unified-desktop-theme/install.sh:108,437-439`, `unified-desktop-theme/bin/udt-accent:670-674,938-939`, `unified-desktop-theme/AGENTS.md:65,283-295,369` +- Modify: `rofi-scripts/bin/udt-powermenu.sh:65,71,77` +- Modify: `hypr-theme/hypridle.conf:14,19,59`, `hypr-theme/sections/autostart.lua:33-40` + +- [ ] **Step 1: unified-desktop-theme** + +In `~/Programming/GIT/unified-desktop-theme`: + +```bash +git rm bin/udt-bulb +command rm ~/bin/udt-bulb +``` + +`install.sh:108`: drop `udt-bulb` from the `for f in ...` list. +`install.sh:437-439`: delete the whole `c_bulb() { ... }` function and the blank line after it. +`bin/udt-accent:670-672`: these three comment lines +```python + # The LED strip waits up to 20 s for its address broadcast, the bulbs + # up to 5 s per bulb for the gateway. All of them read files written above; + # udt-tv is a single UDP datagram to the TV launcher. +``` +become +```python + # The LED strip waits up to 20 s for its address broadcast. All of them + # read files written above; udt-tv is a single UDP datagram to the TV + # launcher. +``` +and line 674 drops `"udt-bulb", ` from the tuple. +`bin/udt-accent:938-939`: drop `"udt-bulb", ` from the `helpers` set. +`AGENTS.md`: delete the `udt-bulb` paragraph (lines 283-295, from "`udt-bulb` does the same" to "separately."); line 65 "keyboard, strip, bulbs and TV" becomes "keyboard, strip and TV"; line 369 "the LED strip and the TRADFRI bulbs do" becomes "and the LED strip do" (fix the list's commas so it reads right). + +Check nothing is left: `grep -rn -i 'bulb\|tradfri' --exclude-dir=.git .` prints nothing. + +Run: `bin/udt-accent --selftest && bin/udt-palette --selftest && bash -n install.sh && tests/ini-merge.sh` +Expected: all pass. + +```bash +git add -A +git commit -m "Retire udt-bulb: the bulb is now agent-lamp's + +The TRADFRI bulb no longer follows the wallpaper accent. It became a +notification light for coding agents, in the separate agent-lamp repo. + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +- [ ] **Step 2: rofi-scripts** + +In `~/Programming/GIT/rofi-scripts/bin/udt-powermenu.sh`, each of the three `udt-bulb off` lines (65, 71, 77) becomes `agent-lamp reset`. + +Run: `bash -n bin/udt-powermenu.sh && grep -c 'agent-lamp reset' bin/udt-powermenu.sh` +Expected: `3` + +```bash +git add bin/udt-powermenu.sh +git commit -m "powermenu: restore the agent lamp instead of udt-bulb off + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +- [ ] **Step 3: hypr-theme** + +In `~/Programming/GIT/hypr-theme`: + +`hypridle.conf:14`: `udt-bulb off` becomes `agent-lamp reset`. +`hypridle.conf:19`: delete `; udt-bulb on` (the line ends with `udt-ledstrip on`). +`hypridle.conf:59`: `udt-bulb off` becomes `agent-lamp reset`. +`sections/autostart.lua`: the comment becomes + +```lua +-- The LED strip goes dark on logout and the agent lamp goes back to how it +-- was. Poweroff and reboot do the same in udt-powermenu.sh, since rc.6 drops +-- the network before Hyprland hears this. +``` + +and `hl.exec_cmd("setsid -f udt-bulb off")` becomes `hl.exec_cmd("setsid -f agent-lamp reset")`. + +Run: `grep -rn 'udt-bulb' . --exclude-dir=.git` prints nothing; `luac -p sections/autostart.lua 2>/dev/null || lua -e 'loadfile("sections/autostart.lua")'` reports no syntax error (skip if neither is installed and say so). + +```bash +git add hypridle.conf sections/autostart.lua +git commit -m "agent-lamp reset replaces udt-bulb on sleep and logout + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +``` + +Tell the user hypridle reads its config at start, so the change applies after a hypridle restart or the next login. + +- [ ] **Step 4: Push all three repos** + +`git push` in unified-desktop-theme, rofi-scripts, hypr-theme and quickshell (each `origin` may fan out to several remotes; that is expected). + +- [ ] **Step 5: Remove the old config** + +After Task 4 passed with the copied config: `command rm ~/.config/udt/tradfri.json`. + +--- + +### Task 9: Global AGENTS.md entry and agent-lamp docs + +**Files:** +- Modify: `~/.config/opencode/AGENTS.md` (not a repo; the file Claude Code's CLAUDE.md imports) +- Modify: `~/Programming/GIT/agent-lamp/README.md`, `AGENTS.md` + +- [ ] **Step 1: Global entry** + +In `~/.config/opencode/AGENTS.md`, after the "Shell aliases in agent shells" section and before the `---` above "Declarative preferences", add: + +```markdown +## Agent lamp +A TRADFRI colour bulb in the room is a notification light for agents, +driven by `agent-lamp` (repo `~/Programming/GIT/agent-lamp`). Purple: a +permission waits; amber: a question waits; red: failed or blocked; green: +finished. Claude Code hooks and opencode's notifier drive it automatically, +so normal use needs no action. For a signal no hook covers (e.g. a long +background job finished, or blocked outside a tool call), run +`agent-lamp <permission|question|error|complete|clear> <session-id>`; the +lamp clears on the user's next prompt. Never run `agent-lamp reset` or +`--pair` unasked: reset clears every agent's state. `statusctl nolamp` (the +quickshell drawer's "No lamp") keeps it dark; respect it, do not toggle it. +(verified: 2026-11-16, depends on the hooks in `~/.claude/settings.json` +and the notifier's command args; re-check if those change.) +``` + +- [ ] **Step 2: Repo docs** + +In the agent-lamp `README.md`, add after Usage: + +```markdown +## Wiring + +- Claude Code: async hooks running `agent-lamp claude` on Notification, + PreToolUse (matcher `AskUserQuestion`), PostToolUse, Stop, StopFailure, + UserPromptSubmit and SessionEnd. +- opencode: `@mohak34/opencode-notifier` with `"command": {"path": + "notify-sound", "args": ["{event}", "{sessionID}"]}`; quickshell's + `notify-sound` forwards both arguments to `agent-lamp`. +- `agent-lamp reset` at logout, suspend and poweroff. +- `$XDG_RUNTIME_DIR/status.nolamp` holding `1` keeps the bulb dark. +``` + +In the agent-lamp `AGENTS.md`, add before "Conventions": + +```markdown +## Runtime + +- State: `$XDG_RUNTIME_DIR/agent-lamp/state.json`, every read-modify-write + under `flock` on `state.lock`. The renderer (`--run`) holds `run.lock` + for its whole life; event commands spawn one only when the state changed. +- Install is a symlink, `~/bin/agent-lamp`, so edits are live; a running + renderer keeps the old code until it exits. +- The known limit: opencode's notifier has no "permission granted" event, + so an opencode permission stays purple until that session's next event. +``` + +Run: `./agent-lamp --selftest && grep -c '—' README.md AGENTS.md` +Expected: `ok`, then `0` for both files. + +```bash +git add README.md AGENTS.md +git commit -m "docs: wiring and runtime notes + +Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>" +git push +``` |
