Cue
Usage

Flow

Why

A flow is the restricted function that describes what an entity does, with one validity duration for every entity of that flow. A step is an opening in that function. The step implementation is the code outside the flow that performs the step.

The current flow run stays available for the next reread. A flow metric is the retained end of a finished flow run. A step metric is the retained end of a finished step run. A person reads those ends over a period. A running flow run is not a metric.

Who

You write a flow when you add one to an organization. flows and fixtureFlows in organizations/fixture/src/index.ts, and fixtureSteps in organizations/fixture/src/steps.ts, are the registrations to copy.

A person reads Flows in the console. A person can open the first entity of a flow, replay a flow, replay from a step, resend a job, run a step without applying its result, cancel a run or an open step, and end a validity. The first opening is that request: an open run waits, and inside the validity duration the recorded result is returned. On a stored flow run the console lists that run's transient files.

How

You meet the function, then the openings it calls, then the registration, then the run the orchestrator keeps, then the Flows screen.

The function

FlowFunction in packages/contract/src/index.ts is (ctx: FlowContext) => void. paceFlow, loadFlow, stallFlow, faultFlow, softenFlow, asideFlow, nestFlow, and broodFlow are that function. defineFlow stores each one as run. organizations/fixture/src/index.ts lists them on flows, and fixtureFlows is that list. nestMidFlow, nestLeafFlow, and broodChildFlow are the child runs those parents open.

reread in packages/engine/src/engine.ts calls definition.run from the first opening, on the operations already stored. openTrackedStep keeps an opening whose step and mode already match. It throws `Reread diverged at ${step}` when they do not.

FlowContext exposes values, openStep, openOptionalStep, openDetachedStep, openChildren, waitGroup, choose, finish, and fail. values is the copy taken when the run opened. The other methods take a step name, a flow name, elements, a group callback, a choice, or nothing. consumeAssignment in apps/orchestrator/src/consume.ts passes starting data, current values, files, and at to implementation.run. The worker loaded secrets into the environment with installEnvironment before it started.

Openings

paceFlow calls ctx.openStep(dwellStep), then ctx.openStep("mark"). loadFlow calls ctx.openStep(dwellStep). asideFlow calls ctx.openDetachedStep(stallStep), then ctx.openStep(dwellStep). The string "mark" is that step name. dwellStep declares dwell, and names includes mark.

openStep calls openTrackedStep with opening required. The first call builds the step with createStep, pushes jobFor, sets run.wait to { kind: "step", step }, and throws SuspendSignal. The next reread returns frame.result once frame.result is set. A required result whose status is failed ends the run in failure and does not open the next step. A required result whose status is not_finished ends the run not finished. After definition.run returns, or after FinishSignal, reread calls settle with success.

openDetachedStep calls openDetached. The first call pushes jobFor and returns without SuspendSignal. acceptResult writes frame.result and, on the first end, calls pushStep. When frame.mode is detached and entity.run.status is anything other than running, acceptResult returns taken([]) and skips drive. The step metric from that first pushStep is in the transition taken returns.

softenFlow calls ctx.openOptionalStep(missStep). That call uses openTrackedStep with opening optional. It waits for frame.result the same way as openStep. A failed or not finished optional result does not stop the run.

Groups, children, and choice

On a new group, waitGroup stores rule: { form: "all" }, then calls define. sealGroup seals the report when judgeRule returns success. A failure or a not finished judgment closes the still-open required and optional steps and stops the run. Until then waitGroup sets run.wait to { kind: "group", rule: frame.rule } and throws SuspendSignal. The call returns frame.sealed.

takeStep records optional or required and pushes jobFor for a new member that is still live. The group rule counts a required step whose result status is done, and a child run whose status is success. An optional step does not count. GroupContext.openStep and GroupContext.openOptionalStep return nothing.

nestFlow calls ctx.openChildren(nestMidFlow, asChildren(sprouted.body)). nestMidFlow calls ctx.openChildren(nestLeafFlow, asChildren(sprouted.body)). broodFlow calls ctx.openChildren(broodChildFlow, asChildren(opened.body)). The first argument is the flow. takeChildren stores it as member.flow. GroupContext in packages/contract/src/index.ts types that parameter as flow: FlowName. A child member with no identities counts as done.

FlowContext.openChildren and openOptionalChildren take flow as a FlowName and elements as one ChildElement or a readonly list. Each element has identifier and startingData. On the context from contextFor, one child waits while child.run.status is running and then returns resultFrom(child), including that child's finish body. A failed required child ends the parent in failure. A not finished required child ends the parent not finished. An optional child does not stop the parent. When the argument is a list, childCall stores normalizeChildrenRule of the call's rule, or { form: "all" } when the call omits it. The same rule is accepted on both openings. withinMin stores openedAt on the first opening. sealChildren calls judgeChildren. A required miss stops the parent. An optional miss seals the report and the parent continues. An empty list records the opening and returns a sealed report. nestFlow, nestMidFlow, and broodFlow open child flows with openChildren.

uniqueElements keeps the first element of each identity. ensureChild calls begin when the child is missing. When restart is true and the child is not running, it calls begin again unless the run is success and now is still within validityEndsAt. The flow openChildren passes restart as !isReread. entityId in packages/contract/src/index.ts returns `${organization}/${flow}/${identity}`.

choose stores the arms in the order of arm.name. It runs every arm whose name differs from taken under contextFor(..., "discarded"), then runs the taken arm under "live". A discarded opening is discardedStep, with discarded: true and no jobs.push. acceptResult returns taken([]) when findStep misses the step and findDiscardedStep finds it. Duplicate arm names, or a taken value absent from those names, throw Reread diverged at a choice.

paceFlow, loadFlow, softenFlow, asideFlow, nestFlow, nestMidFlow, nestLeafFlow, broodFlow, and broodChildFlow call ctx.finish(). stallFlow and faultFlow open one required step and do not call finish(). finish throws FinishSignal in live mode, and the catch in reread calls settleReachedEnd, the same close as a normal return. fail throws FailSignal, and that catch calls settle with failure. None of these flows call fail().

Registration and the step implementation

defineFlow returns the flow with name, entityType, validityDurationMs, source, and run. Each fixture flow sets validityDurationMs to null and entityType to its name. fixtureFlows holds pace, load, stall, fault, soften, aside, nest, nest-mid, nest-leaf, brood, and brood-child. createRegistry throws `Unknown flow ${name}` from get when a name is missing. ensureChild calls registry.get(flowName) for the child flow.

bindOrganization in organizations/fixture/src/steps.ts binds each step onto every flow. The kind is fixture- plus the step name: fixture-dwell, fixture-stall, fixture-miss, fixture-sprout, and fixture-brood. fixtureSteps stores each bound step under flow/step. dwell also answers mark and pass-1 through pass-10.

dwell waits the configured milliseconds, then returns done. stall throws StepHeld. miss returns { kind: "result", status: "failed", discriminant: "failed" }.

runJob loads the bound step with stepBinding. A thrown StepHeld returns before acceptResult. When implementation.run throws and openingFor is optional or detached, runJob sends { kind: "result", status: "failed", discriminant: "failed" } to acceptResult. Any other thrown error is rethrown.

The run

apps/orchestrator/src/server.ts calls openFixtureService with createMemoryClient and watchWorkers: true. That opens createService with flows: fixtureFlows, steps: fixtureSteps, entities: createPostgresEntities(pool), metrics: createMetricPublisher(redis), and metricReads: createMetricsReader(clickhouse). server.ts does not call startRun. pnpm --dir organizations/fixture seed calls seedOrganization only when the organization exports catalogSeed. The fixture does not, so that command starts no run and opens no client database. The log line is seeded fixture 0 runs. startRun writes a run into the orchestrator database.

startRun loads the row with loadFocus, calls engine.request, then persist, then afterCommit. request addresses the entity with entityId. A run whose status is running returns { kind: "waiting" }. A success run with finishedAt and validityEndsAt set, and input.at at or before that instant, returns { kind: "recorded" }. Every other request goes through begin. begin adds one to generation, sets run.status to running, copies input.startingData, clears validityEndsAt, and calls drive.

drive calls applySilence, then reread. applySilence pushes jobFor while the step has no result, now is at or after silenceDueAt, and resendCount is still under maxResends. At maxResends it writes status not_finished and calls pushStep. Service.advance calls engine.advance for each batch from session.due. due in createPostgresEntities selects status = 'running' and silence_due_at <= $1. server.ts reaches the engine through openFixtureService, and it also calls startMetricFlush, createReadServer, and server.listen. seedOrganization is the startRun for an exported catalogSeed.

afterCommit calls enqueueStep for each job and metrics.publish with flowMetrics and stepMetrics. organizations/fixture/src/work.ts starts createStepWorker for each kind. Each job calls consumeAssignment. The orchestrator applies the published result and calls engine.acceptResult inside deps.entities.transaction.

settle returns at once when entity.run.status is not running. Otherwise it sets status and finishedAt, clears wait, and pushes one FlowMetric with that outcome, the run generation, and durationMs. On success, validityEndsAt is addMs(now, validityDurationMs) from registry.get(entity.flow). pushStep pushes one StepMetric when discarded is unset and the step has openedAt, endedAt, and result. When acceptResult receives a worker id, that id is on the step metric. A silence not_finished has no worker id. FlowMetric and StepMetric are declared in packages/contract/src/index.ts.

Transient files

A step writes a transient file with input.files.put. The bytes live in the platform bucket under runs/{organization}/{flow}/{identifier}/{generation}/{name}. consumeAssignment records every name that put wrote and stores that list on the step result. A replay from a step publishes a copy of each kept name into the new generation before the jobs of that generation are sent. A full replay does not copy. The flow run page in the console lists them. Reading a name still uses the current generation.

listRun on TransientFiles in apps/orchestrator/src/transient-files.ts returns { name, bytes }[] for that prefix, sorted by name. GET /entities/:id?files=1 on ReadController calls listRunFilesFor after parseFlowRunPath and readGeneration. The run must still be stored and the person must belong to that organization. GET /entities/:id?file={name} returns the bytes with the stored content type. A name that is not one segment, or a missing file, is 404.

EntityView in apps/console/src/design/views.tsx renders a DataTable titled Files, empty copy No file., page size 50. EntityScreen loads that list with listRunFiles and does not send files on the 2s tree poll. A row opens a dialog: readRunFile previews JSON or text under 1 MiB, and Download goes to GET /api/run-file. After the flow run retention the run is gone and those files are gone.

Postgres and ClickHouse

persist calls session.upsert. createPostgresEntities inserts the run into entities and, on conflict of organization_id, flow, identity, updates status, generation, started_at, finished_at, validity_ends_at, silence_due_at, rule, starting_data, operations, and wait. That row is the current flow run. server.ts passes createPostgresEntities(pool) as entities.

createMetricPublisher appends each metric to the Redis stream metrics on the shared Redis client. That client also writes dispatch tokens. LoopsService calls startMetricFlush and createRedisResultBus each with redis.duplicate(). A blocking read on metrics does not stall step-results, and the reverse does not stall the shared client. startMetricFlush inserts flow rows with insertFlowMetrics into flow_run_metrics and step rows with insertStepMetrics into step_run_metrics. onApplicationShutdown calls quit() on those two duplicated clients.

flowsFor sets the list entities from countEntities and running from countRunning. mergeFlows copies each flow's entities and running from countsByFlow, and includes every flow registered in deps.flows even when that flow has no entity and no run. Those three methods count rows in entities. countRunning and the running column keep status = 'running'. mergeFlows fills runs, success, failure, and notFinished from flowOutcomes, p50Ms from flowDurations, and trend from flowTrend. flowsFor sets failureRate to failure / runs when runs is not 0. createMetricsReader reads the outcome, duration, and trend queries from flow_runs_hourly. flowFor reads that flow's entities and running from countsByFlow, sets failureRate to failure / runs when runs is not 0, fills series from flowSeries, reads step rows from stepCounts on step_runs_hourly, and reads reasons from reasons_daily.

The Flows screen

createReadServer in apps/orchestrator/src/http.ts handles GET. Any other method is status 405. GET /organizations/:organizationId/flows calls flowsFor after metricRange. GET /organizations/:organizationId/flows/:flow calls flowFor. The resolver in server.ts returns the text after Bearer . POST /organizations/:organizationId/flows/:flow on ReadController calls openFlow, which calls startRun.

FlowsPage in apps/console/src/app/organizations/[organizationId]/flows/page.tsx calls currentPerson and renders SignedOutView when that person is missing. It loads the list with readOrchestrator at /organizations/${organizationId}/flows?range=${range} and renders FlowsRoute inside ConsoleFrame with active="flows". The nav item labeled Flows in ConsoleFrame pushes `/organizations/${organizationId}/flows`.

FlowsView shows the title Flows, stats for Entities, Flow runs, Failure rate, and Running now, and one table row per flow. FlowsRoute sends onOpen to `/organizations/${organizationId}/flows/${flow}?range=${range}`. FlowPage loads that path with readOrchestrator and calls notFound() when the load fails. The detail view shows the flow name, flow runs, step runs, failure rate, p50, Running now, the outcome series, the step table, and the reason list. The Start button opens a dialog for the identity and the payload. startFlow in apps/console/src/app/organizations/[organizationId]/flows/actions.ts posts that body to POST /organizations/:organizationId/flows/:flow. openFlow calls startRun with silence duration 60_000, resend maximum 1, and the rule from the flow definition. flowRange returns 24h, 7d, or 30d, and returns 24h for any other query value.

Getting started

  1. In organizations/fixture/src/perf/, add a FlowFunction next to paceFlow, loadFlow, stallFlow, faultFlow, softenFlow, asideFlow, nestFlow, and broodFlow. Call openStep, openOptionalStep, openDetachedStep, openChildren, or finish the way those flows do. paceFlow calls openStep(dwellStep) and openStep("mark"). softenFlow calls openOptionalStep(missStep). asideFlow calls openDetachedStep(stallStep). nestFlow calls openChildren(nestMidFlow, asChildren(sprouted.body)). broodFlow calls openChildren(broodChildFlow, asChildren(opened.body)). waitGroup, choose, and fail are on FlowContext. Append the flow to flows in organizations/fixture/src/index.ts. fixtureFlows is that list.

  2. Register the function with defineFlow, which sets name, entityType, validityDurationMs, source, and run, and append that value to flows. Register each step implementation on the steps array in organizations/fixture/src/steps.ts. bindOrganization writes `${flow}/${step}` and sets the kind to `fixture-${step.name}`.

  3. Copy .env.example to .env in the repository root. loadRootEnv in apps/orchestrator/src/env.ts reads that file. requiredEnv reads DATABASE_URL, REDIS_URL, and CLICKHOUSE_URL, and throws ${name} is required when one is missing. Start the orchestrator Postgres with npx supabase start. Start Redis and ClickHouse with docker compose up -d redis clickhouse. The redis and clickhouse services are the ones in docker-compose.yml. Run npx supabase status and set NEXT_PUBLIC_SUPABASE_ANON_KEY in .env to the anon key it prints. supabaseAnonKey in apps/console/src/lib/supabase-env.ts drops an empty value, and LoginPage then renders SignInForm with configured={false}.

  4. Run pnpm --filter cue-orchestrator serve. The serve script in apps/orchestrator/package.json runs tsx src/server.ts. server.ts calls openFixtureService with fixtureFlows and fixtureSteps, then server.listen(3001, "0.0.0.0"). It does not call startRun. The log line is orchestrator http://127.0.0.1:3001.

  5. In a second terminal, run pnpm --filter @ascentstudio/cue-org-fixture work. The work script in organizations/fixture/package.json runs tsx src/work.ts. work.ts loads the organization's secrets once with readOrganizationSecrets and installEnvironment, then calls createStepWorker. Each job calls consumeAssignment. consumeAssignment publishes the step result, the orchestrator applies it, and settle pushes a FlowMetric when it records success, failure, or not_finished. startMetricFlush in the orchestrator process inserts that metric into ClickHouse. The log line from work.ts is fixture workers plus the kind names. bindOrganization names fixture-dwell, fixture-stall, fixture-miss, fixture-sprout, and fixture-brood.

  6. In a third terminal, run pnpm --dir organizations/fixture seed. The seed script in organizations/fixture/package.json runs cue seed. The fixture does not export catalogSeed, so the command opens nothing and the log line is seeded fixture 0 runs. Load runs start with pnpm --dir organizations/fixture perf, pnpm --dir organizations/fixture perf:load, pnpm --dir organizations/fixture perf:brood, or pnpm --dir organizations/fixture perf:brood:producer. To remove runs an organization left behind, run pnpm --dir organizations/fixture reset. resetOrganization deletes rows from entity_links and entities on the orchestrator database, drains the kind queues, and deletes that organization's metrics. The log line is reset fixture. organizations, memberships, secrets, and the person in deploy/supabase/seed.sql stay.

  7. In a fourth terminal, run pnpm --filter cue-console dev. The dev script in apps/console/package.json runs next dev. Open the URL that command prints, at /login. LoginForm calls signInWithPassword for the Sign in button. The person inserted in deploy/supabase/seed.sql has email pierre@ascent-studio.fr, and the comment there says the password is that same string. on_auth_user_created calls join_fixture, which inserts a membership for organization fixture. After sign-in, LoginForm pushes /. Open /organizations/fixture/flows. FlowsPage renders FlowsView with the title Flows. Click a row. FlowsRoute opens /organizations/fixture/flows/ plus that flow name. Press Start, enter the identity and the payload, and the console opens /entities/ plus the organization, the flow, and the identity.