collaboration Plugin
Design Docs
The `design_docs` plugin (`plugins/design_docs/`) is default-disabled first-party Syrus functionality for collaborative Markdown design documents. Operators can enable it from **Admin → Plugins**. Design docs are separate from attachment-oriented `Document` records. The plugin registers the operator-visible capability as `design_docs`, owns the `DesignDocs::` domain models, JSON API controller, policy, serializer, and create/update services, anchor marker parsing, comment/thread services, suggestion review services, and specs under `plugins/design_docs/app/`. The host app applies only the small associations needed on `User`, `Repository`, and `ChatSession`.
Design Docs
The design_docs plugin (plugins/design_docs/) is default-disabled first-party Syrus functionality for collaborative Markdown design documents. Operators can enable it from Admin → Plugins.
Design docs are separate from attachment-oriented Document records. The plugin registers the operator-visible capability as design_docs, owns the DesignDocs:: domain models, JSON API controller, policy, serializer, and create/update services, anchor marker parsing, comment/thread services, suggestion review services, and specs under plugins/design_docs/app/. The host app applies only the small associations needed on User, Repository, and ChatSession.
Schema
design_docsstores the canonical current Markdown body, title, owner,
visibility, state, optional origin chat session, and optional current version. DesignDocs::DesignDoc#display_id renders user-facing references as DOC-<id>.
design_doc_repositoriesis the n:m join between design docs and
repositories, with a unique (design_doc_id, repository_id) index.
design_doc_collaboratorsrecords explicit private-doc collaborators for v1.design_doc_versionsis append-only at the model layer and stores Markdown,
version number, actor user/kind, optional polymorphic provenance, change summary, metadata, and timestamps.
design_doc_anchors,design_doc_threads,design_doc_comments, and
design_doc_suggestions provide the base inline discussion and owner-reviewed suggestion model. Anchors are stored in canonical Markdown as hidden HTML comments: point anchors use <!-- syrus:anchor id="..." -->, and range anchors use paired <!-- syrus:range-start id="..." --> / <!-- syrus:range-end id="..." --> markers. Rendered Markdown strips these comments; database rows remain authoritative for marker ids, base version, selected text, prefix/suffix context, last known offsets, provenance, state, and permissions. Suggestions are v1 range replacements (change_type: replace) reviewed explicitly by the design doc owner.
design_doc_agent_runsrecords lightweight@syrusthread turns. Each run
belongs to a doc, thread, triggering comment, requesting user, and base version; stores provider/status/timestamps, a prompt context snapshot, output payload, result summary, and error message; and links generated comments/suggestions back to the run for provenance.
DesignDocs::DesignDoc.visible_to(user) implements the v1 visibility rule: owners can see their docs, explicit collaborators can see private docs, and public docs are visible to users who can access at least one associated repository.
Anchor staleness and version-scoped history
Accepting a suggestion can overwrite raw Markdown that other anchors' hidden markers were sitting in — a full-document suggestion is the extreme case, since its replaced range is the entire document. DesignDocs::ReviewSuggestion reconciles every other active anchor around every acceptance (both the normal range-replace path and the marker-less autosave full-document path): an anchor whose marker survived untouched just gets its cached offsets refreshed; an anchor whose marker disappeared gets re-projected onto the new text when its exact previous excerpt still exists exactly once elsewhere in the document, and is otherwise marked status: "stale" immediately (with stale_as_of_version set to the version the acceptance produced) along with any of its still-pending suggestions. A stale anchor's offsets are frozen at their last known position — the anchor is never silently re-derived from numeric offsets once it can no longer be trusted. The pre-existing path where a suggestion's own anchor text has drifted since it was authored (checked against suggestion.original_markdown before any replacement happens) also stamps stale_as_of_version, pinned to the design doc's current version since that path never creates a new one — every code path that flips an anchor to stale keeps the same version-window invariant.
An anchor whose range only *partially* overlaps the accepted range (rather than nesting fully inside or sitting fully outside it) is a special case: the accepted range's replacement can delete just one side of that anchor's start/end marker pair, leaving the other side dangling in the Markdown. Before deciding whether to re-project or mark such a candidate stale, DesignDocs::ReviewSuggestion clears any leftover marker fragment for it first. Marker normalization also repairs unrelated duplicate, mixed, orphaned, or overlapping pending anchors by marking those anchors and suggestions stale, recording a conflict reason, and removing their marker fragments. Corruption on one suggestion therefore does not prevent accepting or rejecting a valid, unrelated suggestion. A problem with the suggestion being reviewed can still return 409 with error.code == "conflict", and the failed review is rolled back.
New range suggestions cannot overlap an active pending range on the same document. The app API returns 422 with error.code == "pending_suggestion_overlap", and the message identifies the pending suggestion that must be accepted or rejected first. Ranges that only touch at a boundary remain valid. The suggestion MCP tool reports the same translated message through its normal invalid-request result.
The current-document editor and Threads rail only render anchors with status: "active" (buildAnchorHighlights's highlight filter and ThreadPanel's current-view filters in DesignDocsSurface.tsx), so stale threads/suggestions disappear from the live view without being deleted. GET /api/v1/app/design_docs/:id/versions/:version_id/threads (backed by DesignDocAnchor.active_as_of(version_number), using each anchor's birth design_doc_version and stale_as_of_version) returns the threads and suggestions that were active as of a specific historical version, so a stale comment remains inspectable when viewing the version where its anchor existed. The version dropdown in the editor title bar fetches this endpoint and renders those results read-only (no reply, resolve, or accept/reject controls) while a non-current version is selected.
Admin API
The app API (/api/v1/app/design_docs) is session-shaped: its serializers, permission payloads, and policy_scope-based visibility are built for the SPA and a signed-in user, even though Api::V1::App::BaseController happens to also accept a bearer token. Operators and orchestrators should instead use /api/v1/admin/design_docs (Api::V1::Admin::DesignDocsController), which follows the same bearer-token-plus-admin-scope convention as the other /api/v1/admin/* controllers: GET /api/v1/admin/design_docs (filterable by state, visibility, and user, matched against the owner's email address), POST /api/v1/admin/design_docs, GET /api/v1/admin/design_docs/:id, PATCH /api/v1/admin/design_docs/:id, and GET /api/v1/admin/design_docs/:id/versions. It sees every design doc instance-wide rather than only the docs visible to the calling user, the same way Api::V1::Admin::JobsController is not limited to the caller's own Jobs.
The admin controller reuses DesignDocs::Create and DesignDocs::Update rather than reimplementing the write paths, so versioning, and the owner-vs-collaborator authorization DesignDocs::Update already enforces, behave identically to the app path: creates and updates are attributed to the API token's own user, and a PATCH from a non-owner becomes a suggestion exactly as it would through the app API instead of silently bypassing ownership. Unlike the app path, where an unchecked PATCH autosaves a draft copy without creating a version, every admin PATCH is treated as a deliberate one-shot change and always checkpoints (checkpoint: true is assumed unless the request explicitly overrides it), so an operator update always produces a new DesignDocs::DesignDocVersion row when it lands as a canonical edit. Serialization follows Admin::JobStateSerializer's resilience convention: a single design doc, version, or list row that fails to serialize renders { id, error_serializing: "..." } instead of 500ing the whole response. With the plugin disabled, every endpoint under /api/v1/admin/design_docs answers plugin_disabled the same way the app API does.
Editor UI
The plugin-owned editor uses a full-width document title bar above the document surface. The title bar contains the editable title, canonical DOC-<id> identity, visibility and state indicators, repository associations with a + picker, a Share popover for visibility and explicit collaborators, and a far-right version dropdown. The body editor uses Rich Text and Markdown tabs over the same canonical Markdown working state instead of an adjacent edit/preview split. Rich Text is selected by default; Markdown remains available as the alternate source-editing mode. Owner edits autosave into the design_docs.markdown working copy so reloads and navigation preserve in-flight edits before an explicit checkpoint. Selecting a version from the title-bar dropdown loads that version's Markdown into the current working copy; it is autosaved like any other edit, while Save creates a new auditable version/checkpoint from the current persisted working copy.
Detail responses include canonical_revision, a SHA-256 fingerprint of the stored title, canonical Markdown (including private anchor markers), state, visibility, repositories, and collaborators. Owner title/Markdown updates send that value as base_revision; autosaves submit only those editable draft fields, not unchanged visibility, state, repository, or collaborator metadata. If a suggestion accept or another canonical write changed the document meanwhile, the API returns 409 with error.code == "revision_conflict" and leaves the newer canonical text untouched. The editor waits for an already-started autosave before reviewing suggestions and applies consecutive reviews in order. On conflict, reload the current document, reconcile the local draft, and retry from its new revision. Successful autosaves still create no version checkpoint.
Canonical Markdown must have a nonblank visible body after hidden anchor markers are stripped. Canonical updates and suggestion reviews reject an empty or marker-only body atomically, without moving anchors, creating a version, or changing suggestion state. The client serializes Rich Text before review only when the editable Rich Text element is mounted; compact, narrow, and other read-only presentations review from the persisted draft and do not manufacture a canonical autosave from an absent editor. This protects the failure mode in which a compact review serialized a null editor as an empty string, projected two pending range anchors onto that empty body, and then checkpointed the marker-only result while attempting to review a suggestion.
Pending suggestions are classified before rendering. Inline-safe suggestions appear inline at their anchored range in both editor modes where practical: the original Markdown range is struck through in the active theme warning color and the proposed replacement appears next to it in the active theme success color. Block-level suggestions, including multiline replacements and replacements that begin with Markdown block markers such as headings, lists, blockquotes, or code fences, render as an anchor mark in the document body and as a structured Current/Proposed block diff in the Threads column. Proposed block Markdown is never injected as inline text inside an existing heading, paragraph, or list item. The default Terracotta theme uses terracotta for warning and green for success. Suggestion previews are display-only. Rich Text conversion keeps the original anchored text in the draft, and canonical Markdown is not changed until the owner accepts a suggestion. New pending suggestions cannot overlap an existing pending suggestion, and selections that cut through partial Markdown block syntax are rejected with a validation error.
Threads rail anchor alignment
Comments and suggestions render as one combined, document-order list in the Threads rail (activeRailEntries in DesignDocsSurface.tsx) sorted by each entry's anchor offset -- not grouped into a comments group followed by a suggestions group -- so reading the rail top to bottom matches reading the document top to bottom, and the two kinds are positioned identically.
Each card's vertical position targets the pixel position of its anchor mark in the currently active editor surface (the Rich Text WYSIWYG body or the Markdown highlight mirror), measured via getBoundingClientRect and applied with a per-card margin-top plus one transform: translateY(...) on the whole card stack (computeRailLayout in designDocRailLayout.ts). When anchors sit too close together for their cards to fit without overlapping, the card nearest the focused anchor/card (the "pivot" -- the clicked item, or the topmost item when nothing is focused) holds its exact position and the rest cascade away from it, earlier cards pushed up and later cards pushed down, preserving document order and a minimum gap. A pushed-up card can end up rendered above the rail's own top edge -- that's expected: selecting that card or its anchor makes it the pivot and snaps it back into exact alignment. Layout recomputes on focus changes, editor mode switches, thread/suggestion set changes, and content/viewport resizes (ResizeObserver plus a window resize listener); it never introduces a separate scrolling container -- the rail stays part of the normal document scroll, and any overflow below the document's end just extends the page's own scroll height.
focusThread/focusSuggestion only ever call scrollIntoView on the in-document anchor mark, never on the rail card: once a card becomes the pivot its position is defined to already match the anchor, so a second, separately-computed scroll target on the card would only race the layout effect's own DOM changes -- most visibly on the last rail entry, where becoming the pivot can shrink the whole stack as it stops absorbing collision push-down from every entry ahead of it. The card catches up for free once the layout effect re-renders with it as the pivot.
Anchors without a rendered mark (e.g. point-kind anchors, or any anchor that briefly has no highlight while a draft edit is unsaved and dirty) fall back to inheriting the previous entry's resolved position rather than being measured, so the cascade still holds even when a marker can't be found. Historical version threads (see "Anchor staleness" above) are exempt from this positioning entirely and keep a plain, unaligned stacking order, since their anchors describe a past Markdown body, not whatever is currently rendered in the editor.
The document detail API includes editor permission flags: can_write_canonical, can_suggest, can_review_suggestions, can_archive, and can_unarchive. Owners see an Edit / Suggest selector in the editor toolbar. Edit is selected by default for owners and continuously persists canonical Markdown working state; clicking Save reveals an optional change summary field and the next Save creates an append-only checkpoint/version with actor metadata. Switching to Suggest persists the draft as an owner-authored pending suggestion for later review. Owners also see metadata, sharing, repository, resolve, suggestion review, and archive controls. Archived docs stay read-only but show Unarchive in the same title-bar action slot where active docs show Archive; unarchiving is a state-only owner transition back to draft. Non-owners with access are forced into Suggest mode: the toolbar does not offer Edit, their in-flight edits autosave as pending suggestions, the save action is labeled as suggestion creation, and accept/reject controls render as pending owner review.
MCP tools
Chat agents can list, read, propose, comment on, suggest changes to, archive, and inspect the section outline of visible design docs. Workflow agents get the read-only subset scoped to docs linked to the run repository. The list_design_doc_sections tool returns every Markdown heading in the current rendered Markdown, with its level, text, start offset, and section end offset, so agents can target suggest_design_doc_change without hand-parsing the full document body.
Thread Mentions
Users who can comment/suggest on a Design Doc can invoke a lightweight Design Docs agent turn by mentioning @syrus in a newly created comment/reply or in an edit that newly introduces the mention. Matching is case-insensitive and ignores mentions in quoted text, inline code, and fenced code blocks to avoid triggering from pasted historical content or examples.
Mention turns are scoped to the thread instead of materializing normal Syrus Jobs. The queued run captures DOC-<id>, the current version and Markdown, the thread anchor, the full thread discussion, pending thread suggestions, doc visibility/repository/collaborator metadata, and a small origin-chat excerpt when one is available. The agent may create a pending suggestion on that thread or post an agent-authored reply such as a clarifying question or an explanation that no safe suggestion can be made. It must not directly mutate canonical Markdown. Requests for repository implementation or file work should be answered with a redirect to the chat Job/Epic proposal flow.
The Design Docs surface shows thread-level status for the latest agent run: queued/running displays Syrus is drafting..., success shows the run summary, failure shows the failure reason, and cancellation shows a canceled state. Duplicate saves of the same triggering comment reuse the existing run, and only one queued/running agent run is active for a given thread at a time.
Chat Workspace Tabs
The Design Docs chat workspace surface is document-focused, not the top-level index. In chat mode it must not infer a design doc id from the chat route's :id param, because that value is the ChatSession id. It resolves the selected document only from plugin tab payload data produced by DesignDocs::WorkspaceTabs.
When a chat has one visible originated or referenced design doc, the plugin declares the legacy design_docs.chat tab with design_doc_ids and design_docs summary data. The frontend selects the first explicit design_doc_ids entry and loads /api/v1/app/design_docs/:id for that doc. When a chat has multiple visible docs, the plugin declares one tab per document (design_docs.chat.<doc_id>) and includes design_doc_id in each tab's data, so tab identity and document identity stay aligned. Chat mode hides index chrome: no FilterBar, smart-folder navigation, repository/owner/state filters, or document list. It keeps the document title bar, editor/review UI, comments, suggestions, sharing metadata, repository metadata, and version controls.
If a chat Design Docs tab is rendered without an explicit document id, the surface shows an empty state instead of guessing DOC-<chat_session_id> or any other derived id.
The plugin owns its migration under plugins/design_docs/db/migrate. The host app adds bundled plugin migration paths at boot, and the shared Rails schema dump remains in db/schema.rb.
Slug Hover Preview
DOC-<id> references linkified anywhere in the app (chat messages, job/epic bodies, design doc comments) come from the shared slug type registry and get a rich hover/click preview popup, the same interaction core already has for JOB-<id>/EPIC-<id> (SlugReferenceCard). GET /api/v1/app/design_docs/:id/preview backs the popup with a payload lighter than DesignDocDetail: copyable display_id, title, owner, collaborators, comments_count (across all threads), latest_version_number, updated_at, and preview_text — the document body with hidden Syrus anchor markers stripped (DesignDocs::DesignDoc#preview_text) and clamped to roughly 100 words so a page referencing many docs never fetches full editor payloads just to preview slugs. Visibility is enforced the same way show enforces it (policy_scope(DesignDoc).find), but a doc that doesn't exist or that the current viewer can't see returns 200 with { id, display_id, accessible: false } instead of an error — enough for the popup to render a minimal "Not accessible" state without leaking whether the doc exists, its title, or any other field.
Design Doc indexes and version histories are paginated. Detail payloads expose one rendered_markdown body, relationship objects without duplicate ID arrays, and suggestions refer to their separately serialized thread by thread_id. Version lists contain metadata only; selecting a version loads its body and historical threads. Autosaves, comments, suggestion creation/rejection, and thread resolution return compact deltas led by canonical_revision; suggestion acceptance returns full detail because the editor must replace its canonical body and reprojected anchors.
The slug type is registered through the plugin's :slug_type provider. The frontend card (plugins/design_docs/app/frontend/slugPreviewCards/DOC.DesignDocPreviewCard.tsx) is discovered separately by core's generic filename-convention glob lookup (app/frontend/pluginSlugPreviewCards.tsx, the same import.meta.glob convention workspace_tab/ui_slot use): the leading DOC. segment of the filename associates this component with registered DOC-<id> slugs — core does not name design_docs or "doc" anywhere. linkifySlugs.tsx derives the prefix directly from the matched slug text, looks it up in the bootstrap slug registry, and passes that entry to SlugReferenceCard, which resolves the component via pluginSlugPreviewCardComponentForPrefix(prefix) without ever importing plugin code or hardcoding a plugin-owned kind. The card renders a condensed collaborator list (first three names, then +N) when there are many collaborators.
Agent Tooling
Chat agents can read docs with list_design_docs and read_design_doc, create new docs with propose_design_doc, add anchored discussion with comment_on_design_doc, suggest edits with suggest_design_doc_change, and archive one doc with delete_design_doc, or archive several docs with one confirmation through archive_design_docs. Agents should prefer the bulk tool for multi-document requests.
read_design_doc defaults to detail: "full". The 64 KiB limit is a per-call Markdown transport limit, not a maximum readable document size. Every full read reports doc_ref, the exact version_number, total_bytes, byte-based start_offset and end_offset, truncated, and next_cursor. When next_cursor is present, pass it back as cursor until truncated is false:
{ "doc_ref": "DOC-123", "max_bytes": 32768 }
{ "doc_ref": "DOC-123", "cursor": "<next_cursor>", "max_bytes": 32768 }
The opaque cursor is integrity-protected and pins every continuation to the version selected by the first call. An edit between calls therefore does not mix revisions; invalid, modified, cross-document, and version-conflicting cursors are rejected. A caller may also begin at an explicit historical version_number. max_bytes defaults to and is capped at 65,536 bytes. Page boundaries are UTF-8 safe and byte ranges can be concatenated to reconstruct the version's canonical Markdown exactly.
The first page preserves the complete metadata, permissions, threads, comments, and suggestions payload. Continuation pages set discussion_included: false and omit those collections, so discussion never consumes or ambiguously changes the Markdown page budget. rendered_markdown describes the returned page after hidden anchor removal; use markdown plus the byte offsets for deterministic reconstruction. By contrast, list_design_doc_sections offsets are Ruby string character offsets into the full rendered Markdown, not pagination byte offsets.
Callers that only need routing or freshness metadata can pass detail: "summary" to receive just DOC reference, title, state, visibility, current version number, pending suggestion count, open thread count, and update timestamp. Summary behavior is unchanged and does not accept pagination inputs.
suggest_design_doc_change requires base_version_number, copied from the current_version_number field returned by the read_design_doc call that observed the content being edited. The preferred locator is original_markdown: when start_offset and end_offset are omitted, the tool searches the current rendered Markdown for that exact text and resolves offsets only when the match is unique. If the text appears a few times, the error numbers each occurrence with surrounding context and computed offsets; retry with occurrence_index: N or include more surrounding text in original_markdown to make the selection unique. If it appears too many times, the tool returns a short narrowing error instead of listing every occurrence. Offset-based suggestions remain supported for callers that already have exact ranges. When offsets and original_markdown are both supplied, the tool validates that the live text at the supplied range still matches. A successful suggestion inserts anchor markers and creates a new document version, so agents must re-read the Design Doc before creating another suggestion. Stale version submissions are rejected before exact selected-text matching or marker insertion.
archive_design_docs accepts a non-empty list of up to 100 canonical DOC-<id> references and one shared audit reason. It normalizes and deduplicates references in first-seen order, checks visibility and archive authorization for every target before creating anything, and skips targets that are already archived. Eligible targets become delete_design_doc members of one pending-action group, so the operator sees one card and can confirm or reject the whole request. Confirmation rechecks state and authorization and shows per-document applied, skipped, or failed outcomes.
delete_design_doc archives by setting state: archived; it is intentionally not physical deletion. Versions, comments, threads, suggestions, anchors, and repository links remain inspectable by direct URL, history, or explicit archived state filters. The tool archives immediately only when the doc is version 1, less than 10 minutes old, and has no comments, threads, or suggestions. All other calls create a pending confirmation with audit payload that includes the DOC reference, internal id, title, state, age, current version, discussion and suggestion counts, repository ids/slugs, and the reason confirmation is required.
Workflow agents receive only list_design_docs and read_design_doc, scoped to the run repository; workflow/run contexts do not expose delete_design_doc or other mutating Design Docs tools. Owners can unarchive from the Design Docs UI; the app API accepts only the standalone archived-to-draft state transition for that path, so archived Markdown cannot be edited in the same request that restores the doc.