Software factory / Agent workflows
Write your first agent workflow
Your team keeps small bugs in Linear, and nobody has time for them. You want an agent to pick them up every few hours, fix each one, and open a pull request for a person to review.
9 min read
An agent workflow does this. It is a TypeScript file in .source/agent-workflows/, written with the same builder as a CI workflow. Its jobs can run agent steps, and the forge runs each job as a factory run.
You need admin access to the repository, and a model key for the provider that you pick (see Add a model key).
1. Connect Linear and give it to the jobs
Connect the Linear MCP server to the repository, as Give your factory an MCP server shows. Then give the connection to the two jobs of the workflow:
src mcp tools linear --agent workflow:linear-fixes/classify --agent workflow:linear-fixes/fix
A job gets the tools of a connection only when the connection names it as workflow:<workflow>/<job>.
2. Write the workflow
Add .source/agent-workflows/linear-fixes.ts:
import { agent, defineAgentWorkflow, manual, schedule, z } from '@tanstack-source/ci'
const model = { provider: 'anthropic', model: 'claude-opus-5-5' } as const
export default defineAgentWorkflow('linear-fixes', {
on: [schedule('0 */6 * * *'), manual()],
})
.job('classify', {
output: z.object({
issues: z.array(z.object({ id: z.string(), title: z.string(), description: z.string() })),
}),
steps: [
agent({
name: 'Find',
model,
prompt: 'List the open Linear issues with the label "agent". Give the id, title and description of each.',
mcp: ['linear'],
output: 'job',
}),
],
})
.job('fix', {
needs: ['classify'],
forEach: { job: 'classify', path: 'issues' },
permissions: { contents: 'write' },
budget: { maxCostUsd: 2 },
steps: [
{ name: 'Install', run: 'pnpm install' },
agent({
name: 'Fix',
model,
prompt: (ctx) =>
`Fix this Linear issue, add a test, then open a pull request into main.\n${JSON.stringify(ctx.item)}`,
tools: ['read_file', 'list_files', 'search', 'run_command', 'write_file', 'open_pr'],
mcp: ['linear'],
}),
],
})
What each part does:
on: the workflow runs every 6 hours (UTC), and when a person starts it by hand.classify: one agent step reads Linear and answers with the list.output: 'job'makes that answer the job's output, checked against the zod schema.fix: runs once for each issue in that list (forEach).ctx.itemis the issue.permissions: { contents: 'write' }: thefixjob can push and open pull requests.budget: eachfixjob stops when it reaches 2 dollars of model cost.
The jobs push to branches named agent/<workflow name>/..., so the name of the workflow cannot have .., or end with . or .lock. The CI checks refuse such a name.
3. Merge it
- Open a pull request with the file, and merge it.
- Open the repository, then Agents. Under Overview, click Workflows.
- Find
linear-fixesin the list. Each job shows the name that its writes show, for examplelinear-fixes-fix.

The forge runs workflow code only from the default branch. A pull request that changes the file does not change what runs until it merges. You do not turn the workflow on anywhere else.
If a workflow file has an error, the CI checks of the commit show it. The Workflows page then lists no workflow until you fix it.
4. Start it by hand
- On the Workflows page, click Run next to
linear-fixes. - Click Start the run. The run page opens.
From a terminal:
src factory workflow run linear-fixes
You need write access to start a run.
5. Watch the run
The run page shows the jobs as a graph: classify, then one fix cell for each issue. Click a cell to read its steps, its output and the log of its agent. The log reads as a chat, with one line for each tool that the agent used. While the cell's job runs, the log shows what the agent writes as it comes. You need write access to open the run page.

Done
Every 6 hours, each Linear issue with the agent label gets a pull request from a branch agent/linear-fixes/<name>. The pull request shows linear-fixes-fix as its author, with an Agent badge, and a person reviews and merges it.
What a job can do
Code gives each job its tools when the job starts, from its permissions and the trust level of the run. The prompt cannot change them.
| The job | What it can do |
|---|---|
| Every job | Read the code, search issues and pull requests, and comment on the item of its run |
| A job with a container | Also run commands and write files in its sandbox |
permissions: { contents: 'write' }, in a run that is not untrusted | Also comment on, label, close and reopen any issue or pull request of the repository, push to agent/<workflow>/<branch>, and open pull requests from those branches into any branch |
| An untrusted run | Only reads, and comments on the item of its run. It reaches only the package registries, and gets no secrets |
No job merges, approves, reviews or pushes to any other branch.
A job with only agent steps that read, with text prompts, and no if, gets no container. It starts at once.
Skip a job with if
Some jobs have nothing to do in some runs. For example, a job that reports the issues has nothing to say when classify finds none. Give the job an if. When it returns false, the job is skipped, and none of its steps run:
.job('report', {
needs: ['classify'],
if: (ctx) => ctx.needs.classify.output.issues.length > 0,
steps: [{ name: 'Count', do: (ctx) => console.log(`${ctx.needs.classify.output.issues.length} issues`) }],
})
- The
ifruns in the job's container, before the first step, from the workflow file on the default branch. It gets thectxof adostep: the event, the inputs, the matrix cell, theforEachelement and the outputs of the jobs it needs.ctx.setOutputandctx.idTokenthrow in it. - When it returns
false, the run page shows the job as skipped: "Its if returned false." A job that needs it, with the defaultwhen, is skipped too. - When it throws, or returns a value that is not
trueorfalse, the job fails. The run page shows why. - A job with an
ifalways gets a container. - The
ifruns one time for each cell. A cell that runs again after a lost container, or after Retry from failed step, does not run itsifagain.
Let an agent step write programs (code mode)
An agent that reads 20 files makes 20 tool calls, and each call costs one more model call. With codeMode: true, the agent can write one TypeScript program that calls its tools, and it gets only the program's result:
agent({
name: 'Find',
model,
prompt: 'List the files that import lodash.',
tools: ['read_file', 'list_files'],
codeMode: true,
})
- The agent gets the tool
execute_typescript. In a program, each tool of the step is a function namedexternal_<tool>, for exampleawait external_read_file({ path: 'src/index.ts' }). These are the step's forge tools, custom tools and media tools. MCP tools and skills are not functions of a program. - The program runs with node in the job's container, in the checkout, with the environment of a
runstep. A job with a code mode step always gets a container. - The agent gets the value that the program returns, as JSON, and the program's console output. The job reads the last 1 MiB of the program's output, so a result can be up to about 1 MiB.
- A program runs for at most the time that its step has left. When that time runs out, the program stops and the step ends, as an agent step does when its time runs out.
- One program runs at a time. When the agent sends two programs in one answer, the second one does not run: the agent gets "One program runs at a time. Wait for the result of the program that runs, then send the next one."
- A program can be up to about 60 KiB of TypeScript. A longer one does not run: the agent gets "The program is over 64 KiB. Send a shorter one."
Turn a workflow off
An admin can disable each workflow. A disabled workflow starts no run, by hand or on a trigger.
- On the Workflows page, click Disable. Click Enable to turn it on again.
- From a terminal:
src factory workflow disable linear-fixes.
What does not work yet
- In a
dostep,ctx.addPathputs a directory first onPATHfor the later steps of the job, as it does in a CI job.setup.node(),setup.pnpm()andsetup.bun()use it, so a later step finds the program. The directories stay for the rest of the job, including after the job object restarts. A new container after a lost one does not have those programs until a step installs them again. The shell of adostep (ctx.sh) has the container'sPATH(/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin), with those directories first, so a script that starts with#!/usr/bin/env node, such as corepack, findsnode. - In a
dostep,ctx.afterJobandctx.summarythrow.
Next
- Start a workflow on an event: run on a new issue, a label, a push or a merge.
- Pass typed outputs between jobs:
output,ctx.needsandforEach. - Keep long jobs going: what happens when a container stops, and how to retry.
- Budgets and limits: stop a job at a cost, and the 2-hour limit.
- Run a coding CLI in a step: Claude Code, Codex or OpenCode. Grok Build is disabled until controlled workspace routing has proof.
Storage preparation
The current storage policy is preparation. Steps keep their time and spend budgets. A job does not go on in a new job: it stops at the 2-hour limit of one job.
Preparation reads legacy and native format 5 logs. Safe legacy writes continue. Writes that need format 5 wait for verified compatible runner and web deployments and a 300-second drain of old objects. Roll back only to a compatible preparation or refusal release. A TEXT-only release cannot read new history safely. Repository-scope and backup fingerprint guards still apply after storage activation. See the repository README, "Prepare the factory log storage rollout", for the exact activation change and proof.
Model spend uses durable receipts. A receipt keeps its account, source job, and original UTC billing month. Delivery retries do not charge it twice. CLI proxy calls keep reservations before they reach the provider. A reset counts an interrupted call as estimated usage and does not resend it. Proxy call receipts own these charges; step totals only carry logical usage and budgets. Custom model calls also use call receipts. Their job totals do not charge those calls again. Own-key calls count usage but do not charge the forge.
Unresolved receipts and reservations remain until settlement. They keep their original account and billing month. A matching acknowledgement remains valid without an age limit. Failed deliveries retry independently in bounded batches. Job teardown and chat reset preserve pending delivery alarms. Custom calls reserve usage before upstream work. Unknown custom calls retain their reservations and never resend automatically. Each completed chat call records its charge before the next call.