Harness state
The harness-state layer holds task and session state for agents: the Scope that binds identity, durable runs with leases, scoped memory, and conversation history.
If an agent stops halfway through a task, a resumed run must know whose work it was, what was asked, what already happened and what is still waiting. Harness state records those facts independently of the model's memory. Scope binds the run to an identity, RunStore holds durable execution state, and ConversationStore holds the history a person reads. The three serve different purposes.
The central rule is that stored state never grants authority. A Scope is built by the host after authentication. Persisted rows, memory entries and conversation records are data. They cannot give an agent a tool, an approval or an identity.
Where the boundary is
Conversation history is what the person saw. Durable run state is what the application can resume from. Do not reconstruct the latter merely by asking a model to summarize the former.
| This layer owns | This layer does not own |
|---|---|
Scope, Task, Binding, Progress, Verification contracts | Authentication, sessions and who a user is |
| Durable run records with leases, checkpoints, events and action receipts | The model loop that produces the work (agent loop) |
| Scoped memory with revision checks | Retrieval over documents (context and memory) |
| Conversation, run and message history in SQLite | Answer policy and UI |
| The link that projects a harness run into a conversation | Tool policy and approvals (tools and permissions) |
Owners and tiers
State has three jobs, so the golden path names three complementary halves instead of one package.
| Job | Import path | Tier | What it is for |
|---|---|---|---|
| Scope binding | recohut_kit.harness.contracts (Scope, Task, Binding, Progress, Verification, ToolPolicy) | core | Frozen, validated contracts. Stdlib only. |
| Run state | recohut_kit.harness.state.RunStore | core | Scoped SQLite runs with fenced leases, checkpoints, events and exact-action receipts. No model loop. |
| Run state, driven | recohut_kit_pydantic_ai.harness.pydantic_ai.Harness | core | run, resume, wake, approve, cancel around a native PydanticAI agent. |
| Scoped memory | recohut_kit.harness.memory.MemoryStore | core | Preferences and notes per scope, with revision-checked correction and removal. |
| Conversation history | recohut_kit.conversations.sqlite_store.ConversationStore | core | Conversations, idempotent runs with admission, run-grouped messages. |
| Scoped history access | recohut_kit.conversations.scoped.ScopedConversations | core | The store bound to a host Scope and a context revision. |
| History codec | recohut_kit_pydantic_ai.conversations.messages | core | encode_model_messages and load_model_messages for native PydanticAI messages. |
| Run to conversation link | recohut_kit.harness.ConversationLink | core | Projects a harness run into an existing, explicitly owned conversation run. |
| Agent registry | recohut_kit.agents | supported | Application-declared agent registrations and persisted, inactive configuration drafts. No loop. |
| Record store | recohut_kit.records | catalog | Scoped, versioned records with compare-and-set writes and append-only history. |
| Assistant runtime | recohut_kit.assistant | catalog | A tenant-scoped assistant runtime for an existing SaaS, built on ConversationStore. |
| Workflow policy | recohut_kit.workflows | catalog | Phase dispatcher, journals, prompt files, memory policies. |
| Coordination | recohut_kit.team, recohut_kit.multi_agent | catalog | Role and delegation admission over run goals, and contracts for handoffs and consensus. |
| Row contracts | recohut_kit.persistence | catalog | Repository and unit-of-work contracts for conversation rows, with an in-memory fake. |
| Other-SDK harnesses | recohut_kit_strands.harness, recohut_kit_openai_agents.harness | catalog | The same session shape around other agent SDKs. |
| Other backends | recohut_kit_databricks.conversations, recohut_kit.integrations.sqlalchemy_persistence | catalog | Alternative conversation stores. |
SQLite plumbing comes from recohut_kit.storage.sqlite, which ConversationStore uses for its migrations. That package belongs to the data-platform layer.
How the pieces fit
The harness writes its own files under the directory you give it: harness.sqlite, memory.sqlite and steps.sqlite. The conversation store is a separate file the application owns. The two meet only through ConversationLink, and neither grants the other authority.
Resumability has two meanings. In-flight resumability (lease, approval wait, resume, wake) belongs to RunStore and Harness. ScopedConversations keeps whole completed runs and does not resume execution in progress. An application that needs both uses both.
Worked examples
Runs, leases and scope isolation
RunStore.start admits one run per scoped request. A retry of the same request returns the existing run. Another scope cannot read the run, a second worker cannot take a held lease, and a changed Binding refuses to continue.
import tempfile
from pathlib import Path
from recohut_kit.harness import Binding, Scope, Task
from recohut_kit.harness.state import RunStore
store = RunStore(Path(tempfile.mkdtemp()) / "harness.sqlite")
alice = Scope("acme", "alice", "helpdesk")
bob = Scope("acme", "bob", "helpdesk")
binding = Binding("cfg-1", "src-1") # configuration version and source version
run = store.start(
alice, "session-1", "request-1", Task("Summarise the policy"), binding,
memory_generation=0, owner="worker-a", lease_seconds=30,
)
print(run.status, run.lease_owner) # running worker-a
retry = store.start(
alice, "session-1", "request-1", Task("Summarise the policy"), binding,
memory_generation=0, owner="worker-b", lease_seconds=30,
)
print(retry.id == run.id) # True: an identical retry is not dispatched again
try:
store.get(bob, run.id) # another scope
except Exception as error:
print(type(error).__name__) # Conflict
try:
store.claim(alice, run.id, binding, memory_generation=0, owner="worker-b", lease_seconds=30)
except Exception as error:
print(error) # Another owner holds the run lease
store.cancel(alice, run.id)
other = store.start(alice, "session-1", "request-2", Task("Next"), binding,
memory_generation=0, owner="w", lease_seconds=30)
try:
store.claim(alice, other.id, Binding("cfg-2", "src-1"), memory_generation=0,
owner="w", lease_seconds=30)
except Exception as error:
print(error) # Run binding changedBinding is how the kit stops a stale checkpoint from running against new code. Change configuration when a prompt, tool, model setting or policy changes, and source when the evidence the run relied on changes.
Conversation history over several turns
ConversationStore takes an explicit file path. admit_run is idempotent per request id, so a repeated request returns the same run with created=False. Messages are encoded from the native agent's result and loaded back as message_history on the next turn.
import asyncio
import tempfile
from pathlib import Path
from pydantic_ai import Agent
from pydantic_ai.messages import ModelResponse, TextPart
from pydantic_ai.models.function import FunctionModel
from recohut_kit.conversations.scoped import ScopedConversations
from recohut_kit.conversations.sqlite_store import Conflict, ConversationStore
from recohut_kit.harness import Scope
from recohut_kit_pydantic_ai.conversations.messages import encode_model_messages, load_model_messages
root = Path(tempfile.mkdtemp())
scope = Scope(tenant="acme", actor="u-1", agent="helpdesk")
store = ConversationStore(root / "conversations.sqlite")
conversation = store.create_conversation(title=None, owner=scope.key) # the application owns the owner string
agent = Agent(FunctionModel(lambda messages, info: ModelResponse(parts=[TextPart(f"turn {len(messages)}")])))
async def turn(request_id: str, question: str):
admission = store.admit_run(conversation.id, request_id)
if not admission.created: # a replay: return what was stored
return store.get_run(admission.run.id, with_messages=True)
history = load_model_messages(store, conversation.id) # prior turns as native messages
result = await agent.run(question, message_history=history)
store.finish_run(admission.run.id, "completed",
messages=encode_model_messages(result.new_messages()))
return result.output
async def main():
print(await turn("req-1", "hello")) # turn 1
print(await turn("req-2", "again")) # turn 3
print((await turn("req-2", "again")).run.status) # completed, from the stored run
try:
store.admit_run(conversation.id, "req-2", request_fingerprint="other")
except Conflict as error:
print(error.reason) # request_reused
asyncio.run(main())
# A facade bound to a host scope: another scope cannot open this conversation.
mine = ScopedConversations(store, scope=scope, context_binding="prompt-v1")
theirs = ScopedConversations(store, scope=Scope("acme", "u-2", "helpdesk"), context_binding="prompt-v1")
shared = mine.create_conversation()
try:
theirs.get_conversation(shared.id)
except Exception as error:
print(type(error).__name__) # NotFoundA harness run projected into a conversation
ConversationLink ties the two stores together. The harness run uses the conversation id as its session id. The link never creates or reassigns a conversation, so a missing or foreign conversation is refused.
import asyncio
import tempfile
from pathlib import Path
from pydantic_ai import Agent
from pydantic_ai.messages import ModelResponse, TextPart
from pydantic_ai.models.function import FunctionModel
from recohut_kit.conversations.sqlite_store import ConversationStore
from recohut_kit.harness import Binding, ConversationLink, Scope, Task, Verification
from recohut_kit_pydantic_ai.harness.pydantic_ai import Harness, Limits
root = Path(tempfile.mkdtemp())
scope = Scope(tenant="acme", actor="u-1", agent="helpdesk")
store = ConversationStore(root / "conversations.sqlite")
conversation = store.create_conversation(title=None, owner=scope.key)
async def verify(run, output):
if output:
return Verification(True, "non-empty answer", evidence=("answer:non-empty",))
return Verification(False, "empty answer")
native = Agent(
FunctionModel(lambda messages, info: ModelResponse(parts=[TextPart("5 days carry over.")])),
instructions="Answer.",
)
harness = Harness(
native,
directory=root / "harness",
tools={},
verify=verify,
memory_tools=False,
binding=lambda: Binding(configuration="prompt-v1", source="corpus-v1"),
limits=Limits(model_requests=10),
conversation=ConversationLink(store, owner=lambda s: s.key),
)
async def main():
result = await harness.run(scope, conversation.id, "req-1", Task("How many leave days carry over?"), deps=None)
print(result.run.status, result.run.output) # completed 5 days carry over.
replay = await harness.run(scope, conversation.id, "req-1", Task("How many leave days carry over?"), deps=None)
print(replay.run.id == result.run.id) # True
print([(h.run.status, [m.role for m in h.messages]) for h in store.load_history(conversation.id)])
print(sorted(path.name for path in (root / "harness").iterdir()))
asyncio.run(main())The link keeps the conversation run open while the harness run waits for approval and seals it only on a terminal outcome. The harness directory holds harness.sqlite, memory.sqlite and steps.sqlite.
Scoped memory
MemoryStore keeps preferences and notes per scope. A write that replaces an existing key must pass the revision it observed, so a stale writer cannot overwrite a newer value. A different scope sees nothing.
import tempfile
from pathlib import Path
from recohut_kit.harness import Scope
from recohut_kit.harness.memory import MemoryStore
store = MemoryStore(Path(tempfile.mkdtemp()) / "memory.sqlite")
alice = Scope("acme", "alice", "helpdesk")
first = store.remember(alice, "reply_style", "short answers", source="user-confirmed", kind="preference")
print(first.revision) # 1
try:
store.remember(alice, "reply_style", "long answers", source="user-confirmed")
except Exception as error:
print(type(error).__name__) # Conflict: overwrite needs expected_revision
second = store.remember(alice, "reply_style", "long answers", source="user-confirmed",
expected_revision=first.revision)
print(second.value) # long answers
print(store.changed_refs(alice, (first.ref,)) == (first.ref,)) # True: the revision a run used has changed
print(store.get(Scope("acme", "bob", "helpdesk"), "reply_style")) # NoneA model observation belongs in a note, which grants no authority. A preference needs the host's confirmation. If memory a run already used is corrected or forgotten, the run ends as memory_invalidated instead of continuing on stale context.
Choosing between owners
| You need | Use |
|---|---|
| Identity and versions for one run | Scope and Binding |
| A run that survives a crash and can be approved later | Harness over RunStore |
| A chat history a UI can list and reload | ConversationStore, linked with ConversationLink |
| Access to history limited to one tenant and user | ScopedConversations |
| Remembered preferences | MemoryStore, written only on host confirmation |
| Versioned business records the model may read but not write | recohut_kit.records |
| A list of agent definitions and editable draft configs | recohut_kit.agents |
| A whole assistant runtime for an existing SaaS | recohut_kit.assistant |
| Several model-driven roles with delegation limits | recohut_kit.team or recohut_kit.multi_agent |
Failure behaviour, limits and gotchas
- Runs are admitted once.
startandHarness.runreturn the existing run for a repeatedrequest_id.ConversationStore.admit_runreturns it withcreated=False. A reused request id with a different conversation or fingerprint raisesConflict("request_reused"). - One running run per conversation. A second
admit_runwhile one is running raisesConflict("busy"). An archived conversation raisesConflict("archived"). - A held lease refuses a second owner.
Conflict: Another owner holds the run lease. The Harness renews its lease while it works, with a defaultlease_secondsof 30. - A changed
Bindingrefuses to continue. Updateconfigurationandsourcehonestly. They are re-read at every continuation. - Scopes are strict. Another scope cannot read a run or a conversation.
ScopedConversationsraisesNotFoundandRunStoreraisesConflict. This is application access control, not SQLite row security. ConversationStoreneeds a real file. An empty path,:memory:or afile:URI raisesValueError. A file with a foreign or newer schema raisesSchemaErrorand is left unchanged. Memory storage also refuses:memory:.ConversationLinkdoes not create conversations. A missing conversation, or one owned by someone else, is refused asNotFound.- Keep the two stores apart. The harness directory and the conversation database are different files with different jobs. Do not point both at one path.
- Finished runs are sealed.
append_messageson a finished run raisesConflict("not_running"). ScopedConversationskeeps whole runs only.history_runsmust be between 1 and 20. It does not resume in-flight work.- Old import names warn.
recohut_kit.harness.pydantic_aiis a deprecated shim for the package path above, and the message codec names onconversations.sqlite_storeare forwarded lazily. New code importsrecohut_kit_pydantic_ai.conversations.messages. - Optional SDKs stay lazy. Importing
recohut_kit.harnessorrecohut_kit.conversationsdoes not loadpydantic_ai.
How is this page?
Last updated on