# Write and check a Workflow

A Workflow is a small Python package: `Agent` instances are the roles, `Context` objects set what each model call sees, plain functions set the order. Once `openprogram programs check` passes, its entries are callable tools. To show instead of write: [record a demonstration](https://fzkuji.github.io/OpenProgram/docs/capabilities/workflows/recording.html).

## Contract in `README.md`

| Item | Required |
| --- | --- |
| Purpose | The concrete task and the evidence needed to complete it |
| Input | Entry parameters, required context, invalid-input behavior |
| Output | Return type, files produced, how success is verified |
| Effects | Model, tool, file, network and external-submission behavior |
| Failure and cancellation | What remains after a failure or interruption; whether retry is safe |
| Dependencies | Imported Workflows, required tools and services |
| Tests | Behavior checks, scripted model replies, separate live checks |
| Usage | One reproducible invocation and its expected result |

Keep functions small. Handle expected invalid input explicitly; let runtime cancellation propagate.

## Layout

```
~/.openprogram/programs/project_report/
├── .git/
├── README.md
├── __init__.py
├── workflow.py
├── steps/
│   └── prepare.py
└── tests/
    └── test_workflow.py
```

The directory name is the package name: a lowercase Python identifier, not a standard-library module or another importable package. Each Workflow is its own Git repository. It imports under its own name (`project_report.steps.prepare`); relative imports and imports of other Workflows both work.

## Roles, Context, functions

| Object | Rule |
| --- | --- |
| Role | `Agent` at module top level. Configuration only: `model`, `instructions`, `tools`, `effort`. Without a model it uses the caller's. |
| Context | Built inside functions, passed to role calls explicitly |
| Function | Plain Python: calls roles, transforms, branches, loops |

```
"""Prepare a project report from verified notes."""

from openprogram import Agent, Context

writer = Agent(instructions="You write project reports.")
reviewer = Agent(instructions="You check facts.", tools=[])


def project_report(notes: str) -> str:
    """Turn this week's project notes into a report."""
    ctx = Context({"notes": notes})
    draft = write_draft(ctx)
    return check(draft, ctx)


def write_draft(ctx: Context) -> str:
    """Write three sections: progress, problems, plans. At most three items each."""
    return writer("Write this week's report", context=ctx)


def check(draft: str, ctx: Context) -> str:
    """Only check that the draft matches the notes. Do not change the style."""
    return reviewer("Fix any mismatch and return the final text",
                    context=ctx.derive({"draft": draft}))


PROGRAM_ENTRIES = [project_report]
```

- `role(prompt, context=ctx)` runs one model turn with the role's tools; `role.choose(prompt, {id: label}, context=ctx)` returns an option ID. Workflow code never calls the free `llm()` or `agent()`.
- `PROGRAM_ENTRIES` lists the tools. Each needs a docstring (tool description) and a type annotation on every parameter (tool schema).
- No decorators, base classes or dispatch tables. Use another Workflow through a normal import.

## What one model call sees

| Part, in order | Defined by |
| --- | --- |
| The role's `instructions`, as the system prompt | `Agent(...)` |
| History, empty by default | `history` of `ctx` |
| Docstring of the Workflow function that called | That function |
| Named blocks of `ctx`, each `name:` then value | The code that builds or derives `ctx` |
| `prompt` | The call |

Nothing else enters: no chat history, recalled memory or other roles' outputs. Context never changes tools or permissions. The docstring comes from the nearest Workflow-package function on the stack and applies to that one request; helpers without one add nothing.

### Context

| Form | Effect |
| --- | --- |
| `Context({"notes": notes})`, `ctx["notes"] = notes` | Blocks |
| `Context(providers={"today": lambda c: ...})` | Synchronous callable evaluated at each call |
| `ctx.derive({...})` | Independent copy; the caller's `ctx` is unchanged |
| `history=None` | No history, the default for a role call |
| `history="thread"` | Earlier calls with this same `ctx` object |
| `history="chat"` | The conversation that invoked the Workflow |
| `history=callable` | `(node, context) -> bool` selects conversation nodes |

History goes in `Context(..., history=...)` or `ctx.derive(history=...)`.

Built-in providers show a model where its call sits:

```
from openprogram.runtime.context import call_path, workflow_source

ctx = Context(providers={"call path": call_path, "program": workflow_source})
```

`call_path` lists Workflow functions on the stack (`project_report → check`); `call_path(docs=True)` adds docstrings. `workflow_source` returns the entry's source. A plain block such as `{"flow": "Draft first, then review."}` also works.

### Entry options

```
ENTRY_OPTIONS = {
    "project_report": {
        "input": {"notes": {"description": "This week's notes", "multiline": True}},
    },
}
```

`ENTRY_OPTIONS` maps an entry to tool options. `"run_in_worker": True` runs in the worker instead of a forked subprocess, for worker-owned state such as browser sessions.

### Resume after a restart

```
from openprogram.runtime.agent.durable_steps import step


def project_report(notes: str) -> str:
    """Turn this week's project notes into a report."""
    draft = step("draft", write_draft, notes)
    return step("check", check, notes, draft)


ENTRY_OPTIONS = {"project_report": {"resumable": True}}
```

| Rule | Detail |
| --- | --- |
| Steps | Runs once, result saved. On continuing the entry reruns from the top; completed steps return saved results, so role calls do not repeat. |
| Outside steps | Runs again: keep it deterministic and side-effect free, with stable step names and order |
| Values | Arguments and results are JSON. A `Context` does not survive; build it inside the step. |
| Continuing | Restart: automatic within `execution.auto_resume_window_seconds`. Paused: from the chat. |
| Changed code | A run is tied to the commit. `execution.code_change_policy`: `keep_original` (default) stops with "Workflow code changed"; `use_latest` continues, and a removed or reordered completed step stops it. |
| Limits | Synchronous; no `run_in_worker` |

## Execution parameters

Users give task, evidence and deliverable, never model IDs, effort, iterations, timeouts, token budgets or retries.

| Case | Rule |
| --- | --- |
| Fixed values | On the role or in code |
| Values that depend on the task | One role call makes the complete plan; code validates keys, types, ranges and limit relationships, and falls back to a validated default |
| Precedence | User constraints and application limits beat model output |
| Resume | A resumable Workflow checkpoints the plan |

## Behavior tests

```
from openprogram.programs._authoring.testing import script_roles

from project_report import workflow as wf


def test_reviewer_sees_the_draft_but_not_the_writer_prompt():
    with script_roles({wf.writer: ["Draft"], wf.reviewer: ["Final"]}) as calls:
        assert wf.project_report("Shipped the parser.") == "Final"

    request = calls[wf.reviewer][0]
    assert "Do not change the style" in request.text      # check() docstring
    assert "Draft" in request.text                        # the draft block
    assert "Write this week's report" not in request.text
    assert request.history_text == ""
```

- A reply is a string or JSON-serializable value (for `response_format`); for `role.choose`, the option ID.
- An exception in the script is raised by the call and stays queued, so it answers the model loop's retries too.
- `request.text`: instructions, docstring, blocks, prompt. `request.history_text`: history.
- Patch tools, files and services with `monkeypatch`. Live provider checks cannot run during a check: keep them out of `tests/`.

## Check and list

```
openprogram programs check ~/.openprogram/programs/project_report
openprogram programs check ~/.openprogram/programs/project_report -m "Tighten the review step"
openprogram programs list
```

1. Imports the package in a separate process and validates `PROGRAM_ENTRIES` and signatures.
2. Runs `tests/` with pytest, in the OS sandbox when available: no network, package read-only, `HOME` an empty temporary directory.
3. Commits to the Workflow's repository when all pass and records that commit in `refs/openprogram/checked`. `-m` sets the message; `--json` prints the report.

Only the checked commit loads: a plain `git commit` does not, and uncommitted edits keep the checked version serving, across restarts too. The worker watches `~/.openprogram/programs` and reloads within seconds. `programs list` and the Programs page show `loaded`, `error` (with the error) or `pending` (with the reason, such as no checked commit yet). History and rollback use Git.

| Case | Behavior |
| --- | --- |
| Where it runs | A copy of the checked commit in `~/.openprogram/programs-cache/<name>/<commit>/`. Files read next to the code must be committed; anything written belongs outside the package. |
| New version fails to import | The previous one keeps running. State `error`, note "Kept version `<old>`; version `<new>` failed." The Programs page heads a red line under the title with it, then the reason and a **See full error** link. |
| Calls still running | The new version waits for them up to 30 seconds, then tries again on the next pass. |

## Run

| From | How |
| --- | --- |
| Chat | Each entry is a tool |
| Programs page | **Abilities → Programs**, select under **Applications**, **Use** opens the form in chat; nothing runs until sent |
| Command line | `openprogram programs run <entry> -a key=value` |
| Python | Importable functions |

Each entry call is recorded in the session graph with a child node per role call, holding the exact request. Plain functions are not recorded.
