Skip to Content
Recodocs

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.

9 min read

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 ownsThis layer does not own
Scope, Task, Binding, Progress, Verification contractsAuthentication, sessions and who a user is
Durable run records with leases, checkpoints, events and action receiptsThe model loop that produces the work (agent loop)
Scoped memory with revision checksRetrieval over documents (context and memory)
Conversation, run and message history in SQLiteAnswer policy and UI
The link that projects a harness run into a conversationTool 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.

JobImport pathTierWhat it is for
Scope bindingrecohut_kit.harness.contracts (Scope, Task, Binding, Progress, Verification, ToolPolicy)coreFrozen, validated contracts. Stdlib only.
Run staterecohut_kit.harness.state.RunStorecoreScoped SQLite runs with fenced leases, checkpoints, events and exact-action receipts. No model loop.
Run state, drivenrecohut_kit_pydantic_ai.harness.pydantic_ai.Harnesscorerun, resume, wake, approve, cancel around a native PydanticAI agent.
Scoped memoryrecohut_kit.harness.memory.MemoryStorecorePreferences and notes per scope, with revision-checked correction and removal.
Conversation historyrecohut_kit.conversations.sqlite_store.ConversationStorecoreConversations, idempotent runs with admission, run-grouped messages.
Scoped history accessrecohut_kit.conversations.scoped.ScopedConversationscoreThe store bound to a host Scope and a context revision.
History codecrecohut_kit_pydantic_ai.conversations.messagescoreencode_model_messages and load_model_messages for native PydanticAI messages.
Run to conversation linkrecohut_kit.harness.ConversationLinkcoreProjects a harness run into an existing, explicitly owned conversation run.
Agent registryrecohut_kit.agentssupportedApplication-declared agent registrations and persisted, inactive configuration drafts. No loop.
Record storerecohut_kit.recordscatalogScoped, versioned records with compare-and-set writes and append-only history.
Assistant runtimerecohut_kit.assistantcatalogA tenant-scoped assistant runtime for an existing SaaS, built on ConversationStore.
Workflow policyrecohut_kit.workflowscatalogPhase dispatcher, journals, prompt files, memory policies.
Coordinationrecohut_kit.team, recohut_kit.multi_agentcatalogRole and delegation admission over run goals, and contracts for handoffs and consensus.
Row contractsrecohut_kit.persistencecatalogRepository and unit-of-work contracts for conversation rows, with an in-memory fake.
Other-SDK harnessesrecohut_kit_strands.harness, recohut_kit_openai_agents.harnesscatalogThe same session shape around other agent SDKs.
Other backendsrecohut_kit_databricks.conversations, recohut_kit.integrations.sqlalchemy_persistencecatalogAlternative 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.

run_store.py
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 changed

Binding 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.

conversations.py
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__)                            # NotFound

A 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.

harness_conversation.py
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.

memory.py
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"))  # None

A 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 needUse
Identity and versions for one runScope and Binding
A run that survives a crash and can be approved laterHarness over RunStore
A chat history a UI can list and reloadConversationStore, linked with ConversationLink
Access to history limited to one tenant and userScopedConversations
Remembered preferencesMemoryStore, written only on host confirmation
Versioned business records the model may read but not writerecohut_kit.records
A list of agent definitions and editable draft configsrecohut_kit.agents
A whole assistant runtime for an existing SaaSrecohut_kit.assistant
Several model-driven roles with delegation limitsrecohut_kit.team or recohut_kit.multi_agent

Failure behaviour, limits and gotchas

  • Runs are admitted once. start and Harness.run return the existing run for a repeated request_id. ConversationStore.admit_run returns it with created=False. A reused request id with a different conversation or fingerprint raises Conflict("request_reused").
  • One running run per conversation. A second admit_run while one is running raises Conflict("busy"). An archived conversation raises Conflict("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 default lease_seconds of 30.
  • A changed Binding refuses to continue. Update configuration and source honestly. They are re-read at every continuation.
  • Scopes are strict. Another scope cannot read a run or a conversation. ScopedConversations raises NotFound and RunStore raises Conflict. This is application access control, not SQLite row security.
  • ConversationStore needs a real file. An empty path, :memory: or a file: URI raises ValueError. A file with a foreign or newer schema raises SchemaError and is left unchanged. Memory storage also refuses :memory:.
  • ConversationLink does not create conversations. A missing conversation, or one owned by someone else, is refused as NotFound.
  • 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_messages on a finished run raises Conflict("not_running").
  • ScopedConversations keeps whole runs only. history_runs must be between 1 and 20. It does not resume in-flight work.
  • Old import names warn. recohut_kit.harness.pydantic_ai is a deprecated shim for the package path above, and the message codec names on conversations.sqlite_store are forwarded lazily. New code imports recohut_kit_pydantic_ai.conversations.messages.
  • Optional SDKs stay lazy. Importing recohut_kit.harness or recohut_kit.conversations does not load pydantic_ai.

How is this page?

Last updated on