Typed TypeScript packages. Dot composes them into one app, and the compiler checks the wiring. With the journal nothing writes to a row directly: every change is an event, and a reducer turns it into the row in the same transaction. Each floor is one step; the two that matter most come with their own drawing sheet.
A Dot app is a list of units. Each unit says what it provides and how it shuts down. start() boots the list top to bottom; dispose() closes it bottom to top. If a unit is not in the chain, it does not run.
import{defineApp,infra}from'@arki/dot';constdatabase=infra({name:'database',provides:{db:()=>openDb(process.env.DATABASE_URL),// ← one factory per key; may be async},asyncdispose({db}){awaitdb.close();},});constapp=awaitdefineApp('pizzeria').infra(database,stripe)// providers before consumers — enforced at compile time.start();awaitapp.stop();awaitapp.dispose();
apps/avocabo/backend/src/app.ts · lines 16, 18, 21, 23–31, 42–48, 65–66 · a real app
What the app runs on: Postgres, a cache, mail, sign-in, locks, vector search, audio storage.
.features(…)
What the app does: its features.
.entrypoints(…)
How the world gets in: the cron clock, the RPC gateway and the web server.
F2 · Wire · the compiler checks the order
Put a unit before what it needs. It will not compile.
Units boot in the order you list them. A unit that needs db must come after the unit that provides it. Swap them, and your editor rejects the line before anything runs.
Elevation: providers below consumers.
sessions and orders both need db. The database unit provides it, so it must come first.
packages/dot/docs/examples/quickstart.ts · lines 9–10, 32–34, 47–48 · two units that need db
import{defineApp,infra}from'@arki/dot';import{defineFeature}from'@arki/dot/feature';exportconstsessions=infra({name:'sessions',needs:{db:database.provides.db},// the handle, not a string: a typo cannot compileexportconstorders=defineFeature('orders').needs({db:database.provides.db})
packages/dot/docs/examples/quickstart-wrong-order.mjs · lines 8, 10, 13 · the mistake
Property ''DOT: a unit in this list cannot be mounted at its position'' is missing in type ...
... NeedsError<EmptyShape, WireNeeds<{ db: Handle<..., "db", "database">; }>> ...
Plain JavaScript has no type check, so the kernel checks too. It stops the app at configure, before any boot hook runs. Its error, ARKI_DOT_E020, names both units and their positions.
Every list boots left to right: .infra() first, then .features([…]), then .entrypoints().
F3 · Feature · model · usecases · infra · entrypoints
Open a feature and read what your product does. The plumbing waits outside.
A feature is one part of your product, like the waitlist. In the middle are its rules: the model, the things it knows, and the usecases, what someone can do: sign up, unsubscribe, count. They are plain functions, with no HTTP, no SQL and no email in them. Around them sit the infra, how the feature talks to the outside, and the entrypoints, how a request gets in. So you read what your product does in one place, test a rule by handing it only what it names, and change the storage or add a new way in without touching a rule. The infra can never reach into the rules: the types forbid it. A feature joins the app with one line.
modelthe things and their rules
usecaseswhat someone can do
infrahow it talks to the outside
entrypointshow a request gets in
Detail · FeatureD-3
apps/avocabo/backend/src/features.ts · lines 48, 53–54, 74, 84 · one line per feature
import{defineFeature,entrypointOnly}from'@arki/dot/feature';import{database}from'../../infra/db';import{cache}from'../../infra/kv';import{emailClient}from'../../infra/mail/client';import{limiter}from'./infra/signup-limiter';import{store}from'./infra/store';import{turnstile}from'./infra/turnstile';constwaitlistDeps=defineFeature('waitlist')// The store binds `db`, the signup limiter binds `kv`; usecases never see them..needs({db:entrypointOnly(database.provides.db),kv:entrypointOnly(cache.provides.kv),// The app's outbound email client; a test fakes the plugin.mailer:emailClient.provides.emailClient,}).infra(store,limiter,turnstile);
.needs({…})
What the feature takes from the app: the database, the cache and the mailer.
entrypointOnly(…)
This service goes to the feature’s infra and entrypoints only. Usecases never see it.
.infra(…)
How the feature talks to the outside world: a store, a rate limiter and a bot check.
Pick<Deps,'repos'>
A usecase names the services it uses. This one uses the repos and nothing else.
F4 · Remember · @arki/journal · five things you can try
Crash it. Retry it. Nothing pays twice, nothing gets lost.
Chapter · @arki/journalsheets J-100 to J-104 · every code line is copied from a real file
Every change is saved with its history and its follow-up work in one go, and you can always prove the table is right.
Simulated in your browser. The code is real.
J-100 · the row is a replay
Your row is its events, replayed.
An entity is a normal Postgres table plus a few small functions called reducers. Each reducer says what one event does to the row. Append an event, and its reducer patches the row in the same transaction. The row stays a plain table you select from. Like event sourcing, without the complexity.
Replaying through version 1 of 2. The live row stays at version 2.
journal_events · the history of order ord_42
seq
version
type
data
42
1
OrderPlaced
{ customerId: 'cus_ada', total: 950 }
43
2
OrderPaid
{ amount: 950 }
orders · the live rowselect * from orders where id = 'ord_42'
id
customer_id
total
status
version
ord_42
cus_ada
950
paid
2
Only status and version changed: .on returned a patch.
journal.replay(db, order, 'ord_42', { throughVersion: 1 })the same reducers, folded from nothing, up to that version
id
customer_id
total
status
version
ord_42
cus_ada
950
placed
1
A read, not a write: the live row is untouched · README.md:366
Why it matters: you get the full history and can rebuild any row at any version, but you still read and query a normal table. Sheet J-103 works because of this.
import{CommandConflict,CommandNotFound,initJournal,need}from'@arki/journal';exportconstj=initJournal({tables,meta:z.object({actorId:z.string()})});exportconstOrderPlaced=j.event('OrderPlaced',z.object({customerId:z.string(),total:z.int().positive()}));exportconstOrderPaid=j.event('OrderPaid',z.object({amount:z.int().positive()}));exportconstOrderCancelled=j.event('OrderCancelled',z.object({reason:z.string().min(1)}));exportconstorder=j.entity('order',orders).create(OrderPlaced,e=>({customerId:e.data.customerId,total:e.data.total,status:'placed'})).on(OrderPaid,()=>({status:'paid'}))// a patch: only the columns that change.on(OrderCancelled,()=>null);// null deletes the row; the events stay
J-101 · all or nothing, then the follow-up work
Pull the plug. Nothing is written, or all of it.
One command, payOrder, makes four writes in one transaction: the event, the row, the inline projection, and the job for the email. Cut the power at any point and Postgres never sees a commit, so none of the four exist. Let it commit, and only then can a worker pick up the job. The job id is the email's idempotency key, so a worker that dies after sending can run the job again and the inbox still shows one email.
Second attempt, same job id, still one email.
1 event
2 row
3 projection
4 job
commit
one transaction · committed
journal_events · new rowseq 43 · v2 · OrderPaid · { amount: 950 }appended first · write.ts:272
customer-stats · inline projectionRan in this transaction. It listens to OrderPlaced only, so OrderPaid leaves placed: 1 as it is.README.md:93 · write.ts:378
journal_jobs · job_c4meffect: order-mail · attempts: 2 acked on attempt 2: doneA worker can pick up the job only after the commit. A job row that never committed does not exist.
inbox · [email protected]order-paid · ord_42 · idempotencyKey: job_c4mStill 1 email after 2 attempts: the provider deduped the second send on its key.
same job id, one emailThe job ran twice as job_c4m. The mail provider dedupes on that key, so the second send changes nothing.
Proof: src/journal.test.ts:245 “a throwing projection rolls back events, row and jobs” · src/jobs.pg.test.ts:166 “a crash after the external effect, before the ack, repeats the job under the same id”.
import{CommandConflict,CommandNotFound,initJournal,need}from'@arki/journal';exportconstpayOrder=j.command('payOrder',z.object({orderId:orderIdSchema,amount:z.int().positive()}),(input,{write})=>write(order,input.orderId,row=>{if(!row)returnCommandNotFound({detail:'Order not found'});if(row.status!=='placed')returnCommandConflict({detail:`Order is already ${row.status}`});return[OrderPaid({amount:input.amount})];// [] means: write nothing}),);exportconstorderMail=j.effect('order-mail',order,{mailer:need<Mailer>()},{OrderPaid:(e,{jobId,mailer})=>mailer.send({template:'order-paid',orderId:e.entityId,idempotencyKey:jobId}),},);
packages/journal/src/write.ts · lines 19, 154, 314–318, 368, 386–389, 434 · the four writes, in order
The webhook arrives three times. The handler runs once.
A payment provider sends a webhook again until you answer. Run the command with the event id as its idempotency key. The first run claims a receipt row and does the work. Every later run with the same key finds the receipt and answers with the stored result. It writes nothing. The same key with a different body is refused as a CommandConflict.
Delivery 3: same reply, the handler did not run, nothing written.
import{CommandConflict,JournalError}from'./errors.js';import{assertRoundTrips,sameValue}from'./storage.js';constheld=awaitdeps.store.bind(tx).receipts.claim({key,command:name,input:throughJson(input)??null,commandId:own});if(held===undefined)returnundefined;if(held.command!==name)returnCommandConflict({detail:`the idempotency key is held by command "${held.command}", not "${name}"`});if(!sameValue(held.input,throughJson(input)??null))returnCommandConflict({detail:`the idempotency key was used by command "${name}" with a different input`});
J-103 · verify, repair, forget
Someone edits the database by hand. Prove it, fix it, forget what you must.
Because the row is a replay of its events (sheet J-100), the journal can always check it. verify folds the events and compares, column by column. repair writes the folded row back, and queues no job. forget rewrites the events that hold personal data to their erased form, stamps them, and repairs the row so it matches. The history still replays.
1 column drifted. Repair writes the folded row back and queues no job.
orders · the live rowselect * from orders where id = 'ord_42'
id
customer_id
total
status
version
ord_42
cus_ada
950
shipped
2
Edited by hand with a plain UPDATE. No event says so.
verify · expected and actual
column
expected
actual
status
paid
shipped
expected: the reducers folded over journal_events
journal_events · history of ord_42 · the source of truth
seq
version
type
data
erased_at
42
1
OrderPlaced
{ customerId: 'cus_ada', total: 950 }
null
43
2
OrderPaid
{ amount: 950 }
null
The README's own OrderPlaced has no erased form. Here it is given one that blanks customerId, the way README.md:260 shows.
Proof: src/journal.test.ts:583 “verify reports a drifted row and repair fixes it from the log” · src/journal.test.ts:688 “forget rewrites the events that have an erased form, stamps them, and repairs the row to match”.
packages/journal/README.md · lines 46, 73–77
import{CommandConflict,CommandNotFound,initJournal,need}from'@arki/journal';exportconstorder=j.entity('order',orders).create(OrderPlaced,e=>({customerId:e.data.customerId,total:e.data.total,status:'placed'})).on(OrderPaid,()=>({status:'paid'}))// a patch: only the columns that change.on(OrderCancelled,()=>null);// null deletes the row; the events stay
Other verbs: replay(db, entity, id, { throughVersion }) (returns the reducer-shaped row), verify(db, entity, id), repair(db, entity, id)
journal.forget(db, entity, id) rewrites every stored event of that entity that has an erased form to it, sets erased_at on those rows, and then repairs the row from the rewritten log, so the row and its history agree. All in one transaction.
An event that can hold personal data declares its erased form: j.event('MessageSent', schema, { erased: data => ({ ...data, content: '' }) }).
J-104 · durable workflow · next · not on npm yet · latest published is 0.2.1
A refund that survives a restart and undoes itself.
A workflow is a list of steps. Every step writes a checkpoint event before and after it runs. Restart the server in the middle of a step and the run goes on from the last checkpoint. The step runs again with the same key, so the provider makes one refund. The run then waits until the provider's webhook sends a signal, or three days pass. Cancel it and the undo functions run, newest first.
Done. One signal, one finish, one refund at the provider.
hold
payBack
settled · waitFor 3d
finish
journal_events · the run's history, one row per checkpoint
provider · paymentshold calls: 1 · refund calls: 1 · release calls: 0 refunds made: 1Every try of payBack sends the same key, so the provider makes one refund.
compensation · newest firstnot runningA step without undo is skipped, and its work stays done.
The run's signal is provider.refund.settled, the one named in the code below.
Proof: src/workflow/runner.test.ts:459 “crash after external success before checkpoint re-runs the step with the same key, and the committed checkpoint never runs it again” · src/workflow/compensation.test.ts:311 “cancel on a parked run undoes completed steps in reverse and ends cancelled” · src/workflow/compensation.test.ts:399 “a dead step waits for an operator by default and compensates with onDeadStep” · src/workflow/wait.pg.test.ts:155 “a signal that commits while the timeout is in flight wins, and the timeout commits nothing”.
packages/journal/README.md · lines 977, 1004–1013
import{z}from'zod';.step('hold',({input,payments})=>payments.hold(input.paymentId,input.amount),{undo:({result,payments})=>payments.release(result.holdId),})// `key` is the same on every try of this step: the provider dedupes on it. `output` checks the stored result, so// `def.read` types it and an operator can supply it by hand (`resolveStep`)..step('payBack',({input,key,payments})=>payments.refund(input.paymentId,input.amount,key),{output:z.object({refundId:z.string()}),})// The run parks here until the provider's webhook sends the signal..waitFor('settled',{signal:'provider.refund.settled',schema:Settled,timeout:'3d'})
F5 · Serve · TanStack Start
One call serves the app. Every route gets its services, typed.
TanStack Start serves the web app, and it is one entrypoint in the chain. startServer starts the app once per process. Then every request gets the started app on context: its services, an RPC client and the caller’s session, all typed.
Every service the app provides, typed. Here, the waitlist’s unsubscribe.
context.rpc
The app’s RPC client. It calls the procedures in the same process.
context.session()
Who is calling, read from the request headers.
F6 · Inspect · and test
See every unit before it runs. Then start the real app in a test.
dot explain prints every unit, what it needs and what it provides. It never boots, so no connection opens. dot doctor boots the app for real, then shuts it down. A test starts the same app you ship.
Detail · InspectD-6
packages/dot/docs/quickstart.md · lines 169, 191–195 · the command, then its real output
import{afterAll,beforeAll,describe,expect,it}from'vitest';import{isFailure,orThrow}from'@arki/failure';import{listen}from'@arki/http';import{app}from'./app';import{hooksEngine}from'./hooks';beforeAll(async()=>{started=orThrow(awaitapp.start());// The worker's HTTP calls (reports, partner webhook, mail provider) reach this server (WEB_ORIGIN).server=awaitlisten(hooksEngine(started.services.db),{port:3576,hostname:'127.0.0.1'});});afterAll(async()=>{server.forceClose();awaitstarted.dispose();});
Structure · the mental model
Plain values, typed failures, declared wiring.
Most code is now written by an agent and read by one. So the rules live in the compiler, the lint rule and the test, not in a convention someone has to remember. A function returns its value or a failure. A unit declares what it needs. Work runs in a scope that owns it. The explicit form is the point: no magic, nothing to unwrap, no runtime to learn.
Returns
The value itself, or a failure. Nobody writes the union; the compiler infers it, and the lint rule reports a call that throws a failure away. Bugs still throw.
packages/failure/README.md · lines 26, 28–32, 34–35, 37–38 · nobody wrote the return type
import{defineFailure,isFailure}from'@arki/failure';constEmailTaken=defineFailure('user.email_taken',{status:409,data:z.object({email:z.string()}),message:'email {email} is taken (someone beat you to it)',});consttaken=newSet(['[email protected]']);constsignUp=(email:string)=>(taken.has(email)?EmailTaken({email}):{email});constresult=signUp('[email protected]');if(!isFailure(result))thrownewError('expected a failure');
Needs
Declared on the unit, once. A unit names the handle it takes. If no unit before it provides that handle, the app will not compile, whether the provider comes later or not at all.
packages/dot/README.md · lines 33, 51–53, 58–60 · the handle is typed
import{defineApp,infra}from'@arki/dot';conststripe=infra({name:'stripe',needs:{db:database.provides.db},// typed handle — destructure in hooksprovides:{stripe:({db})=>makeStripeClient(db),// factories see the needs},
Runs
Owned work on plain Promises and AbortSignal. A scope joins every task it started, then runs cleanup newest first. No fibers, no effect type.
packages/async/README.md · lines 161, 165–171 · cleanup runs newest first