mirror of
https://github.com/donlucasx/xscapes.git
synced 2026-10-20 08:43:32 +02:00
The visual vocabulary was complete and driven entirely by hardcoded numbers.
This is the plumbing: a protocol, a Claude Code adapter, a reducer, and an
installer.
internal/event is the protocol -- one JSON object per line, per-session unix
datagram socket with a JSON-lines spool as the fallback. The scape never learns
what a hook is and the adapter never learns what a wave is, which is the point:
a second adapter should need nothing from the renderer but this file.
internal/reduce folds events into the Activity and companion state the renderer
already consumes. Every constant is written down with the claim about human
attention that justifies it, and the whole package takes an explicit clock so
the constants can be tuned against a recorded session rather than a guess.
Three things were verified against the Claude Code binary's own embedded
schema rather than guessed (notes/claude-hooks-verified.md):
- Subagent identity DOES arrive. SubagentStart/SubagentStop carry agent_id
and agent_type. RESUME item 3 is answered; the field is agent_type, not
subagent_type.
- The 60-second nag needs no timing heuristic. notification_type is a
required field and the nag has its own value, idle_prompt. The measured
log (2,220 Notifications at exactly 60s after Stop, 41.6% of all of them)
is what said a filter was needed; the schema says how to write it. The
allow list fails closed, so a notification type invented next year is
ignored rather than knocked.
- Context for the moon comes from the statusline, not a hook. No hook
carries it, and summing transcript usage against a hardcoded 200k window
is measurably wrong on this machine: 164,450 tokens is 82% of 200k and
16% of the 1M window actually in use.
The installer edits the file holding the secret-expansion guard, so it prints
a plan by default and only writes with --apply. It splices bytes instead of
re-marshalling, refuses to write unless every entry it did not author survives
unchanged, backs up, and renames atomically. Install then uninstall is
byte-for-byte identical on the real 60KB settings.json.
Also fixes a latent renderer bug that only appears once activity moves: the
wave clock scaled absolute elapsed time by level, so a change in activity
teleported the sea, worse the longer the session ran -- 447 of 1920 cells at
ten minutes in, against 44 at five seconds. Phase is integrated now. The
regression test uses the waterline rather than the glyph field, because the
first version measured glyphs and passed against the broken code.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AU2ieNpECMF7S4go2CwcDX
277 lines
7.9 KiB
Go
277 lines
7.9 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// A settings file shaped like a real one: a big unrelated block, an existing
|
|
// hook we must not touch, and awkward characters inside a command string.
|
|
const sample = `{
|
|
"permissions": {
|
|
"allow": [
|
|
"Bash(awk -F',' '{gsub(/[^0-9.-]/,\"\",$4)}')",
|
|
"Bash(grep -qc VERCEL_TOKEN=)"
|
|
]
|
|
},
|
|
"model": "opus",
|
|
"hooks": {
|
|
"PreToolUse": [
|
|
{
|
|
"matcher": "Bash",
|
|
"hooks": [
|
|
{
|
|
"type": "command",
|
|
"command": "cmd=$(jq -r '.tool_input.command // \"\"'); if printf '%s' \"$cmd\" | grep -qE '\\$\\{?[#!]?(VERCEL_TOKEN)'; then exit 2; fi",
|
|
"timeout": 10
|
|
}
|
|
]
|
|
}
|
|
],
|
|
"Stop": [
|
|
{
|
|
"hooks": [
|
|
{
|
|
"type": "command",
|
|
"command": "afplay /System/Library/Sounds/Funk.aiff & disown",
|
|
"async": true
|
|
}
|
|
]
|
|
}
|
|
]
|
|
},
|
|
"statusLine": { "type": "command", "command": "~/.claude/statusline.sh" }
|
|
}
|
|
`
|
|
|
|
func TestInstallIsPurelyAdditive(t *testing.T) {
|
|
out, actions, err := addHooks([]byte(sample), "/usr/local/bin/asciiscapes")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(actions) != len(hookEvents) {
|
|
t.Fatalf("got %d actions for %d events", len(actions), len(hookEvents))
|
|
}
|
|
if err := verifyPreserved([]byte(sample), out); err != nil {
|
|
t.Fatalf("install failed its own safety check: %v", err)
|
|
}
|
|
|
|
var a, b map[string]json.RawMessage
|
|
if err := json.Unmarshal([]byte(sample), &a); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := json.Unmarshal(out, &b); err != nil {
|
|
t.Fatalf("install produced invalid JSON: %v", err)
|
|
}
|
|
// The blocks that matter must come through untouched, byte for byte --
|
|
// not merely equal after a round trip, which would hide a re-escape.
|
|
for _, k := range []string{"permissions", "model", "statusLine"} {
|
|
if !bytes.Equal(a[k], b[k]) {
|
|
t.Errorf("install rewrote %q:\n before: %s\n after: %s", k, a[k], b[k])
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestExistingHooksSurvive(t *testing.T) {
|
|
out, _, err := addHooks([]byte(sample), "/usr/local/bin/asciiscapes")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// The secret-expansion guard is the reason this whole file is careful.
|
|
// Compare the DECODED command, not the raw bytes: the guard is full of
|
|
// backslashes and comparing escaped forms tests the test, not the code.
|
|
var before, after struct {
|
|
Hooks map[string][]struct {
|
|
Matcher string `json:"matcher"`
|
|
Hooks []struct {
|
|
Command string `json:"command"`
|
|
} `json:"hooks"`
|
|
} `json:"hooks"`
|
|
}
|
|
if err := json.Unmarshal([]byte(sample), &before); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := json.Unmarshal(out, &after); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := before.Hooks["PreToolUse"][0].Hooks[0].Command
|
|
found := false
|
|
for _, g := range after.Hooks["PreToolUse"] {
|
|
for _, h := range g.Hooks {
|
|
if h.Command == want {
|
|
found = true
|
|
}
|
|
}
|
|
}
|
|
if !found {
|
|
t.Error("the PreToolUse secret guard did not survive install intact")
|
|
}
|
|
if !bytes.Contains(out, []byte("afplay /System/Library/Sounds/Funk.aiff")) {
|
|
t.Error("the existing Stop hook did not survive install")
|
|
}
|
|
|
|
var top struct {
|
|
Hooks map[string][]json.RawMessage `json:"hooks"`
|
|
}
|
|
if err := json.Unmarshal(out, &top); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := len(top.Hooks["PreToolUse"]); got != 2 {
|
|
t.Errorf("PreToolUse has %d entries, want the original plus ours", got)
|
|
}
|
|
if got := len(top.Hooks["Stop"]); got != 2 {
|
|
t.Errorf("Stop has %d entries, want the original plus ours", got)
|
|
}
|
|
}
|
|
|
|
func TestInstallUninstallIsAByteForByteNoOp(t *testing.T) {
|
|
installed, _, err := addHooks([]byte(sample), "/usr/local/bin/asciiscapes")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
back, n, err := removeHooks(installed)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if n != len(hookEvents) {
|
|
t.Errorf("uninstall found %d entries, want %d", n, len(hookEvents))
|
|
}
|
|
if err := verifyPreserved(installed, back); err != nil {
|
|
t.Fatalf("uninstall failed the safety check: %v", err)
|
|
}
|
|
if !bytes.Equal(back, []byte(sample)) {
|
|
t.Errorf("round trip is not a no-op:\n%s", firstDiff([]byte(sample), back))
|
|
}
|
|
}
|
|
|
|
func TestInstallIsIdempotent(t *testing.T) {
|
|
once, _, err := addHooks([]byte(sample), "/usr/local/bin/asciiscapes")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
twice, actions, err := addHooks(once, "/usr/local/bin/asciiscapes")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !bytes.Equal(once, twice) {
|
|
t.Error("a second install changed the file; it should be a no-op")
|
|
}
|
|
for _, a := range actions {
|
|
if !strings.HasPrefix(a, "skip") {
|
|
t.Errorf("second install did something other than skip: %q", a)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The safety check is the only thing standing between a bug in the splice and
|
|
// a destroyed permission allowlist. Prove it actually fires.
|
|
func TestSafetyCheckCatchesDamage(t *testing.T) {
|
|
cases := map[string]string{
|
|
"a dropped top-level key": strings.Replace(sample, `"model": "opus",`, "", 1),
|
|
"a rewritten permissions": strings.Replace(sample, `"Bash(grep -qc VERCEL_TOKEN=)"`, `"Bash(anything)"`, 1),
|
|
"a removed existing hook": strings.Replace(sample, "afplay /System/Library/Sounds/Funk.aiff & disown", "rm -rf /", 1),
|
|
"a foreign hook slipped in": strings.Replace(sample, `"model": "opus"`, `"model": "sonnet"`, 1),
|
|
}
|
|
for name, damaged := range cases {
|
|
if err := verifyPreserved([]byte(sample), []byte(damaged)); err == nil {
|
|
t.Errorf("the safety check passed %s; it must refuse", name)
|
|
}
|
|
}
|
|
// And it must not cry wolf on the real, correct edit.
|
|
good, _, err := addHooks([]byte(sample), "/usr/local/bin/asciiscapes")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := verifyPreserved([]byte(sample), good); err != nil {
|
|
t.Errorf("the safety check refused a correct install: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestWorksOnAFileWithNoHooksAtAll(t *testing.T) {
|
|
for _, src := range []string{`{}`, `{"model":"opus"}`, "{\n \"model\": \"opus\"\n}\n"} {
|
|
out, _, err := addHooks([]byte(src), "/usr/local/bin/asciiscapes")
|
|
if err != nil {
|
|
t.Fatalf("%q: %v", src, err)
|
|
}
|
|
var probe map[string]json.RawMessage
|
|
if err := json.Unmarshal(out, &probe); err != nil {
|
|
t.Fatalf("%q produced invalid JSON: %v\n%s", src, err, out)
|
|
}
|
|
if err := verifyPreserved([]byte(src), out); err != nil {
|
|
t.Errorf("%q: %v", src, err)
|
|
}
|
|
back, _, err := removeHooks(out)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !bytes.Equal(back, []byte(src)) {
|
|
t.Errorf("%q did not round trip:\n%s", src, back)
|
|
}
|
|
}
|
|
}
|
|
|
|
// The recorded path ends up inside a shell command inside a JSON string.
|
|
func TestRefusesAShellMetacharacterInTheBinaryPath(t *testing.T) {
|
|
for _, bad := range []string{"/tmp/a`whoami`/asciiscapes", "/tmp/a$HOME/x", `/tmp/a"b/x`} {
|
|
if _, err := binPath(bad); err == nil {
|
|
t.Errorf("binPath(%q) was accepted", bad)
|
|
}
|
|
}
|
|
if _, err := binPath("/usr/local/bin/asciiscapes"); err != nil {
|
|
t.Errorf("a normal path was refused: %v", err)
|
|
}
|
|
}
|
|
|
|
// The command must be readable by the person asked to approve it.
|
|
func TestCommandIsNotHTMLEscaped(t *testing.T) {
|
|
out, _, err := addHooks([]byte(sample), "/usr/local/bin/asciiscapes")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if bytes.Contains(out, []byte(`\u003e`)) || bytes.Contains(out, []byte(`\u0026`)) {
|
|
t.Error("the hook command is HTML-escaped; >/dev/null 2>&1 should be legible")
|
|
}
|
|
if !bytes.Contains(out, []byte(`>/dev/null 2>&1 || true # asciiscapes:v1`)) {
|
|
t.Error("the hook command does not have the expected shape")
|
|
}
|
|
}
|
|
|
|
func firstDiff(a, b []byte) string {
|
|
n := len(a)
|
|
if len(b) < n {
|
|
n = len(b)
|
|
}
|
|
for i := 0; i < n; i++ {
|
|
if a[i] != b[i] {
|
|
lo := i - 60
|
|
if lo < 0 {
|
|
lo = 0
|
|
}
|
|
return "at byte " + itoa(i) + ":\n want ..." + string(a[lo:min(len(a), i+60)]) +
|
|
"\n got ..." + string(b[lo:min(len(b), i+60)])
|
|
}
|
|
}
|
|
return "lengths differ: " + itoa(len(a)) + " vs " + itoa(len(b))
|
|
}
|
|
|
|
func itoa(v int) string {
|
|
if v == 0 {
|
|
return "0"
|
|
}
|
|
var b []byte
|
|
for v > 0 {
|
|
b = append([]byte{byte('0' + v%10)}, b...)
|
|
v /= 10
|
|
}
|
|
return string(b)
|
|
}
|
|
|
|
func min(a, b int) int {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|