Template & app data
Permissions refactor merged (#516, 2026-10-06, not deployed yet). On
main, app data no longer lives in a per-workspace D1. Each collection is a platform-owned SQLite Durable Object reached through the PlatformData gateway, and the template'spackages/dbtalks to it over the platform transport (client.ts,wire.ts, deterministicmodel-generator.ts;publisher.tsremoved). The D1 adapter notes below describe what staging and prod still run until cutover. See Permissions & app data.
Workspace seed (packages/template)
Every new workspace is still seeded from this Bun monorepo (baked into the agent image at /opt/template with preinstalled node_modules):
apps/web— TanStack Start + React + Tailwind (published Worker entry includes AppRpc wrapper)packages/data(@workspace/data) — collections, auth helpers, DB wiringpackages/db(workspace copy /@brilliant/dbpatterns) — document store over SQL
Adapters: published Worker → D1 binding; draft/preview → HTTP adapter through conductor /db/exec (PlatformData hop); tests → Bun sqlite; template demos → HttpDatabaseAdapter → services/demo-data (no D1).
Template seed fixes require image rebuild + gradual rollout. AppRpc procedures: register under apps/web/src/rpc/; workflows call via codemode app connector. Seed wiki module: docs/wiki/modules/template-apprpc.md.
Shareable templates (#345, merged)
Status: Merged 2026-10-04 by yoni-monday — waves 1–2 of #310 / #311. Plan: docs/plans/templates.md. Verified live on side env templates. Wave 3 demos landed stacked as #358 — see Template demos.
A template is a shareable, installable snapshot of a published workspace. Chat history and real app data are never copied. Installs detach (source_template_version_id is provenance only — no update propagation).
What landed
| Concern | Behaviour |
|---|---|
| Share | Workspace creator only (same rule as delete); since #442 the studio also requires the caller's known builder membership before the creator check (backend stays authoritative). App menu → “Share as template…” → prepare dialog (title, description, sample-data choice, visibility) → closes on confirm → version panel. The full link is held in tab memory until reload (#442). |
| Version | Snapshots last published commit (deployments.commit_sha). Immutable versions; the share link always serves the latest ready one. “Update” = publish a new version. |
| Archive | Conductor git archive + secret scan (gitleaks); refuse on hit (422 secret_found). Stored under templates/<id>/<version>.tar.gz in BLOBS (outside w/<ws>/ so teardown keeps archives). |
| Install | New draft workspace from the archive (not /opt/template); optional sample data (declarative fixture, owners rewritten to installer; generated from the frozen schema since #442); TEMPLATE.md brief for the coding agent; no chat history. |
| Visibility | tenant | link (listed reserved). Link = /t/<slug>#k=<key>: slug alone → public preview + OG; fragment key (SHA-256 stored) gates Try/Install. Cross-tenant install lands in the caller’s tenant. |
| Policy | tenants.settings.templates.allowLinkSharing (default on). Off → hide link in picker, downgrade every link template to tenant, delete KV projections, audit. Staff suspending the tenant also stops its link templates from spreading (see Suspended tenants, merged PR #462). |
| Public page | apps/template-share (SSR, strict CSP): /t/<slug> with OpenGraph + 1200×630 card per version. Control plane forwards /t/* over TEMPLATE_SHARE service binding. Removed → 410; unknown → generic page. |
| LLM draft | Pitch/description drafted for the prepare dialog (never quotes the chat); owner edits before publish. Bounded wait with manual fallback since #442. |
| Publish pipeline | Cloudflare Workflow TemplatePublishWorkflow in the control plane: archive → demo bundle → OG → mark ready / project KV. Failure leaves the previous ready version serving. |
| Contracts | @brilliant/service-contracts — Effect Schema for every cross-worker shape (formerly required by root CONTRACTS, removed in #592); identity / app-policy / data / BI shapes migrated from capabilities behind zod-parity tests. New template code is Effect end to end. |
Architecture pieces
| Piece | Path | Role |
|---|---|---|
| Domain + API | apps/control-plane/src/templates/ | Effect services (TemplateRepo, share/link, install, Workflow); Hono routes; MCP template tools |
| Studio UI | apps/control-plane/web/…/templates/ | Prepare dialog (SampleDataChoice), version panel, ShareLinkSection (replaced LinkReveal in #442), background template-jobs + TemplateNotices, share-eligibility, /install/:slug (re-resolves on pasted keyed URLs and org changes in #486, merged) |
| Public SSR | apps/template-share | Landing + OG; reads KV ShareRecord + BLOBS og keys only (no Postgres) |
| Conductor | services/conductor/src/templates/ | Archive (+ archive-reuse), secret-scan, sample generation (sample-generation, collection-schemas, schema-grammar, schema-rules), seed-from-tarball init, sample-data load, demo bundle, OG capture, LLM draft |
| Wire shapes | packages/service-contracts (./templates, ./demo, …) | Cross-worker Effect Schema |
| Demo host / data | services/dispatch + services/demo-data | Template demos |
| Infra | infra/pulumi (cloudflare-template.ts, demo.ts) | Bindings, demos namespace, Turnstile, demo origin |
Deploy order: deploy.yml deploys template-share before the control plane (service binding must exist). Full demo stack order: Template demos — Infra & rollout.
Gotchas (from #345)
- Effect on the conductor static graph can trip “Script startup exceeded CPU time limit” —
capabilitiesloads identity Schemas lazily; plain constants live in Effect-free subpaths (bundle-lazy-import.test.ts). - Dispatch minify: Effect Schema grew the bundle; minify keeps gzip size in check.
markReadydates as ISO text: postgres.js rejects a JSDateinside a rawsqlfragment (in-memory unit tests passed; live versions failed). Ingotchas/.- OG card never opens the published URL — a members-only app would render studio sign-in to an anonymous browser; capture uses a fresh sample-data demo session instead.
Follow-ups (not in #345)
Wave 3 demos closed via #358 / #312. Still open at merge: #319 side-env image reuse, #323 remaining shape migration, #325 template-share /health + prod bucket, #326 builder assets in archives, #327 owner-leaves-tenant downgrade, #328 side-env screenshot 502, #335 tenant picker on install.
Community templates (feature-flagged, Daily 2026-11-02)
Per the Brilliant Daily on 2026-11-02 (Slack #brilliant-ai meeting summary "Brilliant Daily, Nov 2, 2026" (ts 1793611281.823869)): community templates are behind a feature flag. A user submits a template, and an admin approves it before it shows. The flag was being turned on for our own account so the team can start creating community templates. The flag's key and the approval surface are not documented here yet.
Decision log: Product & growth decisions: community templates.
Template preparation and sharing fixes (#442, merged)
Status: Merged 2026-10-04 by yoni-monday. Closes #420, #421, #422, #424. Verified on side env templatesqa. No migration or new dependency; existing immutable versions, detached installs and hash-only keys are unchanged. Exact limits live in docs/plans/templates.md.
Description draft
- The draft wait is bounded (about a minute) across conductor, control plane and studio, and cancels the conductor call. Manual edits are preserved, and on any failure the owner gets retry or writes the summary by hand.
- The secret scan moved out of Prepare into the archive step.
- The originally reported stall was not reproduced (the draft returned 200 in about 6.7s); this is protection, not a diagnosis.
Sample data: generated, not chat-written
This supersedes the #345 design where the owner asked the chat agent to write seed/sample-data.json and republish. Chat is no longer involved, and the live workspace is never used as a generation job.
generateSampleData (create / publish-version) | Meaning |
|---|---|
true (Generate) | Conductor generates fake {collection: [docs]} from the frozen published snapshot only, inside the archive step. No builder turns, chat, source rows or source writes. Replaces any committed file. |
| omitted (Keep committed file) | Use the archive's own committed seed/sample-data.json if present; none means empty. Also what pre-#442 queued builds do. |
false (No data) | Leave out even a committed file. |
- Create defaults to Generate; update defaults to Generate when the latest ready version has samples, otherwise empty.
- The choice rides the Workflow payload into
TemplateArchiveRequest.generateSampleData, and the archive result now carrieshasSampleData. - Generation reads only collection names, index/search hints and structural schema rules (a bounded, string/comment-aware static reader, not a TypeScript parser or Zod execution). Supported: inline objects with strings, numbers, booleans, inline enums, literals, nested objects/arrays, optional/nullable/default, literal bounds, one string format (email, URL, UUID, ISO date/date-time).
- Refused before any model call with an actionable
sample_data_invalidissue: dynamic/composed schemas, unions/records, refinements/transforms (includingtrim), conflicting formats, format options, spreads, nonliteral bounds, package/default/namespace imports, unresolved/duplicate/circular names. Recovery: simplify the schema, keep the committed file, or choose No data. - Bounds: 20 collections, 1–8 docs per collection, 80 total, 4KB per doc, 48KB JSON; model budgets 25s each, 50s total. An unavailable model is a retryable 502, not an invalid-data refusal (#446 tracks better missing-model diagnostics).
Archive finalization and replay
- Generated archives are written to R2 with conditional writes (create-only if absent, else the observed ETag). An overlapping loser returns the validated winner's digest, never its own bytes; a missing or mismatched winner fails closed.
- A finalized generated archive is reused only for the exact template/version, commit and intent after digest, secret and sample validation, so a lost acknowledgement never regenerates fake rows (identical bytes, zero model calls on replay).
Studio flow and notices
- Confirming returns the new version at once (
{template, version, link?}); the modal closes and the studio follows that exact version id in the background with ready, failed or stalled notices that survive navigation. - Notification-open claims sit above the app menu so they survive the studio header's inline-to-portal remount, and bind to the exact workspace/app/session.
Share link and eligibility
- The full link (with its key) exists only in the create response, since the server stores just the hash. The studio keeps it in active tab memory: it survives close/navigation/reopen, is lost on reload, and is never put in web storage, cookies or logs.
- Copy and Reset are separate; Reset rotates the key and old links resolve 404. The UI explains reload loss and old-link invalidation.
- Unavailable sharing stays keyboard-reachable but inert, with accessible guidance. The studio requires known builder membership before creator/legacy-role checks; the backend remains authoritative (403).
Gotchas (from #442)
- Testing that a retry returns 200 does not prove replay: assert no second model call and identical archive bytes. Do not assume an HTTP timeout cancels remote execution.
- Playwright's default
waitFor()needs visibility and times out on an empty<ul>; usewaitFor({ state: "attached" }), then check a real interaction. - Radix menu keyboard focus is deferred: wait for focus to change after each key instead of a burst of ArrowDowns.
- Still open: #385 cold-thumbnail visual acceptance.
Suspended tenants stop sharing templates (#462, merged)
Status: Merged into main 2026-10-05 (opened by Brilliant Fixer, merged by yoni-monday), fixes #459. Unit-tested only (control-plane suite 1495 pass); not live-verified on a side env. The Drizzle isTenantSuspended query runs only against Postgres, so the unit suite does not cover it.
Problem: POST /admin/tenants/:id/suspend changed the tenant status and its apps' disabled flags but not its templates. Anyone holding a link could still install a suspended tenant's template into their own tenant, start an anonymous demo, and open its public /t/<slug> page.
| Piece | Behaviour |
|---|---|
tenantSharesLinks(tenantId) (templates/link.ts) | Link sharing is on and the tenant is not suspended (new TemplateRepo.isTenantSuspended). One repo call: a single select of settings + status. Replaces the bare getAllowLinkSharing check in templateByLink (resolve / install / demo start), stillShared, projectShare and the sweep's live-record reconcile. |
| Key check | A suspended tenant's template fails with the same TemplateNotFound (404, identical body) as an unknown slug, so suspension is not an oracle. No new live share record can be written for it. |
| Suspend route | setTenantTemplatesSuspended(…, true) (templates/runtime.ts) writes removed for each link template's share record and deletes its demo:<version> records: /t/<slug> goes away and running demo sessions end at their next request. |
| Resume route | setTenantTemplatesSuspended(…, false) republishes via projectShare. The demo record (republishDemoRecord) comes back only if stillShared still holds afterwards, so it stays down when the owner has left or link sharing is off. |
| Reversible | Template rows, link keys and demo scripts are kept, so resume restores the same links. |
| Best effort | Typed failures and defects are both caught and logged, so the staff route never 500s after the status has already changed. The key check is the hard gate, and the scheduled sweep withdraws any share record left behind. |
Contracts: link-key-check-no-oracle and share-record-events now cover suspension (a suspension's removed write happens after the status change, which already blocks new live writes). New tenant-suspend-withdraws-template-shares.
Known gap (not in #462, tracked in #466): a publish Workflow already running at suspension time can still write a demo:<version> record from demoStep. Nobody can start a session from it, since demo start goes through the key check, and resume would republish it anyway.
Related: session routes refuse suspended tenants too, see Control plane: Session routes recheck membership.
Template copy links, demo Install and install completion (#486, merged)
Status: Merged into main 2026-10-05 by yoni-monday (merge 780f6441, branch fix/template-copy-links). Browser acceptance passed on side env templatelinks (11 flows plus studio e2e-smoke); final head 6edbb107 passed full bun run verify and GitHub CI 47/47, and a live POST /templates/:id/install on templatelinks answered 201 after 16 s with the copy seeded (D1 id set, app draft). No new dependency, endpoint or migration. Server authorization, the suspended-tenant gate, archive/digest checks, detached installs and never copying source rows stay authoritative.
| Concern | Behaviour since #486 |
|---|---|
Copy link, organization (tenant) mode | The studio now offers Copy here too: the keyless /install/<slug> URL, with guidance that the installer must sign in, be in the same organization and hold a builder seat. |
Copy link, public (link) mode | Unchanged from #442: the keyed link lives in tab memory only and Reset is explicit. Copying never changes visibility or rotates the key. |
| Demo → Install | The template-share Try script now opens the demo URL with the same #k=<key> fragment, since the server never learns the key. The dispatch demo banner builds Install from the configured studio origin plus slug and keeps the full fragment, which survives same-origin client-router navigation and reload. With no key, the banner keeps a keyless link to /t/<slug> labelled "Install: full link needed" instead of a link that cannot work. |
| Pasting a keyed URL into an open install page | /install/:slug re-resolves on slug, fragment, signed-in user and organization changes. The key is kept out of query-cache identities, and an install continuation from a retired landing can no longer submit or redirect. |
| Seat guidance | Fails closed: a known user (non-builder) seat sees an accessible explanation and a disabled Install (the backend also answers 403). Public multi-organization selection still switches organization and installs in one click. |
| HTTP install waits for init | Both install routes (POST /templates/by-link/:slug/install, POST /templates/:id/install) now await the conductor init (frozen code, fresh D1, requested sample load) before answering 201. A detached waitUntil init was cancelled about 30 s after the response and could leave a draft app with a null d1_database_id and no samples. The route also registers the same init with executionCtx.waitUntil, so a client disconnect mid-await still leaves it the platform's ~30 s post-response grace (not durable for a longer init). Expected conductor failures mark the app init_failed and still answer 201, so the studio shows retry. If that outcome itself could not be recorded (an OpError), the route answers through opErrorResponse with 502 "Check the app list and try again" instead of a silent 201 or a generic 500 in Sentry; the 502 path is covered by fault-injection tests only. Contract template-install-http-waits-for-init; gotcha in gotchas/template-and-apps.md says not to move the await into the shared installer. |
| Not changed | Plain app creation and the MCP install_template tool keep a detached init, because the MCP result deadline is 20 s; install_template hands waitUntil init.catch(() => {}) so a failed init (already logged) is not an unhandled rejection. Long cold MCP init completion is tracked in #477. |
Key handling: new contracts share-key-leaves-page-as-fragment-only and share-key-fragment-only-handoff (dispatch banner): the template-share page never renders, logs or persists the key; it reads only a whole 22-character base64url #k= fragment, sends it to the control plane only in the demo POST body, and passes it on only as the fragment of the http(s) demo URL. Try and Install stay inert without a whole key. share-key-fragment-only-handoff also records that the demo app's own and third-party scripts can read the fragment key; that is accepted, and Reset (rotating the key) is the remediation.
Explicit limits: external OAuth provider exchange was not run live (fixture auth at the provider boundary). Private → public visibility needs a new published version to restore a revoked demo (#476). Authored hash routes, full-document navigation that drops the fragment, and already-open keyless demos cannot recover a forgotten key; their fallback is explicit.
Schemaless DB engine (packages/db)
ADR: docs/decisions/db.md.
- Schemaless collections over SQLite JSON (D1 / DO SQLite) — no structural migrations for agent-driven apps
- Zod schemas → types + validation; indexes / optional FTS
- Row rules as JSON AST, compiled into WHERE (identity from dispatch context)
- Control-plane Postgres remains human-migrated Drizzle (separate concern; templates tables in
0028_templates.sql)
Who can read / edit live app data
Studio Data tab and MCP data tools: builder-seat creator of the app, or org owner/admin (no recorded creator → owner/admin only). Details and refusal UX: Control plane & studio. Owner decision in #139 (merged).
Internal tables vs Data tab
User collections live as SQLite tables. Platform internals (_prisma_%, _drizzle_%, FTS side tables, and _brilliant_events outbox) are filtered out of the studio Data tab overview (#307). Details: Control plane — What the Data tab lists.
Template demos (Try it)
Shareable templates expose a 30-minute Try it demo on demo.<studio domain> (no D1; SQL via HttpDatabaseAdapter → services/demo-data). Landed in #358 on the templates stack (merged to main with #345). Details: Template demos.
Related
Stable TanStack Start 1.169 pins (#917, merged)
PR #917 (merged 2026-10-14 12:44 IDT by yoni-monday, merge b42f18a5, branch yonibr/upgrade-tanstack-dz5j2) moves the app template and the marketing site from the pre-stable Start line onto stable TanStack Start 1.169. Landed on main.
1.169 is the stable cut of the release the tree was already on (react-start@1.168.49 / react-router@1.170.32). Start 1.169.1 depends on exact react-router@1.170.44, so that pin moves with it.
| Package | Before | With #917 |
|---|---|---|
@tanstack/react-start | 1.168.49 | 1.169.1 |
@tanstack/react-router | 1.170.32 | 1.170.44 |
Four manifests get the pins (lockfile follows):
packages/template/package.jsonpackages/template/apps/web/package.jsonpackages/template/packages/runtime/package.jsonapps/site/package.json
Unchanged:
- Studio and admin stay on the SPA router range (
^1.114) and resolve this same copy. router-clistays1.167.33.- No call-site changes: the tree does not use
.inputValidator(), TanStackuseSession,setResponseStatus,setResponseHeader,sendContext, ortransferResponseBodyOwnership.getRequestHeaderstill uses??inmembers.ts(an emptyx-brilliant-contextis not a JWT).
Rollout:
- Draft apps pick up the new conductor image on the next container start.
- Already published apps keep their bundle until republish.
- Blast radius is the next conductor image (template package manifests are image inputs) and the marketing site worker. Revert is the four pins plus the lockfile.
Lockfile side effects (not extra intentional bumps): @tanstack/react-store 0.9.3 → 0.11.2 (router peer); template @types/bun "latest" 1.4.2 → 1.4.3; @tanstack/start-server-core resolves to 1.169.42 (was 1.169.31), past the GHSA-qx66-fv34-fjm8 fix.
Evidence (PR): template and site tests/builds clean locally; side env ts169 smoked (session, home, turn, code tab, publish). preview_components_budget still fails on the template home SVG wireframe (no header/h1) — that is the scaffold, not Start. The PR was behind #913 (smoke harness Skip on the clarify card); the PR turn needed that click from a local edit not in the diff.