Talyn is a desktop "mission control" app for GitHub PR management, powered by cloud coding agents. It tracks your open/review-requested PRs in a prioritized GitHub panel, and delegates fix/respond/review work to cloud providers that run the agent loop on their own sandbox and open a PR. Talyn Fleet (selfhosted) is the default — Firecracker microVMs on our own hardware, running the workspace's own Claude or Codex subscription. PostHog Code is retired: hidden for everyone, existing connections keep working, and nothing falls back onto it. Codex Cloud is deferred; Claude Code was removed.
As of the cloud-only refactor (June 2026) the app no longer runs anything locally: the bundled daemon, local/remote environments, in-process Claude agents, permission gates, backlog/continuous-build, and the per-task git working tree are all gone. Every task is a cloud task. See docs/CLOUD_PROVIDERS.md.
Target user: engineers who live in GitHub PRs and want to hand routine PR work to cloud agents.
Three front ends: apps/desktop, apps/web and apps/mobile. A new feature, a changed behaviour or a user-visible fix lands in all three in the same change. Mobile is not optional. The rules and the web-only exceptions are in Mobile client — keep it in step.
Repository: git@github.com:Gilbert09/talyn.git (main branch)
After completing each task: stage relevant files, commit with a descriptive message, push to main. No branches or PRs for Talyn itself. Keep commits focused and atomic.
Commit authorship: commits should be authored by Tom directly. Do NOT append Co-Authored-By: Claude … trailers or any other AI-attribution lines to commit messages in this repo.
Every push to main deploys — treat a push as a production release. All deploy/publish workflows are fork-guarded with if: github.repository == 'Gilbert09/talyn' (these guards compare against the CURRENT repo name; update them if the repo is ever renamed, in the same push, or deploys silently skip).
-
test.yml— every push + PR. 3-OS matrix (macOS/Windows/Ubuntu): full builds →typecheck→lint→npm test. The only gate — nothing blocks a deploy on it, so don't push red. -
deploy-backend.yml— push to main touchingpackages/backend|shared,Dockerfile,railway.toml(+workflow_dispatch). Deploys to Railway via CLI token; cutover is health-gated (/healthdoes a real DB check and 503s while draining), so a boot-refusing build keeps the old one serving. NOTE: every deploy briefly overlaps old+new instances — the pg advisory locks (services/advisoryLock.ts) exist for exactly that window. -
deploy-marketing.yml— push to main touchingapps/marketing/**. Lint + typecheck gate, then Vercel prebuilt deploy to www.talyn.dev. -
publish.yml— the stable release, cut every six hours and on demand. The scheduled run is skipped when main has not moved since the latest stable release (/releases/latest+ the compare API, so a run the cron misses is caught up by the next one). On demand: Actions → Publish → "Run workflow" (version input optional; empty auto-picks the next patch, and electron-builder creates the release AND the tag, so no local git needed) or push avX.Y.Ztag. Builds macOS arm64+x64 (signed + notarized), Windows NSIS, and Linux AppImage, publishing a full release, which is what the updater and the talyn.dev download button follow. The tag/input is the single source of truth for the app version (baked intorelease/app/package.jsonat build time, never committed). Aconcurrencygroup queues a manual dispatch behind a scheduled run: theversionjob reads the release list at run time, so two runs in flight would stamp the same version. (nightly.yml, which shipped arm64-only pre-releases on the same cron to nightly-channel users only, was folded into this in Session 96.)Job shape: a
versionjob resolves the version ONCE and fans it out (three legs each computing "next patch above the latest release" would race), then the macOS leg runs alone — it's what creates the GitHub Release (and the tag, on the schedule and dispatch paths) — and only then does awindows-latest/ubuntu-latestmatrix upload into it. Keep that ordering: parallelising all three races three electron-builder processes to create the same release, and chaining means a Windows/Linux failure can't take down a macOS release that already published. The macOS leg publishes a DRAFT (EP_DRAFT) and a last step makes it public, so a leg that fails part-way leaves nothing the updater or the download button can see. On 2026-10-12 a 504 on one Electron download left v0.3.20 as "Latest" with only the arm64 zip. Each leg also downloads its Electron zips first with retries (scripts/prefetch-electron.mjs, then-c.electronDist), because electron-builder does not retry. Windows ships unsigned until an EV cert is bought (SmartScreen warns on first install); settingCSC_LINK/CSC_KEY_PASSWORDfixes it with no workflow change.
Update channels: the desktop picker (Settings → About; persisted in userData via src/main/updateChannel.ts, default stable) maps to electron-updater's allowPrerelease. Since Session 96 nothing publishes a pre-release, so both channels receive the same stable build. The picker is kept so a pre-release track can come back without a client change; removing it (and the "every build as it lands" copy) is an open follow-up.
Do NOT run a whole package suite locally. npm test in packages/backend is
~7 minutes — many suites spin up a real pglite Postgres per file — and running it
after every edit is most of the loop spent waiting. Run what covers the change:
- Backend (
packages/backend, Vitest):npx vitest run <path/to/file.test.ts>for the specific file(s); add paths or a glob (npx vitest run src/__tests__/prMonitor*) when a change spans related suites;-t "<name>"for a singledescribe/it. - Desktop (
apps/desktop, Jest):npx jest <pattern>. - Web (
apps/web, Vitest):npx vitest run <pattern>. - Mobile (
apps/mobile, Jest):cd apps/mobile && npx jest --runInBand <pattern>; typecheck withnpm run typecheck -w @talyn/mobile(it regenerates typed routes first).
Pick by what the change can plausibly break, not by habit — and this holds for a
cross-cutting edit too. Touching packages/shared, a widely-imported helper or a
migration is a reason to run more of the relevant suites, not to run everything:
a schema change means the suites that read those tables, not prMonitor's.
The full suite is CI's job. test.yml runs typecheck → lint → npm test
across macOS, Windows and Ubuntu on every push and PR — broader than a local run
and three platforms wider. Push and let it do that.
It is a BACKSTOP, not a fast feedback loop: that matrix takes about 90 minutes, so it tells you about a break long after you have moved on, and (see below) after the backend has already deployed. Local typecheck + lint is what actually protects the change; CI is what catches what they cannot.
What to always run locally, because it is seconds and catches most breakage before it leaves the machine:
tsc --noEmit # in the package(s) you touched
eslint <changed files>
The consequence to respect: nothing blocks a deploy on test.yml — a push to
main deploys the backend whether or not the suite has finished, let alone passed.
Combined with the ~90-minute matrix, that means a red test is discovered roughly
an hour and a half after the code it breaks is already serving traffic. So delegating
the suite to CI is not the same as not caring about it: watch the run you
triggered, and if it goes red, fixing it is immediate work rather than something
to pick up later. And when a change is risky in a way typecheck and lint cannot
see — a migration, an auth path, anything in the webhook worker — run the suites
around it locally BEFORE pushing. An hour and a half of a broken backend is worse than
two minutes of waiting.
See docs/TESTING.md for the broader strategy.
docs/ARCHITECTURE.md— system diagram, tech stack, core concept details, key decisions, resolved questionsdocs/ROADMAP.md— full phased TODO (Phase 1–20), backlog, known gaps, full priority queuedocs/SESSIONS.md— chronological session notesdocs/CLOUD_PROVIDERS.md— the cloud task provider abstraction (registry, per-provider modules, roadmap)docs/QUALITY_PARITY.md— desktop polish/parity assessment vs Conductor; what's done + prioritized backlog (feed perf, PR diffs/merge, composer, tests)docs/INCREMENTAL_CHECK_COUNTS.md— webhook-driven incremental check counting designdocs/REVIEW_RANKING.md— what the offline experiment found about the Reviews tab's ordering: the shipped model is worth ~+23 points of top-3 once fitted, but a plain newest-first sort is within 1.5 points of the best model found, and recency is provably near its ceilingdocs/MCP_SERVER.md— the hosted MCP server (/api/v1/mcp): tools, auth, what is deliberately not exposeddocs/SETUP.md— env vars / account setupdocs/TESTING.md— testing strategy + coverage
When a session lands non-trivial work, append a note to docs/SESSIONS.md. When a phase item changes status, update docs/ROADMAP.md. When a decision is revisited, update docs/ARCHITECTURE.md.
Keep the session log out of this file. A note in docs/SESSIONS.md is the record; this file carries only what is still true and still load-bearing — Core Concepts, the conventions above. It used to hold a summary of every recent session as well, which grew to 57% of the file: a strictly worse copy of the same notes, always behind, and loaded into every session's context whether or not it was relevant.
A change to the public API, the MCP server or a feature that users see updates its docs in the same pull request. The website pages in apps/marketing/content/docs/ are written by hand. No test catches a page that is out of date, so the author of the change must do it.
- Public API (
packages/backend/src/routes/public/) → runnpm run openapi:generate -w @talyn/backendand commitdocs/api/openapi.json. Then updatedocs/api/*.md, the scopes and overview inapps/marketing/content/docs/api.md, and the endpoint inapps/marketing/content/docs/api-reference.md. Every endpoint inopenapi.jsonmust have an entry inapi-reference.md. - MCP tools (
packages/backend/src/mcp/tools/) → update the tool table indocs/MCP_SERVER.mdand the areas inapps/marketing/content/docs/mcp.md. If a sandbox skill inpackages/backend/src/services/workbenches/skillPack/, a local skill inapps/desktop/src/main/localSkillPack.tsor the briefing inpackages/shared/src/talynBriefing.tsnames the tool, update it too. - Other user-facing behaviour → update the matching page in
apps/marketing/content/docs/. The same change updatesapps/mobile(see Mobile client — keep it in step). A new page also needs an entry inDOCS_NAVinapps/marketing/lib/docs.ts.
- Workspace — groups related repos + integrations (e.g., "PostHog" =
posthog/posthog+posthog/posthog.com+posthog/charts). Every owner always has at least one:services/workspaceBootstrap.tsmints aDEFAULT_WORKSPACE_NAMEone onGET /workspaces(the call every client makes on boot), advisory-locked per owner so concurrent first-loads cannot double-insert. Onboarding therefore opens on Connect GitHub, not on naming a workspace. Consequence to respect: a workspace existing no longer means the user is set up — both front ends readWorkspace.integrations.githubto decide "already onboarded", because keying offworkspaces.length > 0would skip the wizard (and its required GitHub step) for every new user. See Session 106 indocs/SESSIONS.md. - Cloud provider — a vendor that runs the whole agent loop on its own sandbox and opens a PR. Pluggable behind
CloudTaskProvider(packages/backend/src/services/cloudProviders/): a registry + per-providerdispatch/reconcile/credentials. Talyn Fleet (selfhosted) headsCLOUD_PROVIDER_ORDER, PostHog Code is retired (see below), Codex Cloud is deferred (no server-to-server API), and Claude Code was removed (metered API credits only — the fleet runs Claude on the user's own subscription instead). Seedocs/CLOUD_PROVIDERS.md.- PostHog Code is retired, step 1 of 2. The
posthogCodeRetiredflag (posthog-code-retired, break glassPOSTHOG_CODE_RETIRED) has fallback ON, so a PostHog outage or an absent flag keeps it hidden. With it on: a workspace with no PostHog Code row never sees it and its connect routes answer 410posthog_code_retired. The resolver keeps it only as the chosen default or the only connected provider. Neither the code review spill nor quota failover moves work onto it. An existing connection keeps working and shows a move-to-Claude-or-Codex notice. Afalseanswer in PostHog brings it back for one account. The code stays until step 2 deletes it (seedocs/ROADMAP.md). - The fleet is one provider with TWO agents, and the model carries the vendor:
fleetProviderForModelreads the model id, and the fleet builds the microVM's egress route table from it, so a Codex run has no route toapi.anthropic.comat all. Picking an agent per task is picking a model — a second field would be a second source of truth that can disagree. - A task links the PR its run OPENED, and that is a structured field, never a search. PostHog Code answers it with
output.pr_url; the fleet withsandbox.prUrl. The poller used toJSON.stringifythe run and the remote task record and take the first PR URL in it — but both carry text ABOUT other people's PRs (the user's prompt, the agent's closing prose), so a "Daily PR" loop filed its runs against a PR the user had opened the day before and already merged.run.branchis not a substitute: a run that pushed nothing reportsmain. No scrape fallback — a missing link is visibly nothing, a wrong one reads as fact. See Session 126 indocs/SESSIONS.md. - A dispatch always sends the workspace's own key for the vendor it runs, and suppresses the other with
policy.credentials. The gateway fills an absent or blank key from its tenant's sealed custody, so?? ''was a silent route to spending someone else's subscription; no credential is a refusal.cloudTask.extra.llmrecords the vendor, andpoller.recredential+resolveRunCredentialsmust both read it — they used to send the Claude key unconditionally. - The Claude sign-in authorizes at
claude.com/cai/oauth/authorize, NOTplatform.claude.com. Anthropic runs two authorize endpoints behind one client id: theplatformone connects an Anthropic organization (metered credits,org:create_api_key) and has no subscription to give away; thecaione connects a Claude Pro/Max subscription, which is the point of the fleet. Only the authorize host differs — the token URL and the manual redirect are shared. Claude Code chooses on one question,scopes.includes('user:inference'), so the scope list is an input to flow selection and not merely a permission request: send its claude.ai set verbatim and do not trim it on a theory about what a sandbox needs. The failure mode is patient and expensive — the exchange succeeds, Settings says "connected", and every run 403s hours later — soexchangeCodeandperformRefreshboth read the grantedscopeand refuse a grant that cannot run a model, which is what turns it into a connect-time error a person can act on. An ABSENTscopepasses (RFC 6749 §5.1 omits it when the grant matches the request). The authorize leg stores its PKCE verifier throughpatchSelfHostedConfig, which UPSERTS. It used to return silently when the workspace had noselfhostedintegration row — the normal state for a new user, and for anyone who has disconnected, since disconnect DELETES the row — so the sign-in answered 200 with a good authorize URL, wrote nothing, and then reported a completed sign-in as one it had never started. The lesson generalises past this flow:if (!row) returnon a WRITE path reads as caution and is an assertion that no caller ever needs it to create the row. That was true when it was written and false the moment the OAuth flow was added, with nothing anywhere to notice. A revoked grant is RECORDED, not just reported: both refresh paths writereauthRequiredAton an explicit vendor rejection (never on a transient failure), which is what stops every later dispatch re-attempting a dead refresh token and what makesfleetAgentStatusreport "Reconnect needed". It was read in four places and written in none for months — both agents had tests, and they called the writer DIRECTLY, so they proved the seam existed and nothing about whether anything called it. RelatedlyhasCredentialsanswers from STORED CONFIG and never by asking a vendor: it is whatGET /cloud-providerscalls per provider, so a throw there 500s the listing that draws the Settings cards, the default-agent menu and the agent picker — a dead grant used to blank the one screen with the fix on it. See Sessions 135, 138 and 139 indocs/SESSIONS.md. - Two separate gates, and only one of them is a flag.
FLEET_ENABLEDstays an env var read once at boot — it says whether this DEPLOYMENT has fleet hardware to talk to, and no flag can conjure a machine. The AUDIENCE is thetalyn-fleetPostHog flag, evaluated against the workspace owner, fallback OFF — released to every workspace on 2026-09-16, so the flag is now a kill switch and a lever for taking the hardware away from one account rather than an allow-list. A workspace outside the audience has the fleet dropped from its chain and lands on PostHog Code, exactly as before.
- PostHog Code is retired, step 1 of 2. The
- Environment — now just a secret-free marker, one auto-provisioned row per connected cloud provider. Its
type(aCloudProviderType) is how a task resolves its provider; per-workspace credentials live on theintegrationsrow. No daemon, no pairing. PostHog Code's row carries EITHER an encrypted personal API key or an encrypted OAuth token pair, decided byconfig.authMethod(absent = key), and everything downstream reads onegetToken()fromposthogCode/credentials.tsrather than branching — see Session 81. - Task — the unit of work, always delegated to a cloud provider. Types:
code_writing(freeform prompt on a repo),pr_response,pr_review. Lifecycle:queued→in_progress→completed/failed/needs_human. The cloud poller (cloudProviders/poller.ts) drives status + ingests the transcript; review happens on the provider's PR (no localawaiting_reviewgate).needs_humanis a REFUSAL, not a failure, and the difference is expensive. A run that stops because only a person can proceed (a merge gate repo policy says a human must approve, a credential the sandbox lacks, a product decision) lands here with the agent's own words inTaskResult.needsHuman.reason. It records asfailedif you forget, which is indistinguishable from a crash, which is why the auto-keep watcher spent four ~14-minute runs on one Visual-Review-gated PR. The reason deliberately does not go inresult.error— that is the field the admin console renders in its red failure banner.- Neither provider reports it, so the AGENT emits it.
TALYN_NEEDS_HUMAN:(prMergeable.ts) on the last line of its final message, read back byparseNeedsHumanSentinel. Exact prefix, last non-empty line only — an agent discussing the sentinel must not trip it, the same restraint that stopsfindPullRequestUrlregexing prose. Absence means UNKNOWN, never needs_human and never success: the prompt template is workspace-overridable, so a fork that drops the instruction must degrade to the old behaviour. Parsed on every terminal path —error_message(the path the real incident took),output.final_message, the idle-finalize log tail (chunks rejoined in order, because a streamed message splits the sentinel line), and the fleet's error string + transcript tail. - Adding a
TaskStatusmember starts atTASK_STATUS_TERMINAL, aRecord<TaskStatus, boolean>inpackages/shared. Every active/terminal list derives from it, so the compiler routes you to the consumers. Before it existed there were eight hand-written copies, all barestring[]; the nastiest is the front-end stores, where a status in neither set is fetched by neither query and is simply invisible.tasks.statusis plaintextwith no enum or CHECK, so a new value needs no migration. - A terminal task is REUSABLE (
taskCreate.tsREUSABLE_STATUSES≡TERMINAL_TASK_STATUSES) —needs_humanincluded. The next dispatch at that PR rewrites the row in place; excluding it would insert a duplicate and strand a stale row on the PR forever. The durable record of a stand-down is on the PR, the queue's event log and the notification — never the task row. - Both retry loops stand down on it, and neither spends an attempt. The auto-keep watcher (
prAutoMergeWatcher.ts) now reads the task row in its accounting — it used to infer the outcome purely fromprNeedsFollowup(lastSummary)and never looked at the task at all, which is the actual root cause of the four runs. It re-arms whenmergeableBlockerSignaturechanges (the merge queue's "progress, not retries" test, lifted to shared byte-identically so storedseenSignaturesstay comparable), and fires a one-shotauto_keep:needs_human— deliberately notmerge_queue:blocked, because nothing was given up on. The queue parks onblockedCode: 'agent_needs_human', distinct fromawaiting_human_check(ours, from a live Visual Review reading) because this one is the agent's verdict on a gate we cannot see. The queue's park must END the decision walk: the signature it records is in the transition'sset, not yet ond.entry, so the blocked gate would release the entry on the very pass that parked it. See Session 132 indocs/SESSIONS.md.
- Workflow — Now an integration rule: GitHub and Slack source adapters in
services/workflows/sources/feed one engine, and theintegrationcolumn picks the source. PostHog Inbox (posthog_inbox,posthogInboxRulesflag) has its own PostHog connection (theposthog_inboxintegrations row, not a cloud provider;getPostHogInboxConnectionis the one entry point and falls back to a PostHog Code grant withinbox:read). It is polled, and PostHog can also push through a webhook destination (inbound kindposthog_inbox, a "nudge" adapter): every report goes throughingestPostHogReport(connection, reportId), which reads the report from PostHog by id, so a pushed payload never decides an action. While pushes arrive, the poll is a 30-minute reconcile. Talyn can create that destination itself ("Set up push in PostHog",services/posthogInbox/pushSetup.ts, PostHog's hog functions API, scopeshog_function:read/write); its id is on the URL row (migration 0140), and rotate, remove and disconnect keep it in step. Slack channel rules sit behind theslackChannelRulesflag. The Automations page is gone; rules live on/integrations/:kind. user-defined PR automation, released to every workspace. Its audience is theworkflowsPostHog flag (fallback ON);WORKFLOWS_ENABLED=falseis the break-glass override that wins over it. Anything but an explicitfalse/0/off/noreads as on, so a typo turns it on rather than silently off.WORKFLOWS_ALLOWED_EMAILSis gone. A named, workspace-scoped rule: on these PR lifecycle events, matching these conditions, do these actions (labels, reviewers, assignees, a comment, a skill or prompt run, add to My PRs, add to the merge queue). Vocabulary + matcher + validator inpackages/shared/src/workflows.ts(theprFilters.tsargument, higher stakes — a workflow comments and merges); engine inpackages/backend/src/services/workflows/; tablesworkflows+workflow_runs(migration0052). Four things to respect:- It reads the webhook PAYLOAD, never a
pull_requestsrow, which is what lets it fire on every PR in a watched repo including untracked ones and other people's. Hooked intoprocessWebhookDeliveryABOVE theisRefreshEventgate (that predicate is about refreshes, a narrower question). Where a payload is short of a fact — anissue_commentdescribes an issue, so no base branch / head branch / draft; acheck_suite's PRs are{number, base, head}— facts carryunknownFields, a condition on one fails rather than passing, and the engine enriches from the row first (SQL accessors intolast_summary, never the blob). UNIQUE (workflow_id, delivery_id)is the concurrency design. The run row is inserted BEFORE any action runs; a conflict means a redelivery or another replica already owns it. No advisory lock. Settling is TWO writes — outcome first, then the task/PR links best-effort — because one combined UPDATE fails the FK when a linked row has gone and strands the run atrunning.- A rate-limited action is PARKED, not lost.
pending_retry+retry_after(migration0053) hold the instant the gate clears, andservices/workflows/retrySweep.tsre-runs only the actions that have not already succeeded — a run whose comment posted and whose label was gated must not comment twice. NOT an inline wait: these run in the webhook worker's six-wide slow lane and the gate is per ACCOUNT, so a burst from one org would block most of the lane on one wait.rate_gatedis the ONLY retryable code (it is the one failure that is transient AND says when it clears); the run'sfactsare stored because acommentaction interpolates branches the webhook payload no longer has. - Two loop guards, not a quota. Self-echo suppression (skip a delivery whose actor is Talyn's own App, on the events our actions produce — App only, never the connected user; and
pr_mergeddeliberately excluded) plusmax_runs_per_pr_per_hour(default 5) counted fromworkflow_runs, withskippedrows excluded from the count and the refusal announced once per window. - The merge action is the QUEUE, not
mergePullRequest. A direct merge 405s on a gated base. This is why the enqueue path moved out ofroutes/pullRequests.tsintoservices/mergeQueue/membership.ts(per-PRapplyQueueMembershipvs per-callsetQueueMembership).local:skills are refused at save time — the backend cannot read~/.claude/skills.GET /features→{ workflows }decides only what to DRAW; every route, the engine and the task actions gate independently. See Session 117 indocs/SESSIONS.md.
- It reads the webhook PAYLOAD, never a
- Feature flag — PostHog owns every audience. The register is
packages/shared/src/featureFlags.ts(key, PostHog key, break-glass env var, per-flag fallback); the backend reads it throughservices/featureFlags.ts. Never gate onprocess.envat a call site — that reimplements the precedence per gate. Five things to respect:- Precedence is env override → PostHog → the flag's own
fallback. The override short-circuits rather than outvotes, because break glass has to work when PostHog is the broken thing. fallbackis PER FLAG and the two live ones are OPPOSITE.workflowsfails OPEN (a released feature must survive an outage),fleetfails CLOSED (an outage must not open hardware we own to everybody). A shared default silently flips whichever it does not describe. PostHog answeringundefined— a flag nobody created, or one somebody deleted — is the fallback too, NOTfalse.- The distinct id is the Supabase user id, matching
analytics.ts, so a person targeted in PostHog is the same person in their own funnels. Email is passed as a person property, which is what lets a release condition do the literal jobFLEET_ALLOWED_EMAILSused to. - Which subject depends on the flag. Routes ask about the caller; the engine, the poller and dispatch ask about the workspace owner — a webhook has no caller, and a gate that passes when it cannot identify one is not a gate.
availabilitydecides what the release notes may say, and it is a SEPARATE field fromfallbackon purpose — one answers "who has this feature", the other "what do we say when PostHog is down". A flag marked'gated'withholds every "What's new" highlight tagged with it from EVERYBODY, including the accounts its PostHog audience has switched it on for; flipping it to'general'(or deleting the flag) is what announces the feature, and the withheld backlog replays to everyone who missed it. ItsreleaseScopesare the commit scopes the generator tags mechanically. This replaced a hand-written list of scopes inreleaseNotes.tsthat said['fleet']on the day Loops shipped — which is why Loops was announced to every user who could not open it. See Session 124 indocs/SESSIONS.md.workbenchesis released:availability: 'general', and its PostHog audience is everybody. Itsfallbackstaysfalse, because a session box is long-lived fleet hardware that bills box-hours.WORKBENCHES_ENABLEDis its break glass.- Set
TALYN_POSTHOG_PERSONAL_API_KEYin production. With it, flags evaluate in-process and a gate costs no network; without it every gate is an HTTP round trip (cached 30s here). The workflows gate runs once per delivery per watching workspace.GET /featuresdecides only what to DRAW — every route, the engine and the task actions gate independently. Seedocs/SETUP.md§ Feature flags.
- Precedence is env override → PostHog → the flag's own
- Loop — Now the Schedule integration (a "scheduled rule"; names and tables stay). user-defined recurring work, gated by the
loopsPostHog flag (fallback OFF — the opposite ofworkflows, which sits next to it in the nav;LOOPS_ENABLEDis the break glass both ways, andLOOPS_ENABLED=trueis how you run them locally with no PostHog project). A named, workspace-scoped rule: this prompt, on this repository, with this agent and model, on this cron schedule. Every firing starts a session on Talyn Fleet, so the transcript, the PR and the billing gate work unchanged — what Loops adds is the clock. Automations and MCP never create tasks (migration0144):target: 'task'is refused, rulesrun_promptandstart_taskare stored asstart_session, and the MCP toolstalyn_create_task,talyn_fix_pull_requestandtalyn_fix_code_review_findingsare gone. No plan caps how many loops an owner keeps; each firing goes through the box gate (see Billing). Vocabulary + schedule arithmetic + validator inpackages/shared/src/loops.ts(built on croner, this package's first runtime dependency, because DST is the one part nobody hand-rolls correctly); engine inpackages/backend/src/services/loops/; tablesloops+loop_runs(migration0054). Five things to respect:- The schedule is a COLUMN, not a timer.
loops.next_run_atholds the next occurrence and a 30s sweep reads the due rows through a partial index (WHERE enabled). AsetTimeoutper loop would be lost on every Railway deploy — which is every push to main — and double-fire during the old/new overlap. UNIQUE (loop_id, scheduled_for)is the concurrency design, the(workflow_id, delivery_id)trick again and stronger: a webhook delivery id is a token each replica must have received, while a scheduled instant is derived from the loop's own storednext_run_at, so two actors that both think a firing is owed cannot compute different keys. The consequence:next_run_atmust only ever hold an exact occurrence instant — never rounded, never "now".- The order is claim → dispatch → advance, and it is load-bearing. Advancing first turns any crash into a silently dropped firing (
next_run_atin the future, nothing re-selects the loop, the claimed run sitsqueuedforever). Dispatch-first turns a crash into an ordinary retry through the due-scan, made idempotent by the unique claim. The residual window costs one duplicate run, not a lost one. - Catch-up fires ONCE, then advances from
now. Replaying six missed occurrences is six near-identical tasks and, on a free plan, one run plus five refusals; skipping entirely lets a 30-second deploy eat the 09:00 daily run. Re-enabling a loop is resume, not backfill. Overlap is a per-loop setting (skipdefault, recorded in the history), which is what makes a tight cron self-limiting — hence no minimum-interval cap. - Internet access is a per-loop switch, off by default, and fleet-only. A loop's sandbox normally reaches its repository and its agent API through the credential proxy and has NO route anywhere else — which is what stops a prompt that has just read untrusted PR text from posting it out.
internetAccess(migration0055) is a per-loop switch that each firing passes to its session; the fleet executor turns it intopolicy.egress.mode: 'open'. The fleet deleted the old rule that coupled routed egress to dropping credentials — the proxy attaches them in every mode — and the one refusal that survived (a routed run whose GitHub token names no repository) cannot bite us, because every Talyn dispatch names a repo. No egress vocabulary reaches the user: the editor offers "Repository only" / "Allow the internet" and Talyn does the translation. PostHog Code has no equivalent, so the switch is hidden there AND refused by the route — the editor is a courtesy, the route is the gate. - A pinned provider is never failed over for a BROKEN credential — but it is for a SPENT one.
resolveCloudEnvChain's fall-back is right for "fix this PR somehow" and wrong for access that has been REVOKED: somebody who chose Talyn Fleet chose their own subscription and credential custody, so a fleet loop whose grant was withdrawn fails visibly rather than quietly spending metered PostHog credits on a problem only the user can fix. An exhausted quota is a different fact and Tom's call (2026-09-20) is to move it: the setup is correct, the month simply ran out, and the work is still wanted.services/cloudProviders/quotaFailover.tsre-dispatches such a run — the fleet's OTHER agent first (a subscription already paid for), then the rest of the chain, for unattended work too. With PostHog Code retired, the hop stops at the other fleet agent. It cannot just callresolveCloudEnvChain: that resolver thinks in PROVIDERS and the fleet is one provider with two agents, so deferring to it steps over a working Codex subscription on the way to a bill. Detection isselfHosted/exhaustedQuota.ts, pinned to the vendors' own "a human must top this up" sentences — a rate limit is deliberately NOT this, because it clears by waiting and moving off it spends money to avoid a short pause. The exhaustion is REMEMBERED, on the fleet integration row (quotaExhausted) and not in memory, which would die at the next deploy: dispatch reads it and either swaps agent or refuses ascapacity, so the next task never boots a microVM to learn the same thing. The reset is read, never invented —resetInstantFromparses the vendor's own instant and answers null when there is none, because a guessed reset is stored, believed, and silently keeps work off a subscription that came back hours ago; absent one, a five-hour re-probe (the vendors' published consumer window) lets the next ordinary dispatch find out. The hold is cleared by PROOF as well as time — a completed run on that agent, or a fresh sign-in — or it outlives its truth. Each hop is recorded on the task and never retried, and the note goes onmetadata.quotaFailover, NOTtasks.result— the detail panel paints anyresult.success === falsered whatever the status says, and a re-queued task has not failed. Likewise a task-limit hit is a visiblewaiting_slotrun retried until the next occurrence supersedes it — not a silent deferral, which is why the paywall reads as never firing elsewhere. Fleet agents reach the editor throughGET /cloud-providers(already filtered byworkspaceMayUseFleet), so the fleet parts sit behind the fleet flag for free, and the backend re-checks at save time and fire time.
- The schedule is a COLUMN, not a timer.
- Session background jobs and wake-ups are released to every account (decision 2026-11-08). An agent starts a job with
talyn_run_background. The durable supervisor runs the job after the turn ends. A 30 s sweep claims each due wake-up (WHERE status = 'scheduled'). It sends a queued message withorigin: 'talyn'and atrigger. The sweep execs into a box only while a job's keep-awake is on or a turn runs. Each exec keeps the box awake. A job on another sandbox id islost. See the 2026-11-08 note indocs/SESSIONS.md. - MCP server — a vendor's MCP server a workspace connects (Linear, Sentry, Supabase, its own), passed to allowed Talyn Fleet runs. Servers allow all repositories by default and can carry an exact repository allow-list (
mcp_servers.repository_ids, migration0120). Gated by themcp-serversPostHog flag (fallback OFF,availability: 'gated'— it is fleet-only, and it is the surface where somebody pastes a Stripe key, so failing open during a PostHog outage would offer credential storage to accounts nobody chose). It is the one flag with NO env override — Tom's call, its audience is PostHog's alone. So it cannot be run against a deployment with no PostHog project (whatLOOPS_ENABLED=trueis for), and there is no switch to reach for if PostHog is the broken thing; thefalsefallback is what answers then, which turns it off rather than on.readFlagOverridereturnsundefinedfor it always, andenvOverrideis optional onFeatureFlagDefinitionto say so in the type. Uncapped on every plan — unlike tasks, queued PRs, workflows and loops, a connected MCP server spends nothing until a run uses it, and what the run costs is bounded by the task cap already, so charging for the connection was charging twice. Vocabulary + validator + catalog inpackages/shared/src/mcpServers.ts; services inpackages/backend/src/services/mcpServers/; tablemcp_servers(migration0059). Five things to respect:- TALYN holds the credential, not the fleet, and that is the whole design's consequence. Servers go inline on
POST /v1/sandboxes, and the fleet seals an inline secret on arrival and persists it NOWHERE — so its own adoption path (which reads that tenant's stored servers) has nothing to serve for one. Without us re-supplying, a fleetd restart leaves a running box with its MCP routes and no credentials on them, and every tool call 401s for the rest of the run. Three paths must agree, through one sharedmcpIntegrationSecrets: the create body,poller.recredential's push, andrunCredentials' answer to a host pull. The LLM key already had this exact bug once. - The guest never sees a credential. It is configured with a plain
http://<name>.<integration-domain><path>carrying no token; the host's proxy attaches the secret per request. An agent that reads a hostile repo and decides to exfiltrate the Linear key has nothing to find.mcpServersForDispatchis the ONLY function that decrypts — keep it that way. toolsandrepository_idsare TRI-STATE and nothing may collapse them:null= all / inherit,[]= none, a list = exactly those. A restricted server is unavailable to repository-free threads. Reading[]as "all" is the worst available guess about somebody who ticked nothing, and it would make "run this with no tools" the one thing nobody could ask for. The fleet's/run/fleet/mcp.jsoncontract is at v2 for this reason — a v1 reader ignoringtoolswould run every tool on a restricted server, so an old contract is an error rather than a loose read. A loop cannot pick servers any more (mcp_server_idsmust be null); its session uses the workspace servers.- There is NO cap on servers per run or tools per server. YAS's were removed rather than worked around (8/16/32/32/16 — all round numbers). The per-server tool allow-list is the lever instead: same saving, made as a choice. The 64-character tool name STAYS — it is a hard provider limit, and an over-long one 400s the whole request rather than failing one call.
- Remote streamable HTTP only, and the URL rules are the fleet's own. Path required (but an explicit root is fine — Stripe really does serve at
https://mcp.stripe.com/), no userinfo, no query, no fragment, no private or loopback host, and the namegithubis refused because that is the sandbox's own REST API. The validator insharedMIRRORS every one so a user hears it while typing rather than as a dispatch that failed an hour later. OAuth servers connect throughservices/mcpServers/oauth.ts— CIMD first, DCR second (deprecated 2026-07-28), PKCE S256 mandatory, RFC 8707resourcealways sent, refresh advisory-locked and re-read inside the lock because rotation makes a refresh token single-use. When a DCR server refuses the hosted callback withinvalid_redirect_uri(pganalyze allowlists redirect URIs), the desktop app's loopbackhttp://127.0.0.1:<port>/callback(main/mcpOAuthLoopback.ts, port 47823 first) is registered instead and kept on the grant asredirectUri; the desktop forwardscode/stateto/mcp-servers/complete, the backend keeps the PKCE verifier, and web/mobile get a "connect it from the desktop app" error for such a grant. See Session 137 indocs/SESSIONS.md.
- TALYN holds the credential, not the fleet, and that is the whole design's consequence. Servers go inline on
- Code review — AI review of a pull request whose findings are shown in the app. Nothing reaches the PR as comments unless a person presses Post to PR and confirms (see the last point below). Released to every account. Its
code-reviewflag was removed on 2026-10-26;GET /featuresstill answerscodeReview: truebecause older desktop builds hide the feature without that key. Vocabulary + the findings parser + the dedupe key inpackages/shared/src/codeReview.ts; engine inpackages/backend/src/services/codeReview/; tablespr_code_reviews+pr_code_review_runs+pr_code_review_findings+pr_code_review_events(migration0068). Fourteen things to respect:- The units are NOT
tasksrows, and cannot be. Three guards make it impossible and all three are correct for tasks:activePrTaskIdrefuses a second active task on a PR (it exists because three concurrent runs once filled a plan cap),findReusableTaskcollapses to one row per(workspace, repo, PR, type)and REWRITES it, and the old task cap counted every task. So a review's lens units live in their own table, and each unit's box goes through the box gate (see Billing). The fix run IS an ordinarypr_responsetask, deliberately — that is what makes it inheritactivePrTaskId, so a review fix and a merge-queue fix share the one row a PR is allowed and cannot both push to the same branch. - Absence of output is a FAILED unit, never an empty one.
parseCodeReviewFindingsreturning!oksettles the unitunparseable. Inverting that turns a broken agent into a clean bill of health, which is the worst failure this product has available. The parser takes the first fenced block after the LAST sentinel line and never sweeps prose for JSON — thefindPullRequestUrlrestraint, for the same reason. - A partial phase still advances. Some lenses succeeded and others died → the review goes on with what it has, because refusing to show four good findings because a fifth agent timed out is worse than useless. A cycle only fails when a phase produced NOTHING. A dead sweep or judge degrades to "continuing with what the reviewers found".
- The dedupe key excludes the lens AND the line numbers. Two lenses reporting one problem is agreement — one row,
seenCount2, both lenses recorded — and duplicating it is the noisiest failure a multi-lens reviewer has. Line numbers move on every rebase, so the agent's verbatim anchor carries the position instead; a paraphrased anchor is detected at ingest and falls back tofile|title.dismissedis sticky across cycles (thereviewHiddenAtprecedent);fixedandstaleare not, so a key that reappears goes back toopenand the app can say "this came back". - Pacing is about the hardware, not the plan. Three live units per workspace, a fleet-capacity pre-check that is a DB read of the host registry (dialling per unit costs more than the occasional 503), a correction for our own dispatches too recent to appear in the host's ~15s report, and spill to the fall-back provider bounded at two units (no spill at all while PostHog Code is retired: the unit waits for the fleet) — that provider accepts no turn, spend or time cap at all, so unbounded spill converts a queueing problem into a billing one.
timeoutSecis sent (the first Talyn ever has);maxTurnsandmaxBudgetUsdare deliberately NOT, and cost per unit is recorded instead. The cycle gate keeps its advisory lock and the unit ceiling deliberately has none — losing the first race is a paywall bypass, losing the second costs one microVM the fleet refuses anyway. - The merge queue parks on
code_review_blocker, narrowly: blocker severity, confirmed by the judging pass, on a review of the current head, still open. A dismissal, a landed fix or a new commit clears it, and an absent context field means no blocker rather than unknown — a gate that parked on missing information would wedge every entry the first time an older replica built a context. - Depth means MODEL TIER, and the judging passes escalate on every preset. There is no reasoning-effort field on the fleet's create body and no effort variants in the catalogue, so this is the only thing depth CAN mean. The sweep reads every lens's output at once (the largest context the pipeline assembles) and the judge's job is to say no to something plausible, so both run at the top tier for the connected vendor; a preset whose plan says
effort: 'top'escalates its lenses too. Escalation happens AFTER the model ladder, never by pinning at the call site, so the credential-aware rung still picks the vendor — and an id not in the catalogue is returned UNCHANGED rather than resolved throughfleetProviderForModel, whose'anthropic'default is right for choosing a credential and wrong here: a retired OpenAI id would escalate across vendors into a microVM with no egress route to its own API. This was declared and not implemented for the feature's first week; all eight units of the first real review ran Sonnet. - The judge's verdict carries a SEVERITY and a REASON, and both used to be thrown away.
applyJudgementread only the keys of what survived, so a severity the judge corrected never landed and a rejection was recorded with no explanation — which made the pass that drops most candidates unauditable, and on the first real review it kept one of six. The reason is stored and shown;verdictReasonis the one big-ish column carried on the LIST projection (one capped sentence, and the alternative is a request per row for a list opened to skim). - A judge's keep is matched by the candidate ID, never by a key computed again from its answer. The judge is handed each candidate's dedupe key as its id and must send it back (
matchJudgeKeep). It used to be matched by hashing the file, title and anchor the judge returned, and the judge is never shown the candidate's anchor, so one changed word gave a new key, nothing matched, and every unmatched candidate was markedrejected. On 2026-10-07 a judge kept five of sixteen findings, a blocker among them, and the review recorded "Kept 0, dropped 16". The computed key is only the fallback now. A keep that still cannot be placed changes what silence means:applyJudgementthen rejects only the candidates the judge NAMED as dropped (onlyNamedDrops) and leaves the others unchecked and on screen, because one of them is the finding it kept. Relatedly, the prompt reads EVERY changed file (getAllPRFiles). The removed one-pagegetPRFilesreturned GitHub's default page of 30, so a 317-file pull request was reviewed as 25 files and no anchor outside them could verify. The cost is real and by design: units are lenses times parts of 25 files. - Auto-fix exists, is OFF, and is bounded by evidence. The design deliberately excluded it — every other guard here assumes a person chose the findings — and it was added on Tom's explicit ask.
findingsEligibleForAutoFixis the whole safety story: judge-CONFIRMED, at or above a severity floor defaulting to blockers, and withanchorVerifiedtrue. Each bound comes from the first real review, where the single finding that survived judging quoted code that was not at the line it named and was wrong. It still goes throughcreateCloudTask, soactivePrTaskIdand the task cap apply unchanged. - Lens names ARE user-facing, reversing the original "internal vocabulary the user must never see". That rule holds for CONFIGURING a review — a preset is one choice, not a panel of knobs — and not for reading one: cross-lens agreement is the strongest confidence signal the pipeline produces, and rendering it as "2 reviewers agreed" threw the signal away.
CODE_REVIEW_LENS_LABELSmaps the internal keys onto what a person reads. - The public payload rides
emitPullRequestUpdatedas an OPTIONAL field, and both forks merge it on explicit undefined, never??—??swallows the clear a force-push sends and leaves findings pinned to a commit that is gone. Every whole-row response goes throughpublicPrRow()inroutes/pullRequests.tsrather than spreading the decoration by hand, which is what the comment onmergeQueueForPrhad been asking for in prose. See the 2026-09-27 note indocs/SESSIONS.md. - A unit that FAILED is settled from the sandbox's own error, and a vendor limit moves it ONE hop.
reconcileFleetRunreadstaskOutcomeForSandboxand the sandbox error before it looks for a final message. It used to look only for the message, so a run the vendor refused settledunparseable("The agent produced no final message"), the vendor's sentence was thrown away, and a ChatGPT usage limit failed a whole review twice with a connected Claude idle (2026-10-07).unparseablenow means only "the run COMPLETED and the output did not parse"; a failed run isusage_limit,quota_exhaustedorrun_failed, with the sentence infailure_detail(migration0074). The move follows the task rules inquotaFailover.tsand shares itsnextHop: the workspace's OTHER fleet agent only, never PostHog Code, a hold written only for a confirmed exhaustion. Four things are specific to reviews. The limited agent comes from the MODEL the unit ran, not from the words: the text detector answers "claude" for a sentence that names no vendor, and the wrong name re-runs the unit on the limited agent. A unit moves at most once:requeueRunmatches only whilefailed_over_fromIS NULL, and therequeued → claimedupdate intakeRequeuedRunis the claim that stops two passes dispatching it. The second dispatch sends run idtalyn-rev-<id>-r1, because the fleet's create is idempotent on the id and would hand back the dead sandbox. The cycle's own run rows are the memory: a rate limit writes no workspace hold, solimitedAgentsInCyclereads them and the later lenses, the sweep and the judge dispatch on the other agent directly (avoidAgentsondispatchSandboxRun) and do not each boot a microVM to learn the same limit. When every reviewer stopped on a limit,cycleFailureMessagenames the agent, the vendor's own reset time when one is readable, and what to connect. - A team can add its OWN reviewers, and each one is a skill wrapped in Talyn's prompt.
settings.codeReview.customReviewersnames skills ({ skillKey, name }), andbuiltInReviewers: falseturns Talyn's lenses off. A repository skill runs on pull requests in ITS repository only; a Talyn skill runs on all of them;local:is refused. Five rules carry it. The skill is read from the repository's DEFAULT branch, never from the pull request: a pull request that could edit its ownSKILL.mdwould be writing the instructions of its own review. The wrapper is not optional:buildSkillLensPromptkeeps the untrusted-content preamble, fences the skill between two lines of tildes longer than any run of tildes inside it, tells the reviewer that publishing steps in the skill are out of scope, and putscodeReviewOutputContract()LAST, so the last sentinel in the prompt is ours. Structure cannot stop an agent that obeys a skill telling it to report nothing; only the wrapper's words stand against that. The skill and the inline diff share one byte budget (the argv limit behindMAX_INLINE_DIFF_BYTES): a skill over it fails its unit withskill_too_largeand is never truncated. A skill that cannot be loaded fails its unit (skill_unavailable) and never counts as "found nothing". The cycle's reviewers are FROZEN at start onpr_code_reviews.custom_reviewers(migration0075, keys and names only, never the skill text), and a start with no reviewer for that repository is refused (no_reviewers) before the plan gate, so it spends no free-plan cycle. The lens key isskill:<skillKey>, not a hash: two reviewers with one hash would share a unit claim and one would never run. - "Post to PR" is the ONE way findings reach GitHub, and it is a person's choice every time.
POST /pull-requests/:id/code-review/post(services/codeReview/postToPr.ts) writes one review, alwaysCOMMENT, from the user's own account. Four rules carry it. A finding goes inline only on evidence:anchorVerified, and every line inside the RIGHT side of the diff of the reviewed commit; everything else goes in the review body with its file and line. GitHub answers 422 for the WHOLE review when one comment points outside the diff, so a 422 is retried once with every finding in the body. A moved head means no inline comments at all, because the file listing then describes a different commit.posted_at(migration0073) is the idempotency: a posted finding is never posted again, and the column stays set when a later cycle re-opens the finding, because the comment is still on the PR. The select-post-mark sequence runs one at a time per review ON THE POOL (runWithoutScope): a mark written on the request's own transaction is invisible to the press that waits behind it. The queue is per process, so a deploy overlap can cost one duplicate review. A suggested fix is plain text, never a GitHubsuggestionblock: an applied suggestion replaces the commented lines exactly, and the agent's text is not a guaranteed replacement. Auto-posting does not exist and should not be added without the same evidence bounds as auto-fix.
- The units are NOT
- Public API —
/v1, served asapi.talyn.dev/v1, behind thepublic-apiPostHog flag (fallback OFF, evaluated against the TOKEN OWNER). Seedocs/PUBLIC_API.md. Four things to respect:- It is a separate mount, not a subset of
/api/v1. Personal access tokens (talyn_pat_, tableapi_tokens, migration0100) are the only credential: a Supabase JWT, an MCP token or a session token isinvalid_token. Bodies are snake_case with no envelope; errors are{ error: { type, code, message, param, request_id } }. It is mounted BEFOREcors()inindex.ts, so noAccess-Control-*header is ever sent. - A route exists only as a declaration (
definePublicRouteinroutes/public/), with a scope and zod schemas. The router mounts the declarations anddocs/api/openapi.jsonis generated from them;openapi.contract.test.tsfails when they disagree. After a change, runnpm run openapi:generate -w @talyn/backendand commit the file. - Rows leave only through
services/public/projections.ts. Each projection selects explicit columns and reads jsonb as one key in SQL, so nodevice_id,local_path,sandbox_idor fleet key can leave by mistake. A new field is added there, with its test. - Handlers call the apps' services (
createWorkbench,archiveWorkbench,sendMessage), so plan limits and readiness behave the same. The session plan gate is the usage-billing box gate (assertNewWorkbenchBox, called inservices/workbenches/create.ts); its refusals are 402s that carry their notice in snake_case. Local sessions are read-only (409local_runtime).
- It is a separate mount, not a subset of
- Operator console —
apps/adminat admin.talyn.dev. Cross-tenant by definition; gated byusers.is_admin+requireAdmin, which is the whole permission model. Its API is/api/v1/admin(pre-ownerScope). Every mutation requires a reason and writes toadmin_audit_log. - Billing — usage billing: a plan buys box-hours, and every fleet box that runs spends them. The model runs on the user's own subscription, so compute is the only cost Talyn bills. Tiers (
PLAN_LIMITSandPLAN_PRICESinpackages/shared/src/pricing.ts, the one place for the numbers): Free $0, 10 box-hours a month, 2 boxes at a time, sizessmallandstandardonly, no credits, no auto features. Pro $40/mo or $400/yr, 200 box-hours. Max $100/mo, monthly only (Tom's call; annual Max is a 400monthly_only, and Pro annual → Max goes through the portal), 1,000 box-hours, offered to every account oncePOLAR_PRODUCT_ID_MAX_MONTHLYis set (no feature flag, Tom's call); the backend then addsmaxMonthlyMicrostoBillingStatus.pricing, and a client offers Max exactly when it is there. A subscriber's tier comes from their product id. Teams do not sell Max (TeamTierexcludes it). Legacy Pro $15/mo or $150/yr, 50 box-hours, for the old Unlimited subscribers. Above the plan, USD credits pay at $0.22 per standard box-hour, times the size weight (small 0.5, standard 1, medium 1.25, large 2, xlarge 2.5). A box bills the memory it USES, not its booted size: each minute the usage sweep maps the box's measured memory (memUsedMib) to the smallest size that holds it, capped at the booted size (billedSizeForinpricing.ts; a Small box always bills Small), and splits the interval (end_reasonresize) when that size changes: up at once, down only after five lighter minutes in a row. The box gate still checks the REQUESTED size, and the fleet still reserves the booted size on the host. Credits come in packs with optional auto top-up, and each lot expires 12 months after purchase. A paid tier can also buy a usage reset: one payment of the tier's monthly price (POST /billing/usage-reset/checkout, a one-time product per tier inPOLAR_PRODUCT_ID_RESET_*; no feature flag, Tom's call: a set product offers the reset to every account on that tier; web, desktop and mobile). Itsorder.paidsets the current period'sused_wsecto 0 andincluded_wsecto the paid tier's full allowance. It moves the old count toreset_used_wsecand records the order inusage_resets(migration0128). The period end does not move. A refund only recordsrefunded_at: an operator decides what to take back. Polar is the merchant of record (services/billing/{polar,webhook}.ts, webhook/api/v1/webhooks/polar, raw-body, idempotent and order-safe). Money is integer micro-dollars and usage is integer weighted seconds. The ledger is migration0110(usage_intervals,usage_periods,credit_lots,credit_ledger,auto_topup_settings), backend-pool only. The meter isservices/billing/usage/: one interval per running box, closed when the box suspends or goes. The old count caps are gone (active tasks, merge-queue PRs, workflows, loops, review cycles). Margins are pinned by tests:FLEET_BOX_HOUR_COST_ESTIMATE_MICROS($0.04, derivation inpricing.ts) andnetOfPaymentFees(Polar's worst case, 6% + $0.40) feedpricing.test.ts, which fails when a paid tier used to the last included hour keeps under 50% gross margin (annual prices over twelve months too), so change a price or an allowance there first. Plan changes protect the margin twice:POST /billing/change-plantakes upgrades only (Max → Pro is a 409downgrade_via_portal; the portal follows the org's default proration,prorate, so a downgrade applies at once and credits the unused part on the next invoice. Tom chose this overnext_period, which would make portal upgrades wait for renewal too, and accepted the bounded abuse of using Max hours and then downgrading for the credit), and a paid-to-paid upgrade inside a period adds only the share of the extra hours left in the period (includedAfterTierChange, applied byensurePeriodas a compare-and-set on the old tier), the mirror of Polar's prorated invoice. The one gate is the box gate,withBoxGate/checkBoxGateinservices/billing/entitlements.ts, and every new or woken box goes through it. A refusal is aBoxGateErrorand a 402 withusage_exhausted,concurrent_box_limit_reachedorsize_requires_pro. Unattended work (loops, merge-queue and auto-keep fixes, workflows, automatic reviews) never gets a 402. It records a visible deferral (services/billing/boxDeferral.ts), and an unattended box on Free is downsized instead of refused. Two FEATURE gates stay: the auto-keep default and auto-review need a paid tier (402auto_keep_default_requires_unlimited/auto_review_requires_unlimited, on the OFF to ON transition only). MCP servers stay uncapped. Enforcement runs ONLY whenPOLAR_ACCESS_TOKENis set (billingEnabled()): absent means no limits, the dev default. The tier comes from the override, then the subscription and its Polar product, then a team seat, then Free. Comp an account withUPDATE users SET plan_override='pro' WHERE email='…'(unlimitedstill reads as Pro;maxcomps Max); webhooks never touch that column. See Sessions 68, 70, 104, 105 and 121 indocs/SESSIONS.mdfor the old model. - A model API outage suspends the box. When a session turn ends on the vendor's own failure (Claude
API Error: 5xx,overloaded_error, a connection error or timeout; Codexunexpected status 5xx,stream disconnected before completion),services/workbenches/outageResume.tsputs the chat on the usage-limit wait (resumeAt, swept bylimitResumeSweep) on its own ladder (2, 5, 10, 20, then 30 minutes; 8 retries at most), and 30 s later suspends the box. It suspends only if the chat still waits, no other chat runs a turn, and the fleet reports the boxidle, so a background job, terminal or preview keeps it awake. The retry stays on the same agent: an outage is not a reason to switch subscription. Detection isagentOutageFrominpackages/shared/src/agentOutage.ts, pinned to vendor wording; a rate limit or a spent quota wins over it. Claude turns with auto-resume on getCLAUDE_CODE_MAX_RETRIES=5, so Claude Code stops retrying sooner on an awake box. The workspace settingautoResumeOnLimitturns all of it off. - Team plan — seat billing and nothing else, behind the
teamsPostHog flag (fallback OFF,availability: 'gated'). One buyer pays Polar for N seats; each seat gives one GitHub account Unlimited on its own account. A team is now also the multiplayer entity (see Teams and Spaces below), but a workspace is still never shared (Tom's call). Service inservices/billing/teams.ts, routes under/billing/team, tablesteams+team_admins+team_seats(migration0071). Five things to respect:- A seat binds to the numeric GitHub id (
users.github_user_id), never to the login, which can be renamed. That is why a seat can be assigned before its holder signs up.UNIQUE (github_user_id)onteam_seatsmeans one team per person. - The GitHub id comes from the Supabase IDENTITY via the admin API, never from the JWT's
user_metadata. A user can rewriteuser_metadatawithauth.updateUser({ data }), so trusting itsprovider_idwould let anybody claim someone else's paid seat. Seeservices/githubIdentity.ts.users.github_user_idis indexed and NOT unique, because the auth upsert writes it and a stale duplicate must never lock anybody out. - Polar sells the QUANTITY; the seat roster is ours. Polar's own seat-assignment API binds seats to email addresses and is deliberately unused. A team is its own Polar customer (
team_<id>external id). The webhook routes on that prefix OR the team product id, and a team event never touchesusers.plan: that would give the buyer Unlimited on the team's money and take it away on the team's cancel. - The entitlement reads the team tables on the POOL, even from an owner-scoped request. They are backend-only (RLS on, no policy, no
talyn_backendgrant). Order: the user's override, then the user's subscription, then a paid seat, then free. A personalfreeoverride beats a seat, because that is how an operator blocks one account. The flag gates buying and managing, never a paid seat. - Nobody is un-seated as a side effect of a number. Seat assignment takes a per-team advisory lock and refuses on capacity as a whole request. A seat count lowered in the Polar portal is stored as it is: the team shows as over-allocated and new seats are refused until an admin removes people. The last admin of a paying team cannot delete their account or leave the admin list.
- A seat binds to the numeric GitHub id (
- Teams and Spaces: multiplayer, behind the
spacesPostHog flag (fallback OFF,availability: 'gated', break glassSPACES_ENABLED), evaluated for the caller on every route. A team has members (team_members, keyed by the numeric GitHub id, rolesowner|admin|member, sourceinvite|seat) and spaces. A space is a container, not a shared workspace: a session or task in it (workbenches.space_id,tasks.space_id, null = Personal) still runs in its creator's own workspace, with their credentials. Joining a team is free; a seat stays an optional extra, and seat assign and remove keepteam_membersin step (services/teams/seatSync.ts). Migration0116. Four things to respect:- The team and space tables are backend-pool only (RLS on, no policy, no grant), so
routes/spaces.tsmounts BEFOREownerScopeand every read uses the pool with an explicit projection. A space listing never selects a sandbox, device, path, setting, prompt, metadata or result column (.toSQL()tests inroutes/spaces.test.ts). - A space can have an image (
spaces.image, migration0122): a rasterdata:image/...URL that the apps downscale to 128 px before upload, capped at 256 KB byvalidImageinservices/teams/spaces.ts. It shows in place of the colour tile. Access checks (assertSpaceMember,spacesFor) selectSPACE_COLUMNS, which does NOT include the image, because they run on every space request and every 15 s WebSocket recheck. Only the reads that answer with aSpaceuseSPACE_DETAIL_COLUMNS. - Every visibility question goes through
services/teams/access.ts(canViewItem,filterViewable,assertSpaceMember). An item is visible to its workspace owner, or to a member of its space's team whose own GitHub account can read its repository. Items that fail the repository check count inhiddenCount. A thread has no repository, so in a space only its owner sees it; its sessions follow the repository rule. No space route comparesowner_iditself. - A teammate's reads are a narrow, listed path.
readableWorkbenchinroutes/workbenches.tsserves six GET routes only (session, chat events, changes, diff, file, files), never sendslive(a teammate never wakes the owner's box), and strips the sandbox id, device and local path. Every other mutating route stays owner-only; the two prompt routes are below. - An invite by email waits in
team_invites(migration0147), not inteam_members, because an email gives no GitHub id.services/teams/emailInvites.tsstores only a SHA-256 hash of the link token, emails<web app>/invite/<token>through Resend (services/email.ts,RESEND_API_KEY), and gives the link back to the inviter when no email went out. The link is single use (a conditionalUPDATE … WHERE accepted_at IS NULLis the claim), expires afterTEAM_INVITE_TTL_DAYS, and inviting the same email again replaces the token. Accepting adds the caller's own GitHub account as amember; their account email is deliberately NOT compared with the invited one, because the link is the proof. The token travels in POST bodies (/team-invites/preview,/team-invites/accept), never in an API URL. The web app's/invite/:tokenroute moves the token to localStorage at once, so it survives sign-in and onboarding. - A session created in a space runs in the caller's home workspace for that team (
team_members.home_workspace_id, default the oldest workspace they own). When that workspace does not have the repository, Talyn adds it through the "Add repository" path first. See the 2026-11-06 note indocs/SESSIONS.md. A thread can start in a space or move to one; its live sessions move with it, and a session it starts goes in its space (2026-11-09 note). An integration rule'sstart_sessioncan name aspaceId: that session stays in the rule's workspace, and when the owner can no longer use the space it starts in Personal (2026-11-17 note). - Live space events and presence ride the WebSocket (
subscribe_space,presence,space:presence). A subscription is re-checked every 15s with the flag andassertSpaceMember; space delivery uses an explicit event allowlist inservices/teams/spaceEvents.ts, strips sandbox, device and path fields, and checkscanViewItemthrough a 60s cache. Presence (services/teams/presence.ts) expires 60s after the last heartbeat, in a Redis hash whenREDIS_URLis set and in memory otherwise, and relays across replicas throughwsBus. - The prompter pays, per turn. A teammate who passes
canPrompt(view, own home workspace, a fleet account for the chat's agent,permissions.pushon the repo) may send a message (promptableChat); stopping their own turn needs only view access plus being its payer. The payer rides on the queued message (WorkbenchQueuedMessage.payer) and lands onworkbench_chats.payer_user_id/payer_workspace_idwhen the turn starts (migration0117); null is the owner. For that turn the credential set, git identity (GIT_AUTHOR_*/GIT_COMMITTER_*on the turn exec), hot swap, limit resume, box gate (budget only) and meter (usage_intervals.owner_id= payer,payer_changecloses the old interval) are all the payer's. One payer per box: the claim refuses to start a head whose payer differs from a running turn on another chat; the chat waits withdrain_pendingand starts when that turn ends. A host pull between turns answers with the latest turn's payer (currentBoxPayer). Owner and Talyn git actions never use a teammate's set:refreshSandboxCredentialsdefaults to the owner, and Talyn's PR step and Create PR run inwithOwnerCredentials(owner set first, a running teammate turn's set back after). See the P3 note indocs/SESSIONS.md.
- The team and space tables are backend-pool only (RLS on, no policy, no grant), so
- Check ledger + CI verdict —
pr_check_statesholds one row per (repo, head sha, check name), fed bycheck_runANDstatuswebhooks and reseeded by every complete full fetch (reseedCheckLedger, fromprCache.upsertRow). The verdict —ciStatus,humanGates,blockingReason— is derived by ONE function,deriveCiVerdictinpackages/shared/src/checkVerdict.ts, on both the full-fetch and the webhook paths; the front ends renderciStatusand never re-derive required-ness. Seedocs/INCREMENTAL_CHECK_COUNTS.md. Five things to respect:- A failing check with unknown required-ness is BLOCKING (red), never green. The only exception is
MERGEABLE + UNSTABLEread in the same fetch. The webhook path never uses it: the row'smergeStateStatusis from before the failure. Guessing green is how a requiredSemgrep Checks Passdrew as "2 non-required". - No lock on the ledger, and never
withBlockingAdvisoryLockon a hot path. That helper holds its lock on ONE pooled connection and runs the callback's queries on OTHERS, so a burst of callers takes the whole pool and then waits for a connection it will never get. A per-commit lock here did exactly that on 2026-09-30 (19 connections idle in transaction onpg_advisory_xact_lock, the DB watchdog restarted production twice). The lost update it guarded is repaired by the reseed and the settle refresh instead. The flush's ownFOR UPDATEread isNOWAITwith short retries off the connection, and flushes run at most 4 at a time: a plain row-lock wait holds a pool connection for up to 30 s, and on 2026-10-12 such waits filled the pool behind PR rows that a request held through a GitHub call (Session note of that date). - The reseed is detached from
upsertRow, bounded to two at a time, and skipped when an md5 of the ledger already matches the fetch. Detached because that write can sit in a request transaction holding the PR row. Bounded and skipped because a sweep fetches each PR once per watching workspace. needs_humanblocks the merge but is never agent work.prBlocksMergeincludes it (the queue must not submit);prNeedsFollowupexcludes it. Human gates live in theHUMAN_GATESregistry (PostHog Visual Review: the status, plus the requiredVisual regression tests passthat fails because of it). The queue parksawaiting_human_checkand auto-keep stands down from the checks alone — no VR API, no setting.- Nothing polls periodically. Healing is the 90 s per-commit settle refresh (re-armed by every check event), the required-ness recheck, and the 5-min sweep. A change that drops one of those needs a replacement, not a comment.
- A failing check with unknown required-ness is BLOCKING (red), never green. The only exception is
- GitHub outage detector —
services/githubHealth.ts(pure core) andgithubHealthMonitor.ts(poller, broadcast). It answers one question, "is GitHub itself unwell", from two signals, and either one can raise the banner. Signal A is our own traffic: every GitHub call goes throughfetchWithTimeoutingithub.ts, which feeds a rolling 10-minute window per API (rest,graphql). Only a 500, 502, 503, 504 or a transport failure counts. A 4xx and a rate limit NEVER count: GitHub answered, so it is up, andparseRateLimitResponseis asked first. Signal B is githubstatus.com, read once a minute, for the components we depend on; an incident on an unrelated component is not our problem. Four things to respect. The feed swallows its own errors (feedGithubHealth): it runs inside every GitHub call, and a fault there would fail the call and then be counted as a GitHub failure. A failed read of the status page says nothing about GitHub: the last good answer is kept and goesunknownafter 5 minutes. The state is per process, with hysteresis (worse is immediate, better needs 2 clean minutes), and a transport failure on OUR side reads as GitHub's, which the detector cannot tell apart. Clients getGET /system/github-healthand agithub:healthbroadcast on change only. The banner hides the App-coverage rows while GitHub isdown, because that diagnosis calls GitHub; it never hides "GitHub isn't connected", because a token is removed only on a confirmed 401. The one consumer so far is the merge queue:DecisionContext.githubDownstops a failed submit call spending its budget.GITHUB_STATUS_POLL_ENABLED=falsestops the status-page reads only. - GitHub/PR core —
services/{github,githubGraphql,prMonitor,prCache,prFocus}.ts+routes/{github,pullRequests,repositories}.ts+ the desktop GitHub panel / PR pills / detail sheet. This is the heart of the app. (The standalone Inbox — a prioritized queue of PR items needing attention — was removed; PRs needing attention surface directly in the GitHub panel's "Needs attention" / Mine / Review buckets.)
See docs/ARCHITECTURE.md for the full treatment.
The Debug panel now lives ONLY on the operator console (admin.talyn.dev → Ops → Debug). It was removed from apps/web and apps/desktop in Session 80: it streams backend internals across every account, so it belongs on an admin-gated surface rather than in the product. It surfaces app internals live: outbound HTTP, poll-loop ticks, WebSocket traffic, and domain events. It's powered by an in-process debugBus (packages/backend/src/services/debugBus.ts, ring buffer + counters + poller registry) that records metadata only (URLs are query-stripped; no headers/bodies/tokens) and streams over the existing WS as debug:event. UI lives in apps/admin/src/components/panels/DebugPanel.tsx (one copy — the desktop/web duplicates are gone).
Settings → Developer is the per-account view, and it is a different surface with a different rule. routes/developer.ts (/api/v1/developer, both product apps, component DeveloperInternals.tsx) shows a user their OWN GitHub rate limits, fleet agent state and recent activity. It is an ordinary authenticated router, so its whole safety is in four points. The account comes from req.user.id and from nowhere else: no route reads an owner parameter, and a workspaceId must pass requireWorkspaceAccess. An event is returned only on a plain ownerId === userId, never through matchesOwnerFilter, whose all and system values widen the match. Only http, webhook, event and error leave; db, polling and websocket describe the whole backend and never do. toUserDebugEvent builds the row field by field and cuts meta to an allowlist of keys, so a new meta key reaches users only when somebody adds it to META_KEYS after reading its call sites. It polls REST every 10 s; there is no user WebSocket stream, and debug:event still goes to admins only. Two known gaps: no recordWebhook call passes a workspaceId, so the Webhooks filter is empty until the worker records one event per watching workspace; and attribution exists only for workspaces with a GitHub token (registerOwner has one caller), which fails closed.
When you add or change a subsystem, wire it into the bus so the panel stays honest:
- New outbound HTTP (a new external API/integration) → time the call and
debugBus.recordHttp({ service, method, url, status, durationMs, ok, error? })at the central request funnel (seegithub.tsapiRequest/executeGraphql,posthogCode/client.tsrequest). Add a one-liner toSERVICE_INFOinDebugPanel.tsx. - New poll loop →
debugBus.registerPoller(name, intervalMs, description)ininit()(thedescriptionarg is required — that's the tooltip) anddebugBus.pollerTick(name, { durationMs, ok, error? })in the tick'sfinally. - New WebSocket message/broadcast or domain event →
debugBus.recordWs(...)/debugBus.recordEvent(...). If it's a new outbound broadcast type, keep theevent.type !== 'debug:event'loop-guard inwebsocket.tsintact. - New
DebugCategory→ extend the shared type,CATEGORY_INFO,CATEGORY_LABEL,categoryClasses, the filter chips inDebugPanel.tsx, and theCATEGORIESallowlist inroutes/debug.ts— an unlisted value there is not rejected, it silently falls through to "no filter", so the chip appears to do nothing rather than to fail. (dbandwebhookwere missing for exactly that reason until Session 80.)
GraphQL budget cards ("GraphQL budget" row in the panel) show GitHub's per-account GraphQL points budget (inst:<id> for an App installation, else login), fed by services/graphqlBudget.ts. The budget is read off the free rateLimit { limit cost remaining resetAt } field spliced into every batched query (githubGraphql.ts RATE_LIMIT_FIELD); github.ts executeGraphql captures it via graphqlBudget.record(accountKey, …). The tracker is pure / debug-bus-independent on purpose — it also drives a proactive deferral: the reconcile sweep (prReconcileSweep.ts) calls graphqlBudget.shouldDefer(accountKey) and skips an account whose remaining points are in the reserve (RESERVE_POINTS), so webhooks / merge queue / manual refresh keep flowing until the window resets. debugBus.snapshot() just reads graphqlBudget.snapshot() for display. Tests: graphqlBudget.test.ts.
Give the bus the ERROR, not its message. recordDbQuery / recordHttp / pollerTick / recordWebhook all take error?: unknown and run it through describeError, which walks the cause chain. Passing err.message throws away the only useful half of a whole class of failure: drizzle reports Failed query: select … and puts the reason in cause, fetch reports fetch failed and does the same. A red poller card that names the query and not the cause is what turned a one-line fix into an hour — see Session 127. (This is for the bus only; routes that stringify err.message into an API response should keep doing that, since a cause chain is for an operator, not a caller.)
Tests live in packages/backend/src/__tests__/debugBus.test.ts — extend them alongside changes.
The backend runs against Supabase Postgres and we pay for DB egress (result-row bytes shipped DB→backend). A bare Drizzle .select() is SELECT * — it ships every column, including large jsonb blobs the caller usually doesn't touch. The three expensive columns are tasks.transcript (the cloud-run conversation log, often MBs), pull_requests.lastSummary (~2KB, but multiplied across every tracked PR on the poll loops) and pull_requests.body (the PR description, cached so the detail panel paints without waiting on GitHub — read by GET /:id/description and by NOTHING else, which is why it is a column rather than a key in lastSummary: every tick of the auto-keep watcher, the merge-queue broadcast/executor and the monitor reads that blob and none of them want a description). The DB-egress tile in the Debug panel (fed by instrumentEgress in db/client.ts, which records per-query bytes/rows/table) is how you spot regressions — watch it after touching any read.
Rules of thumb when writing or reviewing a query:
-
Never
.select()(=SELECT *) unless the caller genuinely uses every column. Default to an explicit column list. This is most critical on anything that (a) runs in a poll loop or per-request hot path, or (b) reads a table with a large jsonb column (tasks,pull_requests,workspaces.logo,integrations.config). -
Reuse the established projection helpers — don't invent new shapes:
-
services/taskSerialize.ts→taskColumnsNoTranscript(everytaskscolumn excepttranscript) +rowToTask(row, { includeTranscript? }). Any task read that doesn't render the transcript should use this. OnlyGET /tasks/:idandPOST /tasks/:id/messageselect the full row. - For poll-loop / hot-path reads on
pull_requests, define anas constprojection object next to the consumer and type the row asPick<typeof table.$inferSelect, keyof typeof PROJECTION>. Existing examples:QUEUE_COLUMNS(mergeQueueProcessor.ts),WATCH_COLUMNS(prAutoMergeWatcher.ts),PR_CACHE_COLUMNS(prCache.ts),BROADCAST_COLUMNS(mergeQueueBroadcast.ts),PR_LOOKUP_COLUMNS/PR_FLAG_COLUMNS(routes/pullRequests.ts),CLOUD_ENV_COLUMNS(taskQueue.ts). ThePicktype is the regression guard —tscfails if a consumer later reads a column the projection drops, so it can never silently re-bloat.
-
-
Compare a date with
lt/gt/lte, NEVER with a rawsqlfragment.sql\${col} < ${someDate}`andlt(col, someDate)look interchangeable and are not: the interpolated value carries no column type, so drizzle passes it to the driver unencoded and postgres-js throws *"The \"string\" argument must be of type string … Received an instance of Date"* before Postgres is asked. **The suite cannot catch this** — pglite's drizzle session encodes the Date itself, so it passes locally and fails on every request in production. It killed the entire loop scheduler sweep (Session 127); the guard isloopQueryParams.test.ts, which asserts noDate` reaches the driver. -
If you only need a scalar/boolean derived from a big jsonb, compute it in SQL — don't fetch the blob. Use a
sql<...>expression so the column never ships. Precedents:cloudProviders/poller.tsderivestranscriptEmptywith aCASE … jsonb_array_length(transcript) …;prMonitor.fastPollWorkspacederives the in-flight check count withCOALESCE((last_summary -> 'checks' ->> 'inProgress')::int, 0)instead of selectinglastSummary. When you do this, pin the SQL to the JS semantics it replaces with a pglite test (seecloudPollerEgress.test.ts,prMonitorFastPollEgress.test.ts) — keep the JS helper exported as the canonical definition the SQL must match. -
Don't fetch a column to read it once for a rare branch. If a loop reads N rows but only needs an expensive column for the few that hit a condition (e.g.
reconcileRelationshipFlagsonly needslastSummaryfor rows whose flags changed), drop it from the bulk select and re-fetch it per-row inside the branch — N blob fetches/tick become K (usually 0). -
The same discipline applies to what leaves the backend. WS broadcasts and REST responses should serialize a crafted shape, never a raw full row (see
emitPullRequestUpdated/rowToPublicShape). Don't echotranscriptor unread jsonb to the desktop.
When in doubt, add a .toSQL() assertion (expect(query.toSQL().sql).not.toContain('transcript')) — it proves the projection excludes the blob without a live DB (see projectionEgress.test.ts).
Full list in
docs/ROADMAP.md. The active direction is the cloud-provider abstraction indocs/CLOUD_PROVIDERS.md. (The daemon-everywhere / continuous-build / local-execution era docs were deleted in July 2026 — seedocs/SESSIONS.mdhistory if you need them.)
- Cloud provider abstraction — the seam is done and has one live provider, Talyn Fleet (
services/selfHosted/*+cloudProviders/selfhosted/provider.ts, the default). PostHog Code is retired: its code still serves existing connections, and deleting it is step 2. Codex Cloud is deferred — OpenAI exposes no server-to-server cloud-task API (only thecodex cloudCLI or@codexGitHub mentions); note this is a different thing from running Codex on the fleet, which works. Each provider is a self-containedclient + credentials + executor + poller + providermodule — no core changes. Selection is generic:defaultCloudProvider(selfhosted | posthog_code | ask) drives the backend resolver (resolveCloudEnvChain) and both front ends, with an "Ask every time" per-task agent menu on each PR row (the fleet contributes one entry per connected subscription, each carrying its model). Follow-ups: the deferredTranscriptSource/TranscriptConvertergeneralisation; measuring the real ChatGPT access-token lifetime, which decides whether server-side Codex refresh is worth its ToS exposure. - Desktop polish — the composer still has no freeform task entry; every task starts from a PR row or the skill picker. (The dead local-task UI — TaskFilesPanel/TaskGitPanel/awaiting_review flow — was removed in Session 52.)
- Phase 18.2 polish — proper
talyn loginPKCE flow, CLI refresh-token rotation, invite flow.
Recent work: see docs/SESSIONS.md, newest first — one note per session, with the reasoning and the things that turned out not to work.
apps/mobile is the third front end, and every change that users see lands there too. Web and desktop are the reference; mobile follows them. A new feature, a changed behaviour, new copy or a bug fix in apps/web/apps/desktop updates apps/mobile in the same change, unless it is on the web-only list below. When a mobile change is not practical in the same change, say so in the commit and add it to docs/ROADMAP.md. A backend change that alters a response, a WS event or a 402/409 code is a mobile change as well: check apps/mobile uses it the same way the web does.
- Web only (do not port): the terminal, file editing, workflow and loop editors, the Talyn Fleet model choice, and desktop-only things (local skills, the local MCP import). Mobile links to the web for these. Sandbox setup, private routes, MCP servers, API tokens, Slack, PostHog Code and Trunk keys, skills, instructions, memory and code review settings have native editors under
app/settings/(2026-11-09, Tom's call) and follow the web sections like any other screen. - Mirror, do not reinvent. Read the web component first and port its data flow, rules and copy. The mirrors to keep in step:
src/lib/status.ts(webSessionStateIcon,PRStatusPill,PRReviewPill),src/theme/tokens.ts(webapp.csstokens),src/lib/models.ts(shared model catalog),src/features/prs/lists.ts+counts.ts(web PR tabs and badges),src/features/spaces/(web space context andinPersonalList),src/features/billing/model.ts(webBillingActionsrules and refusal copy). - Gate like web. Every flagged surface reads
useFeatures()(src/lib/features.ts, backed byGET /features). A new flag infeatureFlags.tsneeds the same gate on mobile. - Live data goes through the store.
src/workflow/store.tspatches rows from WS events by id (prPatch.tsfor PRs). A new WS event or a new field on a broadcast row needs a patch there, or mobile shows stale data. Never invalidate a whole entity kind on an event; that is what kept every screen marked stale before. - Native modules need a new development build. Add them with
npx expo install, add any config plugin toapp.config.ts, then rebuild withnpx expo run:android/ios. After adding reanimated or worklets, restart Metro with--clear, or the app fails with a worklets version mismatch. A change tosrc/workflow/store.tsneeds a full app restart in development: Fast Refresh swaps the screens but keeps the store object made from the old class, so a screen that calls a new store method crashes the dev app (a release bundle is not affected). - "Share to Talyn" is mobile only (web and desktop have no system share sheet).
plugins/withShareIntent.cjswrapsexpo-share-intent: an iOS share extension (targetShareExtension, app groupgroup.<bundle id>) and an Androidtext/*SEND filter. iOS opens<scheme>://dataUrl=..., which+native-intentsends to/share;src/features/share/ShareIntentBridge.tsxturns the item into/new?prompt=and keeps it as a pending intent through sign-in.scripts/inspect-native.cjschecks the extension. A new iOS profile needs the extension's credentials first (docs/MOBILE_RELEASE.md§ iOS share extension). - Dependency patches live in
apps/mobile/patches(patch-package, applied bypostinstalland byeas-build-post-install).expo-modules-jsi+58.0.23.patchlets the iOS build compile with Xcode 26.3, whose Swift compiler rejects one capture in Expo's code (2026-11-10). When an Expo upgrade changes that package's version, patch-package reports the patch as stale: check whether the new release builds without it, then delete the patch or regenerate it. - Android push needs
TALYN_MOBILE_GOOGLE_SERVICES_JSON(base64google-services.json, an EAS text variable in every environment; 1Password has the original).app.config.tswrites it to.expo/and the fingerprint hashes it, so a local build without it gets no push token AND a runtime that OTA updates never match. Seedocs/MOBILE_PUSH_NOTIFICATIONS.md§ Android credentials. - Android traps that are already solved; keep the fixes. The WS sends an empty
Origin(src/native/socket.ts; the server also accepts its own host). Screens pad from the JS safe-area provider (ScreenContainer), not the nativeSafeAreaView. Edge-to-edge Android does not resize for the keyboard: the inset comes from the keyboard'sscreenY(src/lib/keyboard.ts), andKeyboardAvoidingViewgets nobehavioron Android. - Browser flows return to the app through
returnTo(exact-matchMOBILE_RETURN_SCHEMESallowlist,services/mobileReturn.ts). A new OAuth, install or checkout flow that mobile starts needs the same return target. Purchases sit behindpurchaseMode(EXPO_PUBLIC_PURCHASE_MODE), because store rules decide where in-app buying is allowed. - Docs and release. A new public build variable goes in
apps/mobile/release/policy.cjs, or the build refuses it. User-facing mobile behaviour belongs inapps/marketing/content/docs/with the web behaviour. - Merges to main ship to preview/internal-beta as OTA updates (
.github/workflows/mobile-update.yml;MOBILE_UPDATES_AUTO=0stops it). They are unsigned by decision (2026-11-09): EAS code signing needs a paid EAS plan, so EAS HTTPS and who holdsEXPO_TOKEN/Expo access are the protection, and every check refuses an update certificate (one in a binary rejects every unsigned update). Turning signing on needs the EAS Production plan, a certificate in the config and a NEW binary. A change that needs a new native build (native module, config plugin, app.config native fields) must not be shipped as an update — it changes the fingerprint and needs a new binary.
fastowl/
├── apps/
│ ├── desktop/ # Electron desktop app
│ │ └── src/
│ │ ├── main/ # main + preload
│ │ └── renderer/ # React frontend (components, hooks, stores, lib)
│ ├── web/ # @talyn/web — browser app (app.talyn.dev), Vite + React 19
│ ├── admin/ # @talyn/admin — operator console (admin.talyn.dev), Vite + React 19
│ └── mobile/ # @talyn/mobile — iOS + Android app, Expo + React Native (expo-router)
├── packages/
│ ├── backend/ # Express + WS server, DB, services
│ ├── cli/ # @talyn/cli — `fastowl` binary
│ ├── client/ # @talyn/client — REST + WS transport, shared by every front end
│ └── shared/ # Shared TS types
│ # (packages/daemon removed in the cloud-only refactor)
├── docs/ # ARCHITECTURE, ROADMAP, SESSIONS, CLOUD_PROVIDERS, SETUP, etc.
├── supabase/ # Local dev Supabase stack: `npm run dev:db` (config.toml +
│ # gitignored .env). Local dev must NEVER point at the prod
│ # DB / GitHub OAuth app — see docs/SETUP.md §0 for the why.
├── CLAUDE.md # This file
└── package.json # npm workspace root
Inside packages/backend/src/: db/ (migrations + Drizzle schema/client), routes/ (REST), services/ (taskQueue, cloudProviders/ (registry + poller + posthog/claude providers), posthogCode/ (client/executor/streamer/converter), claudeCode/ (client/credentials/executor/poller/converter — Anthropic Managed Agents, poll-based transcript), github, prMonitor, prCache, taskPullRequest, events, websocket), __tests__/ (Vitest).
Inside apps/desktop/src/renderer/components/: layout/, modals/, panels/, terminal/, widgets/, ui/ (shadcn).
apps/web is a deliberate FORK of the desktop renderer, not a shared build of it. Tom's call: every UI feature gets built separately in each client (desktop, web and apps/mobile), in exchange for the clients being able to diverge freely. What is NOT forked is the backend contract — both import @talyn/client — because two copies of that drift into runtime bugs rather than type errors. Three things the fork must keep straight, all verified with a spike before the app existed:
- Env is
import.meta.env.VITE_*, neverprocess.env.*. Vite'sdefineentries are "defined as globals during dev and statically replaced during build", so mirroring webpack'sEnvironmentPluginwith adefineofprocess.env.TALYN_API_URLserves the dev browser an unsubstituted expression that throws on the missingprocessglobal.vite.config.tsfails a production build outright when a required key is empty (a white screen on a public URL is much worse than the desktop's runtime throw) and refuses any value containingservice_role. - OAuth is a full-page redirect —
signInWithOAuthwith noskipBrowserRedirect, plusdetectSessionInUrl: true. The desktop'sopenExternal(data.url)fires after twoawaits, so itswindow.openfallback has lost user activation and Safari/Firefox block it, silently, on the sign-in screen. - Never carry
migrateLegacyAuthFromLocalStorageacross. On web the "bridge" IS localStorage, so itssetItem-then-removeItemon the same key wipes the session every page load.
packages/client ships dual-format (dist/cjs + dist/esm, picked by the exports map) because Rollup cannot statically see the re-exports tsc's CommonJS output emits as Object.defineProperty(exports, …) getters — Vite fails with "not exported by" — while the desktop's jest suite still needs CJS. Don't collapse it to one format without checking both.
Browser-origin surface (all inert until app.talyn.dev exists): services/originPolicy.ts is the one answer to "may this origin talk to us", shared by the REST CORS gate and the WS upgrade — exact string match, never a pattern (ALLOWED_ORIGINS), because a prefix/suffix rule is how https://app.talyn.dev.evil.com gets in. A rejected origin now denies by omitting the header (cb(null, false)) instead of throwing a 500, CORS is credentials: false (the API is Bearer-only, so CSRF-immunity is structural) with maxAge: 86400 (the non-safelisted client-version header preflights every request). The null-origin concession for the packaged renderer's file:// WS handshake is forgeable by any page and sits behind TALYN_ALLOW_NULL_ORIGIN_WS — flip it to 0 the day anything moves to cookie auth, or it becomes a live cross-site WebSocket hijack. The WS upgrade also accepts an Origin that exactly names the API's own Host (isOwnHost, never a preview host): React Native's Android WebSocket sends https://<api host> by default, and before this rule the mobile app never got live updates. services/webApp.ts owns WEB_APP_URL: read only from env, validated at boot, and webAppUrl() refuses any path that isn't single-slash-relative — it's the GitHub App callback's redirect target, and an open redirect there turns a login flow into a phishing hop. The callback ends per-client (browser → 302 home, desktop → close-this-tab page), decided by the Origin recorded server-side when the state was minted. The mobile app's return is a separate allowlist, services/mobileReturn.ts: a returnTo (talyn-mobile://) on the GitHub install URL, checkout, credit checkout or portal must EXACTLY equal one MOBILE_RETURN_SCHEMES entry (bare scheme://, never a pattern, never http(s)), else 400 invalid_return_to. It is stored on the pending state, so the GitHub callback 302s to ${returnTo}github/callback?github=connected|error&reason=<code>; Polar takes only http(s) URLs, so billing returns go through the public GET /billing/mobile-return hop, which re-validates to. The same returnTo rides on POST /slack/install|link, POST /posthog/oauth/start (stored in mobile_return on their state rows, migration 0127) and POST /mcp-servers/:id/connect (stored on the pending flow). Their ends are ${returnTo}slack/callback, posthog/callback and mcp/callback; the MCP one goes through the web /mcp/callback page, which follows the appReturnUrl that /mcp-servers/complete answers.
packages/client is the single definition of the backend contract — every route signature, every WS event type, the 401-refresh-and-replay, the reconnect backoff. Anything that talks to the backend imports it, so a route change can't be applied to one front end and forgotten in the other. It knows nothing about how a host stores a session or where its build-time env came from: hosts call configureApiClient({ baseUrl, clientVersion, getAccessToken, recoverSession }) once at module scope. The desktop's binding is apps/desktop/src/renderer/lib/api.ts — ~50 lines of Supabase/process.env glue plus export * from '@talyn/client', so the ~40 files importing '../lib/api' never had to move. Add new endpoints here, not in a host app, and remember it compiles to dist (lib: ["ES2022", "DOM"]), so it must be built before the desktop build, the typecheck, or jest.