Skip to content

Commit d02bbda

Browse files
committed
Core: Django-style states, Machine with build-time checks, start/fire/advance, and the base, locmem and django state backends
0 parents  commit d02bbda

26 files changed

Lines changed: 2379 additions & 0 deletions

‎.github/workflows/deploy.yml‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
name: Deploy
2+
3+
on:
4+
push:
5+
branches: [main]
6+
7+
jobs:
8+
test:
9+
runs-on: ubuntu-latest
10+
steps:
11+
- uses: actions/checkout@v4
12+
13+
- uses: actions/setup-python@v5
14+
with:
15+
python-version: "3.12"
16+
17+
- uses: astral-sh/setup-uv@v5
18+
19+
- name: Install
20+
run: uv pip install --system -e ".[dev]"
21+
22+
- name: Run tests
23+
run: pytest
24+
25+
# Every green push to `main` is a release. The version is derived here, not committed, so it
26+
# cannot drift out of sync with what actually shipped.
27+
publish-pypi:
28+
if: github.ref == 'refs/heads/main'
29+
needs: test
30+
runs-on: ubuntu-latest
31+
# Required: the PyPI trusted publisher is registered against this workflow filename
32+
# *and* this environment name. Do not add a required reviewer to it — that would put
33+
# every push behind a manual approval, which is the thing this job exists to remove.
34+
environment: pypi
35+
permissions:
36+
id-token: write # PyPI trusted publishing
37+
steps:
38+
- uses: actions/checkout@v4
39+
with:
40+
fetch-depth: 0 # the version is a commit count; a shallow clone cannot count
41+
42+
- name: Derive the version from the commit count
43+
id: version
44+
run: |
45+
set -euo pipefail
46+
base=$(grep -m1 '^version = ' pyproject.toml | cut -d'"' -f2 | cut -d. -f1,2)
47+
patch=$(git rev-list --count HEAD)
48+
version="${base}.${patch}"
49+
echo "Releasing ${version}"
50+
sed -i "0,/^version = .*/s//version = \"${version}\"/" pyproject.toml
51+
echo "value=${version}" >> "$GITHUB_OUTPUT"
52+
53+
- name: Build sdist + wheel
54+
run: pipx run build
55+
56+
- name: Publish to PyPI
57+
uses: pypa/gh-action-pypi-publish@release/v1
58+
with:
59+
skip-existing: true # a re-run of an already-published commit is a no-op

‎.gitignore‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
__pycache__/
2+
*.pyc
3+
.venv/
4+
*.egg-info/
5+
.pytest_cache/
6+
dist/

‎CLAUDE.md‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# CLAUDE.md
2+
3+
## Rules
4+
5+
- **Commits**: No `Co-Authored-By` lines. Single-line messages (no body). Same convention as
6+
OpenOutFind, OpenOutSend and OpenOutLearn.
7+
- **Always work on `main`.** Never create or switch to a feature branch.
8+
- **Every green push to `main` is a release.** `.github/workflows/deploy.yml` runs the tests, then
9+
derives the version from the commit count and publishes to PyPI via trusted publishing
10+
(environment `pypi`). `needs: test` is the whole gate.
11+
- **No memory**: never use the auto-memory system.
12+
- **No roadmap here.** Work is tracked in `openoutreach-docs/roadmap/AgenticFSM/`. The design,
13+
the milestones and what was weighed and not taken are in
14+
`p1-e3-agentic-fsm-first-version.md` there. Read it before changing the interface.
15+
- **This is a general-purpose library.** Nothing from OpenOutreach's domain (deals, leads,
16+
batches) goes in the code, the docstrings, the README or the tests. The example everywhere is
17+
a shop `Order`. A machine for a real domain lives in the repo that uses the library, as models
18+
live in a Django project and not in Django.
19+
- **The core imports no database and no framework.** `states.py` and `machine.py` use the
20+
standard library only. Anything a backend needs is imported inside that backend's package and
21+
is an optional extra in `pyproject.toml`.
22+
23+
## Project Overview
24+
25+
`agentic_fsm` keeps entity lifecycles: many rows that each sit in a state for days and are moved
26+
by whoever knows something new. A machine is three plain Python things.
27+
28+
- **States** (`states.py`): declared like Django model fields, `pending = InitialState("...")`.
29+
`_StatesMeta` replaces each declaration with its stored value before the enum is built, so the
30+
class is a real `str` enum (`Order.paid == "paid"`, usable as a Pydantic type) whose members
31+
keep their description and kind. The description is required; it's the state's definition.
32+
- **Steps**: a named function of the entity that returns the next state, or `None` for "not now".
33+
- **Transitions**: one list of `(from, to, step)` rows; `from` may be a tuple. A step's allowed
34+
targets out of a state are the rows it sits on there.
35+
36+
`Machine(states, rows, load=, backend=, name=)` (`machine.py`) checks the declaration and raises
37+
`MachineError` naming the state or row. Then:
38+
39+
| Call | Does |
40+
|---|---|
41+
| `start(id)` | puts an entity in the initial state; `AlreadyStarted` if it has one |
42+
| `fire(id, step)` | runs one step (the function or its name); returns the logged `Move`, or `None` for "not now" |
43+
| `advance()` | per unfinished entity, tries the steps out of its state in list order and stops at the first that doesn't return `None`: at most one move per entity per call |
44+
| `state_of(id)`, `in_state(state)`, `history(id)` | reads |
45+
| `graph()` | states and rows as data |
46+
47+
A result outside the step's rows, or one that isn't a state, is logged as a refused `Move`
48+
(`applied=False`, with a `reason`) and never applied. `fire` raises `TransitionError` when the
49+
move can't even be tried (unknown step, entity not started, step doesn't leave the state). Entity
50+
ids are stored as text, so `load` receives a string. The machine never opens a transaction around
51+
a step: a step may send an email or call a model.
52+
53+
## State backends
54+
55+
Laid out and chosen as Django lays out its database backends: one package per backend, each with
56+
a `base` module holding a `StateBackend`, picked by the package's dotted path
57+
(`AGENTIC_FSM_BACKEND=agentic_fsm.backends.django`, or `Machine(..., backend=)`; a machine with
58+
neither raises). `backends/__init__.py:get_backend` imports `<path>.base` on first use.
59+
60+
- `backends/base/base.py`: `BaseStateBackend` (seven calls: `start`, `move`, `refuse`, `current`,
61+
`in_state`, `all_current`, `history`), plus the `Move` and `Current` dataclasses.
62+
- `backends/locmem/`: in memory, for tests.
63+
- `backends/django/`: a Django app (`INSTALLED_APPS = ["agentic_fsm.backends.django"]`, label
64+
`agentic_fsm`) with two models, `LogEntry` (append-only) and `CurrentState` (one row per
65+
entity, with a `version`), and their migration. It's the only place Django is imported.
66+
67+
Every backend keeps the same two things and the same rule: a move rewrites the entity's
68+
current-state row and appends its log row in one transaction, and only if the entity's version is
69+
still the one read before the step ran. A move that finds another version is logged as refused.
70+
71+
## Tests
72+
73+
```bash
74+
uv venv && uv pip install -e ".[dev]"
75+
pytest
76+
```
77+
78+
`tests/conftest.py` holds the example `Order` machine. Its `backend` fixture is parametrized, so
79+
every test that takes `orders` or `backend` runs once on `locmem` and once on `django`
80+
(pytest-django, in-memory SQLite, `tests/settings.py`). A new backend is added to that fixture
81+
and must pass the same tests. After changing a model, write the migration and check
82+
`DJANGO_SETTINGS_MODULE=tests.settings python -m django makemigrations --check --dry-run`.

0 commit comments

Comments
 (0)