Repository navigation
feat(platform): rewrite the AI backend on a minimal YAML-config core - #2857
Merged
Merged
Conversation
larryro
force-pushed
the
refactor/rip-out-legacy-backend
branch
2 times, most recently
from
July 23, 2026 10:54
937309b to
938e28a
Compare
larryro
force-pushed
the
refactor/rip-out-legacy-backend
branch
from
July 24, 2026 07:51
60422d9 to
078e1ba
Compare
A session's virtual key is minted against the gateway record the turn will
route to. resolveGatewayRouting sends a NON-standard provider to a per-model
record (deepseek__deepseek-chat), but provisionSessionGatewayKey wrote the
key under the raw connector slug (deepseek), so the mint's key lookup 404'd
and failed closed ("no gateway key for provider ..."). Standard providers
were unaffected because their raw slug IS the record name, which is why the
vision lane (standard models) never hit it.
Build one provision per connector, then expand it into the exact record the
mint binds to: standard providers keep the shared record; a custom provider
gets one per-model record carrying that name and just that model. Regression
test pins the custom-provider case.
Wire the third-party agent lane end to end and let a conversation equip its agent with capabilities: - listComposerCapabilities resolves the org's skills and its enabled connectors (credential-gated, like the model listing); the composer's capability menu assembles them per conversation and stores the picks on the thread (createThread + threads.capabilities). - startCodingTurn drives a harness turn in the thread's agent-profile sandbox session: managed gateway credential, skills staged into the workspace, the harness run over the streaming exec, the reply appended, usage metered, the harness resume handle kept for the next turn. - A sandbox thread PINS its coding agent: the composer follows the open thread onto its agent and locks the picker (switching is a new chat), so a later turn never silently falls back to the platform lane. - The platform picker group reads "Chat" rather than "Platform agent". KNOWN LIMITATION (next commit replaces this): the coding-turn driver awaits the whole harness exec inside one Convex action, so a cold or long turn can outlive the action's execution window and be killed mid-run. The correct model is the main-branch async pattern — dispatch to the autonomous session, stream events/completion back through a callback, Convex holds only state. Warm turns work today; cold turns are unreliable until that rebuild.
The local-dev writable config root (the TALE_CONFIG_DIR default) moves from .tale-config/ to .tale/config/, nesting it under the already-ignored .tale/ tree. Updates the dev-engine default, the E2E fallback, the docker-entrypoint bind-mount comments, and .gitignore (the new path is already covered by the existing .tale/ rule, so the dedicated entry is dropped and that rule is documented in its place). The env var name is unchanged; only its default value moves. An explicit TALE_CONFIG_DIR still wins; no back-compat shim was added. BREAKING CHANGE: the default local-dev config dir is now .tale/config instead of .tale-config. Move an existing .tale-config/ to .tale/config/ (or set TALE_CONFIG_DIR) so its per-org files are still found.
The synchronous coding-turn driver awaited the whole harness exec inside one
Convex action, so a cold or long turn outlived the action's execution window
(~7.5min observed) and was killed mid-run. Rebuild it on the sandbox's own
autonomy: an exec runs under runnerd with a byte-identical ring-buffer replay,
so it survives disconnects and re-attaches by execId + sinceSeq.
- startCodingTurn (kick): persists the user message and an assistant
placeholder, opens the generation with the drainer's re-attach state, starts
the exec, and drains the FIRST window inline (a warm turn settles here; the
gateway token this window holds never persists). Still running at the
window's close → it schedules the drainer and returns.
- driveCodingTurn: a self-chaining internal action that re-attaches from the
ring-buffer start each ~90s window, re-parses the full output-so-far, SETs
the assistant message, and settles on the harness turn-end — or cuts the
exec at the overall deadline. Re-parsing from the start (not carrying a
per-delta cursor across windows) keeps a JSONL line split across a window
boundary from being stranded by the fresh per-window parser.
- The session is USER-scoped (per org, user), matching the prior model: every
coding thread shares one persistent workspace and `--resume` state, the
container is disposable (a reaped one recreates against the preserved
workspace), and the turn end no longer tears it down. Explicit-destroy and
idle-reap wiring for these sessions is the outstanding lifecycle follow-up.
E2E-verified on the live stack: a cold fresh thread settled ("ASYNC-OK") where
the sync driver timed out, and a second turn resumed the same workspace —
reading back a file the first turn wrote.
The agents area is moving to two built-in agent kinds chosen in chat, so the user-authored roster management UI is retired. Delete the `/dashboard/$id/agents` area — the roster, the per-agent tabs (general/tools/skills/knowledge/instructions), the create dialog, the allowlist editor, metrics, and the `settings/agents` redirect — plus the navigation tiles (desktop + mobile) and the onboarding "Create an agent" step. Scope is UI only. The agent ROSTER backend stays: `convex/tasks/*` binds `agentSlug`, so the store and its loader remain until the task/automation rebind (the aligned follow-up). The project-scoped agents tab and its `useAgents` hook also stay — only the standalone management page goes. Consumers that pointed at the deleted page now fall back to the org home rather than dead-linking: an `agent`-kind org notification, and an agent actor's "view" in the task actor preview. The task-run failure banner drops its "Manage agents" link. Orphaned i18n keys pruned (en/de/fr).
The `emptyStates.agents` copy ("No agents yet" / "Create your first
agent…") belonged to the deleted agents roster page — nothing references
it now. Remove it across en/de/fr and drop its two entries from the
i18n dynamic-key allowlist. The i18n parity + usage suite stays green.
The rest of the agents namespace is deliberately left: much of it is
still referenced by live surfaces (the project agents tab, the model
selector, the role gate), and separating the genuinely-dead keys needs
the dead-code pass that comes with retiring the agent roster backend.
The async coding-turn lane tracked turn state only as the presence of a generations row and discarded the minted gateway key id, so per-turn virtual keys were never revoked (a live, monthly-resetting credential leaked per turn) and a harness that exited without a turn-ended event finalized as an empty success. Anchor the turn on the existing sandboxSessionOps machinery instead of a second, thinner turn model: - provisionTurnGatewayToken now records the key: a sandboxSessionTokens row (hash + scope + turn-deadline expiry) for teardown/destroy revoke, and the key id on the op row for the per-turn finalize. - openCodingOp writes a running agent-run op row (mintedKeyId, deadline, streamed message, usage attribution) with a heartbeat, re-stamped each drain window — the staleness clock a recovery sweep will read. - finalizeCodingTurn elects a single finalizer via claimSessionOpFinalize, so usage metering and VK revoke run exactly once; the winner reads the gateway spend, records it, revokes the key, and marks its token row. - drainCodingWindow consumes the terminal exec result: an exit without a turn-ended event is surfaced as an explicit failure with a reason and a failed op row, never a silent empty reply. Locks the data-layer invariants (exactly-once claim, token revoke, terminal op) with a new coding_turn.test.ts. No schema change: the op row fields already exist; only upsertSessionOp's arg validator widened for agentResultStatus.
There was no way to cancel a running coding turn: the composer's onStop prop was never wired, and the Settings Stop acted on an ops table the lane didn't write. A hung turn ran to its 30-minute deadline with no user escape. Add stopCodingTurn: owner-scoped, it cancels the harness exec in the sandbox (SIGTERM→SIGKILL via runnerd) and settles through the shared finalize, so the exactly-once claim revokes the turn's gateway VK, stamps the op row cancelled, and unlocks the composer. The partial reply is kept with a stop note. Racing the drain loop is safe — the claim elects one finalizer. Wire it end to end: a stop method on the chat seam, and onStop + generating on the composer for a coding turn in flight. The direct lane keeps no cancel yet (its single-action turn is hardened separately). The Settings Stop now also works for coding turns, since batch 1a made the lane write the op rows it reads.
A lost driveCodingTurn reschedule (deploy, restart, action-ceiling kill) or a throwing drain window left a coding turn's op + generation rows running forever: the thread showed "generating" with no user escape and no sweeper — the by_heartbeat index existed for a watchdog that was never rebuilt. The direct lane had the same wedge on a hard-killed action. Register the two deferred crash-recovery crons: - recoverAbandonedCodingTurns (node, 2 min): lists agent-run ops whose heartbeat went stale, probes each exec, and resumes it (still alive — reschedule the drainer) or finalizes it (exited/gone), exactly-once via claimRecoveryResume / claimSessionOpFinalize, revoking the VK on every terminal path. Honors the turn's original deadline (now surfaced by listAbandonedAgentOps). - recoverStaleDirectGenerations (2 min): deletes stale non-coding generation rows so a crashed direct turn unlocks the composer; coding rows are skipped (the op-row sweep owns them, since it probes the live exec first). Also wrap driveCodingTurn's window in try/catch so a throw routes to the unified failure exit instead of silently ending the chain.
Three chat-turn integrity gaps: - Cross-user write (security): the direct lane's startTurn checked only org membership, so any member could run turns that wrote user + assistant messages into another member's private thread (listMessages returned [] for a foreign thread, but the append path only checked org). Gate startTurn on getOwnedThreadInternal, matching the coding lane. - At-most-one turn: a concurrent second send reset the live generation row, orphaning the first turn's exec and double-charging on finalize. Both start actions now refuse a busy thread via hasLiveGenerationInternal before appending anything — the client's send-disable was UX only. - 409 self-heal: ensureAgentSession failed the turn when the spawner still held an orphan container under the deterministic id. It now adopts that container (bound to the same preserved workspace) instead of refusing — reaping via destroy would delete the user's workspace. Also convert getCodingStateInternal from an internalMutation to an internalQuery (it only reads; forcing OCC on a read was needless) and update its callers.
recoverStuckSessions flipped a stuck session row to `expired` but its docstring's "teardown + token revoke is the caller's job" caller never existed — the cron registered the bare mutation and discarded the ids, so an expired session left its gateway VKs live on the gateway forever. Collect the expired session ids and schedule teardownExpiredSessions, which revokes each session's VKs out-of-band. It deliberately does NOT destroy the workspace: expiry is a lifetime cap, not an explicit Destroy, and "never destroy state without explicit permission" is a hard boundary — the container is left to the spawner's idle reaper (which preserves the workspace) and a later turn re-attaches it via the deterministic id. The live-turn exemption now works as intended too: batch 1a made the coding lane write the agent-run op rows the exemption reads, so an unbounded turn is no longer expired out from under itself.
The destroy route deleted the registry entry, then swallowed any backend destroySession error and still returned 200 destroyed:true. The platform's destroySandbox then flipped the session row destroyed — the "success toast, workspace survives" split-brain: the page shows the session gone while the spawner still owns a live container, so the deterministic per-(org,user) id 409s every future create. Now the route lets the backend error propagate: it restores the registry entry and returns 502 destroyed:false, so sessionDestroy (which throws on non-2xx) surfaces the failure and destroySandbox leaves the row live for a retry. Also guard Docker destroySession: confirm the container is actually gone (sessionExists — false only on a definitive "gone", throws on a daemon hiccup) BEFORE deleting the workspace, so a wedged dockerd can't leave a gutted-but-running container. A workspace rm still runs only once the container is confirmed removed.
A provider error mid-reply, or the stream timeout, threw out of runTurn: the finally deleted the generation but no assistant message was written, partial text was lost, and the user was left with a question and no answer plus a transient toast. The failure was also invisible to the chat-health metrics (messages.error had no writer, so real failures were never counted — or were conflated with guardrail blocks). Catch the stream throw in runTurn and persist an assistant message carrying the failure in the messages.error field (distinct from a guardrail blockedReason), returning a refused outcome so the reason still reaches the seam. The read + render path for `error` already existed (the message view exposes it, message-thread renders it) — only the writer was missing. The other two direct-lane wedges are already covered: a crashed action's stranded generation by the recovery sweep, and a concurrent second send by the at-most-one gate.
The composer advertised two things a coding turn can't honour, which the plan's honesty gate forbids: - Connectors: picked connectors were stored on the thread but never mounted (the MCP bridge is Phase 3), so a selection silently did nothing. listComposerCapabilities now returns none and the capability menu hides the group entirely (skills, which do stage, stay). Both return with the sandbox capability bridge. - Managed-incapable harnesses: the picker listed every shipped harness, including byo-only ones (Cursor) that can't route through the session gateway — a managed turn on one built an inert exec that hung to the deadline. listComposerModels now offers only credentialPolicy.managed harnesses, and startCodingTurn refuses a non-managed one up front (defensive against a stale thread pin or a direct API call). The capability menu keeps its connector-rendering code so it lights up unchanged when the backend starts listing bridged connectors.
Turn the project Agents tab into a per-agent capability binding: the
fixed set of third-party coding agents chat offers, each equipped with
the skills and connectors it runs with in this project. Persisted on the
projects row as agentCapabilities (agentId -> {skills, connectors}) — the
durable, project-scoped analog of a chat thread's per-turn assembly. The
skills/connectors catalog reuses the same org-scoped composer actions
chat reads, so the two surfaces cannot drift. setProjectAgentCapabilities
is RBAC-gated, capped and deduped, and drops an emptied entry so an agent
falls back to its default.
The old project-level model/agent curation editor is replaced, not
augmented; its fields still feed governance and the task directory, so
they and their now-unused components remain for the roster retirement
(Phase C/D) to remove wholesale.
Session reconciliation was opportunistic — it ran only when an admin opened the Sandboxes page (the posture Phase 1 forbids), so a released container left the platform row reading "active" until someone looked, and an always-on (pinned) session lost its pin on every spawner restart: the spawner adopts the container but rebuilds its registry without the flag, so the idle reaper stopped it ~30 min later, and the row then read "Idle · Pinned" for a container that no longer existed. Add reconcileSandboxSessions as a 5-min cron across all orgs: - unpinned + gone → hibernate the row (workspace preserved; next turn resumes it), so the fleet page never shows a dead container as active. - pinned + alive → re-assert the pin to the spawner every cycle, well inside the 30-min idle window, so a restart can't drop it. - pinned + gone → recreate against the preserved workspace so always-on holds; a recreate that keeps failing logs (reaching GlitchTip) as unresolved drift instead of a row silently lying "active". Best-effort per session: sessionIsAlive throws on any non-404, so a transient spawner blip leaves the row for the next tick — never hibernated or recreated on an ambiguous probe. The page-mount reconcile stays as an immediate refresh; the cron is the guarantee.
Contract 4 (internal/IMDS unreachable) held on Docker — the runner sits on an --internal bridge whose only exit is the egress proxy, which REJECTs IMDS + RFC1918 at the IP layer. On k8s nothing enforced it: the pod got advisory HTTP_PROXY env (a process can ignore it) and no NetworkPolicy shipped anywhere, so an unconfigured cluster left cloud IMDS and the whole internal network reachable. The session pod was even labelled tale.sandbox/role=session "as the NetworkPolicy selector" — for a policy that never existed. Ship and apply it. KubernetesBackend.init now ensures a default-deny egress NetworkPolicy that allows session pods egress ONLY to DNS and their own namespace (where the egress proxy + gateway live); everything else — IMDS, the node, other namespaces, the internet directly — is denied by omission. It warns loudly (not hard-fails) if the SA lacks networkpolicy RBAC, since an operator may enforce egress externally and a fatal would wedge the spawner on upgrade; enforcement still needs a NetworkPolicy- capable CNI, which the apiserver accepting the object can't confirm. Adds NetworkingV1Api to the client and locks the fence shape with a unit test; the k8s doc now describes the spawner-applied policy + the two residual operator responsibilities (RBAC, CNI).
A coding turn in a project thread now runs its agent pre-equipped with the project's per-agent binding: getProjectAgentCapabilitiesForThread resolves the thread's project (via threadMetadata.projectId) and returns that agent's bound skills/connectors, and the turn unions the bound skills with the conversation's own composer picks before staging them. Union, not override — selecting a project skill must never silently drop a conversation one. Skills only for now: connectors remain carried-but-unstaged (no connector->MCP bridge exists yet, for chat threads either), which is the next slice.
Phase 2 observability, backend half. The turn-fact prereqs already landed (op rows + messages.error); this adds the durable dashboard source and the aggregation, so the plan's release-gate numbers are computable. - sandboxTurnEvents: a durable sidecar (one row per settled turn) that OUTLIVES the session — the op rows are session-scoped and purged on teardown, so history would vanish. Carries only the turn shape (outcome / duration / harness / spend / recovered), never a prompt. - finalizeCodingTurn records it on the exactly-once winner, so each turn counts once; the deadline path marks outcome=timeout, a user Stop marks cancelled, a watchdog-settled turn marks recovered. Threaded the harness through every finalize call site. - getCodingTurnMetrics aggregates a window into the SLO: success rate (excluding user cancels, per the plan's 非用户取消), timeout rate, duration p50/p95, spend, and a per-harness breakdown. Admin-gated (developerSettings) like the Sandboxes page, capped so the reactive scan stays bounded. New table is data-safe (schema-snapshot: no migration). Locks the aggregation math + the access gate with tests. Cold-start/resume latency is a follow-up (needs create-timing plumbing).
Surfaces the durable sandboxTurnEvents the backend now records as a Settings → Metrics → Coding turns page, so the plan's release-gate numbers are visible, not just computable: total turns, success rate (excluding user Stops), timeout rate, p95 duration, stopped + recovered counts, and a per-coding-agent breakdown. Reuses the shared metrics kit (MetricsLayout, the 7/30/90 period select, StatCardGrid) and the admin-gated getCodingTurnMetrics query. Adds the nav entry + en/de/fr strings; prop-driven render + axe tests.
Phase 2 circuit breaker. Builds on the turn-SLO events: getHarnessHealth reads the recent sandboxTurnEvents window per harness and flags one degraded when enough recent turns failed or timed out (a user Stop doesn't count, and it won't trip below a minimum sample). The composer's agent picker subscribes reactively and marks a degraded harness with a "recently failing" suffix + warning icon — a degradation hint, not a block, so the user chooses informed. Clears as soon as the harness recovers. en/de/fr + query tests.
Phase 2 quota product path. getSandboxQuotaUsage reports per-budget (agent / run-code / workflow / render) in-flight session usage against the org cap — counting the creating+active rows that hold a slot, the exact set the reserve enforces (a stopped session freed its slot). The Sandboxes page shows each as a "used / cap" badge that turns yellow at ≥80% and red at the limit, so pressure is visible before a hard refusal rather than only as a failed turn. Admin-gated; en/de/fr + query tests.
The repo-root .env doubles as docker compose's env_file, so the CLI mints container paths into it (TALE_CONFIG_DIR=/app/data). Bun auto-loads that file into process.env before the dev scripts run, so the container path masqueraded as an explicit shell override, won every downstream "process.env wins" merge, and the engine's explicit-key sync pushed it into the local Convex deployment on every boot — org scaffolding then died on the host with EACCES: mkdir '/app' and new orgs came up with no skills, agents, or governance (the "workspace didn't finish setting up" banner). loadEnvFiles now drops /app-prefixed TALE_CONFIG_DIR / TALE_CONFIG_BUILTIN_DIR from process.env and the merged file map when /app does not exist on the host, so a platform .env override lands and the engine defaults apply otherwise. Inside a real container /app exists and nothing changes.
larryro
added a commit
that referenced
this pull request
Sep 5, 2026
lib/automations/expression.ts (731 lines) translated the retired step runner's filter grammar into the engine's template grammar, and nothing ever called it: repo-wide, translateExpression / translateTemplate / ExpressionScope / StepOutputKind appear only in the module and its own test, and the file's history is its landing commit (#2857) plus a refactor touch. knip missed it because the colocated vitest file is an entry, and lib/automations/** is not on the parking list — a module kept alive by its own tests is dead code outside the debt ledger. Finding: automations-domain-3.
This was referenced Sep 17, 2026
Israeltheminer
added a commit
that referenced
this pull request
Sep 22, 2026
useChannelOptions returned a frozen empty array since #2857, and the facet is guarded on a non-empty list, so no Channel control rendered while ?channel=<slug> still filtered server-side invisibly. The derivation it claimed was offline is not: useInboxAvailability and conversations/queries:apiSources both answer. Options are the org's email connectors by title plus each distinct API source by its own slug.
This was referenced Sep 27, 2026
Closed
Closed
This was referenced Sep 27, 2026
yannickmonney
added a commit
that referenced
this pull request
Sep 27, 2026
Linking the baked skills into every harness's user-level skill directory made the repository-over-bake rule depend on each loader: Claude Code ranks user skills above project skills, Codex lists both copies and OpenCode keeps whichever finishes loading last. The per-turn reconcile that withdrew the baked link went away in #2857. runnerd now owns the links (daemon/src/baked-skills.ts) instead of the entrypoint. It reconciles at boot and before every exec: while the workspace ships <name>/SKILL.md in .claude/skills or .agents/skills, the baked link of that name leaves the same directory under HOME, and it comes back once the repository drops the skill. A directory or live link of someone's own is still never touched. The image conformance test now runs every managed harness's golden exec through runnerd: with a repository copy in both directories every harness lists that copy (Hermes, which reads no project skills, keeps the baked one), and the links are withdrawn and restored. Refs #2790
4 of 5 tasks
larryro
added a commit
that referenced
this pull request
Sep 30, 2026
EmailPreview routes every remote image an email draws through /api/image-proxy, but the route went with the Convex HTTP router in #2857 and was never registered on the new backend, so it answered 404 and no remote image in any email has rendered since. GET /api/image-proxy is back as a session-gated door, charged per person on a new security:image-proxy lane. It fetches through the SSRF-safe client with a new credentialless option: with no credential to leak, plaintext http and redirects onto another public host are admitted, while every hop is still resolved, checked and pinned and private and metadata addresses stay refused. It caps an image at 10 MB, runs at most 16 fetches at once per process, and serves only a raster type detected from the bytes; SVG and anything else are refused whatever the host claims. Responses carry a sandboxing CSP and private caching.
This was referenced Nov 4, 2026
2 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Replaces the retired AI/automation backend with a benchmark-validated rewrite built on one workflow engine, YAML-first configuration, and a clean capability surface. Every org data model migrates via versioned, reversible, corpus-covered migrations; every user-visible feature is rebuilt rather than dropped.
Core
services/platform/lib/engine/) — a pure, typed core: one{{ }}template grammar, coded+hinted validation, deterministic JSON repair, derived-edge execution (when/elseOf/forEach/repeatUntil/onError), a sandboxedCodeRunnerseam, and a 12-method dispatch exposed over HTTP and MCP. Purity is enforced by an import-scan selftest.configs/; one safe loader; SOPS secret sidecars.Domains
subscription-brokerauth method. No auto-routing.connector.yml(deterministic mock + live body), multi-credential, OAuth flows, one dispatcher with asystemcaller mode, nativeimap-smtp/webdavbackends, per-credential endpoint/config.visibility: private|org); agents are slim YAML (no starters, per-agent model, timeout, env, or routing).Harness configs are config-first. Docs are rewritten across en/de/fr. The retired
.old/reference tree and the_findings/benchmark corpus are removed.Verification
bun run checkgreen across all workspaces except the pre-existing machine-localpdftotextdaemon test: platform 73,450 tests,@tale/ui1,147, docs 194, migrations 498 across 106 folders with all fourmigrations:checkgates OK, tsc 0, lint 0, SAST 0.Known follow-ups (infrastructure- or decision-gated)
convex codegen:_generated/api.d.tsis hand-maintained (all reconciles + passes tsc); regenerate against a running backend before merge.node-vmis the tested fallback in use.