Harness contracts, run state, and scoped memory
Deterministic host contracts, scoped run fencing with exact-action receipts, scoped memory, and bounded context projection for agent runs.
The recohut_kit.harness package is the host-facing front door for run lifecycle data: who the run belongs to, what task and binding apply, which tool actions were prepared or started, and which remembered records may appear in context. Importing the symbols re-exported from recohut_kit.harness loads no optional model SDK. Applications still own identity, tool authorization, data retention, and outcome verification.
The core also contains PostgreSQL stores, tool access, boundary policies, plans, and delegation helpers. For the optional native loop, install the PydanticAI extension with its harness extra and import Harness from recohut_kit_pydantic_ai.harness.pydantic_ai. The adapter invokes the configured PydanticAI model, which selects tools or returns a final reply.
None of the root exports makes a model call. Nothing here substitutes for authentication, lease enforcement in your workers, or authoritative readback of uncertain external effects.
Purpose
An agent's conversational answer is not enough to resume or audit its work. The harness holds the lifecycle facts the host uses to identify and manage the run.
The harness layer owns contracts that describe scope, task, binding, progress, actions, and verification without tying types to a particular agent framework. It owns durable run state (RunStore): one logical request per row, scoped leases, checkpoints, terminal outcomes, and action receipts. A started action has no stored result yet; uncertain stays false until mark_action_uncertain, and phase is executing until then. It owns scoped memory (MemoryStore): typed host preferences and untrusted notes with revision-checked correction, expiry, and generation bumps that runs can observe. It owns bounded context projection (build_context): escaped JSON for protected task state and recalled memory, with explicit omission counts and ContextOverflow when the protected envelope cannot fit.
It also ships storage protocols (MemoryStorage, RunStorage) so an alternate backend can match the same semantics, conversation and learning links (ConversationLink, ApprovedLessons) that project runs into an existing chat store or read approved procedures, context-isolation helpers (clue templates and minimal shared state), and prompt guidance for context inflow (ContextInflowPolicy) that the host selects—it is not a runtime enforcer.
The layer deliberately does not execute tools, hold model API keys, or prove that an external side effect happened exactly once. A checkpoint is not proof of an effect; Verification is an application sensor. Memory and recalled text are untrusted data, never policy or approval. Verified lessons belong to recohut_kit.learning, not the harness memory tables.
Public API
Symbols below match recohut_kit.harness.__all__. Store classes expose additional methods documented on the class; the run and memory stores are the primary mutation surfaces.
Package root exports
| Name | Kind | What it does |
|---|---|---|
Scope | dataclass | Authenticated tenant, actor, and application agent; never model-supplied |
Task | dataclass | Current request goal, constraints, and host-confirmed evidence |
Binding | dataclass | Executable and source identity that must match again at continuation |
Progress | dataclass | Completed, remaining, and evidence tuples for working state |
Action | dataclass | Exact tool intent with stable logical id and payload digest |
Verification | dataclass | Application outcome record; passing requires authoritative evidence refs |
MemoryInvalidation | dataclass | Terminal outcome naming memory revisions that changed |
HarnessError | exception | Observable harness failure callers must not replace with fabricated output |
Conflict | exception | Scope, lease, revision, binding, or state forbids the operation |
EffectUncertain | exception | An external effect needs authoritative readback before a retry |
TransientError, PermanentError, UnknownOutcomeError | exceptions | Execution failures that call for retry, terminal failure, or reconciliation |
ErrorKind, ClassifiedError, classify_error | types and function | Classify execution errors for the owning runtime |
MemoryInvalidated | exception | Used memory changed during execution; persisted outcome is terminal |
NoProgress | exception | Repeated identical observations exhausted progress allowance |
ContextOverflow | exception | Protected context cannot fit; no provider request was sent |
Run | dataclass | One logical request; authority remains outside stored state |
RunSnapshot | dataclass | Validated run plus digest of persisted JSON |
Approval | dataclass | Named approval of one immutable action with finite expiry |
ActionRecord | dataclass | Effect receipt; started means the receipt has no result yet; uncertain is a separate flag, and phase is executing until mark_action_uncertain |
Event | dataclass | Safe control metadata for a run |
RunStore | class | Scoped run persistence with leases and an action lifecycle, on either a SQLite path or a PostgreSQL storage |
MemoryItem | dataclass | One scoped memory record with provenance and revision |
Recall | dataclass | Ranked recalled items plus count omitted by limits |
MemoryStore | class | Persistent scoped memory with CAS revisions and generation |
ContextView | dataclass | Bounded projection text, memory refs, omissions, token estimate |
build_context | function | Builds ContextView from task, progress, and recall within a budget |
MemoryStorage | protocol | Contract for alternate memory backends |
RunStorage | protocol | Contract for alternate run backends |
ApprovedLessons | class | Reads approved learning procedures via RuntimeProcedures.select |
ConversationLink | class | Syncs harness runs into an existing owned conversation store |
CLUES_TEMPLATE | constant | Canonical fence for compressed inter-agent clues |
ClueRecord | dataclass | One compressed fact or observation snippet |
IsolatedContextState | class | Four-key minimal shared state for multi-agent isolation |
ContextInflowPolicy | dataclass | Host-selected prompt rules for output budget and execution style |
RESPONSE_TEMPLATE and compress_dict_to_clues are imported at the package root but not listed in __all__.
RunStore operations (selected)
| Name | Kind | What it does |
|---|---|---|
start | method | Admit or return an existing run for scope, session, and request id |
claim | method | Claim a non-terminal run whose binding matches and whose lease is free or expired; stores the supplied memory generation (a different generation is not a conflict), or ends the run as memory-invalidated when changed_memory_refs names revisions the run used |
checkpoint | method | Persist working checkpoint, progress, and usage under lease |
finish | method | Moves a leased running run to completed, failed, cancelled, waiting, or interrupted; completed requires a passing Verification |
cancel | method | Cancel a non-terminal run |
prepare_action | method | Record a pending effect, optionally requiring approval |
approve | method | Attach confirmation to an exact action digest with verified identity, current access, and a validated confirmation source by default |
begin_action | method | Move an approved or ungated action to started |
reconcile_action | method | Records the result and marks a started action completed. Durable actions still need authoritative verification. |
events | method | List scoped control events for a run |
MemoryStore operations (selected)
| Name | Kind | What it does |
|---|---|---|
remember | method | Create or CAS-update a record; bumps scope generation |
get | method | Fetch one key if present and unexpired |
recall | method | Ranked query results for context packing |
forget | method | Remove a key at an expected revision |
generation | method | Scope revision allocator after expiry; continuation checks selected refs with changed_refs, not this counter |
changed_refs | method | Which used refs changed since a run recorded them |
purge | method | Delete all items in a scope |
How it composes
The root re-exports wire together a small set of kit packages plus internal harness modules.
| Consumer (harness module) | Imports from other recohut_kit packages |
|---|---|
harness.contracts | recohut_kit.json (JsonValue, as_json_value, fingerprint) |
harness.state | recohut_kit.json, recohut_kit.redaction (require_safe, safe_text), recohut_kit.storage.sqlite |
harness.memory | recohut_kit.json, recohut_kit.redaction, recohut_kit.storage.sqlite |
harness.context | harness.contracts, harness.memory, harness.tokens (estimate_tokens) |
harness.integrations | recohut_kit.conversations.sqlite_store, recohut_kit.json; learning types at type-check time |
harness.protocols | recohut_kit.json; documents shapes implemented by MemoryStore and RunStore |
Kit callers use the core contracts for scoped persistence and effect tracking. The PydanticAI extension supplies the optional model loop.
Minimal usage example
Install uv pip install '.[connectors]' from your Kit checkout to supply Pydantic and HTTPX, which this revision imports during RunStore setup. Create a file-backed SQLite store, admit a leased run, and retry the same scoped request. Both calls return the same run ID.
from pathlib import Path
from tempfile import TemporaryDirectory
from recohut_kit.harness import Binding, RunStore, Scope, Task
scope = Scope("demo", "alice", "quotes")
binding = Binding("config-v1", "catalog-v1")
task = Task("Compare quotes", ("Show a compact table",), ("catalog:1",))
with TemporaryDirectory() as directory:
store = RunStore(Path(directory) / "runs.sqlite")
request = (scope, "session-1", "request-1", task, binding)
lease = {"memory_generation": 2, "owner": "worker-a", "lease_seconds": 60}
run = store.start(*request, **lease)
retry = store.start(*request, **lease)
assert run.status == "running" and retry.id == run.idLimits and gotchas
- Authority stays in the host.
Scope,Task, and approvals are application-supplied; stored memory never grants tool access. - Leases and binding are enforced. A different binding raises
Conflict;claimstores the supplied memory generation, and another owner raisesConflictonly while that lease is unexpired. Terminal runs do not execute again (completed,failed,cancelled,memory_invalidated). - Uncertain effects need readback. Reconcile a started action before completing the run. For an action with a durable
business_key,ActionJournal.verifymust also record authoritative verification beforefinishcan complete. - Approvals are exact. The default path requires the digest, a credential-verified
Principal, currentAccess, and a host validator for the immutable confirming message. Approval records the decision for the host to act on. - Memory is CAS keyed. Blind overwrites raise
Conflict;forgetrequiresexpected_revision.MemoryStorerejects:memory:paths. - Context packing fails closed.
build_contextrequiresmax_tokens(or deprecatedmax_chars). If the protected task and progress block plus the trust envelope (and any supplied resource map) exceed the budget, it raisesContextOverflowbefore any provider call. Token estimates are local, not provider tokenizer exact. - Recalled content is escaped, not trusted. Model-written notes may contain delimiter-like text; tests assert markup escaping in projected context.
- Preferences vs notes. Only
preferenceandnotekinds validate onMemoryItem; host confirmation is required for preferences in the store contract docstring. - Integrations are projections.
ConversationLinkdoes not create conversations;ApprovedLessonsdelegates approval state toRuntimeProcedures. ContextInflowPolicyis guidance only. It emits prompt strings; it does not enforce word or token limits at runtime.
Verification
The example checks that an identical scoped request reuses its run ID. See Verify the examples.
How is this page?
Last updated on