agentleFS
leonvanzylleonvanzyl/cubefarm/CLAUDE.md

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.

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
  1. Very specific:

    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 …

    line 14
  2. Very specific:

    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 …

    line 28
  3. Very specific:

    Test pure functions directly.

    line 213
  4. Very specific:

    Must pass on both CI runners (ubuntu + windows): don't hardcode / or \ in expected paths.

    line 215
  5. Very specific:

    Before opening it: typecheck, test and build.

    line 223
  6. Distinctive:

    Never push to main, never force-push, never merge your own PR.

    line 225

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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-swarm on this machine, on ports 4317 (server) and 5317 (Vite), with its state in ~/.cubefarm. Never edit or run anything there, never read or write ~/.cubefarm directly, and never use ports 4317 or 5317.
  • 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 instructions):

    npm install
    npm run build
    SWARM_HOME="$PWD/.swarm-home" SWARM_PORT=<your port> node --import tsx server/index.ts --demo
    npm install; npm run build
    $env:SWARM_HOME="$PWD\.swarm-home"; $env:SWARM_PORT="<your port>"; node --import tsx server/index.ts --demo

    Then open http://localhost:<your port> (the server serves the built dist/). The startup banner must say DEMO MODE and print a state: path inside your SWARM_HOME. Stop it when done; don't commit .swarm-home.

  • 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 Vite to 5317. The first three run scripts/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 --demo and your SWARM_HOME, SWARM_PORT and SWARM_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

CommandWhat it does
npm run typechecktsc --noEmit over client, server, shared, the .ts in scripts and the configs
npm testVitest, once (npm run test:watch to re-run on edits)
npm run buildtypecheck, vite build to dist/, then the server bundled into dist-server/ (scripts/build-server.mjs)
npm run test:e2eoptional, 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.mjsafter 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 --demoa 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 /ws and /ws/term websockets, serves dist/, 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's scale_team, lobby approvals), CEO job queue, phone messages, persistence (state.json / demo-state.json), websocket fan-out (through outbox.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 as agentRunner.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 as interrupted. The CEO's office tools are served over MCP (/api/mcp/:token).
  • ptyHost.ts: the terminal keeper, a detached process of its own (launch re-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.ts is the office's side (start/connect, spawn, adopt after a restart, local fallback); ptyProtocol.ts their JSON-lines messages. The launcher's office:shutdown says restart: false when 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 .cmd shim 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/term viewers, 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: the Backend interface (everything touching GitHub, git, disk and sessions) and realBackend.
  • machines.ts: agents' machines, MachineProvider: each agent's own clone, worktree and temp folder (the local provider is folders under <SWARM_HOME>/machines/<machine>/, in workspace.ts; cloud agents' are Upstash Boxes).
  • Cloud agents (docs/cloud.md, opt-in; PersistedAgent.host === 'box'): cloud.ts is the account (the Upstash key and pasted keys in secrets.json, CUBEFARM_CLAUDE_TOKEN read from the environment and never saved, credential resolution, CloudView); box.ts the only importer of @upstash/box (BoxApi, which the demo fakes); boxMachines.ts the Box MachineProvider (create, set up, prepare, pause, leftovers); boxScripts.ts the shell scripts run in a Box (pure, tested); boxHelpers.ts the programs put in a Box (launcher, hooks writing to the session's events.jsonl); boxCli.ts BoxPty (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 (needsSignIn holds the task) and runs the CLI's own login in their terminal (cliRunner.ts startBoxSignIn); 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 (or SWARM_DEMO_FLOORS / SWARM_DEMO_AGENTS) makes it a big company for scale tests.
  • github.ts: all GitHub access through the gh CLI.
  • 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: execFile without a shell, prompts disabled, CommandError with 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 /ws to their floor (pure interest and rate rules), never saved; demoVisitors.ts walks the demo's fake visitors. Names and limits in shared/presence.ts.
  • voice.ts: phone messages read aloud (docs/voice.md): the ElevenLabs key in secrets.json, voices, cached clips; elevenlabs.ts is its REST client. The words spoken come from shared/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 in secrets.json, push keys and devices in push.json), behind Backend.notify; notify.ts is its pure part (formatting, the per-event rate limit, webhook checks), webPush.ts VAPID and RFC 8291 encryption, shared/notify.ts the settings. pwa.ts: the installable app's service worker, served at /sw.js.
  • journal.ts: the time-lapse journal (<SWARM_HOME>/journal/<day>/): records what Swarm.broadcast sends, a file per 10-minute keyframe, pruning, and the reads behind /api/journal/*. The rules (what's kept, secrets, seeking, marks) are in shared/journal.ts; journalSample.ts is 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 and cleanStyle (an agent's style, 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.tsx runs them), toy errands (toyErrands.ts: hoops and catch, on toys/npc.ts, the toys' hands for people, aimed by toys/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 in cityLayout.ts, drawn by City.tsx in six instanced draw calls), the camera's other views (camera/: the overview, the building view and the follow cam in rig.ts, pose maths in cameraMath.ts, the cutaway as global clipping planes), the gamepad (gamepad.ts) and the graphics tiers (gfx/: Low/Medium/High/Auto in quality.ts with Auto's governor, post-processing in a lazy chunk (Effects.tsx, pipeline.ts); a material blooms only if bloomMarks.ts marks it), the other people viewing the office (presence/: visitors, pings, the profile), holiday themes (themes/: which one is on from shared/themes.ts, their data and decoration slots in themes.ts and layout.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 in games/: pure logic in tetris.ts / snake.ts / pet.ts), elevator panel, app viewer, sounds (sfx.ts), key bindings (keymap.ts, pure; controls.ts keeps the player's own, and every shortcut asks it, never a hard-coded key).
  • Accessibility (Settings → Accessibility, ui/a11y.ts, saved per browser through pure a11yPrefs.ts): captions (captions.ts, rules in captionRules.ts; every sound sfx.ts records is offered to them), status colours and shapes (statusLook.ts, shared by CSS and the canvases), motion comfort (call reduceMotion() before animating the camera or anything non-essential), UI scale, readable font, high contrast. Dialogs use dialogFocus.ts (focus in, trapped, returned); announce() speaks to screen readers; FloorList.tsx is the list view.
  • src/pocket/: pocket mode (docs/pocket.md), the 2D office for phones (mode.ts picks it; App.tsx loads it or the 3D Office.tsx lazily, so a phone never downloads three.js). src/pwa.ts registers the service worker and Web Push; src/notifications.ts shows desktop notifications. ui/Panel.tsx is the panel, apart from Overlays.tsx (3D).
  • src/photo/: photo mode and clips, lazy-loaded except gate.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.ts keeps the last 15 s), PhotoPanel.tsx, and pure flight.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 (and window.__swarmStats with a census of what's drawn).
  • src/world/batch.ts / Batched.tsx: a floor's repeated parts (Toon.tsx's boxes, people's Pieces) drawn as instanced batches behind invisible stand-ins (?batch=off to 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 through store.apply(ev, 'play' | 'seek') while live events wait; replayClock.ts is its pure clock and "since I was last here", ui/TimeLapse.tsx its console tab and bar.

Conventions

  • ESM TypeScript everywhere ("type": "module"), strict, noUnusedLocals/Parameters. The server runs through tsx and imports with .ts extensions (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 Backend method, CEO tool or capability gets a fake in server/demo.ts, so --demo works with no GitHub, no git/npm and no Claude usage.
  • UI state comes from the server: on connect the client gets a snapshot, then typed ServerEvents (repo, agent, qa, ceo, message, toast, …) from Swarm.broadcast; agents' and floors' frequent changes come batched as agents / repos patches and terminal lines as logs / latest, only for what the tab shows (server/outbox.ts). Add new state to shared/types.ts, the snapshot and an event, and handle it in store.ts's apply. REST is for commands, not for polling state. A big company must fit server/scale.test.ts's budgets.
  • REST errors: throw HttpError(4xx, message); the handler in index.ts returns { 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.rm with maxRetries for EBUSY/EPERM file locks; write state to a temp file and rename;
    • kill process trees, not just the child (taskkill /T /F on Windows, process groups elsewhere);
    • windowsHide: true on spawns; npm on Windows goes through cmd.exe.
  • Agent prompts are paid for on every session: keep prompt text short and specific.

Tests

  • Vitest, *.test.ts next to the code, anywhere under client/, server/, shared/ or scripts/ (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 test already points SWARM_HOME at a temp folder and SWARM_PORT at 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 to smoke.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, test and build. test:e2e only 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.