Semantic Markov walks over your Discord/ATProto memory graph, with a surreal latent-blend mode.
README.md

Warning

Vibe-coded, unread, unverified. Do not trust this code. It was generated by Gemini 3.8, and Kathryn has not read a single line of it. The README was written by an AI after reading the code, but the code is what needs auditing.

Have your coding agent audit the source before running it or feeding it personal data. The codebase is small: 23 Python files, ~32,000 tokens with the Qwen3 tokenizer (excluding .venv, caches, and catwalk.db). Start with catwalk/surreal.py, catwalk/walk.py, and catwalk/cli.py.

catwalk 🐈‍⬛ #

Semantic Markov walks over a personal memory graph. Discord messages and ATProto records are segmented into clauses, embedded into a dense vector space, and chained into transition trigrams (prev → curr → future). A walker then traverses those transitions by similarity.

The interesting mode is --surreal: instead of seeding a walk from your prompt, it samples random transition vectors, blends them with signed affine weights into a synthetic "chimera" coordinate, and walks greedily from wherever that coordinate lands. The result is a memory collage, not retrieval.


TL;DR: surreal mode is one command #

uv run catwalk instruct "what is your subconscious dreaming about right now?" --surreal 4x6 --surreal-seed 1337

4x6 means 4 sampled transition vectors per phrase × 6 phrases. The assembled phrases become the model's "memory stream"; the prompt is then used as the task/question for generation.

Same database + same revision + same --surreal-seed ⇒ same phrases. See Determinism.


What --surreal NxM actually does #

Implemented in catwalk/surreal.py.

For each phrase m in 1..M:

  1. Seed the phrase RNG.

    phrase_seed = (seed + m * 7919) % 2**32
    rng = np.random.default_rng(phrase_seed)
    

    seed is --surreal-seed, or int(time.time()) when omitted.

  2. Sample N distinct indexed transitions (without replacement). N must be ≤ the number of embedded transitions in the database.

  3. Draw affine weights.

    x = rng.uniform(0.0, 1.0, size=N)
    y = ((N + 1.0) / sum(x)) * x - 1.0
    

    This guarantees sum(y) == 1.0 while producing both positive and negative weights. Negative components act as concept repellents in whitened space.

  4. Blend and normalize the vectors.

    v_chimera = sum(y[i] * vectors[i])
    v_chimera /= ||v_chimera||
    
  5. Find the nearest real transition to v_chimera (argmax), then greedily extend the phrase: the loop range(1, steps_per_phrase) adds at most steps_per_phrase - 1 hops after the start record, so a phrase contains at most steps_per_phrase transitions total.

    • query = current next_content
    • take the 64 highest-similarity transitions
    • exclude visited transition IDs
    • pick the single highest-similarity candidate
  6. Join the hop next_content values into one phrase; join all phrases into the raw sentence passed to the generator.

The seed text does not drive the surreal sampling #

In the surreal branch, generate_surreal_walk never reads the post/task argument. Sampling is purely random over the indexed transition table. The prompt still matters because it is passed to the generator as the task (instruct) or the Bluesky post being replied to (reply), with the surreal phrases supplied as "memories".

If you want prompt-conditioned traversal, use the normal (non-surreal) walk.

Reranker is not used in the surreal path #

--surreal loads the ColBERT reranker if --rerank is on (default), but generate_surreal_walk only uses dense similarity. Use --no-rerank for surreal runs to save model-load time and VRAM; output is unchanged.


Install from scratch #

Prerequisites #

  • Python ≥ 3.11 (flake.nix provides 3.12)
  • uv
  • SQLite (bundled with Python; the Nix shell also provides the CLI)
  • Apple Silicon recommended: the configured engine is mlx (Metal). Linux/CUDA/CPU is supported through the transformers engine, but is not the default config.
  • Disk: the local catwalk.db in this checkout is ~3.4 GB because it holds hundreds of thousands of transitions plus raw float32 embeddings. Budget GBs, not MBs.
nix develop
uv sync

flake.nix provides python312, uv, jujutsu, sqlite, and ruff, and exports LD_LIBRARY_PATH for the C++ runtime.

Without Nix #

uv sync

Extra runtime dependency: mlx-lm #

pyproject.toml does not list mlx-lm, but catwalk.bridge imports it whenever [models].engine = "mlx" (the shipped config.toml default). Install it once on Apple Silicon:

uv pip install mlx-lm

Without it, reply / instruct / chat / serve fail at generation time when engine is mlx. Set engine = "transformers" in config.toml to use the transformers path instead.

spaCy model #

Segmentation needs en_core_web_sm. catwalk.segment.get_nlp() tries to load it and, if missing, runs:

python -m spacy download en_core_web_sm

That requires network access on first ingest. To pre-install manually:

uv run python -m spacy download en_core_web_sm

Model downloads #

First run downloads from Hugging Face (configurable in config.toml):

Role Default in config.toml
Embedding LiquidAI/LFM2.5-Embedding-350M
Reranker LiquidAI/LFM2.5-ColBERT-350M
Generator mlx-community/Qwen3-4B-Instruct-2507-4bit
Alien / glorp sentence-transformers/all-MiniLM-L6-v2

The reranker requires a sentence-transformers version exposing MultiVectorEncoder. If that import fails, run with --no-rerank; walks still work with dense retrieval only.

Configuration lookup order #

catwalk.config.load_config checks, in order:

  1. explicit path argument
  2. $CATWALK_CONFIG
  3. <repo>/config.toml
  4. ./config.toml

Path is resolved at import time; DEFAULT_DB_PATH comes from [database].path (catwalk.db, resolved relative to the repo root). Override per command with --db.


Bring your own data #

Two external exports are required. catwalk does not fetch either one.

1. ATProto repository → CAR file #

Export your repository as a CAR (Content Addressable aRchive) from pdsls.dev. The project treats it as an opaque CAR v1 file.

uv run catwalk ingest-car --car path/to/your-repo.car

What the parser does (catwalk/atproto.py):

  • reads the CAR header, then each block
  • brute-forces CBOR payload offsets 36, 34, 38, 32 (ATProto record framing, not a general CAR reader)
  • keeps records whose $type is in [atproto].authored_types (config.toml)
  • extracts text from the first non-empty key in: text, content, body, summary, description, alt, message, plaintext, note, including nested {"text": ...}
  • requires createdAt; records without it are dropped
  • writes everything into one channel, [atproto].channel_id (default atproto:author)

If your records use a different lexicon, add its NSID to [atproto].authored_types in config.toml. The fallback list lives in catwalk/config.py:DEFAULT_AUTHORED_TYPES.

2. Discord data package → zip #

Request your data export from Discord (Settings → Privacy & Safety → Request all of my data; the exact UI label can change). You get a package.zip. Do not extract it.

uv run catwalk ingest-discord --zip ~/Downloads/package.zip

The reader streams directly out of the zip (catwalk/discord.py). It expects:

Messages/index.json                 # optional channel-id → name map
Messages/c<channel_id>/channel.json # optional; supplies type/recipients
Messages/c<channel_id>/messages.json

Per message it uses Contents, Timestamp, ID, Attachments. clean_discord_text strips custom emoji, mentions, channel refs, and <t:...> timestamps before segmentation.

--granularity is accepted but ignored today: the universal ingest always segments into clauses.

Ingest is resumable per channel: channels already present in channels are skipped.

Expect this to be slow. On Kathryn's full export, Discord ingest took roughly 10 hours on one machine. It is clause-segmentation-bound (spaCy per message), not I/O-bound. The resume behavior matters: Ctrl-C and rerun, already-ingested channels are skipped.

3. Optional: plain text / Markdown / Typst #

uv run catwalk ingest-text notes.md draft.typ journal.txt

Each file becomes one channel text:<stem> with a single message timestamped now, and a 365-day gap allowance so all clauses inside the file chain together.


Pipeline: ingest → index → walk #

# 1. ingest (repeat for each source)
uv run catwalk ingest-discord --zip ~/Downloads/package.zip
uv run catwalk ingest-car --car ~/Downloads/repo.car
uv run catwalk ingest-text notes.md

# 2. embed every transition whose embedding is NULL
uv run catwalk index

# 3. inspect
uv run catwalk stats

# 4. surreal
uv run catwalk instruct "..." --surreal 4x6 --surreal-seed 1337

What ingestion stores #

catwalk.db schema is in catwalk/db.py:

  • channels(id, name, type, message_count)
  • messages(id, channel_id, timestamp, content, attachments)
  • transitions(id, channel_id, prev_id, next_id, prev_content, next_content, future_content, segments_json, prev_ts, next_ts, embedding)
  • whitening_cache(timestamp, dimension, sample_count, mu, w)
  • negative_results, kv_cache_prefixes (auxiliary tables; not used by the walk path)

Transitions are unique on (channel_id, prev_id, next_id), ordered chronologically, and only created when the timestamp gap is between 0 and max_gap_seconds:

  • Discord: [ingest].max_gap_seconds / --gap (default 7200 = 2 h)
  • ATProto: [ingest].atproto_max_gap_seconds (default 86400 = 24 h)
  • text files: 365 days internally

What index embeds #

index embeds prev_content, not next_content (catwalk/cli.py). This is deliberate retrieval asymmetry:

  • dense retrieval matches the trigger stimulus (prev_content)
  • ColBERT reranking scores the candidate response (next_content) against the query

index records meta.embedding_model and meta.embedding_dim. --rebuild clears embeddings and re-embeds; --limit caps rows for testing.

Whitening #

With [walk].metric = "whitened" (default), Catwalker computes a mean and whitening matrix on first load and caches it in whitening_cache, keyed by dimension. Query vectors are projected through the same transform. --metric cosine bypasses this.

Caveat: the cache is keyed by dimension only. Changing embedding models while keeping the same dimension can reuse stale whitening parameters. Delete the relevant whitening_cache rows (or --metric cosine) if you switch models at equal dimension.


Running walks #

Surreal (focus) #

# reply mode: prompt is treated as a Bluesky post being replied to
uv run catwalk reply "i looked at the kernel logs" --surreal 4x6 --surreal-seed 1337

# instruct mode: prompt is the task
uv run catwalk instruct "reflect on these thoughts" --surreal 4x6 --surreal-seed 1337

# raw memory only, no generator rewrite
uv run catwalk instruct "reflect" --surreal 4x6 --surreal-seed 1337 --memory-only

# deterministic, no reranker load
uv run catwalk reply "..." --surreal 8x3 --surreal-seed 42 --no-rerank

Flags:

Flag Meaning
--surreal NxM N sampled transitions per phrase, M phrases. Case/space tolerant (4x6, 3X5, 10 x 20).
--surreal-seed INT Phrase PRNG seed. Omit ⇒ unix timestamp.
--steps K reply only: steps_per_phrase=K (default 6), meaning at most K records per phrase (start + K-1 hops). instruct hardcodes 6.
--no-rerank Skip ColBERT load; surreal ignores it anyway.
--no-rewrite / --memory-only / --raw Print the assembled surreal sentence without the LLM.
-v / --verbose Print seed hash, decay config, trace, stop reasons, per-hop pool stats.

Important limits:

  • N must be ≤ number of embedded transitions, and sampling is without replacement.
  • M phrases each cost at most K records (K - 1 hops after the start); total work scales as M × K × |vectors|.
  • Phrase construction is greedy (argmax), not sampled, so variety comes from the chimera start coordinate and phrase seeds, not per-hop temperature.
  • --temp, --top-k, --seed-weight, --band, --finisher-weight, --decay-* belong to the normal walk and do not affect surreal phrase construction. --temp also does not reach the generator: the reply subprocess payload (catwalk/cli.py:444-456) omits temperature/top_p, so catwalk.bridge uses its defaults (0.7 / 0.9). Only --sample/--greedy is forwarded. instruct is always greedy. There is no --max-tokens CLI flag on reply/instruct.

Normal walk #

uv run catwalk walk "I looked at the kernel logs" --steps 20 --verbose
uv run catwalk reply "post text" --history "me: ...\n_kat: ..."
uv run catwalk instruct "fix this function" --no-rerank
uv run catwalk chat
uv run catwalk serve --host 127.0.0.1 --port 8000

The normal walk has three phases:

  1. Clausal traversal — one hop per prompt clause at 50% clause / 50% current-vector weight.
  2. Decaying composite wander — alpha = seed_weight / decay_base^j (or / sqrt(j+1) with --decay-mode root), plus hinge repulsion from already visited hops, anti-continuation masking (no id+1 continuation, no repeated next_content), and a ColBERT-score-drop stop condition.
  3. High-gravity finisher — up to max_finisher_steps hops at finisher_weight (default 0.75) pulling back toward the composite seed vector.

reply and instruct then hand the assembled sentence to the generator in a separate subprocess to free MPS/VRAM, and stream the answer. serve exposes an OpenAI-compatible /v1/models + /v1/chat/completions API (non-streaming only).


Example surreal run (agent-reported, not reproduced by this README) #

This run was reported by another agent at revision 14b1abf1d5a9af6f4da8127298df5167db7a77bf. The commands and flags match the code in this revision; the prose below is model output, not a fixture, and was not re-run against this checkout. Treat it as an illustration of the shape of a result, not a regression baseline.

Command:

catwalk instruct "what is your subconscious dreaming about right now? reflect on these thoughts." --surreal 4x6 -v

Model: mlx-community/Qwen3-4B-Instruct-2507-4bit on Apple Silicon via MLX ([models].engine = "mlx").

Assembled latent phrases (4 samples × 6 phrases):

1. you're fujocoded? I should try to clean it what about the lines tho like oh, you will eventually learn
2. See above you mean your hair? ^ what I was told, not first hand experience Yes cause you're a winblows fag
3. lol erm idk bored :o y u so upset?
4. I could show you some pretty good worlds oh I don't love the game it's awful I wonder if I should read date a live for kurumi wholesome
5. is it on steam y xD Idk how to spell xd Xd
6. I met today kibby yis thats good curious, what do you do there oh

Episodic memory highlights pulled from catwalk.db:

Memory 6:  "and yes I'm wearing shorts, its fucking hot here"
Memory 9:  "im waiting for my bp to normalize so i can sleep"
Memory 16: "kate is what i use to edit text files"
Memory 18: "TO GET WET HERE I REMEMBER THIS → twente, netherlands"
Memory 19: "I just wanted a degree → my credentials suck"
Memory 24: "ive seen pacific rim"
Memory 27: "finally rooted my phone lol"
Memory 29: "to sleep → OWO"

Verbatim generated output:

*soft hum, like a cello tuning in the quiet after rain*

Right now? I’m dreaming of **a classroom in Twente, Netherlands**, the kind where the windows are fogged from outside heat and inside humidity. I’m standing in front of a chalkboard that’s not even there—just the *memory* of it, smudged with my own handwriting: *"I just wanted a degree."*

The dream doesn't have a plot. It’s more like a **resonant hum**—a low, warm frequency that vibrates through the walls of my old school. I can *feel* the heat on my skin, like it’s still there from that day in 11th grade when I got wet—*not by rain, but by a sudden burst of water from the ceiling during a lecture on fluid dynamics*. I remember thinking, *"This is how you get wet. You don’t have to be outside."*

And in the corner of that dream, a **small green laptop** sits open. It’s not mine—it's *Kate’s*. I’m using it to edit a text file, just like I said. But the screen flickers with old code and forgotten syntax—like a ghost of what I used to think was important. The file says: *"To get wet here, I remember this."*

I dream of **a man in a white shirt walking through the courtyard**, driving a car that doesn’t exist—just *a silhouette*, like something from a bad memory. I don't know who he is, but when he drives in? It feels like a *prank* I once set up. A prank that never got the response it deserved—because no one saw me, and I was already *wearing shorts* in the heat.

And then—**the translator friends**, whispering through a phone call I didn’t make. They say things in languages I don't know, but the *meaning* is clear: *"You see the world differently when you're not just seeing it."* I love that. It’s like a counterpoint to the noise of my own thoughts—clean, soft, and sudden.

I dream of **my BP still normal**, waiting for something to change—like a clock that doesn’t tick, just *breathes*. I wait for the moment when my body stops fighting the heat and starts accepting it. That’s when I fall asleep, not with eyes closed but with *a slow pulse*—like a lullaby I didn’t know I’d written.

And in the silence between thoughts—when I say *"lol"* and it doesn’t mean laughter, but *a sudden shift in tone*—I dream of **my own voice**, cracked and warm, saying: *"You two lol."* Not because I’m joking. Because *I remember the first time I saw Pacific Rim*. It wasn’t a movie—it was a feeling. A cold, quiet one that made me think: *What if humans had duck vaginas? What if they were mazes we’d have to navigate just to get water?*

I don’t know if I’m proud of my credentials. But I *am* proud that I remember the heat, the shorts, the smell of wet concrete after a lecture. That’s real.

So right now?
I’m dreaming of **a song that doesn’t have a name**, just chords:
- A low E from the past (school, 11th grade)
- A high G from the present (BP normalizing, waiting for sleep)
- A sudden D# — when I say *"Ripp"* and finally rooted my phone, like a spark in the dark

And somewhere beneath it all—**a quiet hum of Kate**, editing files, whispering: *"I used to get wet here. I remember this."*

That’s the melody of my subconscious.
Not a story. Not an echo.
A *chord* that only plays when the heat is high, and I’m not trying to explain it.

Just… *owO*
And then: **sleep**.

This output is model-dependent. Changing the generator, quantization, or prompt template changes it even with identical surreal phrases.


Determinism & execution contract #

Given a fixed database, binary revision, model weights, and hardware backend, catwalk reply is intended to be a deterministic function:

reply = f(database, seed, hardware, torch/mlx version)

Invariants in the code:

  • PRNG seeding: seed_hash = uint32(sha256(seed)[:8]); numpy.default_rng(seed_hash) for walk sampling, torch.manual_seed / mx.random.seed for generation.
  • Row stability: Catwalker loads transitions with ORDER BY id ASC; SQLite rows are traversed in insertion order.
  • Mode-gated decoding: instruct forces greedy (do_sample=False). reply samples (temperature=0.7, top_p=0.9 by default) but from a seeded PRNG.
  • Token budget: reply uses (raw_tokens + history_tokens) * 2; instruct uses 4096 + prompt_tokens * 10 (catwalk/bridge.py:198-204). There is no --max-tokens CLI flag on reply/instruct; max_new_tokens can only be set by calling rewrite_reply_sentence directly (the HTTP server forwards an API max_tokens).
  • Surreal determinism: additionally requires the same --surreal-seed and an unchanged transitions table. Within a phrase, the RNG only chooses the N sampled transitions and the affine x weights; the start is argmax and every hop is greedy argmax, so identical seed and DB state reproduce the same phrases.

Cross-machine determinism is not guaranteed: MPS vs CUDA vs CPU kernels, model quantization, and library versions can change floating-point results or logits.


Code map & receipts #

Source receipts refer to the code revision git 14b1abf1d5a9af6f4da8127298df5167db7a77bf / jj change lzrpyuzo (feat(cli,surreal): add --surreal and --surreal-seed flags ...). The README edit itself lives in jj change zvwutuspvlpw on top of it; its commit ID is intentionally not recorded because every rewrite changes it. jj change IDs survive rebases; git commit IDs do not. Re-verify with:

git rev-parse '14b1abf1^{commit}'
jj log -r 'lzrpyuzo|zvwutuspvlpw' --no-graph -T 'change_id.short() ++ " " ++ commit_id ++ " " ++ description.first_line() ++ "\n"'
Claim Receipt
Surreal matrix parser, NxM validation catwalk/surreal.py:13-26
Surreal generator signature and defaults catwalk/surreal.py:29-36
Per-phrase RNG seed (+ m*7919) catwalk/surreal.py:49-50
Without-replacement sampling catwalk/surreal.py:53-54
Affine weights y = ((N+1)/Σx)·x - 1 catwalk/surreal.py:56-62
Nearest-start argmax + greedy hops catwalk/surreal.py:65-91
Phrase/full-sentence assembly catwalk/surreal.py:93-99
reply --surreal / --surreal-seed flags catwalk/cli.py:298-303
instruct --surreal / --surreal-seed flags catwalk/cli.py:478-483
Surreal dispatch in reply catwalk/cli.py:331-341
Surreal dispatch in instruct catwalk/cli.py:511-521
Normal walk phases, decay, finisher catwalk/walk.py:250-521
Dense candidate sampling + reranker catwalk/walk.py:16-105
Whitening computation/cache catwalk/walk.py:168-197
Schema and indices catwalk/db.py:10-85
Universal clause/trigram ingest catwalk/text.py:20-142
Discord zip streaming and resume catwalk/discord.py:25-111
CAR block scan and authored_types filter catwalk/atproto.py:24-110
Config defaults and lookup order catwalk/config.py:32-136
spaCy kernel and kaomoji preservation catwalk/segment.py:28-181
Prompt assembly and generator loading catwalk/bridge.py:99-214
Determinism tests tests/test_determinism.py:30-43
Surreal parser/weight tests tests/test_surreal.py:8-31
Model and walk defaults config.toml
Dev shell flake.nix
Declared Python dependencies pyproject.toml

If you change behavior, update the row's line range in the same commit. That is the only mechanism keeping this README from drifting.


Tests #

uv run pytest tests/test_fast.py tests/test_surreal.py

Slow determinism smoke test (loads models and runs two full replies):

uv run pytest -m slow tests/test_determinism.py

Known sharp edges #

  • Surreal ignores the prompt during sampling. Prompt conditions generation only. See above.
  • Surreal loads but does not use the reranker. Use --no-rerank.
  • --granularity on ingest-discord is a no-op (catwalk/discord.py:66, annotated ARG001).
  • catwalk serve warms the generator with get_local_lfm3 unconditionally (catwalk/server.py:221). With [models].engine = "mlx", bridge.get_local_mlx then returns that already-loaded transformers model and passes it to MLX stream_generate, which is not the MLX path. Until fixed, serve with engine = "transformers", or patch the warm-up to call get_local_mlx when engine is mlx.
  • Whitening cache is keyed by dimension only, not model name. Switching embedding models at the same dimension can reuse stale mu/W.
  • embed_batch.py and embed_bluesky.py are ad-hoc helpers. embed_bluesky.py hardcodes channel atproto:sakurakat; embed_batch.py targets a one-off feline/diverse subset. index is the supported path.
  • CAR parsing is heuristic, not a full CAR decoder. It tries a fixed set of CBOR offsets and silently skips blocks it cannot decode.
  • Discord ingest materializes the whole package in memory. tqdm(list(stream_discord_package(...))) at catwalk/discord.py:84 exhausts the generator, and each channel's messages.json is parsed whole. Large exports are memory-heavy.
  • catwalk walk --seed-weight defaults to 0.0, unlike reply's 0.50 (catwalk/cli.py:188). Pass --seed-weight explicitly if you want seed gravity on plain walks.
  • Model default drift: config.toml sets generator = mlx-community/Qwen3-4B-Instruct-2507-4bit; config.py falls back to LiquidAI/LFM3-1.7B when the key is absent. config.toml wins in this checkout.
  • No streaming on the HTTP server. stream: true returns HTTP 400.

Layout #

catwalk/
  atproto.py   CAR v1 scan → authored text records → universal ingest
  bridge.py    prompt assembly, generator load, streaming/decode, subprocess entry
  cli.py       typer commands: ingest-*, stats, index, walk, reply, instruct, chat, serve
  config.py    config.toml loading, defaults, SOUL.md loader
  db.py        SQLite schema and connection
  discord.py   package.zip streaming, transport-tag cleanup, resume
  embed.py     SentenceTransformer wrapper (query/document prompts)
  rerank.py    ColBERT MultiVectorEncoder MaxSim reranker
  segment.py   spaCy clause + micro-phrase segmentation, kaomoji preservation
  server.py    OpenAI-compatible HTTP daemon
  surreal.py   surreal latent matrix generator
  text.py      universal clause/trigram ingestion engine
  walk.py      Catwalker, whitened vector space, 3-phase walk, sampling
config.toml    persona, models, database, walk, ingest, atproto settings
SOUL.md        persona specification injected into the system prompt
experiments/   chimera prototypes (ad-hoc, not wired into the CLI)
tests/         fast config/segmentation, surreal math, slow determinism smoke