Interconnection

How work flows and how every piece connects — the SENSE → THINK → ACT → LEARN loop, the dispatch table, kun engine, machines, Hermes, CRM, and the Claude surfaces

Interconnection

How the whole system holds together: the kun engine, the machine fleet, the Hermes gateway, the self-hosted CRM, and the four surfaces you touch Claude from (terminal, chat, Cowork, phone).

The core insight: nothing talks machine-to-machine. Every machine talks to a small set of shared cloud services — GitHub, Slack, Vercel, the CRM — and those services are the interconnection. No VPN, no port-forwarding, no server administration for the team.

How work flows — SENSE → THINK → ACT → LEARN

You talk to one door — a Claude Code session, from the terminal, the Desktop Code tab, the iPhone (Remote Control), or Slack (Hermes). The session splits the work; you don't. Every surface and every loop follows the same four beats:

 SENSE ─────────────► THINK ─────────────► ACT ─────────────► LEARN ─┐
 aware.mjs            resolve.mjs           lanes + ledger          improve.mjs
 one snapshot of      names → repos and     main session, agents,   findings from the
 everything, 0 tokens blocks; dispatch      Workflows, loops        runs → SAFE fixes,
                      table picks lane,     (kun-claude.sh logs     DECIDE → one issue,
                      model, effort         tokens + cost)          measured before/after
   ▲                                                                       │
   └─────────────────────── the Monday routine closes the loop ◄───────────┘

Talk to kun — plain words, few of them

You sayWhat happens
"mkan listing is broken"the router names ~/mkan (its own CLAUDE.md applies), the session works there
"fix the admission form" (from a kun session)one hint: the hogwarts admission block — and that seek also uses the word — the session picks by context
"fix the admission form" (inside hogwarts)the full block protocol: read the block's records first, update them + its docs + the issue after
"status" / "حالة" on SlackHermes pastes ~/.claude/state/aware.md — zero Claude tokens
"deploy balqalam" on SlackHermes hands it to Claude Code with auto; the router picks hogwarts; the thread stays there
"sync self" / "improve yourself"/sync self: apply safe fixes, refresh the Engine decisions issue, apply what you approved
"yes 9ac6e654" on the Engine decisions issueapproves that row; the next sync self (or Monday) applies it and measures the result

SENSE — awareness of everything happening

node ~/kun/.claude/scripts/aware.mjs takes one zero-token snapshot: the machine (disk + its 24 h trend, swap, sessions, Remote Control), every scheduled job (runs.sh, Hermes cron), spend (the headless ledger plus every transcript's usage — fresh tokens vs cache reads, per surface, average context per turn), the engine (heartbeat, sync tiers, bench age, findings, decisions past review), the queue (reports, issues by priority, Cowork handoffs), main CI per repo, Hermes, WIP, and which sessions are active now. Where you read it:

SurfaceHow
Every session starta ≤5-line brief, silent when green (session-aware.sh, ~30 ms)
iPhone / Slackalerts (below) and "status" via Hermes
Coworkreads ~/.claude/state/aware.md through the filesystem
GitHubeach machine's #133 health report carries an awareness block

Alerts are transitions, not nags: a condition must hold on two refreshes in a row, is sent once, clears when it goes away, and at most 6 go out a day. At the Mac → a banner; away → this machine's ~/.claude/.kun-notify target (Abdout: his Slack DM). Alerted: disk under 10 GB or falling 5 GB/day, the job supervisor gone silent (it handles the jobs themselves, below), Hermes or Remote Control down, a failed main CI, commits unpushed for 12 h. Shown but never alerted: spend, sync, bench, dirty files.

AlertOwner (the one place it comes from)
a job (Mac or cloud) still broken after its re-runssupervise.mjs → one job-health issue + one Slack line
the supervisor silent, disk, CI, Hermes/RC down, unpushedaware.mjs (owner Mac: every 30 min)
the Mac off or asleep past a job's deadlinethe mkan-watchdog Worker (outside the Mac)
report-an-issue queuethe SessionStart reports hook (from aware's cache)
domains, mailthe domains GitHub Action → domains issues
engine findingsimprove.mjs → the Engine decisions issue
weekly planthe Monday routine → one message
repo movement (commits, blockers across the repos)Hermes' 4-hourly heartbeat — its own scanner; it does not repeat aware's alerts

THINK — the router and the dispatch table

resolve.mjs turns names into places before the model guesses. Every repository and every feature block is a keyword: a block of the current repo gets the block protocol (hogwarts) or a one-line pointer to its records (repos on the light protocol); another repo by name (hogwarts, mkan, souq, shifa — and aliases like balqalam, بالقلم, mkan.sd, any production domain) gets a one-line pointer, and so does one of its blocks named beside it (mkan booking, food kitchen); a unique block (admission, timetable, parent-portal, …) gets a one-line hint from any session. Each block key's class — unique, shared or common — is computed when the index is built; plain words (docs, table, finance, grades, listings) never route across repos alone, and kun, codebase and marketing never route bare. The full list is Places. Policy: engine.json → resolver; registry: .claude/memory/repositories.json; per-repo block lists: <repo>/.claude/blocks.json.

Then the session picks a lane — the dispatch table (engine.json → lanes):

WorkLaneModel · effort
Q&A, small edits, decidingthe main sessionOpus 5.5 · session effort
Look up across many files, batches of MCP readsan Explore subagenthaiku · low
Mechanical edit, formatting, githaiku agents (git, comment, icon, …)haiku · low
Research that needs reading and synthesisa forksonnet · low
Build to a known pattern (after plan approval, 2+ files)build agents, briefed in writing; the main loop reviews the diffsonnet · medium
Leads, enrichment, conversion against the CRMlead / funnel agents (job prefix crm:)sonnet · medium (funnel judges on opus · high)
A task from SlackHermes bridge (hermes:bridge) — the lane is picked per taskper task
Review, verify, judgeopus specialists, Workflow verify stagesopus · high
Fan out with verificationa Workflow (qa, handover, textbook, scrape, …) — every stage names its model and effort (lint-enforced)per stage
Long or recurring worka loop through kun-claude.sh (ledgered; lean when it needs no skills or MCP)per job
An errand in Abdout's name/behalf, then Cowork—
An easy one-file task, off the Max poolAntigravity (a)Gemini
Another running sessionListAgents → SendMessage (Code ↔ Code, any machine)—

Keywords and MCP phrases map to a lane too — the full table is Lanes. Fable is the escalate lane: attended sessions only, never a subagent or a headless run.

ACT — every run leaves a receipt

Headless Claude runs go through ~/.claude/bin/kun-claude.sh: same args, same output, plus one ledger line (job, model, effort, tokens, cost, turns, duration) and an optional daily cap. bash ~/.claude/scripts/runs.sh --spend totals it per job. Measured on 2026-11-01: a one-word headless reply from ~/kun cost 67.9K tokens with the context hooks, 61.1K without them (they now stay silent headless), and 39.5K in lean mode (no MCP, no skill listing).

LEARN — kun improves itself

improve.mjs (zero tokens, daily in the heartbeat) reads kun's own evidence — the ledger, the awareness history, the router log, transcripts, lint, health, bench-retire — and files findings with stable ids: SAFE (mechanical — applied automatically), DECIDE (changes behaviour, cost or a fleet surface — one row each on the rolling Engine decisions issue, approved with yes <id>), TRACK (context for the weekly plan). After a change, the detector either stops firing (verified) or comes back (regressed) — measured, never assumed.

The Monday routine (scripts/captain/weekly.sh, Mondays 08:00 on the owner Mac): sense → detect → one ledgered Opus run that applies sync self, syncs the anthropic tier only when a new Claude Code release exists, and writes the week's plan to .claude/memory/weekly/ — never the 2.8M-token bench, never a 36-day catch-up. Abdout gets one message. A Sunday run already plans Monday–Sunday, so a plan written in the last 3 days makes the next tick skip at zero cost.

RESUME — jobs that finish what sleep interrupted

The Mac sleeps with its lid shut, then makes ~50 dark wakes a day (2–30 s, no real network); launchd and Hermes used to fire jobs into them, and every one failed (2026-11-02: ten runs before noon). Four pieces make every scheduled job finish once the Mac is really up — exactly once:

PieceWhat it does
~/.claude/bin/job-run.sh <job> -- cmdevery launchd job's entry: waits for a full wake (pmset -g systemstate has Graphics) + the network + what the job needs (Twenty, the vault Chrome, Docker…), takes a PID lock a sleeping run keeps, caps the run, and records how it went. A dark wake becomes defer, not a failure. lib/runs.sh holds the parts; the mkan lanes and Hermes' Python jobs (hermes-gate.sh) use the same gate
~/.claude/state/runs/<job>.jsoneach job's own record — status, last ok, the live run, the last 10 runs, per-step results. runs.sh judges from it first, so a detached run that Hermes called "ok" the moment it started is judged by how it really ended
supervise.mjs (every 5 min, and within 15 s of a real wake)heals what jobs need (Hermes gateway, Colima + Twenty, the vault Chrome, daemons, plists an installer unwrapped); re-runs a missed or failed slot through the job's own entry, by policy (engine.json → jobs.<job>.resume: auto · tick · alert · heal), never a live run, never twice; escalates what stays broken — one job-health issue (the record) + one Slack line (the push), closed when it recovers. It also checks the cloud schedules hourly: GitHub Actions crons (a fresh failure re-runs once) and every Cloudflare Worker cron route (Workers Logs)
the mkan-watchdog Workeroutside eyes: the supervisor writes a beat every 15 min; when the beat goes quiet and a job's deadline passes, the Worker opens the issue — the one case no check on the Mac can report

In server mode the Mac sleeps or shuts down only when Abdout does it by hand, and looks switched off while it works (policy: engine.json → devices.power; the presence loop in devices.sh enforces it):

SituationWhat happens
On mains, lid open or shutNever sleeps. The display goes dark after two idle minutes.
Mains lost while it was workingKeeps working on battery and tells his phone at once.
Battery at 10%Sleeps on purpose, so the sessions stay in memory until power returns.
Lid shut after mains was already lostSleeps: a laptop being carried.
gabriel sleep · gabriel darkThe manual way to sleep it · screen off now, still working.

It is switched on once with bash .claude/scripts/keepawake-admin.sh apply (macOS asks for the password in its own dialog; rollback undoes it). The same step stops macOS installing updates by itself and puts a line on the lock screen, because a locked screen over the wallpaper looks like a machine that stopped — it has not. gabriel status prints the power line: source, battery, whether it is held awake, and since when it has been up. Healing, re-runs and alerts are live for every job (jobs.$supervise); to stage a change, set live false and list owners in live_owners — the rest then log would-fire instead.

The commands, in one place

node ~/kun/.claude/scripts/aware.mjs              # everything happening, now
bash ~/.claude/scripts/runs.sh                    # every scheduled job: ok / red / stale / defer
node ~/kun/.claude/scripts/supervise.mjs --status # what the supervisor re-ran, healed, escalated
bash ~/.claude/bin/job-run.sh --wrap-plists --dry # which launchd jobs are not behind the gate
bash ~/.claude/scripts/runs.sh --spend            # headless spend per job, last 7 days
node ~/kun/.claude/scripts/resolve.mjs "<words>"  # where would these words route?
node ~/kun/.claude/scripts/improve.mjs            # what kun would improve, and why
bash ~/kun/scripts/captain/weekly.sh --status     # the Monday routine

The big picture

                        ┌─────────────────────────────────────────┐
                        │            SHARED FABRIC                │
                        │                                         │
                        │  GitHub ── code + issues + kun config   │
                        │  Slack ─── databayt-sh (human bus)      │
                        │  Cloudflare ── kun + balqalam + mkan.sd  │
                        │  CRM ───── *.crm.databayt.org           │
                        └────────▲──────────▲──────────▲──────────┘
                                 │          │          │
              git pull/push      │          │          │   browser login
         ┌───────────────────────┘          │          └──────────────────┐
         │                                  │                             │
┌────────┴─────────────┐          ┌─────────┴──────────┐        ┌─────────┴────────┐
│  HOST MACHINE        │          │  TEAMMATE MACHINES │        │  PHONE (iPhone)  │
│  (Abdout's Mac)      │          │  (× 6)             │        │                  │
│                      │          │                    │        │  Claude app      │
│  Claude Code (c)     │          │  Claude Code +     │        │  ← push (away)   │
│  Cowork (Desktop)    │          │  kun config clone  │        │  Slack → Hermes  │
│  Hermes gateway (h)  │◄─────────┼────────────────────┼────────│  Code → Mac·kun  │
│   ↑ Socket Mode      │  (never  │                    │ direct)│                  │
└──────────────────────┘          └────────────────────┘        └──────────────────┘

Machines never connect to each other directly. The arrows all point at the shared fabric.

Layer 1 — Kun engine: a repo, not a service

Kun is the shared brain, and it propagates through git. The .claude/ tree (skills, agents, rules, vocabulary, memory, hooks) is the engine; any machine that clones databayt/kun and runs onboarding becomes an engine node.

databayt/kun (.claude/ config)
     │
     │  clone + daily pull (maintain heartbeat)
     ├────────────────► Abdout's Mac ──┐
     └────────────────► 6 teammate  ───┤  heartbeat status
                        machines       │
                                       ▼
                        Dashboard issue (kun#133)
  • Propagation = git pull. There is no config server.
  • The maintain heartbeat runs daily on every machine: pull → refresh → health-check → report status to the shared dashboard issue. Fleet health is visible without touching anyone's laptop.
  • Drift detection: .claude/engine.json holds the expected counts; /health flags divergence.

Layer 2 — The machine fleet

MachineRunsHosts services?
Host machine (Abdout's Mac)Claude Code (c lane) · Cowork · Hermes gateway (h lane)Yes — Hermes
Teammate machines (× 6)Claude Code + kun config cloneNo — consume everything by URL
Phone (iPhone)Claude app (Code tab, push) · Slack · GitHubNo — a remote control for the host Mac

Only the host machine runs a long-lived service (Hermes). Everyone else consumes the shared fabric with a browser and a terminal.

Layer 3 — Hermes: one binary, two pipes

Hermes (hermes-agent, the h lane) runs on the host machine and is a relay, never the LLM — Claude writes every word. Its bridge runs through kun-claude.sh as the job hermes:bridge, and each Slack task gets a lane from engine.json → lanes (resolve.mjs --lane "<task>"). It carries two unrelated flows:

PIPE 1 — inbound gateway (talk to the machine)
  Phone / Slack app ──DM──► Slack ──Socket Mode──► Hermes ──► machine's agent
                                    (outbound WS,             acts, replies,
                                     no public endpoint)      pushes proactively

PIPE 2 — social egress (the machine talks out)
  kun.databayt.org Social Hub ──HERMES_API_URL──► Hermes ──► Slack / X channels
        (on Vercel)           ──direct Bot/Graph API──────► Telegram + Facebook
                                                             (no Hermes needed)

Hermes-Slack ≠ Slack MCP. Hermes lets you talk to your machine from Slack; the Slack MCP lets Claude post to Slack as a tool. Both coexist — neither replaces the other. Full wiring: Hermes.

Telegram and Facebook deliberately bypass Hermes — the site calls their official APIs directly over HTTPS, which works from Vercel with no local gateway.

Layer 4 — CRM: the business memory

Self-hosted from databayt/crm, served at four product subdomains. It never runs on teammate machines — everyone reaches it by browser with one identity (<id>@databayt.org, the same login as Slack).

WorkspaceURLPipeline
Hogwartshogwarts.crm.databayt.orgSchools, sponsors, pilots
Mkanmkan.databayt.orgProperty/rental leads
Sijilleesijillee.crm.databayt.orgPre-launch prospects
Moallimeemoallimee.crm.databayt.orgPre-launch prospects

Business state flows back into the engine through a human-paced loop: Aseel keeps pipelines clean → the captain reads headline numbers weekly into kun/.claude/memory/pipeline.json → the engine's weekly planning sees real pipeline data. Details: CRM.

Layer 5 — The four surfaces

SurfaceWhereRoleConnects via
Claude CodeTerminal on every machine; the Desktop app's Code tab on the hostThe doing lane — builds, ships, fixesgit/GitHub, MCPs, hooks, skills
Remote ControlEvery host session, plus the always-on kun-rc server ("Mac · kun")Drive running Mac sessions, or start new ones, from the phoneThe Claude app's Code tab · claude.ai/code
Cloud sessionsThe Code tab, claude.ai/code, routines (/schedule)Work that must keep going with the Mac offGitHub repos
Claude chatclaude.ai + mobile appThinking anywhere; the cheapest surface—
CoworkClaude DesktopThe planning lane — two shells (cloud + on-device), Anthropic's Dispatch app, computer use; no Claude Code hooksShares ~/.claude/ by filesystem MCP; hands off via bridge.md + issues
PhoneiPhoneReceive, steer, startBuilt-in push (held while you're at the Mac) · SendUserFile · private Artifacts · Code tab · Slack → Hermes

The host Mac keeps this layer alive with .claude/scripts/devices.sh: a presence service (pushes wait while you're at the Mac), the kun-rc Remote Control server in tmux, and a session-start brief that speaks up when disk, swap or the server need attention. bash ~/.claude/scripts/devices.sh --status shows all of it; policy lives in engine.json → devices.

Cowork and Code never share conversations. They share only files (~/.claude/), GitHub issues, and push notifications. The bridge is deliberately file-shaped — ~/.claude/bridge.md for short handoffs — so either side picks up where the other left off at session start. Details: Cowork.

The connective tissue, one line each

BusCarries
GitHubCode, kun config, work queue (issues), heartbeat dashboard — the durable bus everything settles onto. Tasks for any coding agent on any machine: Machine → Dispatch
SlackThe human bus — team talk, Hermes inbound gateway, Claude's MCP egress
CloudflareThe deploy plane since 2026-09 — Workers + Containers for hogwarts, mkan and kun (scripts/deploy-cloudflare.sh in each repo); Vercel's free account is paused for Hobby usage and still serves the databayt.org DNS until the zone moves
bridge.mdLocal Cowork ↔ Code handoff on the same machine
PushThe instant machine-to-pocket channel — Remote Control's built-in push (held while you're at the Mac) plus the PushNotification tool for explicit pings

Reuse it — run this map for your own team

Everything above is configuration, not product. To stand up the same topology:

  1. Fork databayt/kun — the .claude/ tree is the engine. Strip docs/ and .claude/memory/ of databayt-specific state; keep the structure.
  2. Pick your fabric — a GitHub org (code + issues + config bus), a Slack workspace (human bus), a Vercel team (deploy plane). Free tiers cover a small team.
  3. Run onboarding on each machine — clone, setup.sh, and every laptop becomes an engine node. See Onboarding.
  4. Optional lanes — wire Hermes on one always-on machine if you want chat-to-machine access; self-host a CRM if you have a sales pipeline. Neither is required for the core loop.
  5. Adopt the heartbeat — a daily pull + health report per machine keeps a distributed team's config from drifting. The scripts live in .claude/scripts/.

What's genuinely databayt-specific: the vocabulary (our keywords), the memory (our clients), the docs (our decisions). What's generic and reusable: the layer model, the git-propagated config, the bus discipline, the heartbeat, the Cowork bridge, the Hermes two-pipe pattern.

Contribute to it

Team — work directly on main, no branches, no PRs (see the workflow rule in .claude/rules/github-workflow.md). Docs live in content/docs/; config in .claude/. Commit small and often; deploys run through the deploy skill. When you change the topology (new service, new lane, new bus), update this page in the same commit — the map is only useful while it's true.

Community — the repos are public under github.com/databayt:

  • Questions and ideas → open an issue on databayt/kun.
  • Fixes and additions → fork and open a PR; a maintainer reviews and lands it on main (the no-PR rule is internal discipline, not a door closed to outside contributions).
  • Reusing the engine → you don't need permission; it's open source. If you adapt the map for your team, an issue telling us what you changed makes the pattern better for everyone.
  • Architecture — the 5-layer engine model this map runs on
  • Onboarding — become an engine node
  • Hermes — the gateway lane, full Slack wiring
  • CRM — workspaces, identity, pipeline hygiene
  • Cowork — the planning lane + bridge protocol
  • Self-Hosting — when (and when not) to run your own servers