Sub topic 4
Modeling content as states and transitions
This chapter assumes you can read basic Python (dataclasses, enums, dictionaries) and have used a content workflow with a draft, an edit, and a publish step. The code uses str | None, so it needs Python 3.10 or newer.
An AI-drafted workflow goes wrong in a predictable way. Someone edits text after it was approved, or publishes a draft nobody reviewed. A state machine closes these gaps by defining what each item can be at any moment and which moves are legal. Then the rules live in one place and not in people's habits.
The working model
A content item is always in exactly one state. A transition is a move from one state to another. The set of allowed transitions is written down as data, and every change goes through a single function that checks it.
Five states cover the basic pipeline:
| State | Meaning | Text editable? | Legal next states |
|---|---|---|---|
| `draft` | The AI draft or the author's revision is being prepared | Yes | `in_review` |
| `in_review` | A reviewer is reading the text | No | `approved`, `changes_requested` |
| `changes_requested` | A reviewer rejected this version with notes | Yes | `in_review` |
| `approved` | A reviewer other than the author accepted this exact text | No | `published` |
| `published` | The text is live | No | none |
published is terminal. If published content needs a correction, you create a new item or a new version. You do not move the old one backward. That keeps the record of what went live intact.
Notice what the diagram leaves out. No arrow goes from draft to approved, and none goes from changes_requested to approved. A reviewer must look at the resubmitted version, so a rejected item has to pass through in_review again. Missing arrows are the safety feature.
Encoding the rules as data
The transition table is a dictionary from each state to the set of states it may reach. Keeping it as data has two benefits. You can read the whole policy in ten lines, and you can test it by iterating over the table.
Three design decisions in the code below deserve attention:
- One gate for all moves.
_moveis the only place that changesstate. It checks the table, writes a log entry, and then updates the state. Every public method goes through it. - Rules that depend on who or what. The table says which moves are possible. Other rules say whether this actor may make them. The author-cannot-approve rule lives in
approve, before_moveis called. - A hash of the approved text.
approvestores a SHA-256 digest of the text.publishrecomputes it and refuses to proceed on a mismatch. This ties approval to the exact words and not just to the item.
import hashlib
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
class State(Enum):
DRAFT = "draft"
IN_REVIEW = "in_review"
CHANGES_REQUESTED = "changes_requested"
APPROVED = "approved"
PUBLISHED = "published"
ALLOWED = {
State.DRAFT: {State.IN_REVIEW},
State.IN_REVIEW: {State.APPROVED, State.CHANGES_REQUESTED},
State.CHANGES_REQUESTED: {State.IN_REVIEW},
State.APPROVED: {State.PUBLISHED},
State.PUBLISHED: set(),
}
def digest(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
@dataclass
class Item:
text: str
author: str
state: State = State.DRAFT
approved_digest: str | None = None
log: list = field(default_factory=list)
def _move(self, new_state, actor, note=""):
if new_state not in ALLOWED[self.state]:
raise ValueError(f"cannot go from {self.state.value} to {new_state.value}")
self.log.append({
"at": datetime.now(timezone.utc).isoformat(),
"actor": actor,
"from": self.state.value,
"to": new_state.value,
"note": note,
})
self.state = new_state
def revise(self, new_text, actor):
if self.state not in (State.DRAFT, State.CHANGES_REQUESTED):
raise ValueError("text can only be edited before review or after changes are requested")
self.text = new_text
self.log.append({"at": datetime.now(timezone.utc).isoformat(), "actor": actor, "edit": digest(new_text)})
def submit(self, actor):
self._move(State.IN_REVIEW, actor)
def request_changes(self, reviewer, note):
self._move(State.CHANGES_REQUESTED, reviewer, note)
def approve(self, reviewer):
if reviewer == self.author:
raise PermissionError("the author cannot approve their own item")
self._move(State.APPROVED, reviewer)
self.approved_digest = digest(self.text)
def publish(self, actor):
if self.approved_digest != digest(self.text):
raise ValueError("text differs from the approved version")
self._move(State.PUBLISHED, actor)Running a full cycle
This script, run after the class above, exercises each rule: self-approval, a revision round, and tampering after approval.
item = Item(text="Spring sale starts Monday.", author="ben")
item.submit("ben")
try:
item.approve("ben")
except PermissionError as e:
print(e)
item.request_changes("ana", "Add the end date.")
item.revise("Spring sale runs Monday to Friday.", "ben")
item.submit("ben")
item.approve("ana")
item.text = "Spring sale runs Monday to Sunday." # change made behind the workflow's back
try:
item.publish("ana")
except ValueError as e:
print(e)
item.text = "Spring sale runs Monday to Friday." # restored to the approved wording
item.publish("ana")
print(item.state.value, len(item.log))The output is:
the author cannot approve their own item
text differs from the approved version
published 6The log has six entries: submit, request changes, one edit, a second submit, approve, and publish. Failed attempts leave no entry because the check runs before anything is written. If you also want failed attempts recorded, that is a separate decision, covered in the audit trail chapter.
Why the hash check is there if editing is already blocked
revise refuses edits once the item is approved, so the hash looks redundant. It is defense in depth. In a real system, text lives in a database, and other code paths can touch it: an import job, an admin tool, a "quick fix" script, or a bug. The state check only protects paths that go through the Item methods. The hash check protects the property you actually care about, which is that what goes live is what a person approved.
Common errors
Letting state be set directly. If any caller can write item.state = State.APPROVED, the table means nothing. In a real codebase, make state read-only from outside the class, or store it in a database column that only the transition function updates. The example here is a teaching model and does not enforce that.
Checking permissions only in the interface. A hidden "Approve" button is not a control. The author check belongs in the code that performs the transition, so it holds for the API, for scripts, and for the next developer's shortcut.
Allowing edits in review. If a reviewer or author can change the text while the item is in_review, the reviewer may approve a version they never read. The table above blocks this by making in_review non-editable. If a reviewer finds a typo, the normal path is to request changes. Some teams allow reviewer edits and require a second approval afterward. That is a policy choice, and it should be explicit in the table and not an accident.
Skipping the loop. Teams sometimes add a changes_requested to approved shortcut so that "small fixes" don't need re-review. This is the most common way a gate erodes. A fix after rejection is new text, and it needs a new decision.
Confusing the AI draft with an author. Decide who the author is when an AI model writes the draft. The person who submits the draft, or the editor who owns it, is usually the right answer, because the author-cannot-approve rule needs a human identity to compare against. Recording the model as the author would let anyone approve it.
Missing states for real-world needs. Real pipelines often need rejected (abandoned for good), archived, or unpublished. Add a state only when it changes who can act or what can happen next. Each new state adds arrows to reason about.
Testing the table
Because the policy is data, you can check its shape directly. Two useful tests: every state appears as a key in ALLOWED, and no path leads from draft to published without passing through approved. A short script that walks the table finds the second property:
def reachable(start, table):
seen, stack = set(), [start]
while stack:
s = stack.pop()
for nxt in table[s]:
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
return seen
# Remove APPROVED from the table and check that PUBLISHED becomes unreachable.
no_approval = {s: targets - {State.APPROVED} for s, targets in ALLOWED.items()}
print(State.PUBLISHED in reachable(State.DRAFT, ALLOWED))
print(State.PUBLISHED in reachable(State.DRAFT, no_approval))This prints True and then False. The second line shows that approved is the only way into published, so every publish has an approval behind it.
Exercise
A teammate proposes adding the transition APPROVED -> DRAFT so authors can pull back an approved item for edits. What happens to approved_digest in the current code, and what must you change so that a later publish cannot reuse the old approval?
Show answer
In the current code approved_digest keeps the old value, so if the text were edited and then somehow restored, or if the item were re-approved incorrectly, a stale digest could linger. Reset approved_digest to None whenever the item leaves approved for any state other than published. Also keep approved out of the editable states. The item would then have to pass through in_review and approve again, which stores a fresh digest for the new text.
Exercise
In the demo, item.approve("ben") raises before _move runs. Why does the order of the author check and the _move call matter?
Show answer
If _move ran first, the state would already be approved and a log entry written when the author check failed, leaving an approved item that no valid reviewer approved. Checking first means a rejected attempt changes nothing.