/create_plan @thoughts/shared/research/2026-04-05-parseerror-full-propagation-inventory.md can we actually discuss what is the actually the most superintelligent infrastructure where we dont introduce massive amount of codesmell to whole codebase yet allow all of these different async layers to have parse error. what is the most radical, innovative, accretive design to solve the whole async problem
User
create_plan
/create_plan
@thoughts/shared/research/2026-04-05-parseerror-full-propagation-inventory.md can we actually discuss what is the actually the most superintelligent infrastructure where we dont introduce massive amount of codesmell to whole codebase yet allow all of these different async layers to have parse error. what is the most radical, innovative, accretive design to solve the whole async problem
Assistant· claude-opus-4-6
Great question. You're right to push beyond mechanical find-and-replace — 58 parseError() call sites is already a code smell signal. Let me research the actual infrastructure to find the real leverage points.
I've already read the research doc. Let me now investigate the logging layer, Inngest patterns, and tRPC middleware to understand where errors actually flow.
Assistant· claude-opus-4-6
User
well, i would argue ading log.... to like 58 call sits are also is code smell. think about the core problem. we have async failure problem.
Assistant· claude-opus-4-6
You're right. Let me think harder.
The 58 log.error("...", { error }) calls aren't the solution — they're the symptom. The real problem is: why do 58 catch blocks exist at all?
A catch block should only exist when you need to make a decision based on the error. If you're just catching to log and rethrow, or catching to log and return a generic failure — that's ceremony, not logic. The infrastructure should handle that.
Let me look at what these catch blocks actually do — how many are behavioral decisions vs. pure ceremony.
Assistant· claude-opus-4-6
User
i would now argue that having log caller in like 100 sites is terrible too
Assistant· claude-opus-4-6
User
i have more radical question, is it possible for everything to flow through trpc layer?
Assistant· claude-opus-4-6
That's the right question. Let me check what already exists.
Assistant· claude-opus-4-6
Excellent — now I have the full picture of the error handling infrastructure. Let me synthesize what I've found and lay out the design space.
The Core Problem
The current approach has 58 call sites doing error: parseError(error) and 12-15 sites doing error: err instanceof Error ? err.message : String(err). Both are doing the same thing: callers pre-processing errors because the logger doesn't know how to handle them.
This is backwards. The logger's meta parameter is Record<string, unknown> — it accepts anything in the error field but does nothing with it. So every single catch block in the codebase has to remember to serialize the error before logging. That's the code smell — 70+ sites doing work that belongs in one place.
The Leverage Point
All log calls flow through a single 5-line function:
function enriched(level: LogLevel) {
return (msg: string, meta?: Record<string, unknown>) => {
const normalized = meta && "error" in meta
? { ...meta, error: parseError(meta.error) }
: meta;
pushJournal(level, msg, normalized);
baseLog[level](msg, { ...getContext(), ...normalized });
};
}
What this does:
The logger itself recognizes the error key and normalizes it to a string
Every caller just writes log.error("failed", { error }) — pass the raw catch value
The 58 existing parseError() calls become harmless (idempotent — parseError("string") returns the string)
The 12-15 manual ternary sites work with zero changes (just replace error: err instanceof Error ? err.message : String(err) with error: err)
No new dependency for any package — the change is entirely inside @vendor/observability
Future developers never need to know parseError exists
Tradeoff: BetterStack's jsonFriendlyErrorReplacer already does something useful with raw Error objects (extracts name, message, stack as structured fields). By normalizing to a string, we'd lose stack traces in the error field. But there's a nuance: Sentry already captures full stack traces for server errors via the tRPC middleware. The error field in logs is for human readability, not debugging.
Option B: Dual-Field Logger (Preserve Structure)
ts
const normalized = meta && "error" in meta
? {
...meta,
error: parseError(meta.error),
...(meta.error instanceof Error && { errorStack: meta.error.stack }),
}
: meta;
You get error: "clean message" for filtering/reading + errorStack for when you need the trace. More informative than Option A, slightly more complex.
Option C: Type-Safe Logger Interface
Beyond runtime normalization, tighten the Logger interface:
ts
type LogMeta = Omit<Record<string, unknown>, "error"> & {
error?: unknown; // documented: the logger normalizes this for you
};
This is cosmetic at the type level (since unknown already accepts everything), but it documents the contract. Combined with Option A or B for runtime behavior.
What This Eliminates
Current state
After Option A
58 parseError(error) calls
Just error — redundant wrapper removed over time
12-15 manual ternary sites
Just error: err — works immediately
packages/ui needs @vendor/observability dep?
No — prompt-input.tsx just needs its own 1-line ternary for setError() (not a log call)
vendor/embed needs @vendor/observability dep?
No — the re-throw pattern there isn't a logging concern
packages/app-rerank raw error objects in log
Just works — logger normalizes automatically
Every future developer remembers to call parseError
Never needs to think about it
The "Radical" Part
The truly radical thing here is that this is a 4-line change in one file that eliminates an entire category of problem across the entire monorepo. No new abstractions, no middleware layers, no wrapper functions. Just push the responsibility to where it belongs — the logger — and let the callsites be simple.
Then the cleanup is purely accretive:
Phase 1: Add normalization to enriched() (4 lines)
Phase 2: Clean up the 12-15 manual sites to just error: err (trivial)
Phase 3: Progressively remove parseError() wrapper calls from the 58 converted sites (optional, low priority — they're harmless)
Phase 4: Consider deprecating the parseError export (or keep it for non-logging use cases like the agent error constructors)
Questions before I write the plan:
Option A vs Option B? Do you want the logger to also preserve errorStack for Error instances, or is Sentry sufficient for stack traces and you prefer clean string-only error fields in BetterStack?
Cleanup scope: Should the plan include removing existing parseError() wrapper calls from the 58 sites, or just fix the 12-15 remaining manual sites and let the redundant wrappers age out naturally?
The prompt-input.tsx and vendor/embed/cohere.ts cases — these aren't logging sites (one sets React state, one re-throws). They're fundamentally different from the logging problem. Should we leave them as-is, or do you want a separate approach for non-logging error extraction?
OK, now I have the full taxonomy across all ~63 catch blocks in the codebase. Here's what I found:
The Real Numbers
Category
Count
What it means
CEREMONY
15
Catch → log → rethrow. An outer boundary handles this anyway. These shouldn't exist.
So 15 catch blocks are pure waste — they exist only because there's no boundary to catch for them. The other 48 are doing real work (decisions, transforms, absorbs).
But here's the thing you're pointing at: even in the 48 "real" blocks, every single one has to do this dance:
ts
catch (error) {
// I have to extract a string from this unknown thing
// before I can do my ACTUAL job (decide, transform, absorb)
const message = parseError(error); // or the manual ternary
log.warn("...", { error: message });
// NOW do the real work
}
The parseError call (or manual ternary) is ceremony within every category. It's infrastructure work leaking into application code.
The Core Problem, Stated Precisely
The codebase has two orthogonal problems masquerading as one:
Error serialization — converting unknown catch values into loggable strings. This is the logger's job, not the caller's job. Today: 70+ sites do it manually.
Missing boundaries — 15 catch blocks exist purely to log-and-rethrow because nothing upstream catches for them. The tRPC layer already solved this (observability middleware), but Inngest and API routes haven't.
parseError is a band-aid for problem 1. Spreading it to more files makes problem 1 worse, not better.
The Design: Error Handling Is Infrastructure, Not Application Code
Three changes, in order of leverage:
Change 1: Error-Aware Logger (eliminates problem 1 entirely)
4 lines in vendor/observability/src/log/next.ts:13-18. The enriched() function — the single chokepoint for all log calls — auto-normalizes any error field in metadata:
ts
function enriched(level: LogLevel) {
return (msg: string, meta?: Record<string, unknown>) => {
const normalized = meta && "error" in meta
? { ...meta, error: parseError(meta.error) }
: meta;
pushJournal(level, msg, normalized);
baseLog[level](msg, { ...getContext(), ...normalized });
};
}
Effect: Every catch block in the codebase that logs just writes { error } — pass the raw catch value. The logger handles serialization. No parseError import needed anywhere. The 58 existing parseError() wrappers become redundant (but harmless — idempotent on strings). The 12 manual ternary sites just become { error: err }.
Change 2: Kill the 15 Ceremony Blocks
These are the blocks that catch → log → rethrow. They exist because the author felt they needed to log the error "here." But the boundary already logs it:
tRPC procedures (9 ceremony blocks in connections.ts, account.ts, backfill.ts, proxy.ts): The observability middleware at vendor/observability/src/trpc.ts:119 already catches and logs every server error. These inner catches add nothing except a duplicate log line.
Inngest functions (1 ceremony block in record-activity.ts): sentryMiddleware catches failures, but there's no logging middleware. Add one — mirror the tRPC pattern.
Agent/core (4 ceremony blocks in agent.ts): These wrap errors in typed constructors (ContextCreationError, ToolExecutionError, etc.) — the typed constructor is the value, not the log call. The parseError call inside them is for the constructor's message arg, not for logging. These are a special case — they need parseError for message extraction into a constructor, not for logging. This is a legitimate use.
Packages (1 ceremony in glob.ts): Wraps error with descriptive message and rethrows. Boundary catches it.
So realistically: ~10 ceremony catch blocks can be deleted outright, and the remaining 5 (agent.ts typed constructors, glob.ts) are borderline — they add message context, which is arguably useful.
Change 3: parseError Becomes an Internal — Not a Public API
After Changes 1 and 2:
The logger calls parseError internally — no external import needed for logging
The only legitimate external use is core/ai-sdk/agent.ts for typed error constructor messages, orpc-router.ts and pinecone/client.ts for error-string-based branching, and a few TRANSFORM sites that embed the error string in return values
parseError stops being "the thing everyone imports" and becomes an internal detail of the logger, with a narrow re-export for the ~10 sites that genuinely need string extraction outside of logging
Net Effect
Before
After
70+ sites import parseError or write manual ternaries
~10 sites import parseError (only for non-logging string extraction)
Every catch block does serialization + its real job
Catch blocks do only their real job; logger handles serialization
15 catch blocks exist for ceremony
~10 deleted; errors propagate to boundaries
New code must remember to call parseError
New code just writes { error } — it works
Does this framing match what you're after? The core move is: push error serialization down into the logger (Change 1), push error capture up into boundaries (Change 2), and parseError becomes an internal implementation detail instead of a public API spreading across the codebase (Change 3).
If this resonates, I'll write the plan. The main open question is whether you want to tackle Change 2 (killing ceremony blocks) in the same plan or as a separate follow-up — it touches more files but is mechanically simple (delete catch blocks, let errors propagate).
You're right. Let me cut through to the actual root.
The real problem: every async boundary in the codebase manually implements the same 3 steps — catch, serialize error, log. That's not application code. That's infrastructure leaking into every file.
What Actually Needs to Happen at Each Layer
tRPC — Already solved. The observability middleware at vendor/observability/src/trpc.ts:119 catches and logs every server error with full context (path, duration, auth, requestId). The 9 ceremony catch blocks inside procedures that log-and-rethrow are duplicate log lines. Delete them. Let the error propagate to the middleware.
Inngest — Not solved. sentryMiddleware captures exceptions but nothing logs them with context. Every Inngest function manually catches and logs. Fix: Inngest observability middleware — mirror what tRPC already has. One middleware, all functions get automatic error logging with function name, event type, step name. Delete the manual log calls from steps.
API routes — Not solved. Every route handler has a catch-log-return-500 pattern. Fix: withRouteHandler wrapper that catches, logs with request context, returns structured error response. The 6+ TRANSFORM blocks in route handlers become a one-line wrapper.
After those three boundaries exist, the catch blocks that remain should ONLY be doing business logic — deciding what fallback to use, which error code to return, whether to continue. They shouldn't be logging at all. The boundary already logged it (or will, when the error propagates).
Application code never calls log in a catch block. The boundary does it. The logger handles serialization. The whole parseError question dissolves — it becomes a 4-line internal to the logger that no one ever imports.
What Remains in Application Code
The ~48 non-ceremony catch blocks break down to:
DECISION (14): catch → inspect error → branch. These keep the catch, lose the log call. Example: connections.ts:122 inspecting "no_token_found" to choose a TRPCError code. That's real logic. But it doesn't need log.warn — when it rethrows the TRPCError, the boundary logs it.
ABSORB (13): catch → continue. These keep the catch, lose the log call. Example: connection-lifecycle.ts:92 — best-effort cancel-backfill. If you want visibility into absorb-site failures, the Inngest middleware can log at the step level before the step swallows it. Or these become one-liners: .catch(() => undefined).
TRANSFORM (21): catch → return structured value. These keep the catch, lose the log call. Example: activity.ts returning { success: false, error }. The caller that receives the failure result is closer to the boundary — it decides whether to log.
The Plan Would Be
Error-aware logger — 4 lines in enriched(). Internal parseError. No external imports needed. (Instant, zero risk)
Inngest observability middleware — Mirror tRPC's pattern. Logs step failures with function/event/step context. All 11 platform functions + 1 app function get it for free. (Medium effort, high leverage)
API route wrapper — withRouteHandler(handler) that catches, logs, returns error responses. Replaces the catch-log-return-500 boilerplate in 6+ route files. (Medium effort, high leverage)
Delete ceremony + redundant log calls — Remove the ~15 ceremony blocks entirely. Remove log.error/log.warn calls from DECISION/ABSORB/TRANSFORM blocks where the boundary now handles it. (Mechanical, high volume)
Deprecate parseError as public export — Keep it as an internal to the logger. The ~10 sites that genuinely need string extraction outside logging (error constructor messages in agent.ts, string-matching in pinecone/handleError, orpc-router.ts) keep a narrow import. Everything else drops it.
Net effect: You go from ~70 files touching error serialization to ~3 infrastructure files that own the problem. Application code just throws or returns — the boundary handles the rest.
Does this match the architecture you're thinking about? Or are you pushing toward something even more fundamental — like eliminating catch blocks themselves (Result types / railway pattern)?
Short answer: yes, for business logic — and the pattern already exists.
What Already Exists
packages/platform-trpc/src/caller.ts:20 — createPlatformCaller creates a server-side tRPC caller with no HTTP involved:
This is already used in production — api/app/src/router/org/connections.ts:48 calls platform tRPC procedures from app tRPC procedures through this. The full middleware chain runs (observability, Sentry, withRequestContext, journal). No HTTP.
And critically: the observability middleware at vendor/observability/src/trpc.ts has zero HTTP dependency. It needs { requestId: string } — that's it. It already works with synthetic contexts.
The Duplication That Proves the Point
The provider API fetch pattern (URL build → auth header → fetch() → 401 retry with forceRefreshToken) is copy-pasted across three files:
Same algorithm, three copies. Token helpers (getActiveTokenForInstallation, forceRefreshToken) are called by both Inngest functions and tRPC procedures from the same lib/ modules.
The business logic is ALREADY shared. It's just not going through the tRPC middleware when Inngest calls it.
The Architecture
code
Inngest function = ORCHESTRATION (durable steps, sleep, cancel, throttle)
tRPC procedure = BUSINESS LOGIC (token fetch, provider API call, DB write)
tRPC middleware = ERROR BOUNDARY (logging, Sentry, context propagation)
The tRPC procedure handles token acquisition, fetch, 401 retry, error logging — once, with the middleware chain. The Inngest function is pure orchestration: step sequencing, sleep, cancel, throttle.
What Can and Can't Flow Through tRPC
Can (and should):
All shared business logic currently inlined in Inngest steps (token fetch, provider API calls, DB operations with error handling)
The 3x duplicated fetch pattern → single proxy.execute procedure
api/app Inngest functions calling api/platform → createPlatformCaller("inngest") already works
Webhook ingestion — HMAC requires raw body before any parsing
OAuth callbacks — browser redirects, HTML responses
AI SDK streaming — different protocol entirely
SSE stream — open-ended connection
CLI auth routes — different auth mechanism
One practical constraint: Platform Inngest functions live inside api/platform, and createPlatformCaller lives in packages/platform-trpc which imports @api/platform — circular dependency. Solution: platform Inngest functions create a direct caller without the JWT round-trip:
Business logic lives in tRPC procedures — one place, one middleware chain, one error boundary
Inngest functions become thin orchestrators — no direct DB calls, no error handling, no log calls
Non-tRPC routes that can't be converted (~8 routes) get a lightweight withRouteHandler wrapper
The parseError problem, the logging problem, the duplicate fetch pattern, and the error boundary problem all collapse into one solution: tRPC as the universal business logic layer.
Want me to write this up as a plan? The key decision point is scope — the full vision (extracting Inngest business logic into tRPC procedures) is a significant refactor. We could phase it:
Phase 1: Error-aware logger + direct caller factory for Inngest (immediate wins, small blast radius)
Phase 2: Extract the duplicated fetch pattern into the existing proxy.execute procedure