# Agents, workflows and factories

> How agents, workflows, equipment, schedules, factories and saved teams are built, and their known limits.

Source: https://werker.cloud/docs/engineering/agents-workflows-factories (updated 2026-12-01)

How agents, workflows, equipment, schedules and factories are built.
Using them is in [agents and workflows](../agents-and-workflows.md)
and [factories](../factories.md). Factories add saved teams,
[rooms](factory-rooms.md) where members talk to each other, and a
decisions inbox.

## Agent

One agent doing one job: a name, standing instructions for its role,
and a default task when run on its own (`agents` table, `Agent` in
`packages/domain/src/agents.ts`). Its tools come from the
[tool registry](capabilities.md); code it runs goes in a
[sandbox](sandboxes.md). Standalone agents use workspace-bound tools;
factory members can additionally restrict their allowed tools.

### Equipment

Equipment is how an agent learns: the procedure it worked out on a
run, given to its later runs so they do not work the job out again.

- A step that finishes as done can report a `procedure` with
  `finish_step`: the commands, code and checks that worked, as
  markdown. For a step run by a saved agent, the worker saves it as
  that agent's equipment (`agent_equipment`, one active version per
  agent; older versions are kept as stale with why).
- The agent's next runs get the active procedure in their
  instructions, to follow when it fits and to correct when it does
  not. A corrected procedure replaces it.
- Editing the agent's role or task sets its equipment aside. The agent
  page shows the equipment and can discard it.

Today the agent still reasons on every run, with the procedure in
hand. Replaying a saved program with no model in the loop, which is
where the cost saving is, is not built
([#8](https://github.com/werker-ai/werker/issues/8)). One procedure
per agent assumes an agent does one kind of job; a general agent
reused for different jobs carries the procedure of whichever job
reported last.

## Workflow

Ordered steps; each step is a task done by one agent, and one agent
can serve several steps (`workflows` and `workflow_steps` tables).
Steps run in order and share their outputs. Steps are durable: an
interrupted workflow continues from its last completed step.

- **Creation:** `/new` takes a description and opens `/new/<run id>`,
  which follows creation until the work is saved, then opens the run
  (`apps/app/src/lib/components/creation/creation-view.svelte`). It
  shows what the generator thinks, says and looks at as `creation` run
  events (`packages/runtime/src/creation-feed.ts`). A run queued from
  `/new` is shaped first (`runs.shape`): the generator may ask one
  round of questions with `request_details`, each with a recommended
  answer (`runs.pause.questions`), and then stops with a brief
  (`propose_brief`, `runs.pause.shaping.brief`). Nothing is saved
  until the person approves the brief (`approve_brief`) or presses
  "just do it now" (`start_creation`); each answer starts creation
  again with what was asked and answered
  ([shaping](ui.md#shaping-on-new)). A run queued without shaping
  plans at once and asks only for what the work cannot be done
  without. A request that cannot be created fails with the generator's
  reason and nothing saved. `/runs/<id>` redirects to `/new/<id>`
  until the work is saved.
- **Not ready:** when the work needs something that is not set up (no
  sandbox, a service not connected), `define_workflow` saves nothing.
  The run waits as `needs_input` with those needs in
  `runs.pause.setup`, and `/new/<run id>` lists them with a way to set
  each up (connect a service there, or a link to Admin). Continuing
  starts creation again, so the plan uses what is connected by then.
- **Generation:** The generator chooses an agent for one coherent job,
  or a workflow when explicit stages, handoffs or verification help.
  Many tool calls do not by themselves need a workflow. Its
  `define_workflow` tool saves the chosen kind, name, agents and tasks
  (`packages/runtime/src/workflow/define/workflow.ts`). The worker
  saves an agent linked through `runs.agent_id`, or agents and a
  workflow linked through `runs.workflow_id`, then executes the work
  without a review gate.
- **Brief:** `define_workflow` keeps what done means and what was
  assumed (`WorkBrief` in `packages/domain/src/agents.ts`): from the
  approved brief, else as the generator gives them. They are saved in
  the plan (`runs.plan`, and `plan` on the workflow or agent the run
  created) and in the run's steps (`runs.workflow.brief`), and every
  step's instructions carry them with "do not ask for anything it
  already settles" (`brief_note` in
  `packages/runtime/src/workflow/step/brief.ts`). A later run of the
  saved workflow or agent gets them from its plan. A factory keeps
  them in `factories.brief` (`{ done, assumed }`), and the run that
  writes its team is given them after the description as "Done means"
  and "Assumed" lists (`packages/runtime/src/run/team.ts`); the team's
  generator is told to write the lead to them
  (`packages/runtime/src/workflow/team-brief.ts`).
- **Plan:** `define_workflow` also takes what the description asks of
  the platform (`PlanReport` in `packages/domain/src/agents.ts`):
  - `schedule`: work that repeats ("every morning") is saved as the
    schedule of the new agent or workflow, in the viewer's time zone
    (`runs.time_zone`, sent by `/new`), and is left out of the
    instructions. The work still runs once now.
  - `needs`: the [registry](registry.md) abilities the work depends
    on. `plan_readiness` (`packages/rules/src/creation/plan.ts`) marks
    each ready or not, with what is missing.
  - `unsupported`: parts of the request that are planned registry
    entries, or `other`. The rest of the work is still defined.
  - The plan is saved on the run and on the workflow or agent it
    created (`plan` columns), and the run page shows it. A schedule is
    saved switched off while a need is not ready. Nothing stops the
    run.
  - Work that repeats and reuses a saved agent is saved as a one-step
    workflow: a schedule runs a saved agent's own task, which a reused
    agent keeps.
  - The generator thinks at a high reasoning level where its model
    can; steps run at the model's default.
- **Reusing agents:** the generator is shown the workspace's saved
  agents (name and the start of each role) and told to reuse one whose
  role fits. A factory's members are not offered. An agent it names
  that already exists is used as saved, not saved again, so repeated
  similar work runs under one agent and builds on its equipment.
- **Running:** each step runs in a child conversation whose
  instructions are its agent's. A run keeps a snapshot of the steps
  and agents in `runs.workflow`, so editing an agent changes later
  runs, not one in progress.
- **Running again:** `queue_run` with `workflow_id` or `agent_id`
  executes the saved definition with its current edits. Run pages and
  the runs list expose this as Run again, preserving the run's model;
  they do not send the original description back through generation.
- **Editing:** an agent's name, role and default task can be changed
  at `/agents/<id>`; steps are added, reordered and edited in the
  builder at `/workflows/<id>/builder`. An agent a step uses cannot be
  deleted.
- **History:** each saved change to an agent, workflow, factory or
  saved team is kept as a version, with who made it. The History
  button on its page shows what each version changed and restores an
  earlier one ([versions](definition-versions.md)).

## Step results

`define_workflow` takes a method and a completion condition for each
step. Both become its editable task, separate from the agent’s
standing role. When the plan declares file deliverables, the task
starts with a `Required files:` paragraph, one absolute `/work` path
per line. The step checks these paths against the saved project on
completion, including when its report omits them. This checks
existence, not freshness or contents.

Each step ends by calling `finish_step`
(`packages/runtime/src/workflow/step/tools.ts`) with one of three
statuses:

- **done:** a markdown summary, plus paths of files under `/work` to
  show with the result. The worker saves `/work` as the next version
  of the run's [project](projects.md) and records each named file as a
  file of that version (`step_files`,
  `packages/runtime/src/project/files.ts`); nothing is copied twice.
  The next step gets the summary and the file paths. The run's result
  is the last step's summary.
- **needs_input:** a question only the person who asked can answer.
  The run stops as `needs_input` with where it stopped in
  `runs.pause`; its sandbox is kept. The answer (`answer_run`) queues
  it again, and that step starts over with the question and answer.
  Each resume is a new durable task (`runs.resumes` counts them).
- **failed:** why the task cannot be done; the run fails.

A step that answers in prose without calling `finish_step` is taken as
done, with its answer as the summary. Every report is kept in
`run_steps`.

### The agent's account

A done step can give three optional `finish_step` lists of one-line
statements (`StepAccount` in `packages/domain/src/runs.ts`): `checked`
(what it verified and how), `assumed` (what it took as true) and
`worked_around` (what failed and what it did instead). They are kept
with `done` as `run_steps.account`, trimmed by `step_account`
(`packages/rules/src/account.ts`: at most 8 lines of 400 characters
per list), and are not given to the next step. The run page shows them
as "The agent's account", and a run with workarounds has an "N worked
around" badge. Nothing checks the account against the trace.

Generated and saved agent runs use the same durable step execution as
workflows: they can keep files and ask for input. A run of raw
instructions runs in one conversation, without steps.

**Stop run** sets `cancelled`. Workers abort the durable task and
remove its sandbox; a waiting run's cancellation wakes the cleanup
sweep. Late completion or pause writes cannot change a stopped run
back to another status.

**Archive** sets `runs.archived_at` on a finished run, and Restore
clears it. Nothing is deleted, so its results, files, spans and usage
stay in the cost and observability totals. Both actions need
`delete:run` (owners and admins) and are recorded as `run.archived`
and `run.restored`. Runs cannot be deleted.

## Harness

Agents run on upstream Pi's libraries:
[Pi Durable](https://github.com/earendil-works/pi/tree/main/packages/durable)
(durable conversations, tasks, child tasks, a task graph and stored
sleeps), `pi-ai`, `pi-codemode` and `pi-mcp`. Each run's storage is
owned by the worker that claimed it from the
[queue](database-and-events.md).

Pi is a library here, not what users see. Werker's web UI shows runs:
Pi Durable's `watch()` streams each committed change to a conversation
(transcript, streamed partial answers, tool calls and their output,
usage), which the server forwards to the browser.

## Schedules

The `schedules` table.

- The next time is worked out in the database, in the schedule's time
  zone (`schedule_next`), so 09:00 stays 09:00 across clock changes.
- Every worker checks for due schedules every 30 seconds
  (`start_scheduler` in `packages/core/src/schedules.ts`).
  `claim_due_schedule()` claims one and moves it to its next time in
  the same statement, so two workers never queue the same occurrence.
- A scheduled run is queued like Run: the saved definition as it is at
  that time. A run that cannot be queued (its model is no longer
  offered, the workflow has no steps) is recorded on the schedule and
  shown on the card.

## Once per item

A workflow's last step can run once per item that the step before it
lists: one job per open pull request, for example, several at once.

- **In the builder:** a step's "Run once per item the step before
  lists" switch, with how many jobs may run at once (1 to 10, 3 by
  default). Saved as `workflow_steps.for_each`, and in the workflow's
  versions. It must be the last step and not the first
  (`workflow_step_problems` in
  `packages/rules/src/workflow-steps.ts`).
- **Listing:** the step before it is told it lists items (`prompt_for`
  in `packages/runtime/src/workflow/step/brief.ts`) and finishes done
  with `items`: each a key, a label and the input its job needs. At
  most 50, keys unique (`batch_item_problems` in
  `packages/rules/src/batch.ts`). For a pull request the key is
  `owner/repo#number@head-sha`, so a PR pushed to again gets a new
  job.
- **Queueing:** `finish_step` queues the jobs before it reports
  (`queue_batch` in `packages/db/src/runs/batches.ts`): a
  `run_batches` row for the step, and per item a run of the same saved
  workflow, model and project, holding only the for_each step with its
  item added as untrusted data (`job_instructions`). `item_runs` keeps
  each key once per workflow, ever: an item listed again, by a
  replayed step or by tomorrow's scheduled run, gets no job. The
  step's summary says how many were queued and how many were run
  before. A run of a workflow that is not saved cannot queue jobs.
- **The listing run then ends:** it does not run the for_each step
  itself, and nothing waits for the jobs (`step_after` in
  `packages/rules/src/decisions/step-decide.ts`).
- **At once:** `claim_next_run` takes a batch's job only while fewer
  of that batch than its cap are running, on top of the workspace and
  host limits.
- **Each job** is an ordinary run: its own sandbox, started from the
  workflow's image (`run_sandbox_image`), and a fresh clone through
  the GitHub App connection with `github_git`
  ([sandboxes](sandboxes.md)). A job that cannot go on finishes
  `needs_input` and is listed in Decisions under its label and the
  workflow's name; answering it resumes that job.
- **The board:** the listing run's page shows its jobs under the
  result (`apps/app/src/lib/components/run/run-batch.svelte`): each
  item's status, its result or what it waits for, and a link to its
  run. Refresh reads them again.

## Decide what comes next

Uses a [decision model](decision-models.md). A step can end with a
yes/no question about its result, and the answer decides whether the
run goes on, skips the next step or stops as done.

- **In the builder:** a step's "Then decide what comes next" switch,
  with the question, what yes and what no mean, and an action for each
  (`step-decide-field.svelte`). Saved as `workflow_steps.decide`
  (`StepDecide` in `packages/domain/src/step-decide.ts`), and in the
  workflow's versions.
- **Where it can go** (`workflow_step_problems` in
  `packages/rules/src/workflow-steps.ts`): not on the last step, and
  not on a for_each step. On the step before a for_each step it can
  only go on or stop.
- **Asking:** once the step is done, the workspace's classify@1 is
  asked the question with only the step's name and result
  (`step_decide_request` in
  `packages/rules/src/decisions/step-decide.ts`; the call is in
  `packages/runtime/src/run/decisions/decide.ts`, 10 s at most). Its
  tokens and cost are added to the run's usage.
- **Deciding** (`step_decision`): 0.7 and above takes the action for
  yes, 0.3 and below the action for no. Any other answer, no
  classifier, or a failed or timed-out call goes on, as the workflow
  would without the question. `step_after` gives the next step:
  skipping past the end, or onto a for_each step, ends the run.
- **Shown:** the run's activity says which way it went and why
  ("decided: no (0.12): stopped the run", "unsettled (0.55): went
  on"), the step list shows it under the step, and a skipped step is
  marked skipped.

## Workflow options

A workflow runs on a schedule (above) or when someone starts it. A
trigger on incoming work, verification between steps and an
improvement loop that proposes changes to its steps or skills are not
built ([#7](https://github.com/werker-ai/werker/issues/7)).

## Factory

A saved team with rooms, linked runs and the decisions waiting on a
person ([factory rooms](factory-rooms.md)). A lead coordinates the
specialists it addresses. Factories use the same run engine as agents
and workflows. `/factories` has a New factory dialog holding the
`/new` composer with `/factory` picked
(`apps/app/src/lib/components/factory/new-factory.svelte`).

### The default team

Each workspace has one saved team marked as its default
(`factory_starters.is_default`, at most one per workspace by the
`factory_starters_default` index). It says what a new factory and a
new member start as:

- A factory created without a starter gets the default's members,
  teams and room settings (`created_team` in
  `packages/runtime/src/run/factory/factory.ts`). The factory records
  no `starter_id`: it is not linked to the default.
- New team copies the default's members (`create_starter`,
  `packages/core/src/starters/team.ts`).
- On a team board, an added lead starts as the default's lead and an
  added specialist as its first specialist (`board_presets` in
  `apps/app/src/lib/factory/board/convert.ts`).

The default is created with the workspace: a trigger on
`auth.organization` calls `create_default_starter()`
(`packages/db/sql/001_schema.sql`), so sign-up, admin, eval and test
fixtures and the RLS check all get one the same way. It is named "New
members" and holds a built-in "Factory lead" with no tools and an
"Unassigned specialist" with `shell` and `classify`, both with no
model, so the run's model or the workspace's first is used. There is
no fallback at read time: `get_default_starter`
(`packages/db/src/starters/saved.ts`) throws when a workspace has
none.

It is edited, changed by asking and versioned as any saved team, and
shows a Default badge on `/factories/teams`. It cannot be deleted
(`delete_factory_starter`). Choosing another team as the default is
not built ([#48](https://github.com/werker-ai/werker/issues/48)).

### A team from `/new`

The person describes the work on `/new` and Werker decides between an
agent, a workflow and a team.

- **Who decides:** the generator. Its brief
  (`packages/runtime/src/workflow/generate/brief.ts`) says a team is
  for a standing team or an ongoing collaboration directed with many
  requests; work stated once is an agent or workflow, and repeating
  work is a schedule.
- **How:** a team is [shaped](ui.md#shaping-on-new) like anything
  else: questions, then a brief. Once the person approves or starts,
  the generator calls `define_factory` with a name, what the team
  works on, and what done means and what was assumed. What it works on
  is saved as the factory's description and the two lists as
  `factories.brief`
  (`packages/runtime/src/workflow/define/factory.ts`). The worker
  saves the factory with the default team's members on the model
  picked on `/new`, and queues the
  [change that fits the team to the brief](#a-factorys-team-changed-by-asking)
  (`queue_team_fit` in
  `packages/runtime/src/run/factory/team-fit.ts`). If a
  [planning model](ui.md#planning-model) is set, it writes the team.
- **Once only:** the factory's ID is worked out from the run's ID
  (`run_factory_id` in
  `packages/db/src/factories/created-factory.ts`), so a replayed run
  makes one factory, and no column links the two.
- **Where the person lands:** the creation page opens the factory's
  page, which follows the fit on its activity stream (`change`).
  `/new/<run>` and `/runs/<run>` of that run redirect there
  afterwards.

### Starters

A starter is a workspace's saved team: name, a one-paragraph purpose,
its teams (`factory_starters.teams`: name and purpose, at least one),
each member (role, team by name, name, instructions, responsibilities,
model, tools) and the room settings. One row in `factory_starters`,
members as JSON. With two or more [teams](factory-rooms.md#teams) a
factory created from it gets the same teams, leads and members
(`starter_team` in `packages/core/src/starters/saved.ts`).

- **Pages:** `/factories/teams` lists the starters with their outcomes
  (`read_starter_work` in `packages/db/src/starters/outcomes.ts`). A
  starter's page (`/factories/teams/<id>`) is the shared team page
  (`apps/app/src/lib/components/team-page/`), as a factory's Team page
  is.
- **New team:** a copy of the default team's members
  (`create_starter`, `packages/core/src/starters/team.ts`).
- **Editing:** each change saves the whole starter with
  `edit_starter_team`, checked against the starter rules: one lead, at
  least one specialist, at most `factory_max_specialists`, different
  names, offered models and the workspace's tools. The team board
  (`apps/app/src/lib/factory/board/ops.ts`) adds, renames and removes
  teams and moves members between them. Diffs match teams by name,
  then lead, then place (`team_diff` in
  `packages/rules/src/starters/team-diff.ts`).
- **Change by asking:** a request queues a run on the workspace's
  planning model, else the lead's, that calls `propose_starter_change`
  with the team as it should be
  (`packages/runtime/src/workflow/starter/`). The proposal is shown as
  a diff; Apply writes it as the next version, Discard drops it.
  Models and tools come only from what the workspace offered when
  asked (`packages/rules/src/starters/proposal.ts`). A proposal made
  before the starter changed cannot be applied. Rows:
  `starter_changes`.
- **Drift and copy back:** a factory with `starter_id` whose members
  or room settings differ from the starter is listed with its diff
  (`starter_drift`, `packages/rules/src/starters/diff.ts`) and "Copy
  into starter".
- **Versions:** every write records a `factory_starter` version with a
  reason and the run that made it
  ([versions](definition-versions.md)).
- **From a factory:** Save as starter takes the factory's name and the
  first paragraph of its description (`starter_purpose`).
- **Using one:** a picked starter (the New factory dialog,
  `/new?starter=<id>` or `@`) gives the factory the starter's members,
  room settings and `starter_id`, and no team is fitted to the brief
  (`packages/runtime/src/run/factory/factory.ts`).
  `resolve_starter_members` (`packages/rules/src/starters/content.ts`)
  replaces a model the workspace no longer offers and drops a tool it
  does not have.
- **Permissions:** reading needs `view:agent`, changing
  `update:agent`.

### A factory's team changed by asking

A factory's team is changed the way a [starter](#starters) is: a model
proposes the team as it should be after a request, shown as a diff,
and the person applies or discards it. A new factory's team is fitted
to its brief the same way, applied at once. The web UI is the
factory's Team page (`/factories/<id>/team`, see
[factory rooms](factory-rooms.md#teams)).

How it works:

- **Rows:** a change to a factory is a `starter_changes` row with
  `target = 'factory'` and `factory_id`; `base_updated_at` is
  `factories.updated_at` when it was asked. Triggers move
  `factories.updated_at` on any write to the factory, its members,
  their agents' name or instructions, or its teams
  (`packages/db/sql/001_schema.sql`).
- **Ask:** `ask_change` (`packages/core/src/starters/changes.ts`), the
  same for a starter and a factory, queues a run on the planning
  model, else the lead's, with the models and tools the workspace
  offers now (`queue_change`, `packages/db/src/starters/changes.ts`).
  One change is worked on at a time; a new request discards a waiting
  proposal.
- **Run:** the same `starter` phase and `propose_starter_change` tool
  as a starter's (`packages/runtime/src/workflow/starter/`). The model
  is given the factory's team read as starter content with each
  member's sandbox image (`factory_content`,
  `packages/rules/src/starters/factory.ts`) and the factory's
  description and brief. A member with the shell may be given a listed
  image (`factory_image_problems`, `settle_factory_proposal`).
- **Apply:** `plan_factory_change` matches the proposal to the
  factory's rows (teams by name, then lead, then place; members by
  name, then place within their role; members left out are removed).
  `apply_factory_change` (`packages/db/src/teams/change.ts`) writes it
  in one transaction: teams added, renamed, reordered and removed (a
  removed team's rooms become the leads'), members rewritten, moved,
  added with their own agents and removed, and the room settings. It
  records one version of the factory and of each member's agent, with
  the request as the reason and the run. Refused when the factory
  changed after it was asked, or while the team has turns queued,
  running or waiting. It applies to the next turns.
- **Fitting a new factory:** a factory `/new` makes without a starter
  queues a change with `factory_fit_request` and `auto_apply`
  (`queue_team_fit`, `packages/runtime/src/run/factory/team-fit.ts`).
  The brief tells the model to rewrite every member for the brief and
  to add, remove or regroup members and teams as the work needs. When
  it is proposed, the worker applies it (`apply_fitted_team`). While
  it works, no turn is queued in the factory (trigger
  `refuse_turn_during_team_fit`, and `refuse_during_team_fit` in core
  for the message the person reads) and no member is edited
  (`guard_factory_team_fit`). If it fails, the change's own status is
  `failed` with why in `error`; if it was proposed but could not be
  applied, it stays `proposed` with why in `error`, for a person to
  apply or discard. `fit_factory_team` queues the fit for a caller
  that creates a factory itself.
- **Removing a member:** `remove_factory_member`
  (`packages/core/src/teams/remove.ts`,
  `packages/db/src/teams/remove.ts`) sets
  `factory_members.removed_at`; the row stays, so messages and turns
  keep its name (`Factory.former_members`). A removed member is left
  out of the team, routing, mentions, asks, reading along, room
  instructions and new turns. Refused for a lead (another member is
  made lead first), when its team would not stand without it
  (`removal_refusal`, `packages/rules/src/teams/removal.ts`), and
  while the team has turns queued, running or waiting.
- **Deleting a factory:** `delete_factory`
  (`packages/db/src/factories/delete.ts`) deletes it with its teams,
  members, rooms, messages, turns, asks and changes, then the members'
  own agents (an agent a workflow step uses is kept). Runs,
  `run_usage`, `run_totals`, versions and audit events stay; its
  project stays with `factory_id` null. Refused while any of its turns
  or a change to its team is queued, running or waiting.

## Known limits

- A successful run can hide a broken setup: an agent works around
  stale instructions or failing tools and still reports success. A
  step can say so itself ([the agent's account](#the-agents-account)),
  which depends on the agent saying it.
- Durable recovery can repeat external actions, such as opening a pull
  request or sending a notification, after a restart
  ([#16](https://github.com/werker-ai/werker/issues/16)).
