# Add Relay to an existing application — Mock2 1.13.0 Use this prompt in the application repository. Relay's interface and event contract are portable; the released **Relay 1.2.1 reference package is an implementation for a particular stack**, not a universal drop-in package or a claim that the public npm registry contains `@cpr/relay`. Its declared peers target React 18 and Express 4, with a PostgreSQL/Drizzle store. Read its README, manifest and exported types to understand that implementation. These dependencies are not requirements for a consuming application. Reuse the shared component where compatible; otherwise implement a host-native adapter or port that preserves the accepted contract and proves parity. Compatibility with a different host version must be tested and recorded, not inferred or declared by widening the upstream package's peer ranges. The [interactive demo](https://mock2.fractionate.ai/demos/relay/) is the accepted interface; its activity is clearly labeled simulated, including imported Git and verification-cost examples. Every application needs its own verified integration. A framework upgrade or published demo alone does not mount Relay or connect coding tools. The stable published prompt is https://mock2.fractionate.ai/core/cpr/Relay-App-Integration-Prompt.md; its installed standards path is `.mock2/standards/Relay-App-Integration-Prompt.md`, independent of the reference package's location. Copy the following block into the app's coding session: ```text Implement the complete Relay work dashboard in this existing application using Mock2 1.13.0 and the pinned Relay 1.2.1 interface/event contract. The approved interface is https://mock2.fractionate.ai/demos/relay/. Preserve all its views and interactions; do not replace it with a simplified task list, download-only mockup panel or unrelated dashboard. Keep this application's framework, server, database, authentication, storage and release process. 1. Establish the actual host and candidate before changing it. Read this repository's AGENTS.md/CLAUDE.md and applicable Mock2 instructions, application profile, rules, decisions, inventory, work/handoff records and release instructions. Inspect the actual dependency manager/lockfile, router/navigation, auth/session/bearer middleware, workspace and role model, theme tokens and supported modes, datastore/migration owner, private file storage, realtime transport, test harness, source export/recovery and deployment path. Identify the live baseline. Record where Relay will mount and which existing capability supplies each integration boundary. Do not create another login, identity service, database, independent backend/service, ORM or daemon merely to install Relay. Use the existing host shell and error/loading/empty-state conventions. Read the released core/relay/README.md, feature.manifest.json, event schema/projector and exported host, store, transport and client contracts. Treat the bundled component, router and database migration as reference implementations with their documented compatibility limits. Resolve the exact release commit and verify release hashes. Pin Relay 1.2.1, source/compiled identities and package/archive SHA-256 in application records and the lockfile or vendor manifest as applicable. Never use floating main or mix source, compiled runtime, styles or assets from different candidates. Source changes require rebuilding the affected runtime from that exact source. Use compatible shared UI/runtime pieces through the app's existing dependency process. Where the host differs, build a thin host-native adapter; port only the incompatible boundary while preserving validation, projection, authorization, ordering and full interface behavior. Record ported files, upstream identities and parity evidence. Do not replace the host stack to match a reference example, add dependencies the host does not need, or claim untested compatibility. For an existing Relay integration, plan the reader upgrade before enriched events are emitted. Relay 1.2.0 additionally introduces strict schemaVersion:2 history.commit.observed and check.recorded observations, with minimumReaderVersion 1.2.0. Upgrade all readers and validators before enabling them, apply the additive history-identity migration, and retain compatible readers on rollback. Existing schemaVersion:1 events remain unchanged. Do not add arbitrary fields to them. Within schemaVersion:1 records, task.created checkpoint/next/needsInput and the task.updated type require a minimum reader of 1.1.0; 1.0.1 validators reject them. Update all frontend/server/worker consumers and repository emitter/export/sync/check-capture readers to the pinned 1.2.1 contract first. Verify old history and the first enriched event through every delivery path. Do not infer forward compatibility from the unchanged envelope version. Retain all history during rollback: the 1.0.1 package alone cannot read enriched retained events. Keep a 1.2.0-compatible reader once version-2 observations exist, or provide a tested adapter that preserves stored events and lifecycle semantics. Record the minimum reader and actual rollback path; do not delete or strip history to make an old validator pass. 2. Add persistence and server integration using the host's existing capabilities. Register an additive migration/schema change with the existing datastore owner before enabling queries. The reference migration creates relay_streams and relay_events; use an equivalent host-native representation when needed. Preserve existing application data, event history and references. Disabling/removing Relay retains data; deletion is a separate explicit request. Make each append atomic: check event-ID idempotence and conflicting content, validate schema and causal/workspace transitions, allocate the authoritative monotonically increasing stream sequence, and persist the event together. Use the host datastore's transaction/locking mechanism that provides these guarantees under concurrent requests. A collection of unrelated writes is not a transaction. Retries of an identical event return its existing result; conflicting reuse fails. Do not order delivery by client clocks or invent sequence values in the browser. Mount equivalent authenticated history, event ingestion, stream, comment, control-request and reference routes behind the existing identity middleware at the app's established route prefix. Validate inputs at each boundary, including types, size, malformed JSON and event fields; preserve the contract's causal checks. Use existing error logging, body limits and mutation protection. Do not weaken session/CSRF protection to accommodate Relay; use the existing scoped bearer path where appropriate. Account for upload encoding expansion and bounded request/stream resources. Enforce workspace and action permissions on the server independently of navigation or controls. Honor the requested audience: an admin-only installation restricts page mounting, history, stream, references and human mutations to authorized human admins. Test direct requests from other roles. Map relay.view/comment/request/references to the host's permitted human roles; grant relay.record only to explicitly authorized producers for the named workspace. Map the separate relay.history permission to authorized history operators; it permits importing or retrying the configured repository metadata without granting general event ingestion. Existing machine credentials do not automatically inherit ingestion or human read/mutation permissions. Use explicit grants on the host's existing credential mechanism rather than a second credential service. Derive authenticated actor/producer identity on the server, not from supplied event text. Do not retrieve or mint production identities, sessions or credentials merely for test fixtures. 3. Mount the complete client, live transport and private references. Add the Relay navigation item and page inside the existing authenticated shell, with the required role checks. Preserve the host's default landing section, sign-in/deep-link flow and mobile navigation. Opening the app or Relay must not automatically scroll the document to the section. Do not focus a lower control on initial mount; preserve scroll when explicit user actions require focus. Do not add a separate full-viewport shell or second theme/login system. Keep Work, Connections, Mockups, Daily reports and Run costs tabs at the top. On desktop, put work items in the left independently scrolling column and cards, Git/activity and selected-work details in the right content scroller. Fill the height supplied by the host shell with min-height:0 on nested flex/grid areas; never globally lock unrelated pages. On phones retain top navigation and use list/detail navigation inside the same available height, with safe-area/lifecycle handling. Use a stable client/transport per identity and workspace; dispose the old subscription and data when either changes. Use the existing authenticated JSON and realtime mechanisms. Realtime may use the host's event stream, socket or equivalent transport; it must deliver the contract reliably. Load paginated initial history, resume from the latest delivered server sequence, deduplicate, report connection failures and unsubscribe on unmount. Support bounded stream rotations and reconnection. Configure proxy buffering/timeouts appropriately for the chosen transport. Recheck current session/role/workspace access during live delivery; revocation ends delivery and client reconnection. An open page or network connection is not proof that a worker is active. Map shared theme tokens to the host palette in its supported modes, keeping status colors, icon hierarchy and compact information density. Use the user's/app's timezone. Distinguish loading, unauthorized, offline, stale activity and genuinely empty authorized history; do not substitute demo data when authorization, transport or storage fails. Store references privately with immutable identity, workspace association and integrity hashes. Validate allowed type, extension/signature and size; block executable scripts and SVG. Keep storage objects consistent with events, removing a newly orphaned file if its event append fails. Expose uploads and authorized download/preview through the host, not a public asset library. Only validated PNG/JPEG/WebP images are inline-previewable; recheck authorization and bytes. PDF, text and Markdown remain downloadable attachments. Use existing session-authenticated URLs or authenticated byte fetches/managed object URLs as the host requires, disposing temporary URLs. Never put tokens in URLs or browser storage to enable previews/streams, execute reference files, or inject text/Markdown as raw HTML. Keep safe downloads available when inline preview is absent. An optional Example mode is visibly labeled Simulated, isolated from real history and incapable of production writes, uploads or control requests. It is user-selected, never the default real workspace feed or fallback for a failed integration. Production does not seed pretend running tasks to fill an empty dashboard. 4. Preserve the complete interface and its meaning. Create an acceptance matrix with at least these rows and verify every row in the rendered app: - Compact metric cards with useful colored/sized icons; running, today's measured work time, verified feature/update/patch deployments and needs-input context. Applicable cards filter tasks; All work resets the filter. - Git-style activity grid with month/weekday labels, intensity legend and today highlighted; date selection; useful activity/findings summaries and access to every selected-day event. - Investigation/Build work cards with current status and ticking/stale measured elapsed time; selected task Summary and History & evidence; outcome/summary, current checkpoint, next step, needs-input text, comments, requests and linked work. Desktop side-by-side and mobile stacked layouts retain the same information and actions. - Connections graph showing clickable prerequisites/dependents and design links; show what a prerequisite unblocks, with task status and access to linked tasks. - Mockups gallery with image thumbnails, linked-task context, authenticated preview/download and actual inert reference upload. Formats without safe inline preview remain downloadable. - Execution graph with actual parallel steps, animated active connectors, elapsed/current activity, retained failure/repair/retry attempts and selectable command, findings, logs or summaries, tested revision and reference evidence. Replay preserves earlier failed attempts. - Secondary Idea to outcome view with visually linked origin ideas, combined feature, contributing runs and recorded verified delivery; distinguish idea lead time from measured unique-run work time and link back to evidence/current work. - Separate Daily reports with deployed, still-active and needs-input context and recorded task links. Summaries use real events and do not fabricate work for a report. - Keyboard operation, readable contrast, supported host themes, mobile layout, explicit loading/offline/unauthorized/empty states, stale activity and no initial automatic scrolling. Never invent a completion percentage for an AI reviewer. Show recorded activity, elapsed time and last observation. Only a source that measures completed/total/unit supplies progress. Deployment cards count only deployment.recorded with verified=true and an actual revision. An idea's calendar lead time includes waiting; work time sums each contributing run once, even when ideas combine or steps run in parallel. This is elapsed work visibility, not API billing. 5. Connect actual work producers and repository history separately from the viewer. As part of initial authorized repository/workspace connection, start the lightweight Git lookback automatically in the background. First verify the correct workspace and complete existing-history pagination; preserve and reuse existing records. Use the package's configured backend history adapter or equivalent existing host job mechanism, with a stable repository identity and pinned cutoff commit. Default to the visible recent six-month window, bounded resumable batches and a Load earlier action. Never require a .git directory in a deployed image, accept a filesystem path from the browser, or put repository credentials in the client. Preserve full SHA, parents, subject, author/committer timestamps and import time. Deduplicate by workspace + repository identity + SHA, retaining original evidence across retries and overlapping windows. Show partial/shallow coverage, progress and delivery errors without disrupting live work. Use blue imported squares, green native-activity squares and labeled mixed-day counts. Imported commits remain observations: tests, deployment, intent and work time are unknown absent evidence; do not emit fake successful runs. Calendar navigation must reach earlier imported windows. Use schemaVersion:2 check.recorded for runner results that distinguish executed, reused-valid and prerequisite-blocked checks (in a Mock2 repository, set "relay": {"checkEvidence": true} in .mock2/checks.json once this host reads them; the runner leaves them off otherwise), with input identity, source record, invalidation reason, queue and execution time. Expose these in Run costs and link repeated fields to canonical per-run JSON. Never count cached checks as freshly executed or infer missing model cost/time. Verify changed inputs invalidate reuse and failures/missing prerequisites cannot become passes. Keep the existing Markdown run ledger. Use stable task/idea IDs and unique run/event IDs with append-only events. The installed .mock2/bin/relay.mjs emitter/export/sync and state/relay/events are the reference producer path; use a verified equivalent if this host needs another runtime. Emit task.created and run.started, meaningful step.started/activity/finished and run.finished from real coding/check work. Emit relationship.added for recorded inspired/combines/depends_on/ design links, preserving origins and ownership. A design link is artifactId -> destination taskId in the same workspace; event.taskId is that destination. Failed attempts remain in history; retries use the same logical stepId with increasing attempt and explicit dependencies. Instrument existing checks/deployments and actual coding tools rather than assuming automatic chat capture. The reference check capture uses MOCK2_WORKSPACE_ID, MOCK2_TASK_ID and MOCK2_RUN_ID to associate checks with the owning run. The owner closes that run after its actual outcome; missing checks remain missing and failed checks remain failed. Record sanitized findings, commands and exact tested revisions, not raw transcripts, secrets or sensitive output by default. Older start/end ledgers establish only their recorded durations/statuses. Do not reconstruct imaginary intermediate steps, idea inception dates or progress. The installation's own real work can be recorded with observed timestamps; do not backdate unsupported evidence to fill the UI. task.created may include checkpoint, next and needsInput strings. Append task.updated for later summary/checkpoint/next/needsInput changes; at least one field is required, values are strings up to 8,000 characters and empty strings clear them. Set needsInput:"" when input is resolved. Updates target an existing task in the same workspace and accept no runId, stepId, attempt, status, revision or control fields. Metadata does not refresh execution clocks or start, finish, pause, backlog or prioritize workers. Those require real lifecycle/control events. Connect explicit authenticated delivery to this workspace's HTTPS /events endpoint through the host's existing secret mechanism. The reference sync uses RELAY_INGEST_URL and RELAY_INGEST_TOKEN; keep credentials out of URLs, committed files, logs and chat. Verify TLS. Demonstrate a real task/check emitted locally and delivered into the app, then re-send it to prove idempotence. Do not export private history to another audience without authorization. If an external producer credential or instrumentation is unavailable, report that connection as incomplete; display installation, producer connection and worker-control connection are distinct outcomes. Pause / Move to Backlog / Make Priority append control.requested. Connect an actual worker/control receiver only through a narrowly authorized host path for obtaining requests and acknowledging their workspace/task/action scope. Record control.acknowledged with requestId/action/accepted; the server binds acknowledgments to the authenticated producer. Pending/rejected requests remain visible; only accepted acknowledgments change effective state. Do not imply that a display button stopped a coding process or execute reference files as commands. A viewer does not require adding a control daemon, and ingestion-only credentials must not gain general work-feed read access. 6. Include the feature in deployment, source recovery and verification. Inspect the host's export/snapshot/Git collection, release manifest and restore process. Include new backend modules, vendored UI/runtime/styles, referenced binary assets, producer helpers and applicable tests. Preserve binary bytes/hashes, path layout, executable startup/helper permissions and required registration. A working local tree is insufficient if the deployment collector drops files. Build and inspect the actual release; verify a source/restore round trip and fresh deployed file baselines before promotion through the existing release process. Retain event data/private references on code rollback, with the compatible reader identified above. Run the app's normal checks and focused checks against this exact candidate. Exercise the actual host routes/auth middleware and datastore, not only fake package adapters. Test additive migration, atomic/concurrent ordering, duplicate/conflicting ingestion, malformed inputs, anonymous and cross-workspace denial, role-specific mutations, session/CSRF or scoped-token rejection, explicit producer grants/revocation, paginated history, reconnect cursors/deduplication, access revocation, identity/workspace changes and cleanup. Test real private upload/preview/download, integrity, signatures/types/size limits, attachment-only text/PDF, missing objects, failed-write compensation and denied access. Test metadata without lifecycle side effects, pending/rejected/accepted worker controls, isolated Example with zero production writes, and data retention when disabled. Verify producer delivery/retries over authenticated HTTPS using authorized existing credentials or isolated local test identities; do not fabricate production credentials to complete a test. Render the actual app and approved demo with comparable data at desktop and mobile widths and in supported host themes. Inspect and compare layout, density, spacing, icon hierarchy, status cues, every view and interaction in the matrix, sign-in/deep links and initial scroll position. Save comparison screenshots/findings with candidate identity, viewport, theme and whether data is simulated or real. A saved screenshot without comparison, passing build or no-overflow check is not visual parity. Distinguish isolated authenticated host tests, live unauthenticated probes and live authenticated owner-session checks; do not describe one as evidence for another. Fix omissions in shared code or host adapters/ports as appropriate. Record deliberate theme differences and unresolved limits without marking missing features complete. Record normal-check failures separately. If a failure is pre-existing and outside this change, prove that against the actual baseline, report its exact limitation and continue the authorized feature work; do not claim all checks passed or require an unrelated rewrite to install Relay. Update app integration/change/handoff records with pinned source/compiled identities, any port, schema change, navigation/routes, audience and permission mapping, producer/sync/control paths, minimum reader and rollback, storage/transport settings, complete release/recovery inventory, real test results, visual matrix and remaining gaps. Complete deployment through the existing workflow when this instruction/session already authorizes it. Honor actual project instructions and tool permissions; do not invent another approval flow or re-request authorization already given. Report the installed page, verified behavior and each incomplete producer/control path; publishing standards or a demo alone does not integrate an application. ``` These requirements describe behavior and boundaries, not a framework, database, hosting provider or transport selection. The current reference package's compatibility declarations remain unchanged. Removing the page/routes retains history and private references. Production work feeds are private by default; an externally shareable sanitized view is a separate requested capability. For ongoing recording, implement `Relay-Recording.md` and verify a new coding session end to end. Configure the scoped producer endpoint/token once; use automatic emit/check delivery, an existing host/session-owned structured-event watcher, and lifecycle adapters or command wrapping for every coding entry point. Preserve review-first import where already selected. Report actual capture coverage and pending outbox status; viewer connection alone is insufficient.