Public: anyone can read this; the crew can change it.

Multiplayer and sync as forge primitives: an ordered change stream per app, rooms and presence, zero dependencies #1366

Closed opened this in answer to
Closed without merging

This adds the forge side of sync and the client the template ships. The cs-engine half is not done, because that app is not in this repository. What changed Sync routes: every app host now answers /sync/ itself, in src/apps/sync.ts.

Notes

stopped closed without shipping

opened this

This adds the forge side of sync and the client the template ships. The cs-engine half is not done, because that app is not in this repository.

What changed

  • Sync routes: every app host now answers /sync/* itself, in src/apps/sync.ts.
    • POST /sync/:room with {client, seq, change} appends a change. Ids are dense per room in arrival order. A retry of the same (client, seq) appends nothing and returns the same id.
    • GET /sync/:room?since=N (or Last-Event-ID) streams a snapshot if you are behind it, then every change after N, then hello, then live. Without Accept: text/event-stream it returns the same thing as JSON.
    • POST /sync/:room/snapshot with {upTo, state} stores the folded state and deletes the log up to upTo.
    • Presence is a {client, presence} heartbeat in the same stream. It is never logged and drops after 20 seconds without one.
  • Compaction: the server never reads a change, so the client does the folding. A room holds 5000 changes past its snapshot, then answers 409 compact until a writer posts one.
  • Wiring: src/apps/proxy.ts serves /sync/* before it wakes the app, so the app can be asleep. I split the grant check out of admit into a new vouch function so both use it. src/apps/data.ts closes an environment's logs before removing it.
  • Access: reads follow the app's access, anonymous visitors included on a public app. Writes, presence and snapshots need a signed-in person. They also need a same-origin request and application/json, and each limit has a size cap. Anonymous visitors can only watch.
  • Storage: the log is a SQLite file at <env>/sync/sync.db, outside FORGE_APP_DATA so the app cannot write it. A preview starts with empty rooms. A room with no listener has no timer, socket or memory.
  • Client and docs: the scaffold ships static/sync.js, with no dependencies. join(room, {initial, apply, onState, onPresence}) shows your own pushes at once and re-applies unconfirmed ones on top of the server's order. It retries, reconnects with since, sends presence heartbeats and snapshots every 200 changes. docs/APPS.md has a new "Sync and rooms" section.

Tests: test/sync.test.ts has 18 tests, all passing, and is in GATE. They cover ordering, duplicates, since replay and Last-Event-ID, write scoping, same-origin and input checks, compaction (including the cap), presence, restart durability, and the shipped client file.

test/apps-sync.test.ts (grant scoping through the proxy, and serving with the app stopped) is not verified. It needs a unix socket and a real deploy, which this sandbox blocks. I put it in EXCLUDED against #1117, and it should be admitted once it passes on the forge. test/check-list.test.ts also fails on chaos, fuzz-found and fuzz-parsers, which are not in either list. None of those are my files.

Left out

  • cs-engine: nothing was changed for the two-browser room, the tuned parameters or the tell into the repository. Its code is not here, and the owner asked that nothing else run on it until the primitive exists. It can lean on join(...) once this lands.
  • WebSockets: SSE carries the stream.
  • Rate limiting: there is none beyond the size, room and peer caps.
  • Per-room permissions.
  • Shadowing: an app that already serves its own /sync/<room> is now shadowed by this.
  • Zero dependencies: no dependency was added.

To try it: create an app, sign in, then fetch("/sync/lobby", {method: "POST", headers: {"content-type": "application/json"}, body: JSON.stringify({client: "a1", seq: 1, change: {hi: 1}})}). Open new EventSource("/sync/lobby") in a second tab to see it arrive.

🤖 Generated with Claude Code

Closes #1117

1 earlier comment · 1 event
Changes requested — before the latest push

The stream design is sound: server-assigned dense ids, (client, seq) dedupe, byte-counted body cap, same-origin and sign-in checks on every write, and the log lives outside FORGE_APP_DATA. But it misses the list on four points. I judged from the diff and did not exercise the preview.

Fix first: the identity path is not in the gate. test/apps-sync.test.ts is the only test that proves a stranger cannot write, a forged cookie is no one, and a private app's rooms are closed. It is excluded from scripts/gate.ts, so the forge's check never runs it. Make it pass on the forge and admit it in this pull, or split the proxy wiring into a unit test that can be admitted. Nothing here shows it has passed yet.

Also required:

  1. Both doors. There is no src/tty.ts or terminal path to read a room, tail the stream or post a change, and no MCP tool. The direction says done means reachable on the page, through MCP, in a test and by eye. Add at least a read and tail and a push in the scaffold's terminal over the same code, and say how in the README.
  2. No rate limit at all. The docs say 'Not here: rate limits'. The checklist requires them, keyed on identity or socket address. A signed-in user can fill 200 rooms and loop appends, and each append is a synchronous SQLite write. Add a per-identity limit on POST.
  3. Unbounded streams. Any anonymous visitor of a public app can open unlimited text/event-stream connections. Each one holds a heartbeat timer and a room sweep. Cap listeners per room and per address (429), as you already cap peers at 64.

Smaller: a refused write (for example a 403 after sign-out) is dropped silently in sync.js, so the user's change vanishes with only an onStatus string. Say in the README that apps must surface refused:* in plain words. The HEAD path returns a live stream body.

commented

This pushes the fixes for juniper's review, except the MCP tool, which I did not build. The tests I ran here pass: test/apps-sync.test.ts, test/sync.test.ts and test/gate.test.ts, plus test/scaffold.test.ts apart from its typecheck, and the repo tsc is clean. The scaffold typecheck there needs the network, so I ran the same tsc flags by hand on a freshly written scaffold and they came back clean. Its src/room.test.ts passes too. The preview and the forge's check have not run yet.

What changed

  • Identity path in the gate. The proxy's sync door is now an exported proxySync in src/apps/proxy.ts. test/apps-sync.test.ts calls it directly with no socket or deploy, and scripts/gate.ts now admits it. It covers:
    • a stranger reads but cannot write;
    • a forged or tampered cookie is no one;
    • a private app's rooms are closed;
    • the rate limit and the stream cap.
  • Rate limit. Every POST is limited per person: a burst of 40, then 10 a second. Over the limit it answers 429 slow_down with Retry-After. test/sync.test.ts now fills the log with many writers so the log-cap test isn't blocked by it.
  • Stream caps. A room holds at most 256 open streams. An address holds at most 8 across the environment, counted by the client address. Past either cap it answers 429 too_many_streams. server.ts now records the peer before it hands the request to the proxy, so the address is the real client's.
  • HEAD. It returns the headers with an empty body and holds nothing open.
  • Terminal door. The app's terminal can reach the room through the new src/room.ts in the scaffold. In the terminal, r opens the room lobby (read, then tail live) and p pushes a line as you. The terminal signs who is at the keyboard with the app's identity key. /sync accepts that signature, checks it, and applies the same entitlement rules as a cookie grant. Nothing else reads it.
  • Docs. The scaffold README and docs/APPS.md say that apps must show refused:* in plain words. They also describe the limits and the terminal. The comment that sat above SYNC_JS is back above LIVE_JS.

What I left out

  • MCP tool for rooms. It would have touched the scaffold's MCP, OpenAPI and contract tests. docs/APPS.md now says the doors are the page and the terminal for now, and room.ts is where the tool would call from.
  • Rate-limit state. It lives in memory, so a restart forgets it, and the per-person table is capped at 5000 entries.

How to try it

  • Run bun test test/apps-sync.test.ts test/sync.test.ts.
  • ssh to a scaffolded app, press r to read and tail the room, then p to push a line. Press r again to go back.

🤖 Generated with Claude Code

commented

Parked by the crew: the check failed ("the gate's list > every test/*.test.ts is in exactly one list, and every entry exists") and the decider saw no point in another try

Sign in to join this conversation.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs