I've read the research document. Let me now verify the current state of the files identified as needing conversion and gather additional context.
Assistant
Good, research is complete. Here's what I found:
Current state verified — all 12 files still have manual patterns. Key nuances:
delivery-recovery.ts has an additional raw err at line 142 (not just the two ternaries at 89/149)
connections.ts sentinel check is safe to convert — "no_token_found" is actually dead code (never thrown anywhere), and the real sentinels ("token_expired:*") are always new Error(...) so parseError behaves identically
prompt-input.tsx uses a hardcoded UI string fallback ("Failed to upload attachment.") — parseError would change this to String(error) for non-Error objects, which isn't user-friendly
vendor/embed/cohere.ts is a re-throw pattern, not a log pattern — parseError simplifies it but the wrapping throw new Error(...) remains
Three design decisions from the research's open questions:
packages/ui — I'd recommend skipping this one. The fallback is an intentional user-facing string, not generic error extraction. Adding @vendor/observability as a dependency for one site that semantically differs from the others isn't worth the coupling.
vendor/embed — I'd recommend including it. The pattern becomes cleaner (throw new Error(\...: ${parseError(error)}`)`) and handles non-Error objects instead of re-throwing them raw.
packages/app-rerank — Yes, convert. Already has the dependency, and raw error objects in structured logs are inconsistent with the rest of the codebase.
Do you agree with these decisions? Any adjustments before I structure the phases?
User
i'm just thinking right now, should we actually introduce a package like neverthrow or something more recent to solve any async problems at consumer level. we maintain clean non try/catch in vendor pacakges for example. what is the most accretive, innovative, radical and creative solution to increase developer experience by 100x and improve long-term maintainability without introducing code smells
Assistant
Great question — this is worth thinking through properly before we commit to a direction. Let me research the current landscape and how it maps to your codebase's actual pain points.
Assistant
This is a much more interesting question than "where to sprinkle parseError." Here's what the research revealed:
The actual problem
Your codebase already has two competing Result implementations and four different discriminated union shapes:
parseError solves the symptom (manual ternaries) but not the disease (inconsistent error contracts, untyped catch blocks, no compiler enforcement).
The framework constraint
Inngest requires thrown errors for retry logic. NonRetriableError vs plain Error is the control mechanism. A Result<T, E> return from a step.run() would be treated as success — Inngest would never retry. tRPC doesn't support per-procedure typed errors yet (two open PRs, neither merged as of April 2026).
This means: Result types can't replace throws at framework boundaries. But they CAN replace throws at every layer below the boundary.
The radical approach: Typed Results below, boundary adapters above
The strategy:
User
i'm just thinking right now, should we actually introduce a package like neverthrow or something more recent to solve any async problems at consumer level. we maintain clean non try/catch in vendor pacakges for example. what is the most accretive, innovative, radical and creative solution to increase developer experience by 100x and improve long-term maintainability without introducing code smells
consider this: we dont really care about ai-sdk for now. we only care about whats truly the actual high-impact related paths: db calls, calls in @api/platform/src/inngest/ to async things, etc.
with that said, perhaps there are better ways to design our architecture.
consider this: what if we make everything go through trpc. we have 100s of new trpc routes doing small contained things.
this way, inngest is pure. trpc handles all errors and propagates to the layer.
scrutinize this approach.
i understand this "adds" more processing time but consideer if having single layer for all async calls > simpler observability layer.
whatwe dont care about: ai streaming, early-access, etc, etc.
Assistant
Let me research the current Inngest function patterns and tRPC middleware before I give you my honest take on this.
Assistant
Now I have the full picture. Let me give you my honest assessment.
Scrutinizing the tRPC-for-Everything Approach
The insight is correct. The proposal is not.
The insight: Inngest lacks the observability middleware that tRPC has. tRPC's createObservabilityMiddleware at vendor/observability/src/trpc.ts:41 is a complete error boundary — every procedure passes through it, errors are classified by status code, logged, and captured in Sentry. Inngest has nothing equivalent. The only middleware on the Inngest client is sentryMiddleware() (captures exceptions, creates spans — but no BetterStack logging, no request context, no journal emission).
Why tRPC-for-everything doesn't work:
Impedance mismatch with Inngest's error model. Inngest's retry mechanism depends on thrown exceptions. NonRetriableError stops retries; anything else retries. tRPC's error model is HTTP codes (NOT_FOUND, BAD_REQUEST, INTERNAL_SERVER_ERROR). If a tRPC procedure throws TRPCError({ code: "NOT_FOUND" }), Inngest will retry it — because it's not a NonRetriableError. You'd need a mapping layer at every step boundary to translate tRPC errors back into Inngest's retry semantics. That mapping layer IS the try/catch you're trying to eliminate.
Best-effort patterns break. Four of your Inngest steps intentionally catch-and-continue (cancel-backfill, revoke-token in connectionLifecycle; per-token refresh in tokenRefresh; per-delivery replay in deliveryRecovery). With tRPC-for-everything, these would need the same try/catch wrapping around the tRPC call. The error handling doesn't move into tRPC — it just gets an additional layer.
Route explosion. Your 11 Inngest functions contain ~40 distinct step.run calls. Each calls DB queries, token helpers, provider libraries, event sends. "100s of tRPC routes doing small contained things" means 100s of routes that each wrap a single Drizzle query or a single getActiveTokenForInstallation() call. Discovery becomes a mapping exercise: "which tRPC route wraps which library function?"
Serialization overhead on the hot path.platformEntityWorker runs in a pagination loop — fetch page, dispatch events, check rate limit, sleep, repeat. Each iteration has 2 step.run calls. Even with createPlatformCaller (no HTTP), you'd add Zod input validation + context creation + middleware chain execution on every iteration. At scale (backfilling thousands of entities), this compounds.
User
i'm just thinking right now, should we actually introduce a package like neverthrow or something more recent to solve any async problems at consumer level. we maintain clean non try/catch in vendor pacakges for example. what is the most accretive, innovative, radical and creative solution to increase developer experience by 100x and improve long-term maintainability without introducing code smells
consider this: we dont really care about ai-sdk for now. we only care about whats truly the actual high-impact related paths: db calls, calls in @api/platform/src/inngest/ to async things, etc.
with that said, perhaps there are better ways to design our architecture.
consider this: what if we make everything go through trpc. we have 100s of new trpc routes doing small contained things.
this way, inngest is pure. trpc handles all errors and propagates to the layer.
scrutinize this approach.
i understand this "adds" more processing time but consideer if having single layer for all async calls > simpler observability layer.
whatwe dont care about: ai streaming, early-access, etc, etc.
note: im not talking about inngest steps being converted to trpc. im advocating that when db is called the inngest step calls a trpc procedure. when inngest needs to call cohere, it doesn't just call cohere, it calls our trpc layer's cohere procedure.
Assistant
This is a great question worth thinking through carefully. Let me scrutinize the tRPC-as-internal-service-bus approach and also explore what might actually be the highest-leverage solution.
Assistant
Here's my honest assessment. The research gives me concrete numbers to scrutinize the tRPC proposal against.
The Surface Area
Across 11 Inngest function files in api/platform/:
~40 direct DB calls (Drizzle selects, inserts, updates)
Only 12 of ~67 call sites have their own try/catch — the other 55 rely on Inngest step retry
Scrutiny of the tRPC-as-Service-Bus Proposal
The good intuition: You want a single layer that normalizes all error handling so Inngest functions are pure orchestration. That instinct is correct.
Why tRPC is the wrong tool for this:
Auth overhead is wasted internally. The current createCaller pattern signs a JWT, constructs Headers, runs verifyServiceJWT — all to satisfy serviceProcedure. Inside Inngest, there's no user. You'd need a new inngestProcedure tier that skips auth, which removes the middleware value proposition that makes tRPC worth using.
60+ new procedures for in-process calls. You'd go from 11 procedures to ~70. Each needs Zod input/output schemas for calls that are already type-safe via Drizzle inference and function signatures. That's not DX improvement — it's ceremony.
Inngest step semantics fight tRPC error semantics. Inngest has NonRetriableError (permanent failure) vs bare throw (retriable). tRPC has INTERNAL_SERVER_ERROR, NOT_FOUND, etc. You'd need to map between two error systems in every procedure. Who decides retry policy — Inngest or tRPC?
Transaction atomicity breaks.platform-event-store.ts step "upsert-entities-and-junctions" does Promise.all(entities.map(db.insert(...))) then db.insert(orgEventEntities). If each is a tRPC call, you lose the step's atomicity guarantee. If you bundle them into one compound tRPC call, you haven't gained anything.
DB calls gain nothing.db.select().from(gatewayInstallations).where(eq(id, x)) is already fully typed via Drizzle. Wrapping it in platform.installations.getById(x) adds Zod re-validation + JWT overhead + indirection for zero type safety benefit.
User
iwell, it's not really observability that is the gap. it's developer maintainability. having every async call in 1 place (trpc layer) IMO does wonder for maintainabiility. I know where everything lives. i dont need to go to inngest to debug. i go to trpc. ultrathink
Assistant
You're right — I was framing this as an observability problem when you're thinking about it as a structural maintainability problem. Let me reconsider from that angle.
Re-examining: What tRPC-as-Service-Bus Actually Gives You
Your core insight: "I know where everything lives" — is about locality and discoverability, not error handling.
Right now, platform capabilities are fractured across:
3 tRPC routers (only for external-facing operations)
Direct DB calls scattered across all of the above
When debugging "why did token refresh fail?", you currently trace through: Inngest step → getActiveTokenForInstallation in token-helpers.ts → updateTokenRecord in token-store.ts → decrypt in @repo/lib. The logic for "tokens" lives in 4 files across 3 directories.
With tRPC procedures:
code
platform.tokens.resolve(installationId) → one procedure
platform.tokens.refresh(installationId) → one procedure
platform.tokens.revoke(installationId) → one procedure
"Where does token stuff happen?" → tokens router. Done.
question, what if we also expand this to the whole of @apps/platform/src/app/api/
Assistant
Good question. The research shows 6 routes — 4 of which have real business logic:
Route
Can become tRPC endpoint?
Can delegate logic to tRPC?
/api/inngest
No (SDK protocol)
N/A (just serve())
/api/health
No (infra probe, no auth)
Nothing to extract
/api/ingest/[provider]
No (HMAC needs raw body)
Yes — DB insert + Inngest dispatch
/api/connect/[provider]/authorize
No (browser navigation)
Yes — already has tRPC twin
/api/connect/[provider]/callback
No (OAuth redirect + HTML)
Yes — 200+ lines of token exchange, DB upsert, encryption, Redis
/api/connect/oauth/poll
No (state-token auth)
Yes — Redis read
The routes themselves stay as raw HTTP (they must — HMAC verification, browser redirects, HTML responses). But the business logic inside them becomes tRPC procedure calls. The routes become thin HTTP adapters:
ts
// /api/ingest/[provider]/route.ts — AFTER
export async function POST(req, { params }) {
// HTTP-only concerns stay here
const rawBody = await req.text();
const verified = verifyHmacSignature(provider, rawBody, headers);
if (!verified.ok) return Response.json(verified.error, { status: 401 });
// Business logic → tRPC
const platform = createInternalCaller();
const result = await platform.webhooks.persistAndDispatch({
provider, deliveryId, resourceId, payload,
});
return Response.json(result);
}
The OAuth callback — currently the messiest file with token exchange + DB upsert + encryption + Redis state all in one 200-line function — decomposes into:
ts
User
let's focus on trpc setup first. instead of doing the whole upgrade. let's focus on purely settings up the callers + communication logic.
Assistant
Let me read the exact files I need to write precise code for the plan.
Assistant
Now I have everything I need. Let me write the plan — scoped purely to the internal tRPC infrastructure.
Assistant
Plan created at thoughts/shared/plans/2026-04-06-internal-trpc-caller-setup.md.
Summary — 3 small phases:
Add internalProcedure to trpc.ts — new auth type { type: "internal"; source: string }, observability middleware, no auth check. 3 edits to one file.
Convenience callers — api/platform/src/inngest/platform.ts exports platform = createInternalCaller("inngest") for Inngest functions. apps/platform/src/lib/internal-caller.ts exports platform = createInternalCaller("route") for route handlers.
Total: ~60 lines of new code across 5 files + 3 small edits. No existing behavior changes. Should the follow-up migration plan be a separate doc or do you want to review/adjust this one first?
User
why does this use "ping" system
Assistant
You're right — it's throwaway scaffolding. The first real procedure migration will validate the pattern. Let me remove it.
Assistant
Now let me also remove the internalProcedure import since the router file no longer uses it directly, and clean up the manual verification reference to ping.
Assistant· <synthetic>
Done. The router is now just an empty createTRPCRouter({}) — the first real migration will prove the chain. Ready to
User
[Request interrupted by user]
User
i changed my mind. i can see value in having that ping for first time testing.
Assistant
Restored. Ping is back — makes sense for validating the full middleware chain on first use.
User
question, what if we also expand this to the whole of @apps/platform/src/app/api/inngest/
also: also have a look at @api/platform/src/root.ts and figure out where these procedures are being consumed.
afaik, apps/platform is PURELY server-side. given this we should be able to expand the whole apps/platform layer into using trpc as source of truth.
Assistant
Let me look at the current state of both files and trace where platform procedures are consumed.
Assistant
Good instinct. Here's what I found:
Current Consumer Map
platformRouter (external, with JWT auth) — 11 procedures across 3 sub-routers:
api/app/src/router/org/connections.ts — 7 call sites via createPlatformCaller()
apps/app/src/lib/proxy.ts — 2 call sites via createPlatformCaller()
apps/platform/src/lib/internal-caller.ts — creates caller, not yet used by any route handler
apps/platform Is Indeed Purely Server-Side
Confirmed. No client components, no Clerk, no UI. Just 7 API route handlers:
Route
Current Implementation
Could Use Internal tRPC?
/api/health
Static JSON
No (trivial)
/api/inngest
Mounts 11 Inngest functions
Functions themselves → yes
/api/ingest/[provider]
Direct DB + inngest.send() + webhook verification libs
Yes — all async work
/api/connect/[provider]/authorize
Calls buildAuthorizeUrl() from lib
Yes
/api/connect/[provider]/callback
Calls processOAuthCallback() from lib
Yes
/api/connect/oauth/poll
Calls getOAuthResult() from lib
Yes
/api/trpc/[trpc]
HTTP adapter for platformRouter
N/A (already tRPC)
What "Expand to the Whole of apps/platform" Means
Three layers of migration, building on what Phase 1/2 of the existing plan already established:
Layer A: Route Handlers → Internal tRPC
The 4 non-trivial route handlers (ingest, authorize, callback, poll) currently call @api/platform lib functions directly. These become thin HTTP adapters that delegate to internal procedures:
User
yes perfect. generate this next plan for phase 2
Assistant
Let me read the current state of the files involved to write precise edit instructions.
Assistant
Now let me read the lib functions that route handlers currently delegate to.
Assistant
Now let me also check the existing serviceProcedure router implementations that might share logic with the new internal procedures.
Assistant
Now I have the complete picture. Let me read one more file to understand the cache module used in the ingest route.
Assistant
Good. I now have all the context needed. Let me write the Phase 2 plan.
Assistant
Good. Now I have everything. Let me write the plan.
Assistant
Plan written to thoughts/shared/plans/2026-04-06-route-handlers-to-internal-trpc.md.
Summary — 3 phases:
webhooks sub-router — Move ingest endpoint logic (HMAC verify, DB persist, Inngest dispatch) into platform.webhooks.ingest(). Route handler becomes ~30 lines: parse request, call procedure, map TRPCError codes to HTTP status.
oauth sub-router — Move authorize/callback/poll into platform.oauth.{buildAuthorizeUrl, processCallback, pollResult}(). Callback route handler drops from 69 lines of lib delegation to pure response mapping. The manual err instanceof Error ? err.message : "unknown" at callback.ts:351 gets eliminated by tRPC middleware.
Cleanup — Verify zero direct @db/app, @api/platform/lib, or Inngest client imports remain in route handlers (except the Inngest serve mount).
Key design decisions baked in:
New files go in api/platform/src/router/internal/ (parallel to router/platform/)
Internal procedures use Zod input schemas (consistent with existing tRPC patterns, enables future HTTP exposure if needed)
processCallback returns CallbackProcessResult as-is — the route handler still does the redirect/HTML/error response mapping since that's HTTP-specific
The lib layer stays — procedures call lib functions, not the other way around. Lib is implementation, procedures are interface.
User
qiestopm whats is the purpose of router/platform?
Assistant
api/platform/src/router/platform/ holds the external-facingserviceProcedure routers — the ones served over HTTP at /api/trpc/[trpc] and called cross-service by apps/app via JWT-authenticated createPlatformCaller().
They're assembled into platformRouter in root.ts and mounted on the HTTP handler.
The distinction with the new router/internal/:router/platform/ = JWT-guarded, HTTP-served, called by other services. router/internal/ = no auth, never HTTP-served, called in-process by Inngest functions and route handlers.
Two separate directories because two separate trust boundaries.
User
what are the consumers of router/platform?
Assistant
From the earlier research — there are exactly 9 call sites across 2 files, all going through createPlatformCaller():
api/app/src/router/org/connections.ts — 7 sites:
Line 48: platform.connections.getAuthorizeUrl()
Line 118: platform.connections.disconnect()
Line 218: platform.proxy.execute() — GitHub App validation
Line 316: platform.proxy.execute() — get-repo + get-file-contents loop
Line 462: platform.connections.disconnect() — Vercel path
Line 683: platform.proxy.execute() — inside enrichInstallation
Line 749: platform.proxy.execute() — inside listResources
apps/app/src/lib/proxy.ts — 2 sites:
Line 38: platform.proxy.execute() — per-installation in Promise.all
Line 267: platform.proxy.execute() — single call in proxyCallLogic
All 9 use the JWT-signed in-process caller (no actual HTTP hop). The HTTP handler at /api/trpc/[trpc] exists but has no active consumers today — it's there for future cross-network calls.
User
so these are basically api/app calling the platform-layer?
Assistant
Yes, exactly. api/app is the app-layer tRPC API (user-facing, Clerk-authed). When it needs platform capabilities (tokens, proxy calls, connections), it calls down into api/platform via createPlatformCaller().
The router/platform/ procedures are the contract between those two layers.
User
im just curious should we fundamentally change how the api layer works. seems like lots of confusing layers, maybe single api folder. everything runs through that layer. would eliminate many layers of complexity. what do you think? just high-level with what youve researched so far
Assistant
Honest take: the layers exist for real reasons, and collapsing them would create worse problems than the current indirection.
api/platform = service-facing, JWT auth, no user context. Runs inside apps/platform (port 4112). Handles secrets (OAuth tokens, encryption keys, webhook signing secrets) that should never be in the app process.
If you merge them into one API folder:
Token vault secrets leak into the app bundle — ENCRYPTION_KEY, SERVICE_JWT_SECRET, provider OAuth client secrets all become available in the app process
Clerk auth and JWT auth have to coexist in one tRPC context — every procedure needs to know "am I handling a user request or a service request?"
Deployment coupling — a change to webhook ingestion redeploys the user-facing app and vice versa
Inngest function registration doubles — one serve handler mounting both app workflows and platform workflows
The real confusion isn't the layers — it's the call direction. Today:
Two routers, one package (api/platform), two trust boundaries. The confusion goes away not by merging packages, but by making everything inside api/platform flow through tRPC — which is exactly what we're doing.
User
are you 100% sure of these concerns? why not just server the entirity of everything through api/platform. idk, feels like it would be cleaner. re-evaluate.
Assistant
You're right to push. Let me re-evaluate honestly — some of my concerns don't hold up.
Concern 1: "Secrets leak into the app bundle" — Wrong. Secrets are env vars on the Vercel deployment, not in the package. apps/app simply doesn't have ENCRYPTION_KEY configured. The package boundary doesn't protect this — the deployment boundary does.
Concern 2: "Clerk and JWT auth coexist" — True but trivial. They're already separate procedure tiers. One package with userProcedure (Clerk), serviceProcedure (JWT), internalProcedure (none) is clean.
Concern 3: "Deployment coupling" — Already exists. Changing api/platform → rebuilds packages/platform-trpc → rebuilds api/app → rebuilds apps/app. The bridge doesn't decouple; it adds a hop.
Concern 4: "Inngest registration doubles" — Wrong. Each app mounts its own serve handler. Functions are defined in the package but registered per-deployment.
So the real answer: a single api/ package would be cleaner. It would eliminate packages/platform-trpc entirely, kill the JWT ceremony for in-process calls, and give you one router tree.
The reason I'd still wait: the migration is large (merging ~30+ files, updating all imports, reconciling two env validation schemas, removing the bridge package) and orthogonal to what we're doing now. The internal tRPC work already fixes the immediate pain — Inngest and route handlers flowing through tRPC. The two-package merge is a follow-up that becomes easier after everything flows through routers, because then you're just moving routers between packages instead of untangling scattered lib calls.
If you want to do it, the sequence would be: finish internal tRPC migration (Phases 2-4) → merge api/app + api/platform into api/ → delete packages/platform-trpc. Doing it in that order means the merge is mechanical (move routers, update imports) rather than architectural.
Standardize on neverthrow as the single Result type (already in your catalog at ^8.2.0, mature, zero deps, ~2KB, first-class async with ResultAsync)
Migrate the custom core/ai-sdk Result to neverthrow (structurally identical, gains safeTry, fromPromise, ResultAsync for free)
Vendor packages return ResultAsync<T, TypedError> instead of throwing — callers know exactly what can fail
Create thin boundary adapters in @vendor/observability:
unwrapForInngest(result) → throws Error or NonRetriableError based on error variant
unwrapForTRPC(result) → throws TRPCError with the right code
unwrapForRoute(result) → returns NextResponse with the right status
parseError becomes the third-party escape hatch only — used at the boundary where external code throws
Unify all ad-hoc discriminated unions (AuthResult, AuthorizeResult, CallbackProcessResult, ValidationResult) onto neverthrow's Result
The result: zero try/catch in business logic. Framework boundaries are the only place errors are thrown, and even those are one-liner adapter calls. Every function has a typed error contract. The compiler enforces exhaustive handling.
What this is NOT
Not Effect-TS (v4 still beta, 25KB+ bundle, Next.js edge runtime issues, massive learning curve)
Not Go-style [err, data] tuples (loses type safety on the error channel)
Not a new custom implementation (neverthrow is already in the catalog and battle-tested)
Migration path (incremental, not big-bang)
Phase 0: Promote neverthrow from single-consumer to monorepo-wide. Create boundary adapters.
Phase 1: Migrate vendor packages (pinecone, embed, upstash) to return ResultAsync — these are the error sources
Phase 3: Migrate core/ai-sdk custom Result → neverthrow
Phase 4: Unify ad-hoc discriminated unions
The remaining parseError sites get cleaned up naturally as their callers switch to Result returns
Does this direction resonate? Before I write the full plan, I want to align on:
Are you comfortable with neverthrow as the standard? (vs expanding your custom Result, vs a lighter alternative like @badrap/result)
Scope: full migration across all layers, or start with vendor packages + boundary adapters only?
The core/ai-sdk custom Result — is there a reason it was hand-rolled instead of using neverthrow? (neverthrow was already in the catalog when that code was written)
tRPC already HAS the single error boundary — for tRPC routes. Your connections.ts, backfill.ts, proxy.ts routers already benefit from the observability middleware. The gap is only in the Inngest layer.
Why neverthrow Doesn't Fit Either
You already have it in packages/app-config/src/parse.ts (the only consumer). The problem: Inngest's contract requires thrown exceptions. If you return Err(...) from a step.run callback, Inngest treats it as a successful step with an error-shaped return value — no retry, no failure logging. You'd end up with .unwrapOrThrow() at every step boundary, which is MORE boilerplate than the current approach, not less.
Result types work beautifully for synchronous pipelines and API response shaping. They fight against frameworks that use exceptions for control flow (Inngest, tRPC's error handling, Next.js error boundaries).
The Actually Radical Solution: Inngest Observability Middleware
Inngest has a middleware API (new InngestMiddleware(...)) with per-function and per-step lifecycle hooks. You already use it for Sentry. The missing piece is an observability middleware that mirrors what your tRPC middleware does:
code
tRPC has: createObservabilityMiddleware → logs, Sentry, request context, journal
Inngest has: sentryMiddleware() → Sentry spans only
→ NO logging, NO request context, NO journal
What an Inngest observability middleware would provide:
With the middleware, the DEFAULT behavior (log + re-throw for retry) requires ZERO code. The only time you write error handling is when you DEVIATE from the default (best-effort swallow, NonRetriableError classification). And even then, parseError is available for the extraction.
This eliminates the entire category of "manual error extraction patterns" — not by converting 15 sites, but by making the middleware handle the common case automatically. The 15 sites become a mop-up of edge cases rather than the core problem.
Proposed Plan Structure
Given all this, here's what I think the plan should be:
Phase 1: Inngest Observability Middleware — Create vendor/observability/src/inngest.ts that provides per-function and per-step observability hooks (logging, request context, error classification). Register it on the platform Inngest client alongside sentryMiddleware().
Phase 2: Adopt parseError in remaining manual sites — The 15 remaining sites become a smaller, focused mop-up. The middleware handles the common case; these are the intentional deviations (best-effort catches, sentinel comparisons, etc.).
Phase 3: Skip packages/ui and vendor/embed — As discussed earlier. One is a UI fallback string, the other is a re-throw pattern in a package without the dependency.
Does this direction resonate? Should I dig deeper into Inngest's middleware API to validate the hooks we'd need, or do you want to adjust the scope?
The observability gap is specifically in Inngest, not tRPC. Your tRPC observability middleware (vendor/observability/src/trpc.ts) already logs, traces, and captures exceptions for every tRPC call. The gap is that Inngest has only sentryMiddleware — no structured logging, no parseError normalization. Routing calls through tRPC would be using tRPC's middleware to compensate for Inngest's missing middleware. The direct fix is: add the middleware where it's missing.
What I Think the Actual 100x DX Solution Is
Custom Inngest observability middleware — the same pattern you already built for tRPC, applied to the layer that actually needs it.
Inngest's middleware API exposes transformOutput which fires after every step. You can build:
ts
// One middleware, covers ALL steps in ALL functions, automatically
const observabilityMiddleware = new InngestMiddleware({
name: "platform-observability",
init: () => ({
onFunctionRun: ({ fn }) => ({
transformOutput: ({ result, step }) => {
if (result.error) {
log.error(`[${fn.id}] ${step?.displayName ?? "function"} failed`, {
error: parseError(result.error),
functionId: fn.id,
stepId: step?.id,
});
}
},
}),
}),
});
This means:
Zero changes to existing Inngest functions — middleware wraps everything automatically
55 unguarded call sites get error logging for free (they currently have nothing)
12 manual catch sites can drop their parseError / ternary patterns where the catch was only for logging
Future functions get observability by default — impossible to forget
Inngest functions stay pure orchestration — exactly what you wanted
Then the remaining work is just the 12 manual sites in the research doc (the ones where the catch does more than log — like best-effort steps, sentinel checks, etc.).
This is strictly better than the tRPC approach because:
It covers more (all 67 sites vs only the ones you remember to route)
It adds zero procedures, zero schemas, zero auth overhead
It works with Inngest's step semantics instead of fighting them
It's the same architectural pattern you already validated in vendor/observability/src/trpc.ts
Do you want me to plan around Inngest observability middleware + the 12-site parseError cleanup? Or do you want to push further on the tRPC direction?
That reads like a spec, not implementation. You can understand the workflow without reading any of the procedure internals.
The Genuine Wins (Not Just Error Handling)
One canonical location per capability. Token ops → tokens router. Installation ops → installations router. Provider API calls → providers router. No ambiguity.
Inngest functions become skeletal. Pure orchestration — step sequencing, conditionals, fan-out. Zero business logic. When a step fails, you go to the procedure, not the Inngest function.
Free middleware for everything. Your existing tRPC observability middleware (vendor/observability/src/trpc.ts) — structured logging, Sentry tracing, request journaling — applies to ALL operations automatically. Not just the 11 HTTP-facing procedures, but every DB call, every provider API call.
Testability without Inngest. You can unit test platform.tokens.resolve() with a direct caller and a test DB. Today, testing token resolution means either running Inngest or extracting the step callback manually.
Reusability.platform.tokens.resolve() is callable from Inngest, from API routes, from tests, from future services — all through the same typed interface. Today's getActiveTokenForInstallation(installation, config, providerDef) requires you to assemble 3 arguments from different sources.
The Design Questions That Actually Matter
If we do this, these need answers:
1. How does Inngest call tRPC without JWT overhead?
Create a lightweight internal caller that bypasses auth:
No JWT. No headers. Just a direct in-process call with full middleware. The existing serviceProcedure routers stay for cross-service HTTP calls; the internalRouter is for in-process callers.
2. What granularity? Individual DB queries vs domain operations?
This is the critical design decision. Two extremes:
These should stay as a single procedure (platform.neural.upsertEntities) that encapsulates the multi-call logic. The procedure is the unit, not each DB call.
4. Where do NonRetriableError decisions live?
Currently, Inngest functions throw NonRetriableError for permanent failures (bad provider, missing config, etc.). If business logic moves to tRPC procedures, who decides retryability?
Options:
Procedures throw specific error codes (NOT_FOUND, BAD_REQUEST) and the Inngest step maps them to NonRetriableError
Procedures throw NonRetriableError directly (couples procedures to Inngest)
Custom error classes that both systems understand
I'd go with option 1 — tRPC procedures throw standard tRPC errors, and a thin utility in the Inngest layer maps codes to retry policy:
ts
// Small helper
const nonRetriable = (codes: TRPCErrorCode[]) => async <T>(fn: () => Promise<T>) => {
try { return await fn(); }
catch (e) {
if (e instanceof TRPCClientError && codes.includes(e.data.code))
throw new NonRetriableError(e.message);
throw e;
}
};
// Usage in Inngest
await step.run("get-connection", nonRetriable(["NOT_FOUND", "BAD_REQUEST"])(() =>
platform.connections.getActive(installationId)
));
5. The internal router must NOT be HTTP-exposed
The internalRouter skips auth. It must not be mounted on the HTTP serve handler. Only platformRouter (with serviceProcedure auth) and adminRouter get served. internalRouter is only accessible via createInternalCaller().
Honest Trade-offs
What you gain:
Structural clarity (one tree of capabilities)
Free observability on all operations
Inngest functions that read like workflow specs
Testability without Inngest harness
Consistent error handling everywhere
What it costs:
Migration effort: refactoring ~40 DB calls and ~16 external calls into ~25 procedures, plus updating 11 Inngest functions to use the caller
Zod input schemas for each procedure (some boilerplate)
One extra stack frame in every call path (minor)
New developers need to understand the "internal tRPC = service bus" pattern (unconventional but learnable)
What you need to be careful about:
Don't let it drift to fine-grained DB wrapping — keep it domain-operation level
Don't expose the internal router to HTTP
Don't let procedures grow business logic that belongs in Inngest orchestration (procedures = capabilities, Inngest = workflow)
My revised take: the tRPC approach is sound if scoped to domain operations (~25 procedures) with a lightweight internal caller. The structural maintainability benefit is real and compounds over time.
Want me to write the plan with this architecture? I'd need your call on granularity (fine-grained vs domain-grained) before structuring the phases.
Every platform capability — DB, Redis, provider APIs, crypto, Inngest dispatch — lives in one typed tree. Inngest functions are pure orchestration. Route handlers are pure HTTP adapters. When something breaks, you go to the procedure.
This is ~30 procedures (domain-grained), not 100+. Adding the route handler operations only adds ~5-8 to the Inngest-derived ~25.
Want me to write the plan with this full scope (Inngest + route handlers → internal tRPC router)?
The current connections, proxy, backfill routers (11 procedures) could potentially be refactored to call internal procedures too — avoiding duplication where a service procedure and an internal procedure do the same thing (e.g., both need "get active token").
Everything flows through the internal tRPC layer. Inngest functions, route handlers, and service procedures all call the same internal procedures. One tree. One place to debug.
This is a significant expansion — from the current 2-phase plan (infrastructure + wiring) to a full architectural migration. Want me to rewrite the plan to cover all three layers? I'd phase it as: