Real-Time Co-Editing Workspace for Humans and AI Collaborators
Medium · System Design · Software Engineer · Onsite
Prompt
You are tackling an 8–12 hour take-home engineering project for a software engineer role on an AI product team, followed by a deep-dive technical review session. Using AI coding assistants is encouraged, and their full session transcripts are submitted alongside your code, automated tests, and written architecture notes; evaluators look for disciplined agentic workflow, sharp 0-to-1 product scoping, and thoughtful user and developer experience. Because the review round evaluates your submission as a working prototype, any deferred scope must be documented explicitly with its engineering rationale.
Core task: Build a real-time collaborative document workspace in which human teammates and AI agents read and edit the same shared document concurrently.
Before locking in your design, clarify the operating assumptions you are committing to: - Document format & scale: Plain Markdown, rich text, or source code, and the largest document size supported. - Active concurrency: How many human collaborators and simultaneous AI agent invocations share one document at once. - Agent interaction model: Whether users invoke an agent on a highlighted passage or agents also run autonomously in the background, and whether agents mutate document text directly or submit reviewable change proposals. - Connectivity behavior: Seamless recovery from brief connection drops versus multi-hour offline editing. - Human oversight: Approval gates, authorship visibility, and undo controls over agent modifications.
Structure your work across three stages:
- Stage 1 — Prototype scope & implementation: Define what ships within the 8–12 hour budget and what is deferred. Explain how concurrent edits converge, how reconnecting clients catch up, how a multi-second agent run reads document context and anchors its edits accurately while humans keep typing, how collaborators inspect, accept, or undo agent changes, how state and live presence are persisted, how convergence is tested, and how your AI coding logs reflect spec-driven, test-verified iteration.
- Stage 2 — Prototype critique & scaling limits: Defend your trade-offs across merge algorithms, direct writes versus proposed diffs, and history retention versus storage footprint. Pinpoint which components hit scaling limits first (in-memory room servers, edit-history growth, high-fanout documents, and LLM latency and token cost), and surface unaddressed team needs (trust, attribution, agent access control, external model data privacy) alongside UI rough edges (live generation visibility, outdated proposals, and undo ergonomics).
- Stage 3 — Enterprise customer extension: Plan how to integrate a new enterprise requirement: mandatory human sign-off on every agent modification, a complete per-edit audit trail attributing every human and agent change, and selective rollback of everything a single past agent run modified without losing subsequent human edits—covering conflict handling, task-level engineering estimates, roadmap ordering, and measurable success criteria.
Scope & Expectations
- Convergence, anchoring, and disciplined prototype cut: Justify your real-time merge strategy (such as CRDTs or operational transformation), reconnection sync protocol, character-accurate anchoring for slow agent edits, persistence and presence model, automated convergence tests, and structured AI-assisted coding workflow within 8–12 hours.
- Capacity estimation & bottleneck analysis: Quantify keystroke update rates, WebSocket fan-out, history growth, and LLM token spend to identify what saturates first, while critiquing security, permission boundaries, data privacy, and collaborative UX gaps.
- Enterprise approval, attribution, and selective rollback: Enforce server-side human approval, preserve merge-resilient authorship metadata per edit, and design conflict-aware selective revert of an earlier agent run backed by concrete task estimates and rollout milestones.
Step-by-step walkthrough
Clarify requirements and scope the 10-hour prototype
Because this prompt is an 8–12 hour take-home followed by a rigorous onsite design review, our work has two goals: ship a small prototype that genuinely merges concurrent human and AI edits without losing work, and document every shortcut upfront so we can defend it during the review.
Clarifying assumptions we commit to first
- Document type and size: Plain Markdown edited in a browser code editor (CodeMirror) with a live preview, up to ~100 pages (~300,000 characters). Rich text is deferred because nested formatting blocks roughly double the diffing and cursor-anchoring code without changing the core concurrency ideas.
- Concurrency: Up to ~10 active editors and 1–2 concurrent AI agent runs per document in the prototype; supporting hundreds of passive viewers is addressed in the Stage 2 scaling review.
- How agents participate: A user highlights a passage and invokes an agent (for example, "make this clearer" or "fix grammar"). Background agents are deferred to follow-up design.
- Proposals vs. direct edits: By default, an agent creates a proposal (a suggested diff that a human must click to accept or reject). Users can toggle "apply immediately" for low-risk tasks, which runs through the exact same server pipeline with automatic acceptance so authorship tracking and undo still work identically.
- Offline support: Automatic recovery from brief disconnects (seconds to minutes) ships in the prototype; multi-hour offline editing with conflict review is deferred.
- Human control: Live streaming preview while the agent thinks, inline accept/reject controls, per-character authorship coloring, and one-click undo of accepted agent edits.
Prototype scope cut (logged in
DECISIONS.md)Status Feature Why Ships Real-time co-editing via a CRDT library (Yjs), reconnect sync, and presence (live cursors, selections, and an "agent is writing here" badge) Proves concurrent human + agent editing converges cleanly Ships Selection-scoped agent runs with streaming ghost-text preview, word-level diff proposals, staleness detection, and accept/reject Solves the core "slow agent on a moving document" problem Ships Server-verified authorship registry and an "authorship tint" UI toggle Lays the foundation for trust, auditability, and selective revert Ships Automated chaos convergence tests (dropped, delayed, duplicated, and reordered messages) plus anchoring tests Proves correctness instead of hoping manual clicks caught races Deferred Rich-text trees, background agents, multi-hour offline merge UI, multi-server room sharding, SSO, and conflict-aware selective revert Out of an 8–12 hour budget; designed in Stages 2 and 3 Count operations, bandwidth, and model costs
Before picking databases or server topologies, we count how many messages, disk writes, and model tokens flow through the system. Every assumed constant is labeled so the prototype can measure the real value.
1. One busy document (5 humans typing + 1 AI agent generating) Human typing speed ~60 words/min x 5 chars/word = ~5 chars/s per active typist Client batching coalesce local keystrokes every 50 ms (caps bursts at <= 20 msgs/s) Incoming edit updates 5 people x ~5 updates/s = ~25 edit updates/s Presence updates ~25 cursor/selection updates/s WebSocket fan-out (25 edits + 25 presence) x 4 other browsers = ~200 msgs/s outbound AI agent generation ~50 tokens/s x ~4 chars/token = ~200 chars/s (~11 s for 500 tokens): - Bad: stream tokens into shared doc -> +50 DB writes/s, +250 msgs/s out, pollutes undo history - Good: stream ephemeral preview -> 0 DB writes while generating, 1 write when accepted 2. Pilot fleet (2,000 open documents, avg 1.5 active editors + 1.5 passive viewers = 3 sockets/doc) Active editors 2,000 docs x 1.5 = 3,000 editors (typing ~30% of the time) Incoming edit updates 3,000 x 5 updates/s x 0.30 = ~4,500 edit updates/s (+ ~4,500 presence/s) Outbound fan-out each message goes to ~2 other sockets on that doc -> ~18,000 msgs/s out Database write options: - 1 transaction per edit update -> ~4,500 commits/s (saturates single-writer SQLite fast) - Group commit across all docs every 20 ms -> 50 commits/s (still durable before broadcast) - Per-doc batch every 1 s (~40% of docs active in a 1 s window) -> ~800 writes/s (risks 1 s loss) Server RAM 2,000 open docs x ~1-5 MB in-memory history = ~2-10 GB RAM 3. AI agent workload (each active editor invokes an agent once every 10 minutes = 600 s) Agent runs/s 3,000 editors / 600 s = 5 runs/s Tokens per run ~6,000 input tokens (selection + section + outline), ~500 output tokens Token throughput 30,000 input tokens/s (108M/hr) and 2,500 output tokens/s (9M/hr) Hourly API cost 108M x ($3 / 1M) + 9M x ($15 / 1M) = $324 + $135 = ~$459/hour (Sending full 300,000-char / ~75,000-token docs would cost ~12x more!) Latency ~1 s to first token + (500 / 50) = ~11 s total per run -> A human typing at 5 chars/s inserts ~55 chars while the agent works!What saturates first from these numbers
- The single prototype server process holds every open document in RAM and routes all ~18,000 outbound messages/s on one event loop; it is also a single point of failure.
- Per-keystroke disk commits (~4,500 commits/s) hit SQLite's single-writer lock long before CPU or network limits. Group commit (flushing all pending updates across documents in one transaction every 20 ms) drops disk flushes to 50/s while keeping durability before broadcast.
- Model latency (~11 s) is a day-one correctness hazard, and model cost (~$459/hr) dominates infrastructure cost. Because humans type ~55 characters during an 11-second run, numeric character offsets captured when the run started are already wrong when the model finishes.
- Streaming raw model tokens into the document state is the wrong design: it multiplies write load, bloats history with half-written words, and forces a user who rejects a suggestion to run an undo instead of simply discarding a preview.
Choose CRDTs over OT and design the reconnect sync protocol
When two collaborators edit the same text simultaneously, replicas need a rule that guarantees everyone ends up with the exact same document (convergence). The two classic families are:
- Operational Transformation (OT): A central server assigns a strict global order to every edit operation (
insert(pos=10, "a")) and mathematically shifts ("transforms") concurrent operations' character indices against earlier operations. - Conflict-Free Replicated Data Type (CRDT): Every inserted character receives a permanent, globally unique identifier
(client_id, clock_counter)and remembers the IDs of its left and right neighbors when it was typed, so edits merge in any arrival order (commutativity) and applying the same update twice has no extra effect (idempotency).
Capability Operational Transformation (OT) CRDT (Yjs) ------------------------ ------------------------------------ --------------------------------------- Slow agent edit (~11 s) Must transform output against every Anchor directly to permanent character keystroke since the base revision IDs; IDs never shift when text is added Authorship after merges Tracked per server revision log Built into every character's (client_id, counter); survives arbitrary merges Reconnect / offline sync Must replay against retained server Exchange compact state vectors and send revision history only missing updates Main downsides Central ordering required; hard to Deleted items leave small tombstones; combine with slow branches concurrent rewrites interleave wordsWhy we choose Yjs (a sequence CRDT): First, building OT or a CRDT from scratch in 8–12 hours is a trap. Second, Yjs gives us permanent character IDs out of the box, which directly solves both slow-agent anchoring and merge-proof authorship, while shipping ready-made CodeMirror bindings, cursor awareness, and compact binary encoding. Its main trade-off is tombstones (lightweight markers kept where characters were deleted so late-arriving edits still know where deleted neighbors lived), which slowly grow memory and disk size unless compacted.
Reconnect-safe WebSocket sync protocol
A state vector is a tiny summary map
{ client_id -> highest_counter_seen }describing everything a replica already knows. Whenever a browser connects or reconnects after a drop, both sides run a two-step handshake:Browser (local Y.Doc) Server (authoritative persisted Y.Doc) |--- sync-step-1 (browser state vector) -------->| |<-- sync-step-2 (updates browser is missing) ---| |<-- sync-step-1 (server state vector) ----------| |--- sync-step-2 (offline edits server lacks) -->| validated & saved before broadcast |<== live binary updates + awareness cursors ===>|Because Yjs updates are commutative and idempotent, network retries, reordered packets, or brief Wi-Fi drops never duplicate text or cause replicas to diverge.
- Operational Transformation (OT): A central server assigns a strict global order to every edit operation (
High-level architecture, API, and database schema
Browser A (CodeMirror + Y.Doc) Browser B ... LLM Provider API | WebSocket /docs/{id} | ^ v v | HTTPS stream +------------------------------------------------------------------+------------+ | Collaboration Server (single Node.js process in prototype) | | - Room Manager: doc_id -> in-memory Y.Doc, active sockets, awareness state | | - Update Validator: decodes Yjs binary; enforces sender owns client_id | | - Agent Runner: builds local context, streams ephemeral ghost-text previews | | - Proposal Service: word-level diffs -> hunks, character-ID anchors, apply | +-------------------------------------------------------------------------------+ | durable append (updates, snapshots, writers, runs, proposals, hunks) v +-------------------------------+ | SQLite (WAL mode, prototype) | --> PostgreSQL + S3 cold history in production +-------------------------------+WebSocket & HTTP contracts
WebSocket /docs/{doc_id} C -> S hello { client_id } binds Yjs client_id to authenticated user sync-step-1 | sync-step-2 | update binary Yjs CRDT frames awareness { cursor, selection, name } ephemeral presence (never written to DB) S -> C sync-step-1 | sync-step-2 | update | awareness agent.preview { run_id, start, end, text } ephemeral streaming ghost text proposal.updated { proposal_id, status, hunks } HTTP REST POST /docs/{doc_id}/agent-runs { agent, instruction, selection: { start, end }, mode } -> 201 POST /proposals/{proposal_id}/accept { hunk_ids? } -> 200 { applied: [...], stale: [...] } POST /proposals/{proposal_id}/reject { hunk_ids? } -> 200 POST /agent-runs/{run_id}/cancel -> 200 GET /docs/{doc_id}/writers maps client_id -> human user or approved agent hunkRelational schema
documents (doc_id PK, title, owner_id, policy_proposals_only BOOL, created_at) doc_access (doc_id, user_id, role ['owner'|'editor'|'viewer'], PK (doc_id, user_id)) doc_updates (doc_id, seq, update_blob, sender_user_id, created_at, PK (doc_id, seq)) doc_snapshots (doc_id, upto_seq, state_blob, created_at, PK (doc_id, upto_seq)) -- every 500 updates writers (doc_id, client_id, actor_type ['person'|'agent_hunk'|'revert'], person_id, run_id NULL, hunk_id NULL, approved_by NULL, approved_at NULL, PK (doc_id, client_id)) agent_runs (run_id PK, doc_id, invoked_by, instruction, model, mode, status, tokens_in, tokens_out, created_at) proposals (proposal_id PK, run_id, status ['pending'|'accepted'|'rejected'|'stale'|'partial']) hunks (hunk_id PK, proposal_id, start_anchor BLOB, end_anchor BLOB, original_text, new_text, status, decided_by NULL, decided_at NULL)Opening a document loads the newest row in
doc_snapshotsplus only thedoc_updatesrows withseq > upto_seq, keeping startup fast without discarding fine-grained edit history.Deep dive: anchoring a slow agent's edit while people keep typing
Suppose Maya highlights
"The checkout failed."at character offsets10..30and asks an agent to make it more formal. While the model spends 11 seconds generating"The payment request timed out.", Devon types"Incident: "(10 characters) at index0. Look at what happens with naive integer offsets versus relative positions (anchors tied to specific CRDT character IDs):At t = 0 s (Maya invokes agent on indices 10..30): "Summary:\n\nThe checkout failed." ^ ^ start = char_id(M,10) end = char_id(M,29) [inward-clamped] At t = 8 s (Devon types "Incident: " at index 0 while agent is still thinking): "Incident: Summary:\n\nThe checkout failed." ^ ^ Naive offsets 10..30 now slice "Summary:\n\nThe checko" -> CORRUPTS DOCUMENT! Character-ID anchors resolve to 20..40 ("The checkout failed.") -> EXACT MATCH!Step-by-step lifecycle of an agent edit
- Capture inward-clamped anchors at invocation: For a non-empty selection
[selFrom, selTo),startAnchorattaches to the first selected character (assoc = 0, right-associated) andendAnchorattaches to the last selected character (assoc = -1, left-associated). That way, text typed immediately before or after the selection stays outside the bracket. For a zero-width cursor insertion (selFrom === selTo), both anchors share a singleassoc = -1position right after the preceding character. - Build local context: Send only the selected text, its containing Markdown section, and the document's heading outline (~6,000 tokens instead of 75,000).
- Stream an ephemeral preview: Broadcast incoming tokens as
agent.previewevents rendered as translucent ghost text at the resolved anchor, plus an awareness cursor showing"Rewrite agent (Maya) is editing...". Nothing touches the CRDT yet. - Diff into word-level hunks: A hunk is one minimal contiguous change (for example, replacing
"checkout failed"with"payment request timed out"while leaving"The "and"."untouched). Replacing the entire paragraph as one blob would wipe out words a human typed elsewhere in that paragraph during the 11 seconds AND falsely credit the agent as the author of every unchanged word. - Anchor each hunk and detect staleness: Map each hunk to its own
startAnchorandendAnchor. If a human edited outside that hunk, the anchors glide cleanly with the surrounding edits. If a human edited inside the exact words of that hunk, its current slice no longer matcheshunk.originalText, so only that hunk is markedstalewhile sibling hunks remain ready to accept. - Re-verify on accept and apply under a fresh server-owned
client_id:
import * as Y from "yjs"; function createSelectionAnchors(ytext: Y.Text, selFrom: number, selTo: number) { if (selFrom === selTo) { const point = Y.createRelativePositionFromTypeIndex(ytext, selFrom, -1); return { startAnchor: point, endAnchor: point }; } return { startAnchor: Y.createRelativePositionFromTypeIndex(ytext, selFrom, 0), endAnchor: Y.createRelativePositionFromTypeIndex(ytext, selTo, -1), }; } function resolveRange(doc: Y.Doc, start: Y.RelativePosition, end: Y.RelativePosition) { const a = Y.createAbsolutePositionFromRelativePosition(start, doc); const b = Y.createAbsolutePositionFromRelativePosition(end, doc); if (a === null || b === null || a.index > b.index) return null; return { from: a.index, to: b.index }; } function applyHunkAsAgent(liveDoc: Y.Doc, hunk: Hunk, usedClientIds: Set<number>) { const range = resolveRange(liveDoc, hunk.startAnchor, hunk.endAnchor); const body = liveDoc.getText("body"); // Deleting anchored chars collapses the range rather than returning null, so verify exact text: if (range === null || body.toString().slice(range.from, range.to) !== hunk.originalText) { return { status: "stale" as const }; } // Allocate an unused 32-bit clientID before cloning state (~1% birthday collision at 10,000 writers) let writerDoc = new Y.Doc({ gc: false }); while (usedClientIds.has(writerDoc.clientID)) { writerDoc = new Y.Doc({ gc: false }); } Y.applyUpdate(writerDoc, Y.encodeStateAsUpdate(liveDoc)); let hunkUpdate: Uint8Array | null = null; writerDoc.on("update", (u: Uint8Array) => { hunkUpdate = u; }); const writerText = writerDoc.getText("body"); writerDoc.transact(() => { writerText.delete(range.from, range.to - range.from); writerText.insert(range.from, hunk.newText); }); return { status: "applied" as const, update: hunkUpdate!, clientId: writerDoc.clientID }; }The server writes the
writersrow (client_id -> agent_hunk, run_id, hunk_id, approved_by) and appendshunkUpdatetodoc_updatesbefore applying and broadcasting it to connected browsers.- Capture inward-clamped anchors at invocation: For a non-empty selection
Deep dive: character-level authorship that survives every merge
Selective rollback and compliance auditing only work if every surviving or deleted span retains immutable metadata tying it to the exact human editor or agent invocation across arbitrary concurrent merges.
- Who inserted each character: Every character run in Yjs permanently carries its creator's
(client_id, counter). Merging never alters item IDs. Looking upclient_idin thewriterstable immediately tells us whether a word came from Maya, Devon, or Hunk 3 of Agent Run 812 (approved by Maya). - Who deleted each character: Yjs stores deletions as compact ID ranges (
DeleteSet) without recording who deleted them. Because every update passes through our server, the server decodes each incoming update'sDeleteSet, subtracts IDs already deleted in the server's in-memoryY.Doc(crucial because a reconnecting browser's sync message repeats historical deletions it already knew about!), and logs(target_client_id, clock_start, length) -> deleter_actorfor genuinely new deletions. - Preventing spoofing: Because browsers generate their own random
client_idin JavaScript, a malicious or buggy client could claim someone else's ID. Onhello, the server bindsclient_idto the authenticateduser_id(rejecting IDs bound to any other user). Every incoming binary update is decoded by the validator: if it introduces new items under aclient_idnot owned by that user, the server drops the update and closes the socket. Agentclient_ids are minted exclusively insideapplyHunkAsAgenton the server, so no browser can forge agent text or bypass approval. - Why not attach authorship as a rich-text formatting attribute? Formatting attributes in editors are mutable operations that another client can overwrite, strip on copy-paste, or forge, and they double operation count. Item IDs are immutable and server-verified.
- Who inserted each character: Every character run in Yjs permanently carries its creator's
Presence, durable persistence, convergence tests, and failure handling
- Presence & undo UX: Yjs awareness (an ephemeral in-memory broadcast channel) carries human cursors plus synthetic cursors for active agent runs so teammates see where an agent is working. Local
Ctrl+Zuses Yjs'sUndoManagerscoped strictly to that user's ownclient_ids so pressing undo never accidentally reverts a teammate's sentence; accepted agent runs expose an explicit "Undo agent change" button. - Persistence with garbage collection disabled (
gc: false): EveryY.Docruns withgc: falseso tombstoned characters keep their original text bytes, allowing audit history to display deleted sentences and selective revert to restore them. Updates are persisted before broadcast, with full state snapshots every 500 updates. - Automated convergence & chaos tests:
- Chaos network property test: Spawn 4 in-memory clients and 1 server room behind a seeded fake network that randomly delays, duplicates, reorders, and drops packets while injecting disconnect/reconnect cycles. After a final sync handshake, assert all 5 documents have byte-identical text and match a fresh
Y.Docrehydrated fromdoc_snapshots + doc_updates. Run 200 seeds in CI. - Concurrent anchoring test: Start an agent run on Paragraph 2; concurrently test (a) typing in Paragraph 1, (b) editing one word inside Paragraph 2, and (c) deleting Paragraph 2. Assert full clean apply in (a), partial hunk staleness in (b), and full proposal staleness in (c).
- Crash recovery test: Kill the server mid-burst, restart from SQLite, reconnect clients, and verify zero lost characters and intact authorship mappings.
- Chaos network property test: Spawn 4 in-memory clients and 1 server room behind a seeded fake network that randomly delays, duplicates, reorders, and drops packets while injecting disconnect/reconnect cycles. After a final sync handshake, assert all 5 documents have byte-identical text and match a fresh
Failure mode System behavior Browser loses Wi-Fi Edits queue locally in Y.Doc; state-vector handshake reconciles cleanly on reconnectServer process crashes Restarts from latest snapshot + tail updates; reconnecting clients replay any unacked local keystrokes Model API times out or errors Run marked failed, ghost-text preview cleared, zero partial edits touch the documentTarget paragraph deleted mid-run Anchors resolve to modified/empty slice; hunks marked stalewith "Re-run on current text"Forged client_idin updateValidator rejects binary frame before persistence or broadcast and closes socket Disk / DB write fails Room switches to read-only error banner immediately; never broadcasts unpersisted state Disciplined AI coding-agent workflow (visible in submitted chat logs)
- Write
SPEC.mdfirst (data model, sync/anchoring invariants, non-goals) and load it at the start of every coding-agent session. - Decompose into ~8 small vertical tasks (room sync -> chaos test harness -> validator &
writers-> agent preview -> hunk anchoring -> UI), one commit per task. - Ask the coding agent to write failing convergence and anchoring tests before implementation code, review every diff line by line, and push back explicitly in chat whenever the agent suggests shortcuts like integer character offsets. Record every deferral in
DECISIONS.md.
- Presence & undo UX: Yjs awareness (an ephemeral in-memory broadcast channel) carries human cursors plus synthetic cursors for active agent runs so teammates see where an agent is working. Local
Product review: scaling bottlenecks and trust, privacy, and UX gaps
In the Stage 2 review, proactively walk through what breaks first as usage grows:
- Single-process room memory and CPU: One Node process caps out around a few thousand active rooms. Scale horizontally by sharding rooms by
doc_idusing short-lived leases (timed ownership locks in Redis/etcd so exactly one server owns a livedoc_idat a time). If a server dies, its lease expires, another node loadssnapshot + tail, and clients reconnect via CRDT handshake with zero data loss. - Database commit rate (~4,500 updates/s): Migrate SQLite to PostgreSQL and enable group commit (flushing all rooms' queued updates in a single transaction every 20 ms -> 50 commits/s while preserving "durable before broadcast"). Avoid 1-second unpersisted batching: if the server crashes, a bystander browser replaying someone else's recent edit would trip the sender-ownership validator!
- Hot documents (1,000 concurrent viewers): All-to-all cursor awareness grows quadratically (
O(N^2)). Split passive viewers onto read-only fan-out relays, throttle cursor broadcasts to 5 Hz, and show cursors only for active editors. - History & tombstone bloat (
gc: false): Years of keystrokes bloat RAM and load latency. Move updates older than 30 days to S3 object storage, checkpoint snapshots aggressively, and keepgc: falseindefinitely only for workspaces paying for compliance history. - Model cost (~$459/hr) and latency: Keep context local, enable provider prompt caching on document outlines, route simple grammar fixes to smaller models, enforce per-workspace token budgets, and auto-cancel runs if the target selection is deleted.
Team needs and UX gaps still open after the prototype
- Trust, access control, and privacy: Agents must run with delegated permissions intersected with the invoking user's server-verified access — never prompt instructions ("do not read secret sections"), which are vulnerable to prompt injection (malicious instructions hidden inside document text to hijack an AI agent). Enterprise teams also need zero-data-retention model agreements, secret redaction before API calls, and workspace model-region pinning.
- UX gaps: Overlapping agent previews are hard to read; stale proposals need a 3-way diff viewer instead of just "re-run";
Ctrl+Zskipping agent edits surprises users unless "Undo agent change" is prominent inline; screen-reader announcements (aria-live) for remote agent edits are missing.
- Single-process room memory and CPU: One Node process caps out around a few thousand active rooms. Scale horizontally by sharding rooms by
Enterprise extension: mandatory approval, audit history, and selective revert
Stage 3 asks how we add mandatory human sign-off, an immutable per-edit audit log, and selective rollback of a specific earlier agent run while preserving subsequent human edits.
1. Mandatory human approval (
policy_proposals_only = true)Enforce on the server, never just by hiding a UI button: disable auto-apply for the workspace so
applyHunkAsAgentonly executes inside an authenticated human editor'sPOST /proposals/{id}/acceptrequest. Record per-hunkapproved_byandapproved_atinwriters, and run a nightly invariant check verifying every agentclient_idin live documents has a valid human approval row.2. Complete audit history
Retain
doc_updates, the ingest-time deletion log, andwritersindefinitely for enterprise workspaces (tiering updates older than 30 days to S3), add anaudit_eventstable for non-text lifecycle events (run started, hunk rejected, revert executed), and ship an exportable timeline filterable by user orrun_id.3. Selective revert of Agent Run
Rwithout erasing later human workWhy can't we just restore a snapshot from before Run
R? Because restoring an old snapshot wipes out every sentence humans wrote afterR! And why can't a CRDT simply "un-delete" the tombstonesRdeleted? Because CRDT tombstones are permanent monotonic deletions — clearing a deleted flag locally would be re-deleted on the next peer sync. Instead, selective revert inspects each hunkhofRusing itsclient_id:Example: Original text was "fast car". 1. Run R (hunk client_id = 99) deleted "fast" (tombstone) and inserted "rapid sleek" -> "rapid sleek car" 2. Case A (Clean): Human later typed " blue" after "car" -> "rapid sleek car blue" Revert deletes surviving items with client_id=99 ("rapid sleek") and inserts fresh items "fast" at the tombstone's position -> "fast car blue" (human's " blue" is untouched!) 3. Case B (Conflict): Human edited INSIDE R's words to make "rapid very sleek car" Item "very " has Yjs left-origin pointing into client_id=99! Auto-deleting R's words would orphan "very car". Mark hunk conflicting -> show side-by-side [Revert anyway | Keep | Edit].Cleanly reverted text is inserted under a new server
client_idregistered inwritersasactor_type = 'revert'with links to the original author IDs so the authorship view displays"Written by Maya (restored by revert of Run 812)". Because the revert is an ordinary CRDT transaction, the revert itself can be undone.Task-level estimate, roadmap order, and success metrics
Phase & Task Engineer-Days Phase 1 (Unblock compliance): Server proposals_onlypolicy, validator hardening, per-hunk approval UI9 Phase 2 (Auditability): Infinite retention + S3 tiering, audit_events, filterable history & CSV/JSON export6 Phase 3 (Selective revert): Conflict-detecting revert engine, side-by-side conflict UI, chaos property tests, security review 12 Total 27 engineer-days (~4 weeks for 2 engineers with 25% buffer) - Roadmap impact: Shipping Phases 1 -> 2 -> 3 pushes multi-server room sharding out by ~4 weeks, while pulling snapshot/S3 archiving forward because
gc: falseretention increases document size. - Success metrics:
0unapproved agent items in daily audits;0lost human edits in property tests and production tickets; percentage of reverts completing conflict-free; median proposal review latency and "accept all" rate (watching for rubber-stamping); p95 load time< 1 sfor 1 MB enterprise docs.
- Roadmap impact: Shipping Phases 1 -> 2 -> 3 pushes multi-server room sharding out by ~4 weeks, while pulling snapshot/S3 archiving forward because
Summary of key design trade-offs
- Yjs CRDT over OT: Permanent character IDs solve slow-agent anchoring, per-character authorship, and reconnect sync with off-the-shelf browser bindings, trading off tombstone memory overhead and binary validation on the server.
- Proposals first, direct mode as auto-accept on the same pipeline: Keeps humans in control while sharing 100% of the attribution, staleness, and revert machinery.
- Ephemeral ghost-text preview instead of streaming tokens into the CRDT: Saves ~50 DB writes/s per run, keeps history clean, and makes rejecting a bad suggestion zero-cost.
- Word-level hunks with per-hunk server
client_ids: Preserves concurrent human edits in the same paragraph, preserves original authorship on unchanged words, and enables hunk-granular revert, trading off state-copy overhead on accept. - Group commit (20 ms) and
gc: falseper workspace: Group commit scales writes ~90x without ever broadcasting unsaved edits; disabling garbage collection enables audit history and selective revert for workspaces that need compliance.
Intuition & how it works
Imagine five people editing a shared poster made of movable letter tiles on a table, while an assistant takes a Polaroid photo of one sentence, walks into another room for 11 seconds to rewrite it, and comes back to swap the tiles. If the assistant remembers where to edit by counting "start at the 10th tile from the top-left corner," even a single word added at the top of the poster while they were gone shifts every tile's number and makes them overwrite the wrong words. Instead, if every letter tile has a permanent serial number printed on its back, the assistant can clip their edit directly to the serial numbers of the exact tiles they photographed — no matter how much text teammates add or delete above or below, those serial numbers move right along with the sentence.
A naive design fails in three ways at once: anchoring edits to numeric character indices corrupts nearby sentences whenever someone types concurrently; streaming raw AI tokens straight into the shared document floods the database and forces users to manually undo rejected drafts; and replacing a whole paragraph as one block wipes out concurrent human edits inside that paragraph while falsely crediting the AI as the author of every unchanged word.
Here is a concrete 4-step trace showing how character-ID anchors and word-level hunks (minimal contiguous text changes) work together:
1. t = 0 s: Document is "Summary: The checkout failed."
Maya selects "The checkout failed." (indices 9..29) and asks the agent for formal wording.
The system records inward-clamped anchors on tile IDs: start = (Maya,9) ['T'], end = (Maya,28) ['.'].
2. t = 4 s: While the model generates tokens (~11 s total), Devon types "Incident! " at index 0,
and Maya changes "The" to "Our" inside the sentence:
Document is now "Incident! Summary: Our checkout failed."
Meanwhile, the agent streams ghost-text previews over an ephemeral channel (0 database writes).
3. t = 11 s: Agent proposes "The payment request timed out." Diffing against "The checkout failed."
produces one word-level hunk: replace "checkout failed" (tiles (Maya,13)..(Maya,27)) with
"payment request timed out", leaving "The" and "." untouched!
4. Maya clicks Accept: Tiles (Maya,13)..(Maya,27) resolve to indices 23..38, which STILL read
"checkout failed". The server applies ONLY that hunk under a fresh server-minted client_id = 901:
Final text: "Incident! Summary: Our payment request timed out."
Authorship: "Incident! " -> Devon | "Our " -> Maya | "payment request timed out" -> Agent Run (approved by Maya).
Key trade-offs
- CRDT (Yjs) vs. Operational Transformation (OT). A CRDT (Conflict-Free Replicated Data Type — a data structure whose concurrent updates merge to the exact same state in any arrival order) assigns every character a permanent
(client_id, counter)ID, giving us slow-agent anchoring, per-character authorship, and reconnect sync almost for free. OT (Operational Transformation — a central-server method that shifts character indices of concurrent operations past each other) avoids storing deleted-character markers, but transforming an 11-second-old agent edit or a long offline session requires replaying server revision logs. The CRDT's costs are tombstones (small markers kept for deleted characters), character-level rather than semantic merges when two people rewrite the exact same words simultaneously, and decoding binary updates on the server for validation. - Proposals by default vs. direct edits. Proposals keep a human in control and make rejecting unwanted output free, at the cost of an extra click. Implementing "apply immediately" as auto-acceptance on the exact same server hunk path keeps one unified pipeline for staleness checks, attribution, and revert.
- Ephemeral ghost-text preview vs. streaming tokens into the document. A separate WebSocket preview event adds a small UI layer, but avoids ~50 CRDT updates/s per running agent, keeps keystroke history clean, and ensures failed or rejected runs leave nothing to undo.
- Word-level hunks vs. whole-selection replacement. Diffing agent output into minimal hunks preserves concurrent human edits elsewhere in the paragraph and preserves human authorship on unchanged words, at the cost of per-hunk anchor state.
- One server-minted
client_idper accepted hunk vs. one per agent run. Giving each accepted hunk a dedicatedclient_idenables hunk-granular approval auditing and selective revert; cloning the in-memoryY.Docon accept costs a few milliseconds for megabyte-scale documents. - Retaining tombstones (
gc: false) vs. aggressive compaction. Keeping deleted bytes in tombstones lets enterprise workspaces audit who deleted what and selectively restore agent deletions, at the cost of larger snapshots and RAM usage; tiering old logs to object storage bounds hot database size. - Group commit (20 ms) vs. per-update commits or 1-second batching. Group commit (bundling all pending updates across rooms into a single disk transaction every 20 ms) reduces commits from ~4,500/s to ~50/s while still persisting every edit before broadcasting it. Delaying persistence to 1-second batches after broadcast risks losing a second of edits on crash and breaks sender-ID validation when another browser replays relayed edits.
Common mistakes
- Anchoring agent output to numeric character offsets captured at invocation, causing edits to splice into the wrong sentence whenever anyone types above the selection during the ~11-second model call.
- Overwriting the entire selected paragraph with the model's output, silently deleting words a teammate typed inside that paragraph during generation and erasing human authorship on unchanged words.
- Streaming model tokens directly into the CRDT document, multiplying network fan-out, polluting undo/audit history with partial tokens, and turning "Reject" into a messy undo operation.
- Tracking authorship via rich-text formatting attributes or offset side tables, both of which drift or get overwritten during concurrent merges and can be forged by clients.
- Trusting browser-chosen
client_idvalues without server binding, allowing a client to spoof another user's identity or inject unapproved "agent" edits. - Re-attributing historical deletions during reconnect sync, forgetting to filter out tombstones the server already knew about when decoding a reconnecting client's
DeleteSet. - Implementing "revert agent run" by restoring an earlier document snapshot, which wipes out every human edit made anywhere in the document after that agent run.
- Enforcing agent read/write permissions inside the system prompt rather than in server-side code, leaving confidential sections exposed to prompt injection (hidden instructions in document text that trick the model).
- Testing convergence only on clean, in-order delivery instead of randomized packet drops, duplicates, reorderings, and mid-edit reconnects, or submitting AI coding logs driven by a single giant unreviewed prompt.
Follow-up questions
- How can an autonomous background agent maintain an up-to-date document abstract without overwhelming editors with constant change requests? Give the summary a dedicated agent-owned block (such as a collapsible top callout or side panel) so it never collides with paragraphs humans are actively writing, and trigger regeneration only after the document has been idle for ~2 minutes following a meaningful change (such as a modified heading or >3% text delta, capped at once every 15 minutes). Keep at most one pending summary proposal at a time — any newer run supersedes the older unreviewed draft — and surface a quiet "Summary update ready" badge rather than interrupting editors with pop-ups. Generating incrementally from the previous summary plus only the changed sections also keeps token costs low, while enterprise workspaces still route acceptance through a single human click.
- What changes are needed to handle multi-hour offline work sessions that reconnect with large divergent edits? Persist the local
Y.Docand unsent updates in browser IndexedDB so edits survive tab restarts; when the user reconnects, Yjs's state vector handshake (exchanging compact{ client_id -> max_counter }summaries) automatically syncs hours of edits without needing server-side transform logs. Because CRDT convergence guarantees identical characters but not sensible prose when two people rewrote the same sentence offline, compute the overlapping byte ranges between the offline branch and concurrent online edits right after sync and open a "Review merged sections" sidebar with authorship highlights and one-click keep/revert per block. Before committing the offline sync, the server re-checks that the user's edit access was not revoked while they were offline, and marks any pending agent hunks touched by the merge asstale. - When a document exceeds the language model's context limit, how do you select what context the agent receives? Assemble a focused ~6,000-token context window tailored to the task: the anchored selection, its surrounding Markdown section, a cached outline of all headings with one-sentence section summaries, and the top-k relevant passages fetched via keyword and embedding search (RAG — Retrieval-Augmented Generation, fetching relevant snippets rather than feeding an entire corpus). For document-wide tasks like unifying terminology, run a map-reduce pass section by section against a shared glossary, anchoring every proposed hunk to its own character IDs so staleness and approval still work independently per section. Record the exact chunk IDs read on
agent_runsand badge the UI whenever the agent operated on partial context. - How do you enforce access boundaries so an agent invoked by one collaborator cannot inspect or modify restricted content? Never give the model ambient credentials or rely on prompt instructions; instead, mint a short-lived, run-scoped token on the server whose permissions equal the intersection of the invoking user's live ACL and the agent's narrow role. Every retrieval query, section read, and proposal creation executes on the server and filters against
doc_accessbefore text ever enters the prompt, andPOST /proposals/{id}/acceptre-verifies the approver's edit permission at click time (cancelling in-flight runs immediately if access is revoked). Because the LLM has zero direct database/network tools beyond returning text hunks for the server-supplied context, prompt injection hidden inside a document cannot escalate privileges or exfiltrate unauthorized data.
Follow-up questions
- How can an autonomous background agent maintain an up-to-date document abstract without overwhelming editors with constant change requests?
- What changes are needed to handle multi-hour offline work sessions that reconnect with large divergent edits?
- When a document exceeds the language model's context limit, how do you select what context the agent receives?
- How do you enforce access boundaries so an agent invoked by one collaborator cannot inspect or modify restricted content?
Similar questions
- Scalable Text-to-Speech Platform: Prototype, Review, and Batch Extension
- Career Motivation, Company Fit, and Agentic Coding Workflows
- Temporal Key-Value Store and Longest Dependency Chain
- Production Configuration and Rollout Platform for RAG Systems
- Undocumented API Discovery and Resilient Client Rebuild
- Vision and Numerical Pipeline Utilities
More Luma AI interview questions
- Scalable Text-to-Speech Platform: Prototype, Review, and Batch Extension Medium
- Career Motivation, Company Fit, and Agentic Coding Workflows Medium
- Undocumented API Discovery and Resilient Client Rebuild Medium Pro
- Temporal Key-Value Store and Longest Dependency Chain Hard Pro
- Production Configuration and Rollout Platform for RAG Systems Hard Pro
- Vision and Numerical Pipeline Utilities Medium Pro