The credit ledger that pays for AI work uses the same hold/charge pattern described in the ledger post; this post is about the shape of the repository around it.
Why split a product into 24 packages?
A package is a promise about coupling. Code inside one package can change freely; code that crosses a package boundary changes through an export, a type or a contract. That is the entire benefit, and it is worth paying for only when the boundary matches something real: a provider, a protocol, a data store, or a surface that ships on its own schedule.
The email platform has four kinds of real boundary:
- Storage.
dbowns the Prisma schema and the migrations. Everything else talks to the database through it, so a schema change has one home. - Providers.
sendwraps the email provider behind aSendProviderinterface, with a fake and a second adapter behind the same shape.dnsdoes the same for DNS record generation and verification. Swapping a provider is a package change, not a search across the app. - Protocols.
api-specholds the OpenAPI document;sdkis generated from it;mcpdispatches to the same/v1handlers. Three consumers, one definition. - Surfaces.
uiholds the design tokens and components,templatesholds the email templates,contentholds the MDX pages. Each ships to a different audience and can be reviewed independently.
The alternative, one Next.js app with folders called lib/send and lib/dns, looks similar in a file tree and behaves very differently. Nothing stops lib/send from importing the Prisma client, the AI router and the UI kit on the same day, and nothing tells a reviewer that it happened. A package boundary makes that import a dependency change in package.json, which is visible in the diff.
The package map
The map below groups the documented packages by what they own. It is not the full dependency graph, but it is the part a new engineer or a new agent needs first.
| Group | Packages | Owns | Typical dependencies |
|---|---|---|---|
| Data | db, core |
Schema, migrations, plans, credits, flows, segments, attribution | db, pure libraries |
| Delivery | send, dns, render, templates |
Provider adapters, DNS records, block document to MJML, template sets | db, core, provider SDKs |
| Surface | api, api-spec, sdk, mcp, oauth |
REST handlers, OpenAPI contract, typed client, tool dispatch, OAuth 2.1 | core, db, api-spec |
| Safety | netguard, webhooks, tokens |
SSRF checks, signed outbound delivery, HMAC tokens | Node built-ins, db |
| Money | billing |
Stripe and Shopify billing behind one interface | db, core |
| Integrations | integrations |
Shopify, Medusa, importers | core, db, netguard |
| AI | ai |
Model routing, prompts, tool definitions, cost logging | core, db, netguard |
| Product | ui, content |
Tokens and components, MDX pages | Nothing server-side |
Two rules hold the map together. A package never imports an app, and an app never reaches into another package’s internals. The first keeps the packages testable without a running web server. The second is what makes pnpm -r typecheck a meaningful check rather than a formality.
The dependency rule that makes it work
The dependency direction is one-way: apps compose packages, packages compose lower-level packages, and the graph has no cycles. A cycle is not a style problem; it means two packages are really one, and the build order becomes undefined.
Three mechanisms enforce it in practice:
- Explicit workspace dependencies. A package can only import what it lists in
package.json. pnpm links workspace packages by name, so a bare import of a package it has not declared does not resolve. - Per-package typecheck. Each package has its own
tsconfigand runstsc --noEmiton its own source, and one workspace command runs them all. When packages depend on each other’s types, TypeScript project references are the standard way to make that build order explicit. - A provider interface at every external edge.
SendProvider,ImageProviderand the DNS provider each define the operations the product needs, not the vendor’s full API. The adapter is the only file that knows the vendor’s field names.
The provider interface is also a test strategy. The fake send provider stands in for the vendor, so the send tests assert on the gate, the headers and the suppression rules without a network call. The same shape lets a model provider be swapped by configuration, which matters when the cheapest acceptable model changes.
What does not belong in a package
Not every folder deserves to be a package. A package needs a boundary that someone could plausibly replace, test in isolation, or ship separately. A utils package is usually a sign that the boundary was not found: it becomes the place where unrelated helpers accumulate, and it ends up imported by everything, which means it constrains nothing.
The same test applies to a package that exists only to re-export another one. That adds a build step and a version number without adding a constraint.
Contract first: one spec, four consumers
The API work starts from api-spec, an OpenAPI 3.1 document. The server implements it, the SDK is generated from it, the MCP server dispatches to the same handlers, and the docs and connectors are built from it. One definition, four consumers, and a contract test that fails when the server drifts.
That choice has a visible consequence in the MCP package: it does not re-implement business logic. Each tool validates its arguments, then calls the same /v1 handler the public API uses. Because the handler is shared, the MCP tool inherits the API’s validation, credit handling and audit logging instead of reimplementing them.
// The MCP tool and the REST route share one handler.
export const checkRank = defineTool({
name: "check_rank",
input: CheckRankInput,
run: async (input, ctx) => {
const res = await apiRoute("POST", `/v1/lookups`, { body: input, ctx });
return res.status === 202 ? res.body : { error: res.body.error };
},
});
The same pattern covers the package boundary between ai and mcp: the tool definitions live in ai, and mcp adapts them to the protocol. The in-app assistant and the hosted MCP server therefore expose the same registry, which is why the 22 tools in the plan could grow to 36 without a second implementation.
How agents work inside the boundary
The package layout was chosen before the build, not extracted afterwards, because the build ran as parallel agent work. Each agent got a worktree and a branch, and the brief named the packages it owned. A worktree that needed a change in a package it did not own had to ask for a small pull request first.
That rule is what made 36 parallel runs mergeable. File ownership by package means two agents rarely touch the same file, and when they do, the merge conflict is a signal that the boundary was wrong. Merges are ordered so that a package’s dependents land after it, with --no-ff merges so each agent’s work stays visible as a unit.
The review step is separate from the build step. A lead reviews every merge for file ownership, skipped tests, typecheck and the specific risk points: approval bypass, tenant scoping and money paths. An agent’s report is a claim, not evidence; the evidence is the command output on the merged tree.
Comparison: three ways to structure a product monorepo
| Approach | Boundary strength | Parallel work | Main cost |
|---|---|---|---|
| One app with folders | Weak: any file can import any file | Poor: agents collide in shared folders | Cheap to start, expensive to untangle |
| One package per domain | Strong at domain edges | Good, if the briefs respect ownership | More manifests and build configuration |
| One package per provider or protocol | Strongest at replaceable edges | Best: adapters are independent | Over-splitting when the edge is not real |
Which should you choose?
Start with one app and a small number of folders, and split a package when a boundary becomes real: a provider you might replace, a contract with more than one consumer, or a surface that ships separately. For a product built by parallel agents, split earlier than feels natural, because file ownership is what prevents collisions. Do not split by layer alone. A types package and a utils package add ceremony without constraining anything.
What broke and what we changed
A safety package existed and one caller skipped it. The Medusa integration accepted an account-supplied base URL and fetched it without the SSRF guard, then sent the tenant’s bearer token to that host. The package was correct; the call site bypassed it. The fix routed outbound fetches through safeFetch and added the missing IPv6 ranges, including 6to4, Teredo and local-use NAT64. A shared helper only helps if the platform makes the unsafe path impossible, not merely available.
The critical finding was a tenant-scope bug in an import. A customer’s import could block email to other customers’ contacts. The fix scoped the write and added a regression test. Package boundaries do not enforce tenancy; the scoping convention does, which is why the tenant-isolation suite is separate from the unit tests.
The MCP package advertised more than it could run. An audit found the stdio package listing 36 tools while only 5 could execute on that build. The bridge was rebuilt the next day. A tool registry is a contract with the model, and a tool that lists but fails is worse than a missing one, because the model plans around it.
Two packages were built but not composed. Billing and usage jobs existed as code but were not registered with the worker, so the scheduled work they performed never ran in the deployment. The fix was composition rather than new logic: register the job in the worker that already had the queue. A package that nothing imports is dead weight, and a green test suite does not prove the app assembled it.
Related
Frequently asked questions
Why use pnpm workspaces instead of a single package?
A workspace gives each package its own manifest, its own dependencies and its own typecheck, while keeping one lockfile and one install. That is enough to make imports explicit and to let parallel work stay in separate folders. A single package with path aliases gives the same import syntax without the dependency declaration, so the boundary is invisible in review.
How many packages is too many?
When a package exists only to re-export another, or when two packages always change together, the split is costing more than it returns. A useful test is whether you could describe the package's job in one sentence without using the word "shared". If not, the boundary is a folder, not a package.
Does every package need its own tests?
Every package needs tests for the behaviour it owns, not for the behaviour it imports. The database package tests migrations and scoping, the send package tests the gate and headers, the render package uses golden files. The app-level tests then cover the composition. Duplicating the same assertion at three levels makes the suite slower without making it stronger.
How do you stop a package from importing the app?
By making it impossible to resolve. The package's package.json only lists workspace packages it may use, and the app is not one of them. A relative path that climbs out of the package is caught in review, and a lint rule can catch it earlier. The important part is that the dependency has to be declared, so the mistake shows up as a manifest change.
Why generate the SDK instead of writing it?
Because the spec and the SDK drift the moment they are maintained separately, and the drift is invisible until a customer hits it. Generation makes the spec the source of truth and turns a mismatch into a build failure. The same document feeds the docs and the MCP tool schemas, so one correction propagates.
Is a monorepo required for parallel agents?
No, but it helps. Agents collide on files, and a package layout gives each agent a natural ownership boundary that a brief can name. Separate repositories would give stronger isolation at the cost of cross-repo versioning, which is worse for a product whose packages ship together.
