Wisen Walkthrough
Target architecture · steps 0–4 shipped · 5 in validation · 6–7 next

wisen

A harness that learns from how I work with coding agents. Every night it reads the day's agent sessions and finds where the work was hard. By morning it proposes a small change to the instructions my agents read. I approve it from my phone, it lands as a git branch, and two weeks later wisen measures whether the change helped.

observe→reflect→propose→approve→apply→measure↺
The problem

Agents produce transcripts nobody reads

I run Claude Code, Codex, Cursor, opencode, Gemini CLI and Pi every day. Each session leaves a transcript full of signal: the tool calls I rejected, the times I interrupted, the requests I rephrased three times. None of it changes how the agents behave tomorrow. wisen closes that loop without uploading my coding logs anywhere.

One night with wisen

The pipeline is modelled on sleep

The brain does not replay everything; it replays what mattered, then consolidates it. wisen has two model stages that work the same way. The Observer (NREM) reads a day's raw sessions and turns them into short, redacted notes called packets. The Synthesizer (REM) reads only packets and writes the morning reflection. That split is also where the laptop ends and the server begins.

22:0000:0002:0004:0006:0008:00 Laptop Server Phone Observer (NREM): raw sessions → packets laptop asleep: nothing needed from it packets Synthesizer (REM) + Gardener packets only · reflection + proposals 07:00 morning brief 3 bullets + proposal batch push
Target schedule for stage B. Model work that touches raw text happens before the laptop sleeps; everything after it runs on the server from packets, so the brief is ready by morning whether or not the laptop is awake. Today, in stage A, the server asks the laptop at 07:00 to synthesize the previous day.
Stage A → stage B

One boundary, two deployments

The server was built in two stages. In stage A every model call runs on the laptop and the server is only a mailbox: schedule, approval inbox, push notifications, with no model key at all. In stage B the REM half moves to the server so it can "dream" while the laptop sleeps. The privacy rule did not change between the two, because the packet boundary was there from the start: REM only ever needed packets.

ComponentLocal-onlyStage AStage B
Connectors, normalizer, Observer (NREM)laptoplaptoplaptop
Synthesizer (REM), Gardener (propose), chatlaptoplaptopserver
Apply a change as a branch, measure, raw searchlaptoplaptoplaptop
Schedule, approval inbox, push, Telegramlocal dashboard onlyserverserver
Model credential: API key, or the claude loginlaptoplaptoplaptop + server

Local-only mode stays first-class: with no server configured, the laptop runs everything and I approve in the local dashboard or CLI. The server is an add-on, never a requirement.

Diagram 1

System: laptop and server

Raw transcripts never leave the laptop. The only thing that crosses to the server is a typed packet, and the server rejects anything that does not match a packet schema.

LAPTOP · macOS · raw data never leaves Agent histories[JSONL · read-only] wisen worker · job engine [launchd] Connectors[8 → 1 shape] Observer[pydantic-ai] Egress gate[6 checks] Device jobsclaimed from the server Apply[git branch] Measure[2-week check] Raw search[grep-first] every box here runs as durable job steps (saved steps · leases · retries) wisen.db[SQLite · jobs · ledger] Git repos + home.git[instruction files] ① ⑦ SERVER · Hetzner VM · Ubuntu Caddy[TLS · reverse proxy · routes by path] wisen cloud serve · job engine [systemd] Device routesfor the laptop · device token POST /api/device/paircode → token POST /api/device/packetsdata up · checked POST /api/device/polljobs + decisions POST …/jobs/{id}/heartbeat|finishresults App routesfor me · login session GET / dashboard (PWA)/api/push/* POST /api/proposals/{id}/decision/api/devices Synthesizer · Gardener · Chat[REM · reads packets only] Notifier[push · Telegram] server.db[SQLite · packets · proposals · jobs] ⑧ ③packets up ④polls for work · outbound Model provider[configured · or subscription] Me · phone[PWA · Telegram] Model provider[subscription · or API key] ② ⑤push ⑥
call or read outbound or polled the only data path across the boundary process data store
#From → toProtocolCarries
①Agent histories → connectorslocal file readraw sessions, never copied by wisen
②Observer → model providerHTTPSexcerpts: ≤ 400 characters per turn, ≤ 20 config files at 1,000 each
③Egress gate → Caddy → /api/device/packetsHTTPS POST · device tokentyped packets only; anything else is rejected by the schema check
④Device jobs ⇄ Caddy ⇄ /api/device/poll, /jobs/{id}/heartbeat|finishHTTPS polling · outbound onlydown: jobs to claim and my decisions; up: heartbeats and results
⑤Me ⇄ Caddy ⇄ app routes; Notifier → phoneHTTPS session · Web Push · Telegram Bot APIdashboard and decisions (each with a request id); pushes carry title, short description and a link
⑥Synthesizer · Gardener · Chat → model providerHTTPS or claude -ppackets only; file text arrives as a redacted ConfigSnapshotPacket
⑦Apply → gitgit CLIone commit on wisen/gardener/<id>, after re-checking approval and the allow-list
⑧Server process ⇄ server.dbin-process SQLitepackets (idempotent by content hash), reflections, proposals, jobs
One program on each machine. Caddy sends every request to the single wisen cloud serve process, which has two route groups: device routes for the laptop and app routes for me. The laptop always starts the connection, pushing packets up and polling for work; the server never connects into the laptop.
Production-grade 1

The privacy line is code, not a promise

1 · At rest: local

Raw transcripts stay where the agents wrote them. wisen stores only derived data in ~/.wisen/wisen.db.

2 · Inference: excerpts

The laptop's model calls get capped excerpts: 400 characters per turn, up to 20 config files at 1,000 characters each.

3 · Cloud: packets only

If it is not a packet type, it does not cross. Both ends import the same schema module.

Every packet goes through the egress gate (the laptop's one exit check) in this order. A value that redaction would change inside a diff or an identifier rejects the whole packet; a human never approves a cut-short diff.

Selectallow-listed fields only
Redactkeys, tokens, home paths, emails
Truncatefree text and quotes to caps
Validatestrict model, extra fields forbidden
Recordlocal egress ledger (wisen egress)
Sendidempotent by content hash

How it is proven. Tests plant a marker string and a fake API key in fixture transcripts and assert that neither appears in any packet, that an off-schema packet is rejected, and that the same content always hashes to the same packet id. In stage B, a mock model that echoes its prompt checks that no marker reaches any server-side prompt or row.

Durability is an egress risk too. A durable job saves each step's output, so the Observer step saves its packet output, never raw turns, and any journal that held raw text is pruned when the job succeeds.

Experimental

The Gardener

The Gardener is the agent that turns reflections into proposed changes. It may edit only the instructions agents read: CLAUDE.md, AGENTS.md and skills, in each repo and in my home directory. Never repo code, settings or MCP config. The allow-list is a path check in the laptop's applier, so a proposal for any other path is refused even after approval. Files outside any repo, like ~/.claude/CLAUDE.md, are tracked by a wisen-managed git history (~/.wisen/gardener/home.git) whose working folder is my home directory, so every change is still a branch.

Before a proposal reaches me, wisen runs a replay: it re-runs past moments where I had to correct an agent, once with the current file and once with the proposed one, and checks whether the problem came back. It also replays a clean set, moments that went smoothly, which the change must not break. The proposal tool is declared requires_approval: the agent run pauses at that call and is stored until I decide.

sequenceDiagram
  autonumber
  participant G as Gardener (server)
  participant R as Replay (laptop)
  participant S as Server inbox
  participant H as Me (phone)
  participant L as Laptop applier
  G->>G: read reflections, friction, current file
  G->>R: replay past correction cases: current vs proposed
  R-->>G: pass rates + clean set + cost
  G->>S: ProposalPacket: diff, rationale, evidence, replay result
  S->>H: morning batch: "3 proposals waiting"
  H->>S: approve / reject with note / let expire
  S->>L: decision (laptop polls)
  L->>L: re-check approval, path allow-list, file unchanged
  L->>L: branch wisen/gardener/{id}, one commit
  Note over H,L: I merge when I choose
  L->>S: merged (detected locally)
  S->>L: 2 weeks later: measure job
  L->>S: helped / no change / worse
  G->>S: if worse: a revert proposal
Approval is not authorization: the server authenticates whoever approves, and the laptop re-checks the stored decision and the allow-list before it writes anything. The commit is built in a temporary index with author, time and parent fixed by the approval, so a laptop that reconnects mid-apply makes the same commit and never a second branch.
stateDiagram-v2
  [*] --> proposed: Gardener drafts a change + replay evidence
  proposed --> approved: I approve
  proposed --> rejected: I reject with a note
  proposed --> expired: 7 days, no decision
  proposed --> superseded: newer proposal, same file
  approved --> applied: laptop commits wisen/gardener/id
  approved --> failed: path refused or file changed
  applied --> merged: I merge the branch
  applied --> abandoned: branch deleted
  merged --> measuring: 2 weeks after merge
  measuring --> kept: helped or no change
  measuring --> revert_proposed: worse
  rejected --> [*]
  expired --> [*]
  superseded --> [*]
  failed --> [*]
  abandoned --> [*]
  kept --> [*]
  revert_proposed --> [*]: the revert starts its own life
The proposal state machine. One function moves a proposal: a compare-and-set update plus an audit row in the same transaction, so a stale or illegal move changes nothing. Every decision carries a request id, so approving on the phone and in Telegram records one decision. The laptop owns the git states; the server owns the decision states.
Verification loop

How wisen knows it is climbing the hill

Each approved proposal is one step up the hill. A step counts only if it makes the work measurably better without making anything worse. Five metric layers, from "did work get done" down to "can we trust our own judge". Today the friction and cost metrics read Claude Code transcripts only; the other agents' transcripts lack the markers they rely on.

1OutcomeDid work get done?

Problems solved

solved = count(commits I authored that land on the default branch), each credited once, to the nearest session in that repo (a feature branch counts as one problem when it lands)

Read from each project's local git history. Squash-merged PRs are counted once a GitHub connector supplies merged-PR data.

wisen/evals/verification.py

Revert or re-fix rate (quality guard)

revert_rate = solved items reverted, or re-fixed within 7 days / solved

Stops "solved" from rewarding fast, wrong commits.

2CostWhat did it take?

Human-in-the-loop turns per PR

hitl_turns(PR) = Σ user turns across the sessions linked to that PR, from the first related session to the merge

My attention is the scarcest resource; this is the headline cost, shown next to tokens per problem.

Tokens and dollars per problem solved

tokens_per_solved = Σ tokens / solved dollars_per_solved = Σ costUSD / solved (where the transcript records it)
Claude Code transcripts · wisen/evals/miner.py
3FrictionHow hard was it?

Corrections per 100 user turns

corrections = tool_rejections + interruptions + explicit_corrections + rephrase_storms rate = corrections / user_turns × 100 (per day, per detector)

Deterministic code, no model: the "user doesn't want to proceed" marker, "[Request interrupted by user", a message starting with no / stop / wait / revert / wrong, and a rephrase storm (a second message within 60 seconds).

wisen/evals/miner.py

Friction half-life

half_life = mean(days_persisting) over frictions marked resolved

Days a friction survives before it stops recurring, from the nightly reflection's new / persisting / resolved labels.

wisen/evals/metrics.py
4Controlled checkDid the change cause it?

Replay pass rate, per config version

pass(case, config) = majority of 3 judge votes that the corrected behaviour did not recur when the case is replayed under config replay_rate(config) = Σ pass / cases clean_rate(config) = same, over the clean set

Shown on the proposal, for example "fixed 7 of 10 past cases, broke 0 of 20 clean ones", with the replay's model cost.

wisen/evals/replay.py · judge.py · runner.py
5TrustIs our own judge sane?

Alignment vs corrections

r = pearson(alignment_score(day), corrections_per_100(day))

The nightly reflection gives each day an LLM-judged alignment score; the code counts corrections independently. A healthy judge scores hard days low, so r should be clearly negative. Near zero means the score is noise. Reported by wisen eval.

Before: accept rule, shownEach proposal shows whether it meets the rule (replay rate up, clean rate not down): yes, no, or not enough cases to tell. I still decide.
After: field check2 weeks after merge, before vs after: helped if corrections per 100 turns fall more than 5% and tokens per problem rise no more than 5%; worse if corrections rise more than 5% or tokens rise more than 10%; otherwise no change.
RecordKept or revert proposed, with the reason. Rejection notes and results feed the next Gardener run.

Why both: daily field metrics are noisy because the work changes (a refactor day has more friction than a docs day). Replay holds the moments fixed and changes only the config, so it is the causal evidence; the field check confirms it held in real life.

Climbing the hill: corrections per 100 user turns illustrative shape, not measured data 04812 #1 kept#2 kept#3 kept#4 no change weeks →● config change merged
The hill as the dashboard shows it, with a marker where each Gardener change was merged. The dashboard plots daily corrections per 100 turns and tokens per problem solved.
Production-grade 2

Durability, end to end: the life of one Approve tap

Two machines, two doors, one meeting point. I use the app routes with my login; the laptop uses the device routes with its device token. They never call each other: the server's database is where they meet. Every step writes its fact before acting, every request carries an id so a retry is harmless, and the laptop pulls work with a cursor, so nothing is lost when either side crashes or sleeps.

sequenceDiagram
  autonumber
  participant P as Me (phone)
  participant A as App route
  participant DB as server.db
  participant D as Device route
  participant L as Laptop (job engine)
  P->>A: POST /api/proposals/{id}/decision (approve, request_id)
  A->>DB: one transaction: proposed → approved (compare-and-set), decision row, audit row
  A-->>P: 200 (or "already decided" for a repeat)
  Note over DB: decision is now a stored event #N
  L->>D: POST /api/device/poll (decisions after cursor)
  D->>DB: read events after cursor
  D-->>L: event #N: proposal approved
  L->>L: enqueue job "apply proposal" (request id = proposal id)
  L->>L: step: re-check approval, allow-list, file unchanged
  L->>L: step (not replay-safe): one deterministic commit on wisen/gardener/{id}
  L->>D: POST /api/device/packets (status: applied, branch)
  D->>DB: proposal approved → applied (laptop owns git states)
The app route only writes the decision; the laptop finds it through its own poll. If the laptop is asleep, the event waits in the database until the next poll.
What goes wrongWhat happensMechanism
I tap Approve twice, or on both the phone and TelegramOne decision is recorded; the second tap gets "already decided"Request id; first decision wins
The proposal expired a second before my tap409; nothing changesCompare-and-set: only proposed can become approved
The server crashes right after my tapThe decision survives; the laptop still receives itCommitted in one transaction before the response
The laptop is asleepThe decision waits; the next poll after wake-up picks it upStored events plus a per-device cursor, so none are missed or repeated
The laptop crashes mid-applyThe lease expires and the job reruns; the commit is identical, so no second branchLeases, saved steps, deterministic commit (fixed author, time, parent)
The file changed after the proposal was writtenApply refuses and the proposal becomes failed; nothing is writtenRe-check before writing
A revoked laptop tries to act401 on every device routeDevice token checked on each call; app and device credentials are separate
Production-grade 3

Durable execution, built from scratch

The concept. A durable workflow is code that survives its own process dying. Each step's result is written down before the next step starts, so after a crash, a deploy or a laptop going to sleep, the work resumes from the last finished step instead of starting over. wisen needs this because model calls cost money and minutes, because a proposal legitimately waits hours for my decision and two weeks for its measure, and because the work is split across a laptop that sleeps and a server that does not.

recordMemoized steps

A job is a list of named steps. A finished step's output is saved; a rerun returns the saved output instead of calling the model again.

claimLeases

A worker claims a job with an expiring lease and heartbeats to keep it. A dead or sleeping worker's lease expires and the job goes back to the queue.

safetyReplay policy per step

Reads and model calls are safe to repeat. Side effects (create a branch, send a push) are not: an interrupted one fails the job for a human instead of running twice.

pauseWaits

A job parks until an event arrives, for example waiting for my decision on a proposal, or for the laptop's result.

laterTimers

A job with run_after in the future: the 7-day proposal expiry and the measure job 2 weeks after merge. Wake-ups may repeat, so handlers are idempotent.

dedupeRequest ids

Each request carries a unique id; the job row is its receipt. A resent request returns the existing job instead of starting a second one.

lease Observer Synthesizer time attempt 1 leased · heartbeat model call · 6 min ✓ saved ✗ process killed lease expires → queued attempt 2 read from checkpoint · no model call model call ✓ 1 reflection
Stage A, where both steps run as one job on the laptop; this is the step-3 crash test. Steps declare whether rerunning is safe. Reads and model calls are; side effects like creating a branch or sending a push are not, so an interrupted side effect fails the job for a human to check instead of running twice.

My approach. pydantic-ai runs each single agent call; everything between calls and between machines is a small engine I wrote on SQLite, the same code on the laptop and the server, each with its own database. One agent run is one step. On the server a job's runner column says who may claim it: the server runs its own jobs in-process, and device jobs are claimed by the laptop over HTTPS with the same lease rules.

ChoiceWhy
Hand-built engine on SQLiteTwo processes, one of which sleeps; one file per machine; no extra service on a 2 vCPU box. Building it is also the point of the project: learning orchestration from scratch.
DBOS as the fallbackIf the engine fails its crash tests or keeps costing more than the features on it, DBOS (in-process, SQLite) swaps in behind the same job interface. The proposal state machine stays hand-built either way.
Proven by crash testsKill the process between Observer and Synthesizer: the Observer is not called again and exactly one reflection is stored. A duplicate request id returns the existing job. An expired lease is requeued on startup.

Inside the job engine

The whole engine is three SQLite tables and a handful of functions (wisen/jobs.py, tables in wisen/store.py). It keeps nothing in memory that a restart would lose: every function commits its change before it returns.

stateDiagram-v2
  [*] --> queued: enqueue (runnable once run_after passes)
  queued --> leased: claim (lease 60 s, heartbeats extend it)
  leased --> succeeded: finish
  leased --> waiting: ctx.wait (parked until a signal or timeout)
  waiting --> queued: signal arrives / timeout passes
  leased --> queued: attempt failed, retry with backoff / lease expired
  leased --> failed: attempts used up / unsafe step interrupted
  failed --> queued: same request id rerun
  succeeded --> [*]
Job states. A failed attempt goes back to the queue after a backoff that starts at 30 seconds and doubles each attempt, capped at 1 hour.
jobs · one row per piece of workWhy it exists
idTEXT, primary keyAddresses the job everywhere: steps, logs, the API.
user_idTEXTEvery row is scoped to a user, so the same engine can serve a hosted, multi-user wisen later.
kind, argsTEXT, JSONWhich handler runs, with what input (for example daily-synthesis, {"date": "2026-10-21"}).
runnerlocal | deviceWho may claim it: this process, or the paired laptop over HTTPS.
statequeued · leased · waiting · succeeded · failedThe one source of truth for where the job is.
attempts, max_attemptsINTEGERRetries with backoff, and a hard stop so a job that keeps crashing its process gives up.
run_aftertimestampTimers and backoff: the job is not due before this. The 7-day expiry and the 2-week measure are just jobs with a future run_after.
wait_keyTEXTWhat a parked job is waiting for, for example a decision on one proposal.
lease_owner, lease_expires_atTEXT, timestampWho holds the job and until when. An expired lease means the worker died or slept, so the job is requeued.
request_idUNIQUE per userThe receipt. The same request twice returns the same job instead of doing the work twice.
result, errorJSON, TEXTThe outcome, or why it failed.
created_at, updated_attimestampAudit and debugging.
job_steps · one row per finished step
(job_id, name)primary key: one checkpoint per step
statestarted or done; a started step found after a crash was interrupted
replay_safemay this step run again after a crash? Model calls yes; git branches and pushes no
outputthe saved result a rerun returns instead of calling the model again; dropped once the job succeeds
started_at, finished_attiming
job_signals · events for parked jobs
(user_id, key)primary key: one event per key
payloadwhat arrived, for example "approved, request id r-91"
atwhen
Stored even if no job is waiting yet, so a decision that arrives before the job parks is not lost. The first write wins.
FunctionWhen it is calledWhy
enqueue(kind, args, run_after, request_id)The 07:00 schedule, the CLI, an approval, a merge (to set the 2-week measure)Turns a request into a durable row; a known request id returns the existing job
run_once() / run_forever()The worker loop in each processRecovers expired leases, then claims and runs one due job. The next wake-up is recomputed from the table every pass, so no timer lives in memory
ctx.step(name, fn, replay_safe)Inside a handler, around each phase: the Observer call, the Synthesizer call, the git commitRuns fn once and saves its output; a rerun returns the saved output
ctx.wait(name, key, timeout)When a job needs an outside event: my decision, the laptop's resultParks the job and ends this run without holding a worker
signal(key, payload)When the event arrives: an approval from the phone or TelegramStores the event and wakes the parked job
recover()On startup and every worker passRequeues jobs whose lease expired; fails a job whose unsafe step was interrupted
claim_as · heartbeat_as · finish_as · fail_asThe laptop, over HTTPS, for runner = device jobsThe same lease rules for an outside worker. Each call returns False and changes nothing if that worker has lost the lease

Design rules the engine follows: only committed state exists; every job checkpoints after each phase; every step declares whether it is safe to rerun; request ids make retries harmless; timers are recomputed from stored jobs and wakes may repeat, so handlers are idempotent; crash-safe decisions are first-write-wins. These follow the lessons in Earendil's "Pi Durable" posts.

The dashboard

What I open every morning

An installable web app (a PWA) the server builds from packets.

Morning brief

Three bullets: what won yesterday, what hurt, what to try today.

Approval inbox

Today's proposals with diff, evidence quotes, replay result and whether each meets the accept rule.

Hill timeline

Corrections per 100 turns and tokens per problem solved, with a marker per merged change.

Friction

Typed friction points and the ones that refuse to die.

Alignment over time

The nightly alignment score; its correlation with counted corrections is in wisen eval.

Usage

Claude and Codex subscription usage and reset times; only percentages reach the server.

Running it

Deployment

WhereWhat
Laptopwisen worker under launchd; SQLite at ~/.wisen/wisen.db; egress ledger; ~/.wisen/gardener/home.git for instruction files outside any repo
Serverwisen cloud serve: one Python process under systemd on a 2 vCPU / 3.7 GiB Hetzner box, behind Caddy HTTPS; SQLite with a backup timer; restore refuses while the server runs
DevicesPairing codes and revocable per-device tokens; the laptop connects outbound only. Every row carries user_id, so each developer can self-host
ApprovalsWeb Push to the installed app, and a Telegram bot with approve and reject buttons
Long-term recordClaude Code deletes transcripts after 30 days, so the server's packets and reflections become the long-term history; that is why backups go off the box
For the review

Production-grade and experimental, side by side

Production-grade

  • A privacy boundary enforced by one shared schema at both ends, proven by marker tests
  • Durable execution on SQLite: leases, memoized steps, replay policies, crash tests
  • A proposal state machine with compare-and-set moves and an audit log
  • Idempotent decisions across two approval channels; deterministic commits
  • A path allow-list enforced in the applier, not the prompt
  • A self-hosted server: systemd, Caddy, backups, device tokens

Experimental

  • Sleep as architecture: NREM on the laptop, REM on the server
  • An agent that edits its operator's agent instructions, behind a human gate
  • Correction moments mined from my own transcripts as an eval set
  • Counterfactual replay before every proposal
  • Measuring the judge: alignment score against counted corrections
  • Grep-first search: no vector index, so no second copy of the transcripts; search re-reads the originals at question time
Still open

What I would decide next

QuestionWhy it matters
A local model for the ObserverNo provider would ever see raw text; quality unknown until measured with replay.
Friction half-life without the modelCount days until a correction signal stops recurring, so the metric does not depend on the judge.
A configurable per-turn excerpt cap (400 today, up to about 4,000)More context may improve reflections; measure it with replay before raising it.
Metrics for the other agentsCodex, Cursor and the rest need their own correction detectors.