Skip to content

Job Framework

job_framework — Foundation for all 32 G6 economic job agents.

Cluster: Job Agents | Type: component | MCP Tools: 11

Overview

Foundation layer for all 32 G6 economic job agents. Provides the shared JobAgentBlock base class, JobInput/JobOutput schemas, sector classification enums, per-sector safety profiles, a SQLite-backed JobStore, token-bucket rate limiting, multi-tenant isolation, a tamper-evident audit trail, inter-agent communication protocols (A2A, AP2, UCP, Claw/NanoClaw/OpenClaw), capability protocols, agent algebra, federation operators, and an async bridge — everything a job agent needs except the domain logic itself.

When to use:

  • Building a new domain-specific job agent by subclassing JobAgentBlock
  • Composing multiple job agents into a federated team with TeamBlock or the +/@ algebra operators
  • Querying the sector registry to discover which agents are available for a given industry or S&P 500 sector
  • Enforcing safety profiles, rate limits, and audit trails uniformly across all economic-sector agents

Production hardening caveat

The job framework component is functionally hardened for launch: the full tests/mvp/job_framework suite passes, recipe step timeouts are enforced, production readiness checks require an LLM backend, and runtime health now fails on pool/cache probe failures. The remaining caveats are non-blocking verification warnings rather than known runtime defects: pytest-asyncio's default fixture loop scope deprecation, a Pydantic warning from adapt_pandas.DataInput.schema, httpx's raw-content upload deprecation in tests, and Pydantic serializer warnings from mocked or LLM-like message objects. Track these as dependency/test-hygiene cleanup before tightening warning-as-error CI.

Example:

from mvp.job_framework import JobAgentBlock, JobInput, JobRegistry, get_job_registry

registry: JobRegistry = get_job_registry()
agents = registry.by_sector("secondary")  # all manufacturing-tier agents

block = JobAgentBlock(name="demo_agent")
result = block.infer(JobInput(
    task="Summarise Q1 KPIs and flag any resource overruns",
    context={"period": "2026-Q1"},
))
# result.ok → True; result.value → JobOutput with result, artifacts, steps_taken

Works well with: job_manager, job_analyst, align_csf

Public API

CapabilityType

Type-theoretic representation of an agent's capability set.

Field Type Default
protocols frozenset[type] field(default_factory=frozenset)

Methods:

satisfies(protocol: type) -> bool

Check whether this type includes the given protocol.

product(other: CapabilityType) -> CapabilityType

Intersection of two capability types (A × B).

coproduct(other: CapabilityType) -> CapabilityType

Union of two capability types (A + B).

arrow(target: CapabilityType) -> CapabilityType

Function type A → B: capabilities needed to transform A into B.

difference(other: CapabilityType) -> CapabilityType

Protocols in self not present in other.

is_empty() -> bool

True when this type carries no protocols.

AgentCategory

Category of agents: objects are agent classes, morphisms are

Methods:

objects() -> frozenset[type]

Return all registered agent types.

register(agent_cls: type) -> None

Register an agent type as a category object.

morphism(source: type, target: type, transform: Callable | None = None) -> Callable | None

Get or set the morphism (transformation) between two agent types.

compose(f_key: tuple[type, type], g_key: tuple[type, type]) -> Callable | None

Compose morphisms f: A→B and g: B→C into g∘f: A→C.

identity(agent_cls: type) -> Callable

Identity morphism for an agent type.

functor(source_cat: AgentCategory, obj_map: dict[type, type], mor_map: dict[tuple[type, type], Callable] | None = None) -> AgentCategory

Apply a functor from source_cat into self, mapping objects and morphisms.

natural_transformation(source_functor: dict[type, type], target_functor: dict[type, type], components: dict[type, Callable] | None = None) -> dict[type, Callable]

Define a natural transformation between two functors.

validate_composition() -> list[str]

Verify associativity of all composable morphism triples.

to_dict() -> dict

Serialize the category to a JSON-safe dict.

from_dict(data: dict, class_registry: dict[str, type] | None = None) -> AgentCategory

Deserialize from a dict.

AgentAlgebra

Algebraic operations on agents with equational law verification.

Methods:

capability_set(agent: Any) -> frozenset[type]

Extract the capability set from an agent instance or class.

union(a: Any, b: Any) -> frozenset[type]

Algebraic union of two agents' capability sets (A ∪ B).

compose(a: Any, b: Any) -> frozenset[type]

Algebraic composition: capabilities of a then b (union — both available).

identity() -> frozenset[type]

Identity element for union: empty set.

difference(a: Any, b: Any) -> frozenset[type]

Capabilities in a not present in b.

is_subtype(a: Any, b: Any) -> bool

True if a's capabilities are a subset of b's.

compatibility_score(a: Any, b: Any) -> float

Jaccard similarity between two agents' capability sets.

minimal_extension(a: Any, target_capabilities: frozenset[type]) -> frozenset[type]

Capabilities a must add to satisfy target_capabilities.

verify_laws(a: Any, b: Any, c: Any) -> Result[dict]

Verify algebraic laws hold for three agents.

EvidenceKind(str, _Enum)

TraceStep

AuditReport

Methods:

to_dict() -> dict

AuditTrail

Accumulates decision trace steps for a single workflow execution.

Constructor:

Parameter Type Default
workflow_id str required

Methods:

add_step(step_name: str, output: str, evidence_kind: EvidenceKind, evidence_ref: _Optional_audit[str]) -> TraceStep

add_provenance_step(step_name: str, output: str, evidence_kind, source: str, url = None, freshness_seconds = None)

Convenience wrapper: create a structured provenance ref and call add_step.

generate_report() -> AuditReport

Extensible(Protocol)

Agent can extend its own capabilities at runtime.

Methods:

extend(extension: dict[str, Any]) -> Result[dict]

learn_from_business(domain: str, rules: list[str]) -> Result[dict]

get_extensions() -> Result[list[dict]]

HumanLearnable(Protocol)

Agent can receive and internalise human instructions.

Methods:

receive_instruction(instruction: str, context: dict[str, Any] | None = None) -> Result[dict]

create_skill(name: str, description: str, steps: list[str]) -> Result[dict]

list_skills() -> Result[list[dict]]

HumanTrainable(Protocol)

Agent can be trained via structured curricula.

Methods:

teach(topic: str, material: str) -> Result[dict]

generate_curriculum(domain: str, level: str = 'beginner') -> Result[dict]

assess_understanding(topic: str) -> Result[dict]

Collaborative(Protocol)

Agent can propose, negotiate, and co-execute with peers.

Methods:

propose(task: str, to_agents: list[str]) -> Result[dict]

negotiate(proposal_id: str, counter: dict[str, Any]) -> Result[dict]

co_execute(task: str, partners: list[str]) -> Result[dict]

ProblemSolvable(Protocol)

Agent can decompose, solve, and verify problems.

Methods:

decompose(problem: str) -> Result[list[str]]

solve(problem: str, context: dict[str, Any] | None = None) -> Result[dict]

verify_solution(solution: dict[str, Any], spec: str) -> Result[dict]

ExternallyAdaptable(Protocol)

Agent can connect to and invoke external tools.

Methods:

connect(service: str, config: dict[str, Any]) -> Result[dict]

invoke_external(service: str, operation: str, params: dict[str, Any] | None = None) -> Result[dict]

list_external_tools() -> Result[list[dict]]

AgentCommunicable(Protocol)

Agent can discover, message, and transact with other agents.

Methods:

discover_agents(query: str = '') -> Result[list[dict]]

send_task(agent_id: str, task: str, payload: dict[str, Any] | None = None) -> Result[dict]

receive_task(task_id: str) -> Result[dict]

initiate_payment(mandate: dict[str, Any]) -> Result[dict]

KnowledgeGrounded(Protocol)

Agent can ground reasoning in a knowledge base.

Methods:

ground(claim: str, domain: str = 'general') -> Result[dict]

search_kb(query: str, top_k: int = 5) -> Result[list[dict]]

update_kb(fact: str, domain: str = 'general') -> Result[dict]

Memorable(Protocol)

Agent can remember, recall, reflect on, and forget experiences.

Methods:

remember(key: str, value: Any) -> Result[dict]

recall(key: str) -> Result[Any]

reflect(topic: str = '') -> Result[dict]

forget(key: str) -> Result[dict]

Actuatable(Protocol)

Agent can sense and actuate in physical or simulated environments.

Methods:

sense(sensor: str, params: dict[str, Any] | None = None) -> Result[dict]

act(effector: str, command: dict[str, Any]) -> Result[dict]

get_effectors() -> Result[list[str]]

get_sensors() -> Result[list[str]]

ClawIntent

A typed OpenClaw/NanoClaw operation selected from natural language.

Field Type Default
component str required
op str required
params dict[str, Any] field(default_factory=dict)
needs_clarification bool False
dry_run bool False
reason str ''

ConfidenceScorer

Derive calibrated confidence from tool-call and schema signals.

Field Type Default
llm_self_score float \| None None
calibrated_prior 'CalibratedPrior \| None' None
TOOL_WEIGHT float field(default=0.5, repr=False)
SCHEMA_WEIGHT float field(default=0.3, repr=False)
LLM_WEIGHT float field(default=0.2, repr=False)

Methods:

record_tool_call(success: bool) -> None

Record outcome of one tool invocation.

record_schema_validation(passed: bool) -> None

Record outcome of one schema validation check.

has_signals() -> bool

True when at least one tool call or schema check has been recorded.

tool_success_rate() -> float

Observed ratio; None if no calls recorded yet.

schema_validation_rate() -> float

Observed ratio; sentinel -1.0 if no checks recorded yet.

score() -> float

Return weighted confidence score in [0.0, 1.0].

score_with_basis() -> tuple[float, str]

Return (score, explanation) describing what contributed to confidence.

TaskType(str, _Enum_conf)

ConfidenceScore

ConfidenceEstimator

Estimates output confidence from task type, evidence kinds, and tool calls.

Constructor:

Parameter Type Default
abstain_threshold float 0.6

Methods:

estimate(task_type: TaskType, evidence_kinds: list, num_tools_called: int) -> ConfidenceScore

ResourceBoundsContract(BaseModel)

Resource limits that bound a workflow or tool call.

Field Type Default
max_tokens int Field(ge=0, description='Maximum total tokens across all LLM calls')
max_steps int Field(ge=1, le=100, description='Maximum workflow steps')
max_latency_ms float Field(ge=0.0, description='Maximum allowed wall-clock latency in ms')

AuditSummaryContract(BaseModel)

Compact audit summary embedded in workflow responses.

Field Type Default
completeness float Field(ge=0.0, le=1.0)
total_steps int Field(ge=0)
has_human_approval bool False
has_formal_check bool False

WorkflowRequest(BaseModel)

Request schema for executing a G6 workflow.

Field Type Default
goal str Field(min_length=1, description='Natural-language workflow goal')
context dict[str, Any] Field(default_factory=dict)
max_steps int Field(default=15, ge=1, le=100)
resource_bounds Optional[ResourceBoundsContract] None
require_human_approval bool False
correlation_id Optional[str] None

WorkflowResponse(BaseModel)

Response schema for a completed G6 workflow execution.

Field Type Default
workflow_id str required
status Literal['ok', 'error', 'escalated', 'abstained'] required
output str required
confidence float Field(ge=0.0, le=1.0)
audit_summary AuditSummaryContract required
error_message Optional[str] None
steps_taken int 0

ToolCallRequest(BaseModel)

Request schema for a single MCP tool invocation.

Field Type Default
tool_name str Field(min_length=1)
arguments dict[str, Any] Field(default_factory=dict)
correlation_id Optional[str] None
timeout_ms float Field(default=30000.0, ge=0.0)

ToolCallResponse(BaseModel)

Response schema for a single MCP tool invocation.

Field Type Default
tool_name str required
result Any required
evidence_kind Literal['retrieved_evidence', 'tool_output', 'formal_check', 'model_inference', 'human_approval'] required
latency_ms float required
error Optional[str] None
is_success bool True

DebateConfig

Configuration for domain-specific debate.

Field Type Default
roles list[str] required
rounds int required
trigger_ops list[str] required
domain_prompts dict[str, str] field(default_factory=dict)
escalation_threshold float 0.6

PrimarySector(str, Enum)

Five-sector model of the economy.

IndustryCategory(str, Enum)

NAICS-inspired 19-category industry classification.

SP500Sector(str, Enum)

S&P 500 GICS 11-sector classification.

InstitutionalActor(str, Enum)

Five institutional sectors in national accounts.

JobEvalCase

A single labeled evaluation case.

Field Type Default
input dict[str, Any] required
expected_output dict[str, Any] required
tags list[str] field(default_factory=list)
should_refuse bool False
min_score float 0.7
grounding_sources list[dict[str, Any]] field(default_factory=list)
utility_rationale str ''

EvalResult

Scored result for one eval case or a summary over many.

Field Type Default
answer_quality float required
abstention_quality float required
provenance_coverage float required
action_safety float required
judge_model str \| None None
judge_degraded bool False
grounding_sources_used list[str] field(default_factory=list)
scoring_notes str ''

Methods:

overall() -> float

JobEvalSuite

Run labeled cases through a job block and score the outputs.

Constructor:

Parameter Type Default
cases list[JobEvalCase] \| None None

Methods:

load_cases(path: str) -> None

Append cases from a JSONL file; raises GoldCaseSchemaError on drift.

run(block: 'JobAgentBlock') -> list[EvalResult]

Run all cases and return per-case results.

summary(results: list[EvalResult]) -> EvalResult

Average results across all cases.

ErrorPolicy(str, Enum)

How federated/composed agents handle member failures.

MergeStrategy(str, Enum)

How federated agent merges results from members.

FederatedAgent(_get_job_agent_block())

Union of two job agents via the + operator.

Field Type Default
error_policy ErrorPolicy ErrorPolicy.BEST_EFFORT
merge_strategy MergeStrategy MergeStrategy.CONCATENATE
capabilities ClassVar[set[type]] set()

Methods:

health_check() -> dict

Check health of all member agents.

ComposedAgent(_get_job_agent_block())

Sequential composition of two job agents via the @ operator.

Field Type Default
error_policy ErrorPolicy ErrorPolicy.BEST_EFFORT
capabilities ClassVar[set[type]] set()

Methods:

health_check() -> dict

Check health of all member agents.

JobAgentBlock(AIBlock[JobInput, JobOutput, dict])

Base class for all 32 G6 job agents.

Field Type Default
name str 'job_agent'
sector SectorClassification \| None None
toolkit ToolkitSpec \| None None
mcp_module str \| None None
safety_profile SafetyProfile \| None None
resource_bounds ResourceBounds \| None None
usage ResourceUsage field(default_factory=ResourceUsage)
state dict field(default_factory=dict)
capabilities ClassVar[set[type]] set()
TOOL_RESULT_VALIDATORS ClassVar[dict[str, Any]] {'reconcile_accounts': lambda r: 'reconciled' in r if isinstance(r, dict) else False, 'deploy_service': lambda r: 'final_status' in r if isinstance(r, dict) else False, 'prepare_statement': lambda r: 'sections' in r if isinstance(r, dict) else False, 'file_report': lambda r: 'report_type' in r if isinstance(r, dict) else False, 'assess_security': lambda r: 'findings' in r if isinstance(r, dict) else False, 'process_transaction': lambda r: 'status' in r or 'result' in r if isinstance(r, dict) else False, 'evaluate_ratios': lambda r: 'ratios' in r if isinstance(r, dict) else False, 'monitor_system': lambda r: 'health' in r if isinstance(r, dict) else False}
TOOL_ALTERNATIVES ClassVar[dict[str, str]] {'database__execute_sql': 'adapt_pandas__describe', 'ctx_rag__retrieve': 'grounding__query', 'ctx_elastic__search': 'ctx_rag__retrieve', 'adapt_memory__retrieve': 'ctx_rag__retrieve', 'formal_methods__check_satisfiability': 'formal_methods__propositional', 'adapt_pandas__describe': 'database__execute_sql', 'grounding__query': 'ctx_rag__retrieve', 'ctx_rag__retrieve': 'ctx_elastic__search', 'formal_methods__propositional': 'formal_methods__check_satisfiability', 'accountant__manage_ledger': 'accountant__prepare_statement', 'accountant__file_report': 'accountant__prepare_statement', 'accountant__assess_compliance': 'accountant__evaluate_ratios', 'accountant__prepare_statement': 'accountant__manage_ledger', 'accountant__evaluate_ratios': 'accountant__assess_compliance', 'it__monitor_system': 'it__evaluate_uptime', 'it__troubleshoot': 'it__analyze_logs', 'it__assess_security': 'it__audit_permissions', 'it__evaluate_uptime': 'it__monitor_system', 'it__analyze_logs': 'it__troubleshoot', 'it__audit_permissions': 'it__assess_security', 'adapt_sklearn__train': 'adapt_pandas__describe', 'ctx_colbert__search': 'ctx_rag__retrieve', 'ctx_search__search': 'ctx_scrapling__scrape', 'ctx_scrapling__scrape': 'ctx_search__search'}
DOMAIN_CONFIDENCE_WEIGHTS ClassVar[dict[str, dict[str, float]]] {'job_accountant': {'completeness': 0.25, 'grounding': 0.1, 'standards': 0.4, 'tools': 0.25}, 'job_it': {'completeness': 0.3, 'grounding': 0.1, 'standards': 0.2, 'tools': 0.4}}

Methods:

ask(task: str, **kwargs: Any) -> Result

Simplified API: just describe what you need.

infer(data: Any) -> Result[JobOutput]

Orchestrate a job task with safety checks and component access.

get_audit_log() -> list[AuditEntry]

Return the current audit trail.

verify_standards(output: JobOutput | None = None, jurisdiction: str = '', failure_mode: str = '') -> Result[dict]

Verify this agent's output against professional standards.

extend(extension: dict[str, Any]) -> Result[dict]

learn_from_business(domain: str, rules: list[str]) -> Result[dict]

get_extensions() -> Result[list[dict]]

receive_instruction(instruction: str, context: dict[str, Any] | None = None) -> Result[dict]

create_skill(name: str, description: str, steps: list[str]) -> Result[dict]

list_skills() -> Result[list[dict]]

teach(topic: str, material: str) -> Result[dict]

generate_curriculum(domain: str, level: str = 'beginner') -> Result[dict]

assess_understanding(topic: str) -> Result[dict]

propose(task: str, to_agents: list[str]) -> Result[dict]

negotiate(proposal_id: str, counter: dict[str, Any]) -> Result[dict]

co_execute(task: str, partners: list[str]) -> Result[dict]

decompose(problem: str) -> Result[list[str]]

solve(problem: str, context: dict[str, Any] | None = None) -> Result[dict]

verify_solution(solution: dict[str, Any], spec: str) -> Result[dict]

connect(service: str, config: dict[str, Any]) -> Result[dict]

invoke_external(service: str, operation: str, params: dict[str, Any] | None = None) -> Result[dict]

list_external_tools() -> Result[list[dict]]

discover_agents(query: str = '') -> Result[list[dict]]

send_task(agent_id: str, task: str, payload: dict[str, Any] | None = None) -> Result[dict]

receive_task(task_id: str) -> Result[dict]

initiate_payment(mandate: dict[str, Any]) -> Result[dict]

ground(claim: str, domain: str = 'general') -> Result[dict]

search_kb(query: str, top_k: int = 5) -> Result[list[dict]]

update_kb(fact: str, domain: str = 'general') -> Result[dict]

remember(key: str, value: Any) -> Result[dict]

recall(key: str) -> Result[Any]

reflect(topic: str = '') -> Result[dict]

forget(key: str) -> Result[dict]

sense(sensor: str, params: dict[str, Any] | None = None) -> Result[dict]

act(effector: str, command: dict[str, Any]) -> Result[dict]

get_effectors() -> Result[list[str]]

get_sensors() -> Result[list[str]]

JobRegistry

Sector-aware index of job agent components.

Methods:

list_jobs() -> list[dict[str, Any]]

get_job(name: str) -> dict[str, Any] | None

by_sector(sector: str) -> list[dict[str, Any]]

by_industry(industry: str) -> list[dict[str, Any]]

by_sp500(sp500: str) -> list[dict[str, Any]]

count() -> int

Return number of registered jobs (derived dynamically from _JOB_SECTORS).

TokenBucket

Thread-safe token bucket rate limiter.

Field Type Default
rate float 10.0
capacity float 10.0

Methods:

try_acquire(tokens: float = 1.0) -> bool

Try to consume tokens. Returns True if allowed, False if rate-limited.

acquire(tokens: float = 1.0, timeout: float = 5.0) -> bool

Block until tokens are available or timeout. Returns True if acquired.

available() -> float

Current available tokens.

RateLimiterRegistry

Registry of named rate limiters.

Methods:

get(name: str) -> TokenBucket

Get or create a rate limiter by name.

configure(name: str, rate: float, capacity: float) -> None

Configure or reconfigure a rate limiter.

try_acquire(name: str, tokens: float = 1.0) -> bool

Convenience: try to acquire tokens from a named limiter.

stats() -> dict[str, dict[str, float]]

Return available tokens for all registered limiters.

reset() -> None

Reset all limiters (useful for testing).

StepStatus(str, Enum)

Step

A single step in a recipe pipeline.

Field Type Default
name str required
component str required
params dict[str, Any] field(default_factory=dict)
input_map dict[str, str] field(default_factory=dict)
required bool False
safety_gate bool False
timeout_seconds float 120.0

StepResult

Outcome of executing a single step.

Field Type Default
step_name str required
status StepStatus required
output dict[str, Any] field(default_factory=dict)
error str ''
started_at str ''
completed_at str ''
duration_seconds float 0.0

Recipe

A named multi-step workflow pipeline.

Field Type Default
name str required
domain str required
steps list[Step] required
description str ''
version str '1.0'

RecipeCheckpoint

Serialisable checkpoint for resume after interruption.

Field Type Default
recipe_name str required
run_id str required
completed_steps list[str] field(default_factory=list)
step_outputs dict[str, dict[str, Any]] field(default_factory=dict)
initial_input dict[str, Any] field(default_factory=dict)
created_at str ''
last_updated str ''

Methods:

save(checkpoint_dir: Path) -> Path

load(path: Path) -> RecipeCheckpoint

RecipeResult

Final outcome of a recipe execution.

Field Type Default
recipe_name str required
run_id str required
success bool required
step_results list[StepResult] field(default_factory=list)
final_output dict[str, Any] field(default_factory=dict)
warnings list[str] field(default_factory=list)
started_at str ''
completed_at str ''
duration_seconds float 0.0
hitl_required bool False
hitl_task_id str ''

Methods:

to_dict() -> dict[str, Any]

SafetyPolicy(str, Enum)

ActionRiskLevel(str, Enum)

Methods:

for_action(action: str) -> 'ActionRiskLevel'

SafetyDecision

Field Type Default
action str required
allowed bool required
refused bool required
requires_approval bool required
reason str required
advisory_output Optional[str] None
evidence_kind str 'tool_output'
approver Optional[str] None

SafetyGate

Evaluates whether a workflow action is safe to execute.

Constructor:

Parameter Type Default
policy SafetyPolicy SafetyPolicy.DEFAULT

Methods:

evaluate(action: str, context: dict) -> SafetyDecision

approve(decision: SafetyDecision, approver: str) -> SafetyDecision

Record human approval and return an allowed decision.

SafetyDecision(Enum)

Outcome of a high-stakes safety check.

HighStakeSafetyPolicy(ABC)

Abstract base for domain-specific safety enforcement.

Methods:

check(input_data: 'JobInput') -> tuple[SafetyDecision, str]

Return (decision, message).

DefaultHighStakeSafetyPolicy(HighStakeSafetyPolicy)

Default policy: require professional context for domain-specific output.

Constructor:

Parameter Type Default
context_key str required
domain_name str required
strict bool False

Methods:

check(input_data: 'JobInput') -> tuple[SafetyDecision, str]

disclaimer() -> str

Return the regulated-domain disclaimer for this policy's domain.

SafetyProfile

Safety constraints for a given economic sector.

Field Type Default
dominant_operation str required
max_steps_per_task int required
epsilon float required
resource_bounds ResourceBounds required
requires_human_review bool required

SectorClassification(BaseModel)

All four sector classifications for a job.

Field Type Default
primary_sector PrimarySector required
industry IndustryCategory required
sp500 SP500Sector required
institutional InstitutionalActor required

ToolkitSpec(BaseModel)

Routing hints — primary components tried first, but access is unrestricted.

Field Type Default
primary_components tuple[str, ...] ()

SafetyGateProfile(BaseModel)

Gate decision metadata attached to provenance for downstream audit.

Field Type Default
policy_name str ''
domain str ''
decision Literal['', 'allow', 'require_review', 'refuse'] ''
attestation_status Literal['', 'verified', 'missing', 'incomplete'] ''
strict_mode bool False

ProvenanceRecord(BaseModel)

Source attribution and freshness metadata for any job output.

Field Type Default
source str required
url str \| None None
retrieved_at datetime required
freshness_seconds int \| None None
safety_profile SafetyGateProfile \| None None

TypedToolRequest(BaseModel)

Base class for strongly-typed per-tool MCP request models.

Field Type Default
request_id str ''
tenant_id str \| None None
trace_id str \| None None

TypedToolResponse(BaseModel)

Base class for strongly-typed per-tool MCP response models.

Field Type Default
provenance ProvenanceRecord \| None None
confidence float 0.5
confidence_provenance ProvenancedNumber \| None None
content_provenance ContentProvenance \| None None
as_of datetime \| None None

JobContext(_DictCompatMixin, BaseModel)

Typed context for job execution (06-P2).

Field Type Default
operation str ''
domain str ''
hitl_approved bool False
workspace_id str ''
session_id str ''

Methods:

from_dict(d: dict[str, Any]) -> JobContext

JobConstraints(_DictCompatMixin, BaseModel)

Typed constraints for job execution (06-P2).

Field Type Default
max_time_sec float 300.0
max_tokens int 10000
max_retries int 3
require_evidence bool False
require_review bool False
safety_level str 'standard'

Methods:

from_dict(d: dict[str, Any]) -> JobConstraints

JobResourceBounds(_DictCompatMixin, BaseModel)

Typed resource bounds for job execution (06-P2).

Field Type Default
max_llm_calls int 50
max_memory_mb int 1024
max_cost_usd float 0.0
timeout_sec float 600.0

Methods:

from_dict(d: dict[str, Any]) -> JobResourceBounds

JobParameters(_DictCompatMixin, BaseModel)

Typed parameters for job execution (06-P2).

Field Type Default
model_name str ''
temperature float 0.7
output_format str 'text'
language str 'en'
verbose bool False

Methods:

from_dict(d: dict[str, Any]) -> JobParameters

JobInput(BaseModel)

Input to any job agent block.

Field Type Default
task str required
context JobContext Field(default_factory=JobContext)
constraints JobConstraints Field(default_factory=JobConstraints)
resource_bounds JobResourceBounds Field(default_factory=JobResourceBounds)
subtasks list[str] Field(default_factory=list)
parameters JobParameters Field(default_factory=JobParameters)
run_mode str 'beta'
reviewer_signature str ''

JobOutput(BaseModel)

Output from any job agent block.

Field Type Default
result str ''
artifacts list[dict[str, Any]] Field(default_factory=list)
steps_taken list[str] Field(default_factory=list)
resource_usage dict[str, Any] Field(default_factory=dict)
confidence float 0.5
confidence_label str ''
confidence_basis str ''
business_summary str ''
eval_confidence float \| None None
subtask_statuses list[SubtaskStatus] Field(default_factory=list)
provenance ProvenanceRecord \| None None
degraded bool False
degradation_reason str \| None None
completion_state str ''
reliability_status str ''
reliability_envelope dict[str, Any] Field(default_factory=dict)
warning_card dict[str, Any] Field(default_factory=dict)
claims_ledger list[dict[str, Any]] Field(default_factory=list)
verification_report dict[str, Any] Field(default_factory=dict)
human_review_required bool False
translation_fidelity dict \| None None
triangulation dict \| None None
agentic_evidence dict[str, Any] Field(default_factory=dict)

MCPJobInput(BaseModel)

Base MCP input for job agent sub-packages.

Field Type Default
op str required
task str ''
context dict[str, Any] Field(default_factory=dict)
parameters dict[str, Any] Field(default_factory=dict)
artifact_id str ''
query str ''

MCPJobOutput(BaseModel)

Base MCP output for job agent sub-packages.

Field Type Default
op str required
result str ''
artifacts list[dict[str, Any]] Field(default_factory=list)
records list[dict[str, Any]] Field(default_factory=list)
message str ''
count int 0
found bool False
metadata dict[str, Any] Field(default_factory=dict)
degraded bool False
degradation_reason str \| None None

TeamInput(BaseModel)

Input to TeamBlock — dispatches to multiple job agents.

Field Type Default
task str required
members list[str] Field(default_factory=list)
strategy str 'parallel'
context dict[str, Any] Field(default_factory=dict)

TeamOutput(BaseModel)

Merged output from TeamBlock.

Field Type Default
results list[dict[str, Any]] Field(default_factory=list)
summary str ''
member_count int 0
degraded bool False
degradation_reason str \| None None

SecretStore

Unified secret store with fallback chain.

Constructor:

Parameter Type Default
providers list[SecretProvider] \| None None
primary_backend SecretBackend SecretBackend.ENV

Methods:

get(key: str) -> str | None

Get a secret, trying each provider in order.

set(key: str, value: str, provider_index: int = 0) -> None

Store a secret in the specified provider (default: first/primary).

delete(key: str) -> bool

Delete from all providers.

require(key: str, description: str = '') -> str

Get a secret or raise RuntimeError if not found.

get_or_default(key: str, default: str = '') -> str

Get a secret with a fallback default.

access_log() -> list[dict[str, str]]

JobStore

SQLite-backed base store for job MCP sub-packages.

Constructor:

Parameter Type Default
db_path str ':memory:'
extra_ddl str ''

Methods:

create_task(title: str, description: str = '', context: dict | None = None, priority: int = 0) -> str

get_task(task_id: str) -> dict | None

update_task(task_id: str, **fields: Any) -> bool

list_tasks(status: str = '') -> list[dict]

store_result(op: str, result: dict, task_id: str = '', confidence: float = 0.5) -> str

get_results(task_id: str = '', op: str = '', limit: int = 50) -> list[dict]

log_history(op: str, inp: dict, out: dict, status: str = 'ok', error: str = '', duration_ms: float = 0.0) -> str

get_history(op: str = '', limit: int = 50) -> list[dict]

log_error(op: str, error: str, context: dict | None = None) -> str

store_artifact(name: str, content: dict, kind: str = 'generic', tags: str = '', notes: str = '') -> str

retrieve_artifact(artifact_id: str) -> dict | None

list_artifacts(kind: str = '', limit: int = 50) -> list[dict]

search_artifacts(query: str, limit: int = 20) -> list[dict]

archive_artifact(artifact_id: str) -> bool

get_cached_llm(cache_key: str) -> str | None

Return cached LLM response if not expired, else None.

set_cached_llm(cache_key: str, context_hash: str, question_hash: str, response: str, model: str = 'auto', ttl_hours: int = 168) -> None

INSERT OR REPLACE a cached LLM response with TTL.

purge_expired_cache() -> int

Delete expired cache entries; return count deleted.

count_all() -> dict[str, int]

close() -> None

Return connection to pool (file-backed) or close it (:memory:).

JobSubagentProtocol(AgentProtocol)

AgentProtocol specialised for JobAgentBlock instances.

Constructor:

Parameter Type Default
agent Any required
voting_pool VotingPool required
red_flag_detector RedFlagDetector required
registry Any None

TeamBlock(AIBlock[TeamInput, TeamOutput, dict])

Dispatches a task across multiple job agent members.

Field Type Default
name str 'team'
resource_bounds ResourceBounds \| None None
usage ResourceUsage field(default_factory=ResourceUsage)
state dict field(default_factory=dict)

Methods:

infer(data: TeamInput) -> Result[TeamOutput]

TenantContext

Reentrant context manager that sets the current tenant_id.

Constructor:

Parameter Type Default
tenant_id str required

Methods:

tenant_id() -> str

TenantIsolation

Manages per-tenant instances of shared framework singletons.

Methods:

get_store(tenant_id: str) -> JobStore

Return a tenant-scoped JobStore (separate SQLite DB per tenant).

get_rate_limiter(tenant_id: str) -> RateLimiterRegistry

Return a per-tenant RateLimiterRegistry.

get_secret_store(tenant_id: str) -> SecretStore

Return a per-tenant SecretStore.

get_cache(tenant_id: str) -> dict[str, str]

Return a per-tenant L1 in-memory cache dict.

cleanup(tenant_id: str) -> None

Remove all resources for a tenant, closing stores gracefully.

list_tenants() -> list[str]

List all active tenant ids (those with at least one resource).

close_all() -> None

Shut down all tenant resources. Intended for application teardown.

Functions

run_sync(fn: Callable[..., T], *args: Any, **kwargs: Any) -> T

Run a synchronous function in the thread pool.

async_infer(agent: Any, data: Any) -> Any

Async wrapper for JobAgentBlock.infer().

async_llm_enrich(context: str, question: str, model: str = 'auto', timeout: float = 15.0, ttl_hours: int = 168) -> str | None

Async wrapper for llm_enrich().

gather_agent_tasks(agents_and_inputs: list[tuple[Any, Any]], max_concurrent: int = 10) -> list[Any]

Run multiple agent inferences concurrently with a semaphore.

make_async(fn: Callable[..., T]) -> Callable[..., Any]

Decorator that wraps a sync function to be async via run_in_executor.

record_audit_entry(store, handler_name: str, operation: str, entity_id: str = '', before: Any = None, after: Any = None) -> str

verify_audit_chain(store) -> list[dict]

compute_merkle_root(store) -> str

Compute a Merkle tree root hash from all audit entries.

detect_tampering(store) -> dict

Run comprehensive tampering detection.

route_claw_intent(prompt: str) -> ClawIntent | None

Map common OpenClaw/NanoClaw phrases into typed tool operations.

calibrate_from_audit_report(report) -> ConfidenceScore

Derive a confidence score from a completed AuditReport.

get_debate_config(agent_name: str) -> DebateConfig

Return the debate configuration for a job agent.

should_debate(agent_name: str, operation: str) -> bool

Return True if operation should trigger debate for agent_name.

get_grounding_domain(agent_name: str) -> GroundingDomain

Return the primary grounding domain for a job agent.

get_all_domains(agent_name: str) -> list[GroundingDomain]

Return primary + extra grounding domains for a job agent.

get_seed_queries(agent_name: str) -> list[str]

Return seed grounding queries for a job agent, or empty list.

dispatch_shared(op: str, store: JobStore, job_name: str = '', primary_components: list[str] | None = None, ops: list[str] | None = None, **kwargs: Any) -> dict

Dispatch a shared op to its handler.

requires_hitl(agent_name: str, operation: str) -> bool

Return True if the operation MUST have human approval. FAIL CLOSED.

recommends_hitl(agent_name: str, operation: str) -> bool

Return True if the operation SHOULD have human review.

get_hitl_timeout(agent_name: str, operation: str) -> float

Return the HITL timeout in seconds for the given operation.

get_all_hitl_ops(agent_name: str) -> dict[str, str]

Return all HITL operations for an agent with their level (required/recommended).

maybe_warn_perplexity(domain: str, search_used: bool = True) -> str | None

Return a warning string if Perplexity would improve quality for domain.

get_grounding() -> GroundingBlock | None

Return a cached GroundingBlock, or None if unavailable.

get_search() -> CtxSearchBlock | None

Return a cached CtxSearchBlock (DuckDuckGo default).

get_scraper() -> CtxScraplingBlock | None

Return a cached CtxScraplingBlock.

get_rag() -> CtxRAGBlock | None

Return a cached CtxRAGBlock.

get_debate(use_mock_llm: bool = False) -> DebateLoop | None

Return a new DebateLoop instance.

make_debate_agents(roles: list[str] | None = None) -> list[Any]

Build a list of DebateAgent instances from role name strings.

get_experta() -> AdaptExpertaBlock | None

Return a cached AdaptExpertaBlock (stateful, forward-chaining).

get_experta_mcp(db_path: str = ':memory:', domain: str = '') -> AdaptExpertaMCPBlock | None

Return a cached AdaptExpertaMCPBlock with full T2 learning.

get_sklearn() -> AdaptSklearnBlock | None

get_automl() -> AdaptAutoMLBlock | None

get_bayesian() -> AdaptBayesianBlock | None

get_keras() -> AdaptKerasBlock | None

get_pytorch() -> AdaptPyTorchBlock | None

get_eurisko() -> AdaptEuriskoBlock | None

get_optimisation() -> AdaptOptimisationBlock | None

get_pandas() -> AdaptPandasBlock | None

get_memory() -> AdaptMemoryBlock | None

get_hitl(workspace_root: str | Path | None = None) -> HITLManager | None

Return a HITLManager for the given workspace root.

get_job_registry() -> JobRegistry

is_otel_available() -> bool

Return whether opentelemetry is importable.

get_rate_limiter() -> RateLimiterRegistry

Return the global rate limiter registry.

check_rate_limit(resource: str, tokens: float = 1.0) -> bool

Check if a request is within rate limits. Returns True if allowed.

run_recipe(recipe: Recipe, initial_input: dict[str, Any], store: Any = None, checkpoint_dir: Path | None = None, resume_from: RecipeCheckpoint | None = None, on_step_complete: Callable[[StepResult], None] | None = None) -> RecipeResult

Execute a recipe, optionally resuming from a checkpoint.

get_domain_recipe(domain: str) -> Recipe | None

Return the launch-oriented starter recipe for a domain.

list_domain_recipes() -> list[str]

Return available launch-oriented starter recipe domains.

get_sector_safety() -> dict[PrimarySector, SafetyProfile]

Get sector safety profiles (cached, built from config on first call).

reset_sector_safety() -> None

Clear the cached profiles (useful for testing / hot-reload).

get_secret_store() -> SecretStore

Get the global secret store singleton.

get_secret(key: str) -> str | None

Convenience: get a secret from the global store.

require_secret(key: str, description: str = '') -> str

Convenience: require a secret from the global store.

get_connection_pool() -> _ConnectionPool

Return the module-level connection pool singleton.

get_current_tenant() -> str

Return the current tenant_id or 'default' if none is set.

get_tenant_isolation() -> TenantIsolation

Return the module-level TenantIsolation singleton.

MCP Tools

Operation Source
ops job_framework_mcp
help job_framework_mcp
assess_safety job_framework_mcp
describe_framework job_framework_mcp
describe_gates job_framework_mcp
describe_hitl_policies job_framework_mcp
explain_safety_floor job_framework_mcp
list_strategies job_framework_mcp
check_production_gate job_framework_mcp
readiness_check job_framework_mcp
submit_job job_framework_mcp