Skip to Content
Recodocs

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.

8 min read

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

NameKindWhat it does
ScopedataclassAuthenticated tenant, actor, and application agent; never model-supplied
TaskdataclassCurrent request goal, constraints, and host-confirmed evidence
BindingdataclassExecutable and source identity that must match again at continuation
ProgressdataclassCompleted, remaining, and evidence tuples for working state
ActiondataclassExact tool intent with stable logical id and payload digest
VerificationdataclassApplication outcome record; passing requires authoritative evidence refs
MemoryInvalidationdataclassTerminal outcome naming memory revisions that changed
HarnessErrorexceptionObservable harness failure callers must not replace with fabricated output
ConflictexceptionScope, lease, revision, binding, or state forbids the operation
EffectUncertainexceptionAn external effect needs authoritative readback before a retry
TransientError, PermanentError, UnknownOutcomeErrorexceptionsExecution failures that call for retry, terminal failure, or reconciliation
ErrorKind, ClassifiedError, classify_errortypes and functionClassify execution errors for the owning runtime
MemoryInvalidatedexceptionUsed memory changed during execution; persisted outcome is terminal
NoProgressexceptionRepeated identical observations exhausted progress allowance
ContextOverflowexceptionProtected context cannot fit; no provider request was sent
RundataclassOne logical request; authority remains outside stored state
RunSnapshotdataclassValidated run plus digest of persisted JSON
ApprovaldataclassNamed approval of one immutable action with finite expiry
ActionRecorddataclassEffect receipt; started means the receipt has no result yet; uncertain is a separate flag, and phase is executing until mark_action_uncertain
EventdataclassSafe control metadata for a run
RunStoreclassScoped run persistence with leases and an action lifecycle, on either a SQLite path or a PostgreSQL storage
MemoryItemdataclassOne scoped memory record with provenance and revision
RecalldataclassRanked recalled items plus count omitted by limits
MemoryStoreclassPersistent scoped memory with CAS revisions and generation
ContextViewdataclassBounded projection text, memory refs, omissions, token estimate
build_contextfunctionBuilds ContextView from task, progress, and recall within a budget
MemoryStorageprotocolContract for alternate memory backends
RunStorageprotocolContract for alternate run backends
ApprovedLessonsclassReads approved learning procedures via RuntimeProcedures.select
ConversationLinkclassSyncs harness runs into an existing owned conversation store
CLUES_TEMPLATEconstantCanonical fence for compressed inter-agent clues
ClueRecorddataclassOne compressed fact or observation snippet
IsolatedContextStateclassFour-key minimal shared state for multi-agent isolation
ContextInflowPolicydataclassHost-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)

NameKindWhat it does
startmethodAdmit or return an existing run for scope, session, and request id
claimmethodClaim 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
checkpointmethodPersist working checkpoint, progress, and usage under lease
finishmethodMoves a leased running run to completed, failed, cancelled, waiting, or interrupted; completed requires a passing Verification
cancelmethodCancel a non-terminal run
prepare_actionmethodRecord a pending effect, optionally requiring approval
approvemethodAttach confirmation to an exact action digest with verified identity, current access, and a validated confirmation source by default
begin_actionmethodMove an approved or ungated action to started
reconcile_actionmethodRecords the result and marks a started action completed. Durable actions still need authoritative verification.
eventsmethodList scoped control events for a run

MemoryStore operations (selected)

NameKindWhat it does
remembermethodCreate or CAS-update a record; bumps scope generation
getmethodFetch one key if present and unexpired
recallmethodRanked query results for context packing
forgetmethodRemove a key at an expected revision
generationmethodScope revision allocator after expiry; continuation checks selected refs with changed_refs, not this counter
changed_refsmethodWhich used refs changed since a run recorded them
purgemethodDelete 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.contractsrecohut_kit.json (JsonValue, as_json_value, fingerprint)
harness.staterecohut_kit.json, recohut_kit.redaction (require_safe, safe_text), recohut_kit.storage.sqlite
harness.memoryrecohut_kit.json, recohut_kit.redaction, recohut_kit.storage.sqlite
harness.contextharness.contracts, harness.memory, harness.tokens (estimate_tokens)
harness.integrationsrecohut_kit.conversations.sqlite_store, recohut_kit.json; learning types at type-check time
harness.protocolsrecohut_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.id

Limits 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; claim stores the supplied memory generation, and another owner raises Conflict only 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.verify must also record authoritative verification before finish can complete.
  • Approvals are exact. The default path requires the digest, a credential-verified Principal, current Access, 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; forget requires expected_revision. MemoryStore rejects :memory: paths.
  • Context packing fails closed. build_context requires max_tokens (or deprecated max_chars). If the protected task and progress block plus the trust envelope (and any supplied resource map) exceed the budget, it raises ContextOverflow before 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 preference and note kinds validate on MemoryItem; host confirmation is required for preferences in the store contract docstring.
  • Integrations are projections. ConversationLink does not create conversations; ApprovedLessons delegates approval state to RuntimeProcedures.
  • ContextInflowPolicy is 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