cubefarm
CLAUDE.md144 starsChanged 58 days agoMITView on GitHub
A cartoon first-person 3D office (React Three Fiber) over a Node orchestrator that runs one coding-agent session (Claude Code, Codex or OpenCode) per agent, plus the CEO, working through GitHub issues. Agents are interchangeable (no roles: any free agent builds, tests or fixes) and each works on a machine of its own (docs/agents.md). This is the app the company runs on: a live office is running from this repo right now. README.md is the quick start; docs/how-it-works.md and CONTRIBUTING.md have…
- Installs packages
In this repositoryOne other file it gives its agents.
- docs/agents.mdAGENTS.md
The file
We split this CLAUDE.md into the rules it gives an agent
6 rules. About 0 are common, 1 is distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Very specific: line 14
Test only in demo mode (fake GitHub, fake agents, no Claude usage), with an isolated SWARM_HOME and your reserved SWARM_PORT (from your job …
- Very specific: line 28
Never real mode (no --demo), and never npm run dev / npm run demo / npm start / npx cubefarm: they default to 4317, and dev/demo default …
- Very specific: line 213
Test pure functions directly.
- Very specific: line 215
Must pass on both CI runners (ubuntu + windows): don't hardcode / or \ in expected paths.
- Very specific: line 223
Before opening it: typecheck, test and build.
- Distinctive: line 225
Never push to main, never force-push, never merge your own PR.
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
cubefarm
A cartoon first-person 3D office (React Three Fiber) over a Node orchestrator that runs one coding-agent session
(Claude Code, Codex or OpenCode) per agent, plus the CEO, working through GitHub issues. Agents are interchangeable (no
roles: any free agent builds, tests or fixes) and each works on a machine of its own (docs/agents.md).
This is the app the company runs on: a live office is running from this repo right now. README.md is the quick start; docs/how-it-works.md and CONTRIBUTING.md have the details.
It ships on npm as cubefarm (npx cubefarm); it used to be called Office Swarm.
SAFETY (read first)
- The live office runs from
C:\Projects\office-swarmon this machine, on ports 4317 (server) and 5317 (Vite), with its state in~/.cubefarm. Never edit or run anything there, never read or write~/.cubefarmdirectly, and never use ports 4317 or 5317. Test only in demo mode (fake GitHub, fake agents, no Claude usage), with an isolated
SWARM_HOMEand your reservedSWARM_PORT(from your job instructions):npm install npm run build SWARM_HOME="$PWD/.swarm-home" SWARM_PORT=<your port> node --import tsx server/index.ts --demonpm install; npm run build $env:SWARM_HOME="$PWD\.swarm-home"; $env:SWARM_PORT="<your port>"; node --import tsx server/index.ts --demoThen open
http://localhost:<your port>(the server serves the builtdist/). The startup banner must sayDEMO MODEand print astate:path inside yourSWARM_HOME. Stop it when done; don't commit.swarm-home.- Never real mode (no
--demo), and nevernpm run dev/npm run demo/npm start/npx cubefarm: they default to 4317, anddev/demodefault Vite to 5317. The first three runscripts/office.mjs, the launcher, which also updates its own folder (git fetch + merge, npm install, build) when the office or you ask for it (u). Run it only in a throwaway clone outside the live office, with--demoand yourSWARM_HOME,SWARM_PORTandSWARM_CLIENT_PORT. - Agents are ordinary coding-agent CLI sessions on the manager's own setup, unsandboxed, by the manager's choice. The
office's workflow rules (no pushes to the default branch, no merging, QA leaves GitHub alone) live in their prompts
and instructions, not in enforcement: don't add hooks, permission rules or sandboxes that refuse tool calls.
ANTHROPIC_*/CLAUDE_*are stripped from agent and preview env.
Scripts
| Command | What it does |
npm run typecheck | tsc --noEmit over client, server, shared, the .ts in scripts and the configs |
npm test | Vitest, once (npm run test:watch to re-run on edits) |
npm run build | typecheck, vite build to dist/, then the server bundled into dist-server/ (scripts/build-server.mjs) |
npm run test:e2e | optional, local only: Playwright (e2e/, playwright.config.ts): builds (E2E_SKIP_BUILD=1 reuses your dist/), boots a demo office on E2E_PORT (default 4399; set it to your reserved port) with a temp SWARM_HOME, and smoke-tests it headless in a local Google Chrome, else Playwright's Chromium. Stops at once if the browser is missing: never install it mid-task |
node scripts/smoke-package.mjs | after a build: packs the npm package, installs it into a temp folder and boots its demo |
npm run bench -- --port <yours> | after a build: the scale benchmark (scripts/bench.mjs): boots the big-company demo headless, visits the lobby and three floors, writes FPS, frame-time p95, CPU per frame, draw calls, triangles, heap, audio nodes and websocket traffic to a JSON report (--help) |
node --import tsx server/index.ts --demo | a demo office (see SAFETY for the env it needs) |
CI (.github/workflows/ci.yml): Node 24, npm ci → typecheck → test → build → package smoke test, for every PR
and push to main, with a throwaway SWARM_HOME and SWARM_PORT=0, on ubuntu-latest always and on windows-latest
and macos-latest unless a PR touches nothing OS-sensitive (only client/, e2e/, docs: they show as skipped).
e2e is not part of CI. Locally, typecheck, test and build must pass before you open a PR. Don't run test:e2e
unless an issue asks for it. If your change shows up in the office, boot your own demo office, check it in a real
browser with the Playwright tools, and put screenshots in the PR. .github/workflows/release.yml publishes to npm when the manager runs it from GitHub's Actions tab or pushes a
v* tag (npm trusted publishing, tied to that file name); never publish or tag releases yourself.
Code map
Server (server/, Node + Express 5 + ws, run by tsx in development; esbuild bundles it into dist-server/ for npm):
index.ts: entry; picks the real or demo backend, REST routes under/api, the/wsand/ws/termwebsockets, servesdist/, shutdown.config.ts:SWARM_PORT(default 4317),SWARM_HOST(default 127.0.0.1;npx cubefarm --host),SWARM_HOME(default~/.cubefarm),--demo, state file, intervals, the default projects folder.swarm.ts: the orchestrator. Floors, agents, scheduling/auto-assign, build → QA → fix → merge loop, team changes (the CEO'sscale_team, lobby approvals), CEO job queue, phone messages, persistence (state.json/demo-state.json), websocket fan-out (throughoutbox.ts).outbox.ts: what goes out on/ws: agents' and floors' changes batched on a 250 ms tick as patches of what changed, terminal lines only to the tabs that show them (shared/watch.ts), catch-ups when a tab's watch changes.agentRunner.ts: one Agent SDK session; options, env stripping, Playwright MCP, and turning the SDK stream into terminal lines.cliRunner.ts: the terminal runtime (the default): one agent as the real CLI in a node-pty, same session contract asagentRunner.ts. Claude Code reports through HTTP hooks (POST /api/hooks/:token; PreToolUse approves every call); Codex reports turn endings (notify) and, once the manager trusts them, its steps (-c hooks.*); OpenCode only turn endings. Codex/OpenCode screenshots are collected from the session's Playwright output folder. Esc in a terminal ends the session asinterrupted. The CEO's office tools are served over MCP (/api/mcp/:token).ptyHost.ts: the terminal keeper, a detached process of its own (launchre-spawns it outside the office's process tree) holding the CLIs' pseudo-terminals and relaying their hooks, so agents keep working through office restarts.ptyClient.tsis the office's side (start/connect, spawn, adopt after a restart, local fallback);ptyProtocol.tstheir JSON-lines messages. The launcher'soffice:shutdownsaysrestart: falsewhen quitting: CLIs stop then. An agent's CLI stays at its prompt after building or fixing (keepAlive): follow-ups and prompts typed there reuse it.clis.ts: the CLIs (Claude Code from the SDK's bundled binary, Codex, OpenCode): detection, Windows.cmdshim unwrapping, each one's command line, and the helper scripts they call back with.terminal.ts:AgentTerminal, a headless xterm mirror per agent (replay for late viewers, saved to disk), its/ws/termviewers, and keystrokes/resizes to the running CLI.ceo.ts: the CEO's office MCP tools (createOfficeTools, zod-validated:scale_team,configure_agent, issues, triage),scalePlan(team-size arithmetic),ceoSystemPrompt,ceoJobPrompt.backend.ts: theBackendinterface (everything touching GitHub, git, disk and sessions) andrealBackend.machines.ts: agents' machines,MachineProvider: each agent's own clone, worktree and temp folder (the local provider is folders under<SWARM_HOME>/machines/<machine>/, inworkspace.ts; cloud agents' are Upstash Boxes).- Cloud agents (docs/cloud.md, opt-in;
PersistedAgent.host === 'box'):cloud.tsis the account (the Upstash key and pasted keys insecrets.json,CUBEFARM_CLAUDE_TOKENread from the environment and never saved, credential resolution,CloudView);box.tsthe only importer of@upstash/box(BoxApi, which the demo fakes);boxMachines.tsthe BoxMachineProvider(create, set up, prepare, pause, leftovers);boxScripts.tsthe shell scripts run in a Box (pure, tested);boxHelpers.tsthe programs put in a Box (launcher, hooks writing to the session'sevents.jsonl);boxCli.tsBoxPty(the CLI under tmux, its events read from a byte offset, reattached after drops and restarts). Credentials only ever travel as one Box command's environment. Without a key for its CLI, a cloud agent's CLI uses its own login in the Box:Swarm's sign-in checks it before each task (needsSignInholds the task) and runs the CLI's own login in their terminal (cliRunner.tsstartBoxSignIn); the office never reads that login. demo.ts:createDemoBackend(): fake GitHub, fake sessions (drawn into the agent's terminal in the terminal runtime), fake previews and machines for--demo;--floors N --agents N(orSWARM_DEMO_FLOORS/SWARM_DEMO_AGENTS) makes it a big company for scale tests.github.ts: all GitHub access through theghCLI.workspace.ts: floor checkouts, the preview worktrees (<SWARM_HOME>/workspaces/<owner>__<repo>/desks/<name>), local machines (clone, worktree, branch sweep, removal with leftovers), fast-forwarding main, a git lock per clone, stopping processes an agent left running.exec.ts:run/git/gh:execFilewithout a shell, prompts disabled,CommandErrorwith stderr.previews.ts: one preview per floor: ports (6300 + floor), statuses, config validation; and the PR theatre's PR previews (prTheatre.ts: their slots, ports, eviction and idle stop, pure;syncProxy.ts: compare mode's synced scrolling).previewGateway.ts: previews through the office's own address at/preview/<port>/for other devices, with a service worker keeping the apps' root paths under it.qaShots.ts: QA's screenshots of each PR's latest round, kept for the app viewer's QA panel.previewRunner.ts: checks out, installs and runs a floor's app in its preview worktree; kills the process tree.httpError.ts:HttpError(status, message).officeUpdate.ts: the office's self-update: the drain decision, the launcher contract (IPC,last-update.json).pacing.ts: pacing new work after Claude's usage warnings: the start/skip decision and the usage state.presence.ts: shared presence: relays tabs' poses, emotes and pings on/wsto their floor (pure interest and rate rules), never saved;demoVisitors.tswalks the demo's fake visitors. Names and limits inshared/presence.ts.voice.ts: phone messages read aloud (docs/voice.md): the ElevenLabs key insecrets.json, voices, cached clips;elevenlabs.tsis its REST client. The words spoken come fromshared/speech.ts.secrets.ts: that file's reads and merged writes.notifier.ts: notifications (docs/pocket.md): the rate-limited fan-out to open tabs (desktop), Web Push and the chat apps' webhooks (secrets insecrets.json, push keys and devices inpush.json), behindBackend.notify;notify.tsis its pure part (formatting, the per-event rate limit, webhook checks),webPush.tsVAPID and RFC 8291 encryption,shared/notify.tsthe settings.pwa.ts: the installable app's service worker, served at/sw.js.journal.ts: the time-lapse journal (<SWARM_HOME>/journal/<day>/): records whatSwarm.broadcastsends, a file per 10-minute keyframe, pruning, and the reads behind/api/journal/*. The rules (what's kept, secrets, seeking, marks) are inshared/journal.ts;journalSample.tsis the demo's made-up day.
The cubefarm command (bin/cubefarm.js, plain JS): checks Node/git/gh/Claude login, starts dist-server/index.js,
opens the browser; login and doctor subcommands.
The launcher (scripts/office.mjs, plain JS; npm run dev / demo / start): runs the server (plus Vite with
--dev, watching server/ and shared/) with SWARM_LAUNCHER=1 and an IPC channel, and applies office updates:
stop, fast-forward, install/build, restart, roll back on failure, <SWARM_HOME>/last-update.json. Its pure decisions
are in scripts/officeSteps.mjs (tested in officeSteps.test.ts).
Shared (shared/, imported by both sides):
types.ts: the REST/websocket contract (WorldSnapshot,ServerEvent, views, settings).issues.ts: issue conventions (swarm:skip,Depends on #N, hold-up ranking).journal.ts: the time-lapse journal's format and pure rules, for the server and the replay.watch.ts: which terminal lines a tab gets: its floor, open panels, the workers list's latest lines.looks.ts: the look editor's options andcleanStyle(an agent'sstyle, checked on the server).
Client (client/, Vite root; React 19, R3F, drei, zustand):
src/world/: the 3D building: floors, desks, characters (appearance.ts,characterParts.ts,Figure.tsx,face.ts), elevator, whiteboard, player movement and collisions (layout.ts), canvas textures (draw.ts),toys/(Rapier physics), where people can walk (walkways.ts: the walk grid, paths, named spots and steering, on the roomba's grid), errands that get them up (errands.ts: the registry and who may go;ErrandDirector.tsxruns them), toy errands (toyErrands.ts: hoops and catch, ontoys/npc.ts, the toys' hands for people, aimed bytoys/npcAim.ts), comings and goings (socials.ts: new agents by elevator, leavers with a box, chats, visits, the CEO's stroll), the time of day (sky/time.ts,sky/useDayTime.ts) and the city outside (outside/: the seeded layout incityLayout.ts, drawn byCity.tsxin six instanced draw calls), the camera's other views (camera/: the overview, the building view and the follow cam inrig.ts, pose maths incameraMath.ts, the cutaway as global clipping planes), the gamepad (gamepad.ts) and the graphics tiers (gfx/: Low/Medium/High/Auto inquality.tswith Auto's governor, post-processing in a lazy chunk (Effects.tsx,pipeline.ts); a material blooms only ifbloomMarks.tsmarks it), the other people viewing the office (presence/: visitors, pings, the profile), holiday themes (themes/: which one is on fromshared/themes.ts, their data and decoration slots inthemes.tsandlayout.ts, each theme's scene in one lazy chunk loaded only while a theme is on;?theme=and?date=for QA).src/ui/: HTML overlays: HUD, terminal (LiveTerminal.tsx: xterm.js on/ws/term), Kanban, manager's console, phone (with its mini-games ingames/: pure logic intetris.ts/snake.ts/pet.ts), elevator panel, app viewer, sounds (sfx.ts), key bindings (keymap.ts, pure;controls.tskeeps the player's own, and every shortcut asks it, never a hard-coded key).- Accessibility (Settings → Accessibility,
ui/a11y.ts, saved per browser through purea11yPrefs.ts): captions (captions.ts, rules incaptionRules.ts; every soundsfx.tsrecords is offered to them), status colours and shapes (statusLook.ts, shared by CSS and the canvases), motion comfort (callreduceMotion()before animating the camera or anything non-essential), UI scale, readable font, high contrast. Dialogs usedialogFocus.ts(focus in, trapped, returned);announce()speaks to screen readers;FloorList.tsxis the list view. src/pocket/: pocket mode (docs/pocket.md), the 2D office for phones (mode.tspicks it;App.tsxloads it or the 3DOffice.tsxlazily, so a phone never downloads three.js).src/pwa.tsregisters the service worker and Web Push;src/notifications.tsshows desktop notifications.ui/Panel.tsxis the panel, apart fromOverlays.tsx(3D).src/photo/: photo mode and clips, lazy-loaded exceptgate.ts(on/frozen, the K and I keys,__swarmPhoto):PhotoScene.tsx(its own camera; frozen, the frame loop stops and it draws on change),post.ts(filters and depth of field on the finished picture),recorder.ts/instantReplay.ts(MediaRecorder;webmRing.tskeeps the last 15 s),PhotoPanel.tsx, and pureflight.ts,shots.ts,filters.ts.src/store.ts: the zustand store;apply(ServerEvent)folds websocket events into UI state.src/api.ts: REST calls; errors become toasts.src/net.ts: the websocket connection with reconnect; it sends the tab's watch (src/watch.ts) as it changes.src/perf.tsx: render pausing, adaptive DPR,?stats(andwindow.__swarmStatswith a census of what's drawn).src/world/batch.ts/Batched.tsx: a floor's repeated parts (Toon.tsx's boxes, people'sPieces) drawn as instanced batches behind invisible stand-ins (?batch=offto compare).src/world/paint/: canvas textures recorded here and painted in an OffscreenCanvas worker, with the canvas path as fallback (?paint=main).src/replay.ts: the time-lapse: plays the journal throughstore.apply(ev, 'play' | 'seek')while live events wait;replayClock.tsis its pure clock and "since I was last here",ui/TimeLapse.tsxits console tab and bar.
Conventions
- ESM TypeScript everywhere (
"type": "module"), strict,noUnusedLocals/Parameters. The server runs through tsx and imports with.tsextensions (import { run } from './exec.ts'); client files import without extensions. - Comments are sparse and say why: a short header comment per file describing its role,
/** */on exported functions and interface fields when the name isn't enough, inline notes for Windows or safety reasons, and// ---------- section ----------dividers in long files. No commented-out code. - Demo parity: every new
Backendmethod, CEO tool or capability gets a fake inserver/demo.ts, so--demoworks with no GitHub, no git/npm and no Claude usage. - UI state comes from the server: on connect the client gets a
snapshot, then typedServerEvents (repo,agent,qa,ceo,message,toast, …) fromSwarm.broadcast; agents' and floors' frequent changes come batched asagents/repospatches and terminal lines aslogs/latest, only for what the tab shows (server/outbox.ts). Add new state toshared/types.ts, the snapshot and an event, and handle it instore.ts'sapply. REST is for commands, not for polling state. A big company must fitserver/scale.test.ts's budgets. - REST errors: throw
HttpError(4xx, message); the handler inindex.tsreturns{ error }JSON, anything else is a logged 500. Validate request bodies by hand at the route or in the swarm. - CEO tools: zod input schemas, errors worded so the CEO can act on them, small outputs.
- Windows first (the office runs on Windows):
- build paths with
path.join/path.resolve; paths may contain spaces, so pass args as arrays (execFile), never string-built shell commands; fs.rmwithmaxRetriesfor EBUSY/EPERM file locks; write state to a temp file andrename;- kill process trees, not just the child (
taskkill /T /Fon Windows, process groups elsewhere); windowsHide: trueon spawns; npm on Windows goes throughcmd.exe.
- build paths with
- Agent prompts are paid for on every session: keep prompt text short and specific.
Tests
- Vitest,
*.test.tsnext to the code, anywhere underclient/,server/,shared/orscripts/(e.g.shared/issues.test.ts,client/src/world/layout.test.ts,server/ceo.test.ts). Config:vitest.config.ts. - Test pure functions directly; extract logic into pure helpers rather than mocking. No network, no
gh, no Claude sessions, no real~/.cubefarm:npm testalready pointsSWARM_HOMEat a temp folder andSWARM_PORTat 0. - Must pass on both CI runners (ubuntu + windows): don't hardcode
/or\in expected paths. - E2E: one spec file per feature, setup from
e2e/helpers.ts; new e2e tests go in their feature's spec file or a new one, never appended tosmoke.spec.ts.
Pull requests
- One issue per PR,
Closes #<n>in the body. Keep the diff small and on-topic. - Many PRs merge in parallel and auto-merge sends conflicts back: don't reformat, reorder or rename code you aren't changing, and don't touch unrelated files.
- Before opening it:
typecheck,testandbuild.test:e2eonly when an issue asks for it; CI doesn't run it. - Say how you verified it and list your assumptions. UI changes get screenshots from the demo office.
- Never push to
main, never force-push, never merge your own PR.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

