Skip to content

Core

Shared domain models, base types, and enums used across the framework.

Types

types

Reusable Pydantic type annotations and validators.

CurrencyCode intentionally lives in synthorg.budget.currency next to the ISO 4217 allowlist data. Importing it here would force core to depend on budget, introducing a circular import via the many budget modules that already import from core.types. Consumers who need the validated currency type import it from synthorg.budget.currency.

ModelTier module-attribute

ModelTier = Literal['large', 'medium', 'small']

Model capability tier: large (most capable), medium, small (cheapest).

AutonomyDetailLevel module-attribute

AutonomyDetailLevel = Literal['full', 'summary', 'minimal']

Level of autonomy instruction detail in prompt profiles.

PersonalityMode module-attribute

PersonalityMode = Literal['full', 'condensed', 'minimal']

Personality section verbosity in prompt profiles.

NotBlankStr module-attribute

NotBlankStr = Annotated[
    str, StringConstraints(min_length=1), AfterValidator(_check_not_whitespace)
]

A string that must be non-empty and not consist solely of whitespace.

validate_unique_strings

validate_unique_strings(values, field_name)

Validate that every string in values is unique.

Raises:

Type Description
ValueError

If duplicates are present.

Source code in src/synthorg/core/types.py
def validate_unique_strings(
    values: tuple[str, ...],
    field_name: str,
) -> None:
    """Validate that every string in *values* is unique.

    Raises:
        ValueError: If duplicates are present.
    """
    if len(values) != len(set(values)):
        dupes = sorted(v for v, c in Counter(values).items() if c > 1)
        msg = f"Duplicate entries in {field_name}: {dupes}"
        raise ValueError(msg)

Enums

enums

Domain enumerations for the SynthOrg framework.

SeniorityLevel

Bases: StrEnum

Seniority levels for agents within the organization.

Each level corresponds to an authority scope, typical model tier, and cost tier defined in synthorg.core.role_catalog.SENIORITY_INFO.

StrategicOutputMode

Bases: StrEnum

Controls how strategic agents frame their recommendations.

Applies to any agent with a strategic output mode set (C-suite, VP, Director, or any agent with an explicit override).

  • option_expander: Present all options with analysis through each lens.
  • advisor: Recommend top 2-3 options with reasoning and caveats.
  • decision_maker: Make a final recommendation with full justification.
  • context_dependent: Resolves based on agent seniority -- C-suite/VP maps to decision_maker, others to advisor.

AgentStatus

Bases: StrEnum

Lifecycle status of an agent.

RiskTolerance

Bases: StrEnum

Risk tolerance level for agent personality.

CreativityLevel

Bases: StrEnum

Creativity level for agent personality.

MemoryLevel

Bases: StrEnum

Memory persistence level for an agent (§7.3).

MemoryCategory

Bases: StrEnum

Memory type categories for agent memory (§7.2).

ConsolidationInterval

Bases: StrEnum

Interval for memory consolidation.

OrgFactCategory

Bases: StrEnum

Category of organizational fact (§7.4).

Categorizes shared organizational knowledge entries by their nature and purpose within the company.

CostTier

Bases: StrEnum

Built-in cost tier identifiers.

These are the default tiers shipped with the framework. Users can define additional tiers via configuration. Fields that accept cost tiers (e.g. SeniorityInfo.cost_tier) use str rather than this enum, so custom tier IDs are also valid.

CompanyType

Bases: StrEnum

Pre-defined company template types.

SkillPattern

Bases: StrEnum

Skill interaction patterns for company templates.

Based on the five-pattern taxonomy: Tool Wrapper, Generator, Reviewer, Inversion, and Pipeline.

Attributes:

Name Type Description
TOOL_WRAPPER

On-demand domain expertise; agents self-direct using specialized context.

GENERATOR

Consistent structured output from reusable templates.

REVIEWER

Modular rubric-based evaluation; separates what to check from how to check it.

INVERSION

Agent interviews user before acting; structured requirements gathering.

PIPELINE

Strict sequential workflow with hard checkpoints between stages.

DepartmentName

Bases: StrEnum

Standard department names within the organization.

TaskStatus

Bases: StrEnum

Lifecycle status of a task.

The authoritative transition map lives in synthorg.core.task_transitions.VALID_TRANSITIONS. Summary for quick reference:

CREATED -> ASSIGNED | REJECTED
ASSIGNED -> IN_PROGRESS | AUTH_REQUIRED | BLOCKED | CANCELLED
            | FAILED | INTERRUPTED | SUSPENDED
IN_PROGRESS -> IN_REVIEW | AUTH_REQUIRED | BLOCKED | CANCELLED
               | FAILED | INTERRUPTED | SUSPENDED
IN_REVIEW -> COMPLETED | IN_PROGRESS (rework) | BLOCKED | CANCELLED
AUTH_REQUIRED -> ASSIGNED (approved) | CANCELLED (denied/timeout)
BLOCKED -> ASSIGNED (unblocked)
FAILED -> ASSIGNED (reassignment for retry)
INTERRUPTED -> ASSIGNED (reassignment on restart)
SUSPENDED -> ASSIGNED (resume from checkpoint)
COMPLETED, CANCELLED, and REJECTED are terminal states.
FAILED, INTERRUPTED, and SUSPENDED are non-terminal (can be reassigned).
AUTH_REQUIRED is non-terminal (waiting for authorization).

TaskType

Bases: StrEnum

Classification of the kind of work a task represents.

Priority

Bases: StrEnum

Task urgency and importance level.

Complexity

Bases: StrEnum

Estimated task complexity.

WorkflowType

Bases: StrEnum

Workflow type for organizing task execution.

Matches the four workflow types defined in the Engine design page (docs/design/engine.md, Workflow Types section).

WorkflowNodeType

Bases: StrEnum

Node type in a visual workflow definition.

Each node represents a step or control-flow element in the visual workflow editor.

WorkflowValueType

Bases: StrEnum

Typed value kinds for workflow I/O declarations.

Used by :class:WorkflowIODeclaration to enforce typed contracts on subworkflow inputs and outputs at save time and at runtime.

WorkflowEdgeType

Bases: StrEnum

Edge type connecting nodes in a visual workflow definition.

Encodes the relationship semantics between workflow nodes.

WorkflowExecutionStatus

Bases: StrEnum

Lifecycle status of a workflow execution instance.

Tracks the overall progress of an activated workflow definition from creation through completion or cancellation.

WorkflowNodeExecutionStatus

Bases: StrEnum

Per-node execution status within a workflow execution.

Tracks whether each node in the workflow graph has been processed, skipped (conditional branch not taken), or resulted in a concrete task.

ArtifactType

Bases: StrEnum

Type of produced artifact.

ProjectStatus

Bases: StrEnum

Lifecycle status of a project.

ToolAccessLevel

Bases: StrEnum

Access level for tool permissions.

Determines which tool categories an agent can use. Levels SANDBOXED through ELEVATED form a hierarchy where each includes all categories from lower levels. CUSTOM uses only explicit allow/deny lists, ignoring the hierarchy.

The concrete category sets for each level are defined in ToolPermissionChecker._LEVEL_CATEGORIES.

ToolCategory

Bases: StrEnum

Category of a tool for access-level gating.

DecisionMakingStyle

Bases: StrEnum

Decision-making approach used by an agent.

CollaborationPreference

Bases: StrEnum

Preferred collaboration mode for an agent.

CommunicationVerbosity

Bases: StrEnum

Communication verbosity level for an agent.

ConflictApproach

Bases: StrEnum

Conflict resolution approach used by an agent.

TaskStructure

Bases: StrEnum

Classification of how a task's subtasks relate to each other.

Used by the decomposition engine to determine coordination topology and execution ordering. See the Engine design page.

CoordinationTopology

Bases: StrEnum

Coordination topology for multi-agent task execution.

Determines how agents coordinate when executing decomposed subtasks. See the Engine design page.

ActionType

Bases: StrEnum

Two-level action type taxonomy for security classification.

Used by autonomy presets (see Operations design page), SecOps validation, tiered timeout policies, and progressive trust. Values follow a category:action naming convention.

Custom action type strings are also accepted by models that use str for action_type fields -- these enum members are convenience constants for the built-in taxonomy.

MergeOrder

Bases: StrEnum

Order in which workspace branches are merged back.

Determines the sequence of merge operations when multiple agent workspaces are being merged into the base branch.

ConflictEscalation

Bases: StrEnum

Strategy for handling merge conflicts during workspace merges.

Controls whether merging stops for human review or continues with an automated review agent flagging conflicts.

ApprovalStatus

Bases: StrEnum

Status of a human approval item.

ApprovalRiskLevel

Bases: StrEnum

Risk level assigned to an approval item.

ApprovalSource

Bases: StrEnum

Origin of an approval item, fixed at creation.

Routing of a decided approval (mid-execution resume vs. review gate) keys off this persisted discriminator rather than a live parked-context probe, so the flow is deterministic even when the parked-context backend is momentarily unavailable.

Attributes:

Name Type Description
PARKED_CONTEXT

Backs a parked agent execution context (SecOps escalation or the request_human_approval tool); the decision resumes the parked run.

REVIEW_GATE

Any other approval (autonomy, hiring, promotion, pruning, scaling, training, signals, ...); the decision drives the review-gate transition. Default.

ConflictType

Bases: StrEnum

Type of merge conflict detected during workspace merges.

AutonomyLevel

Bases: StrEnum

Autonomy level controlling approval routing for agents.

Determines which actions an agent can execute autonomously vs. which require human or security-agent approval (see Operations design page).

DowngradeReason

Bases: StrEnum

Reason an agent's autonomy was downgraded at runtime.

FailureCategory

Bases: StrEnum

Machine-readable failure classification for recovery results.

Used by RecoveryResult to provide structured failure diagnosis that enables smarter checkpoint reconciliation and task reassignment routing. UNKNOWN is the honest default for error messages that cannot be confidently classified -- it is explicit rather than a silent TOOL_FAILURE lie.

DecisionOutcome

Bases: StrEnum

Outcome of a review gate decision.

Used by DecisionRecord for the auditable decisions drop-box.

ExecutionStatus

Bases: StrEnum

Runtime execution status of an agent.

Tracks whether an agent is currently executing, paused (e.g. waiting for approval), or idle. Used by AgentRuntimeState for dashboard queries and graceful-shutdown discovery.

TimeoutActionType

Bases: StrEnum

Action to take when an approval item times out (see Operations design page).

TaskSource

Bases: StrEnum

Origin of a task within the system.

Distinguishes tasks created internally by agents from those originating from client simulation or external API calls.

compare_seniority

compare_seniority(a, b)

Compare two seniority levels.

Returns negative if a is junior to b, zero if equal, positive if a is senior to b.

Parameters:

Name Type Description Default
a SeniorityLevel

First seniority level.

required
b SeniorityLevel

Second seniority level.

required

Returns:

Type Description
int

Integer indicating relative seniority.

Source code in src/synthorg/core/enums.py
def compare_seniority(a: SeniorityLevel, b: SeniorityLevel) -> int:
    """Compare two seniority levels.

    Returns negative if *a* is junior to *b*, zero if equal,
    positive if *a* is senior to *b*.

    Args:
        a: First seniority level.
        b: Second seniority level.

    Returns:
        Integer indicating relative seniority.
    """
    return _SENIORITY_RANK[a] - _SENIORITY_RANK[b]

compare_autonomy

compare_autonomy(a, b)

Compare two autonomy levels.

Returns negative if a is more restrictive than b, zero if equal, positive if a is less restrictive than b.

Parameters:

Name Type Description Default
a AutonomyLevel

First autonomy level.

required
b AutonomyLevel

Second autonomy level.

required

Returns:

Type Description
int

Integer indicating relative autonomy.

Source code in src/synthorg/core/enums.py
def compare_autonomy(a: AutonomyLevel, b: AutonomyLevel) -> int:
    """Compare two autonomy levels.

    Returns negative if *a* is more restrictive than *b*, zero if equal,
    positive if *a* is less restrictive than *b*.

    Args:
        a: First autonomy level.
        b: Second autonomy level.

    Returns:
        Integer indicating relative autonomy.
    """
    return _AUTONOMY_RANK[a] - _AUTONOMY_RANK[b]

Agent

agent

Agent identity and configuration models.

PersonalityConfig pydantic-model

Bases: BaseModel

Personality traits and communication style for an agent.

Big Five (OCEAN) floats (0.0-1.0) are internal scoring dimensions used for compatibility calculations. Behavioral enums produce natural-language labels injected into system prompts that LLMs respond to effectively.

Attributes:

Name Type Description
traits tuple[NotBlankStr, ...]

Personality trait keywords.

communication_style NotBlankStr

Free-text style description.

risk_tolerance RiskTolerance

Risk tolerance level.

creativity CreativityLevel

Creativity level.

description str

Extended personality description.

openness float

Big Five openness (curiosity, creativity). 0.0-1.0.

conscientiousness float

Big Five conscientiousness (thoroughness). 0.0-1.0.

extraversion float

Big Five extraversion (assertiveness). 0.0-1.0.

agreeableness float

Big Five agreeableness (cooperation). 0.0-1.0.

stress_response float

Emotional stability (1.0 = very calm). 0.0-1.0.

decision_making DecisionMakingStyle

Decision-making approach.

collaboration CollaborationPreference

Preferred collaboration mode.

verbosity CommunicationVerbosity

Communication verbosity level.

conflict_approach ConflictApproach

Conflict resolution approach.

Config:

  • frozen: True
  • extra: forbid
  • allow_inf_nan: False

Fields:

traits pydantic-field

traits = ()

Personality traits

communication_style pydantic-field

communication_style = 'neutral'

Communication style description

risk_tolerance pydantic-field

risk_tolerance = MEDIUM

Risk tolerance level

creativity pydantic-field

creativity = MEDIUM

Creativity level

description pydantic-field

description = ''

Extended personality description

openness pydantic-field

openness = 0.5

Big Five openness (curiosity, creativity)

conscientiousness pydantic-field

conscientiousness = 0.5

Big Five conscientiousness (thoroughness, reliability)

extraversion pydantic-field

extraversion = 0.5

Big Five extraversion (assertiveness, sociability)

agreeableness pydantic-field

agreeableness = 0.5

Big Five agreeableness (cooperation, empathy)

stress_response pydantic-field

stress_response = 0.5

Emotional stability (1.0 = very calm)

decision_making pydantic-field

decision_making = CONSULTATIVE

Decision-making approach

collaboration pydantic-field

collaboration = TEAM

Preferred collaboration mode

verbosity pydantic-field

verbosity = BALANCED

Communication verbosity level

conflict_approach pydantic-field

conflict_approach = COLLABORATE

Conflict resolution approach

SkillSet pydantic-model

Bases: BaseModel

Primary and secondary skills for an agent.

Attributes:

Name Type Description
primary tuple[Skill, ...]

Core competency skills.

secondary tuple[Skill, ...]

Supporting skills.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_unique_ids

primary pydantic-field

primary = ()

Primary skills

secondary pydantic-field

secondary = ()

Secondary skills

ModelConfig pydantic-model

Bases: BaseModel

LLM model configuration for an agent.

Attributes:

Name Type Description
provider NotBlankStr

LLM provider name (e.g. "example-provider").

model_id NotBlankStr

Model identifier (e.g. "example-medium-001").

temperature float

Sampling temperature (0.0 to 2.0).

max_tokens int

Maximum output tokens.

fallback_model NotBlankStr | None

Optional fallback model identifier.

model_tier ModelTier | None

Capability tier ("large"/"medium"/"small") set during model matching and updated by budget auto-downgrade. Controls prompt profile selection.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

provider pydantic-field

provider

LLM provider name

model_id pydantic-field

model_id

Model identifier

temperature pydantic-field

temperature = 0.7

Sampling temperature

max_tokens pydantic-field

max_tokens = 4096

Maximum output tokens

fallback_model pydantic-field

fallback_model = None

Fallback model identifier

model_tier pydantic-field

model_tier = None

Model capability tier (large/medium/small)

AgentRetentionRule pydantic-model

Bases: BaseModel

Per-category retention override for an agent.

Structurally identical to :class:~synthorg.memory.consolidation.models.RetentionRule but defined in core to avoid a core -> memory import dependency.

Attributes:

Name Type Description
category MemoryCategory

Memory category this override applies to.

retention_days int

Number of days to retain memories in this category.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

category pydantic-field

category

Memory category this override applies to

retention_days pydantic-field

retention_days

Number of days to retain memories

MemoryConfig pydantic-model

Bases: BaseModel

Memory configuration for an agent.

Attributes:

Name Type Description
type MemoryLevel

Memory persistence type.

retention_days int | None

Days to retain memories (None means forever). Also serves as the agent-level global default for retention when per-category overrides are not specified.

retention_overrides tuple[AgentRetentionRule, ...]

Per-category retention overrides for this agent. These take priority over company-level per-category rules during retention enforcement.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_retention_consistency
  • _validate_unique_override_categories

type pydantic-field

type = SESSION

Memory persistence type

retention_days pydantic-field

retention_days = None

Days to retain memories (None = forever)

retention_overrides pydantic-field

retention_overrides = ()

Per-category retention overrides for this agent

ToolPermissions pydantic-model

Bases: BaseModel

Tool access permissions for an agent.

Attributes:

Name Type Description
access_level ToolAccessLevel

Tool access level controlling which categories are available.

allowed tuple[NotBlankStr, ...]

Explicitly allowed tool names.

denied tuple[NotBlankStr, ...]

Explicitly denied tool names.

mcp_capabilities tuple[NotBlankStr, ...]

MCP capability patterns controlling which internal MCP tools the agent can see. Supports wildcards (e.g. "tasks:*", "*:read", "*").

sub_constraints ToolSubConstraints | None

Optional per-agent sub-constraints overriding the access level defaults. When None, the checker resolves defaults from the access level.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_no_overlap
  • _validate_mcp_capability_format

access_level pydantic-field

access_level = STANDARD

Tool access level

allowed pydantic-field

allowed = ()

Explicitly allowed tools

denied pydantic-field

denied = ()

Explicitly denied tools

mcp_capabilities pydantic-field

mcp_capabilities = ()

MCP capability patterns (e.g. 'tasks:read', 'agents:*')

sub_constraints pydantic-field

sub_constraints = None

Per-agent sub-constraint overrides

AgentIdentity pydantic-model

Bases: BaseModel

Complete agent identity card.

Every agent in the company is represented by an AgentIdentity containing its role, personality, model backend, memory settings, tool permissions, and authority configuration.

Attributes:

Name Type Description
id UUID

Unique agent identifier.

name NotBlankStr

Agent display name.

role NotBlankStr

Role name (string reference to :class:~synthorg.core.role.Role).

department NotBlankStr

Department name (string reference).

level SeniorityLevel

Seniority level.

personality PersonalityConfig

Personality configuration.

skills SkillSet

Primary and secondary skill set.

model ModelConfig

LLM model configuration.

memory MemoryConfig

Memory configuration.

tools ToolPermissions

Tool permissions.

authority Authority

Authority configuration for this agent.

autonomy_level AutonomyLevel | None

Per-agent autonomy level override (None uses department/company default).

strategic_output_mode StrategicOutputMode | None

Per-agent strategic output mode override (None inherits company strategy config default).

hiring_date date

Date the agent was hired.

status AgentStatus

Current lifecycle status.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_seniority_autonomy

id pydantic-field

id

Unique agent identifier

name pydantic-field

name

Agent display name

role pydantic-field

role

Role name

department pydantic-field

department

Department name

level pydantic-field

level = MID

Seniority level

personality pydantic-field

personality

Personality configuration

skills pydantic-field

skills

Skill set

model pydantic-field

model

LLM model configuration

memory pydantic-field

memory

Memory configuration

tools pydantic-field

tools

Tool permissions

authority pydantic-field

authority

Authority scope

autonomy_level pydantic-field

autonomy_level = None

Per-agent autonomy level override (D6)

strategic_output_mode pydantic-field

strategic_output_mode = None

Per-agent strategic output mode override. None inherits the company strategy config default.

hiring_date pydantic-field

hiring_date

Date the agent was hired

status pydantic-field

status = ACTIVE

Current lifecycle status

Company

company

Company structure and configuration models.

ReportingLine pydantic-model

Bases: BaseModel

Explicit reporting relationship within a department.

Attributes:

Name Type Description
subordinate NotBlankStr

Role name (or agent identifier) of the subordinate.

supervisor NotBlankStr

Role name (or agent identifier) of the supervisor.

subordinate_id NotBlankStr | None

Optional unique identifier for the subordinate. When multiple agents share the same role name, this disambiguates which agent is meant. Any stable unique string is valid (e.g. the agent's merge_id in the template system).

supervisor_id NotBlankStr | None

Optional unique identifier for the supervisor. When multiple agents share the same role name, this disambiguates which agent is meant. Any stable unique string is valid (e.g. the agent's merge_id in the template system).

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_not_self_report

subordinate pydantic-field

subordinate

Subordinate role name or identifier

supervisor pydantic-field

supervisor

Supervisor role name or identifier

subordinate_id pydantic-field

subordinate_id = None

Optional unique identifier for the subordinate

supervisor_id pydantic-field

supervisor_id = None

Optional unique identifier for the supervisor

subordinate_key property

subordinate_key

Hierarchy lookup key: subordinate_id when set, else subordinate.

Unlike _identity_key(), returns the raw value without case-folding or namespace tagging.

supervisor_key property

supervisor_key

Hierarchy lookup key: supervisor_id when set, else supervisor.

Unlike _identity_key(), returns the raw value without case-folding or namespace tagging.

ReviewRequirements pydantic-model

Bases: BaseModel

Department review policy.

Attributes:

Name Type Description
min_reviewers int

Minimum number of reviewers required.

required_reviewer_roles tuple[NotBlankStr, ...]

Role names that must be among reviewers.

self_review_allowed bool

Whether an agent can review their own work.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

min_reviewers pydantic-field

min_reviewers = 1

Minimum number of reviewers required

required_reviewer_roles pydantic-field

required_reviewer_roles = ()

Role names that must be among reviewers

self_review_allowed pydantic-field

self_review_allowed = False

Whether self-review is allowed

ApprovalChain pydantic-model

Bases: BaseModel

Ordered approver list for an action type.

Attributes:

Name Type Description
action_type NotBlankStr

Action type this chain applies to.

approvers tuple[NotBlankStr, ...]

Ordered tuple of approver agent names.

min_approvals int

Minimum approvals needed (0 = all approvers required).

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_approvers

action_type pydantic-field

action_type

Action type for this chain

approvers pydantic-field

approvers

Ordered approver names

min_approvals pydantic-field

min_approvals = 0

Minimum approvals (0 = all required)

DepartmentPolicies pydantic-model

Bases: BaseModel

Department-level operational policies.

Attributes:

Name Type Description
review_requirements ReviewRequirements

Review policy for this department.

approval_chains tuple[ApprovalChain, ...]

Approval chains for various action types.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_unique_action_types

review_requirements pydantic-field

review_requirements

Review policy

approval_chains pydantic-field

approval_chains = ()

Approval chains for action types

WorkflowHandoff pydantic-model

Bases: BaseModel

Cross-department handoff definition.

Attributes:

Name Type Description
from_department NotBlankStr

Source department name.

to_department NotBlankStr

Target department name.

trigger NotBlankStr

Condition that triggers this handoff.

artifacts tuple[NotBlankStr, ...]

Artifacts passed during handoff.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_different_departments

from_department pydantic-field

from_department

Source department

to_department pydantic-field

to_department

Target department

trigger pydantic-field

trigger

Trigger condition

artifacts pydantic-field

artifacts = ()

Artifacts passed during handoff

EscalationPath pydantic-model

Bases: BaseModel

Cross-department escalation path.

Attributes:

Name Type Description
from_department NotBlankStr

Source department name.

to_department NotBlankStr

Target department name.

condition NotBlankStr

Condition that triggers escalation.

priority_boost int

Priority boost applied on escalation (0-3).

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_different_departments

from_department pydantic-field

from_department

Source department

to_department pydantic-field

to_department

Target department

condition pydantic-field

condition

Escalation condition

priority_boost pydantic-field

priority_boost = 1

Priority boost on escalation (0-3)

Team pydantic-model

Bases: BaseModel

A team within a department.

The lead is the team's manager. The lead may also appear in members if they are also an individual contributor.

Attributes:

Name Type Description
name NotBlankStr

Team name.

lead NotBlankStr

Team lead agent name (string reference).

members tuple[NotBlankStr, ...]

Team member agent names.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_no_duplicate_members

name pydantic-field

name

Team name

lead pydantic-field

lead

Team lead agent name

members pydantic-field

members = ()

Team member agent names

Department pydantic-model

Bases: BaseModel

An organizational department.

Department names may be standard values from :class:~synthorg.core.enums.DepartmentName or custom names defined by the organization.

Attributes:

Name Type Description
name NotBlankStr

Department name (standard or custom).

head NotBlankStr | None

Department head role name (or agent identifier), or None if the department has no designated head. When absent, hierarchy resolution skips the team-lead-to-head link for this department.

head_id NotBlankStr | None

Optional unique identifier for the department head. When multiple agents share the same role name used in head, this disambiguates which agent is meant. Any stable unique string is valid (e.g. the agent's merge_id in the template system).

budget_percent float

Percentage of company budget allocated (0-100).

teams tuple[Team, ...]

Teams within this department.

reporting_lines tuple[ReportingLine, ...]

Explicit reporting relationships.

autonomy_level AutonomyLevel | None

Per-department autonomy level override (None to inherit company default).

policies DepartmentPolicies

Department-level operational policies.

ceremony_policy dict[str, Any] | None

Per-department ceremony scheduling policy override as a raw dict for YAML-level flexibility (templates pass raw dicts before full validation). None inherits the project-level policy. Consumers construct CeremonyPolicyConfig from this dict when needed.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _deepcopy_ceremony_policy
  • _validate_head_id_requires_head
  • _validate_unique_team_names
  • _validate_unique_subordinates

name pydantic-field

name

Department name

head pydantic-field

head = None

Department head role name or identifier

head_id pydantic-field

head_id = None

Optional unique identifier for the department head

budget_percent pydantic-field

budget_percent = 0.0

Percentage of company budget allocated

teams pydantic-field

teams = ()

Teams within this department

reporting_lines pydantic-field

reporting_lines = ()

Explicit reporting relationships

autonomy_level pydantic-field

autonomy_level = None

Per-department autonomy level override (D6)

policies pydantic-field

policies

Department-level operational policies

ceremony_policy pydantic-field

ceremony_policy = None

Per-department ceremony policy override

CompanyConfig pydantic-model

Bases: BaseModel

Company-wide configuration settings.

Attributes:

Name Type Description
autonomy AutonomyConfig

Autonomy configuration (level + presets).

approval_timeout ApprovalTimeoutConfig

Timeout policy for pending approval items.

budget_monthly float

Monthly budget in the configured currency.

communication_pattern NotBlankStr

Default communication pattern name.

tool_access_default tuple[NotBlankStr, ...]

Default tool access for all agents.

middleware MiddlewareConfig

Agent and coordination middleware configuration.

session_replay_on_start bool

When True, replay the previous session from the event log on agent start (requires an EventReader and resume_execution_id).

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

autonomy pydantic-field

autonomy

Autonomy configuration (level + presets)

approval_timeout pydantic-field

approval_timeout

Timeout policy for pending approval items

budget_monthly pydantic-field

budget_monthly = 100.0

Monthly budget in the configured currency

communication_pattern pydantic-field

communication_pattern = 'hybrid'

Default communication pattern

tool_access_default pydantic-field

tool_access_default = ()

Default tool access for all agents

middleware pydantic-field

middleware

Agent and coordination middleware configuration

session_replay_on_start pydantic-field

session_replay_on_start = False

Replay session from event log on agent start

HRRegistry pydantic-model

Bases: BaseModel

Human resources registry for the company.

available_roles and hiring_queue intentionally allow duplicate entries to represent multiple openings for the same role or position.

Attributes:

Name Type Description
active_agents tuple[NotBlankStr, ...]

Currently active agent names (must be unique).

available_roles tuple[NotBlankStr, ...]

Roles available for hiring (duplicates allowed).

hiring_queue tuple[NotBlankStr, ...]

Roles in the hiring pipeline (duplicates allowed).

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_no_duplicate_active_agents

active_agents pydantic-field

active_agents = ()

Currently active agent names

available_roles pydantic-field

available_roles = ()

Roles available for hiring

hiring_queue pydantic-field

hiring_queue = ()

Roles in the hiring pipeline

Company pydantic-model

Bases: BaseModel

Top-level company entity.

Validates that department names are unique and that budget allocations do not exceed 100%. The sum may be less than 100% to allow for an unallocated reserve.

Attributes:

Name Type Description
id UUID

Company identifier.

name NotBlankStr

Company name.

type CompanyType

Company template type.

departments tuple[Department, ...]

Company departments.

config CompanyConfig

Company-wide configuration.

hr_registry HRRegistry

HR registry.

workflow_handoffs tuple[WorkflowHandoff, ...]

Cross-department workflow handoffs.

escalation_paths tuple[EscalationPath, ...]

Cross-department escalation paths.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_departments

id pydantic-field

id

Company identifier

name pydantic-field

name

Company name

type pydantic-field

type = CUSTOM

Company template type

departments pydantic-field

departments = ()

Company departments

config pydantic-field

config

Company-wide configuration

hr_registry pydantic-field

hr_registry

HR registry

workflow_handoffs pydantic-field

workflow_handoffs = ()

Cross-department workflow handoffs

escalation_paths pydantic-field

escalation_paths = ()

Cross-department escalation paths

Role

role

Role and skill domain models.

Skill pydantic-model

Bases: BaseModel

Structured capability description, A2A AgentSkill-aligned.

Mirrors the A2A protocol AgentSkill shape so projection to A2AAgentSkill is lossless. proficiency is the SynthOrg-specific addition used for quality-aware routing ("route to the agent with the highest Python proficiency").

Attributes:

Name Type Description
id NotBlankStr

Unique skill identifier (e.g. "code-review").

name NotBlankStr

Human-readable display name (e.g. "Code Review").

description str

Capability description for semantic matching.

tags tuple[NotBlankStr, ...]

Searchable tags for multi-faceted routing.

input_modes tuple[NotBlankStr, ...]

MIME types the agent accepts for this skill.

output_modes tuple[NotBlankStr, ...]

MIME types the agent produces for this skill.

proficiency float

Proficiency level in [0.0, 1.0]. Default 1.0 preserves legacy boolean-match scoring when proficiency is unspecified.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

id pydantic-field

id

Unique skill identifier

name pydantic-field

name

Human-readable display name

description pydantic-field

description = ''

Capability description for semantic matching

tags pydantic-field

tags = ()

Searchable tags for multi-faceted routing

input_modes pydantic-field

input_modes = ('text/plain',)

MIME types the agent accepts for this skill

output_modes pydantic-field

output_modes = ('text/plain',)

MIME types the agent produces for this skill

proficiency pydantic-field

proficiency = 1.0

Proficiency level in [0.0, 1.0]

Authority pydantic-model

Bases: BaseModel

Authority scope for an agent or role.

Attributes:

Name Type Description
can_approve tuple[NotBlankStr, ...]

Task types this role can approve.

reports_to NotBlankStr | None

Role this position reports to.

can_delegate_to tuple[NotBlankStr, ...]

Roles this position can delegate tasks to.

budget_limit float

Maximum spend per task in base currency units.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

can_approve pydantic-field

can_approve = ()

Task types this role can approve

reports_to pydantic-field

reports_to = None

Role this position reports to

can_delegate_to pydantic-field

can_delegate_to = ()

Roles this position can delegate tasks to

budget_limit pydantic-field

budget_limit = 0.0

Maximum spend per task in base currency units

SeniorityInfo pydantic-model

Bases: BaseModel

Mapping from seniority level to authority and model configuration.

Attributes:

Name Type Description
level SeniorityLevel

The seniority level.

authority_scope NotBlankStr

Description of authority at this level.

typical_model_tier ModelTier

Recommended model tier (e.g. "large").

cost_tier NotBlankStr

Cost tier identifier (built-in CostTier or user-defined string).

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

level pydantic-field

level

Seniority level

authority_scope pydantic-field

authority_scope

Description of authority at this level

typical_model_tier pydantic-field

typical_model_tier

Recommended model tier

cost_tier pydantic-field

cost_tier

Cost tier identifier (built-in or user-defined)

Role pydantic-model

Bases: BaseModel

A job definition within the organization.

Attributes:

Name Type Description
name NotBlankStr

Role name (e.g. "Backend Developer").

department DepartmentName

Department this role belongs to.

required_skills tuple[NotBlankStr, ...]

Skills required for this role.

authority_level SeniorityLevel

Default seniority level.

tool_access tuple[NotBlankStr, ...]

Tools available to this role.

system_prompt_template NotBlankStr | None

Template file for system prompt.

description str

Human-readable description.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

name pydantic-field

name

Role name

department pydantic-field

department

Department this role belongs to

required_skills pydantic-field

required_skills = ()

Skills required for this role

authority_level pydantic-field

authority_level = MID

Default seniority level for this role

tool_access pydantic-field

tool_access = ()

Tools available to this role

system_prompt_template pydantic-field

system_prompt_template = None

Template file for system prompt

description pydantic-field

description = ''

Human-readable description

CustomRole pydantic-model

Bases: BaseModel

User-defined custom role via configuration.

Unlike :class:Role, the department field accepts arbitrary strings in addition to :class:~synthorg.core.enums.DepartmentName values, allowing users to define roles in non-standard departments.

Attributes:

Name Type Description
name NotBlankStr

Custom role name.

department DepartmentName | str

Department (standard or custom name).

required_skills tuple[NotBlankStr, ...]

Required skills for this role.

system_prompt_template NotBlankStr | None

Template file for system prompt.

authority_level SeniorityLevel

Default seniority level.

suggested_model NotBlankStr | None

Suggested model tier.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

name pydantic-field

name

Custom role name

department pydantic-field

department

Department (standard or custom name)

required_skills pydantic-field

required_skills = ()

Required skills for this role

system_prompt_template pydantic-field

system_prompt_template = None

Template file for system prompt

authority_level pydantic-field

authority_level = MID

Default seniority level

suggested_model pydantic-field

suggested_model = None

Suggested model tier

Role Catalog

role_catalog

Built-in role catalog and seniority information.

Provides the canonical set of built-in roles from the Agents design page (Role Catalog) and the seniority mapping (Seniority & Authority Levels).

get_builtin_role

get_builtin_role(name)

Look up a built-in role by name (case-insensitive, whitespace-stripped).

Parameters:

Name Type Description Default
name str

Role name to search for.

required

Returns:

Type Description
Role | None

The matching Role, or None if not found.

Source code in src/synthorg/core/role_catalog.py
def get_builtin_role(name: str) -> Role | None:
    """Look up a built-in role by name (case-insensitive, whitespace-stripped).

    Args:
        name: Role name to search for.

    Returns:
        The matching Role, or ``None`` if not found.
    """
    result = _BUILTIN_ROLES_BY_NAME.get(normalize_identifier(name))
    if result is None:
        logger.debug(ROLE_LOOKUP_MISS, role_name=name)
    return result

get_seniority_info

get_seniority_info(level)

Look up seniority info by level.

Parameters:

Name Type Description Default
level SeniorityLevel

The seniority level to look up.

required

Returns:

Type Description
SeniorityInfo

The matching SeniorityInfo.

Raises:

Type Description
LookupError

If no entry exists for the given level.

Source code in src/synthorg/core/role_catalog.py
def get_seniority_info(level: SeniorityLevel) -> SeniorityInfo:
    """Look up seniority info by level.

    Args:
        level: The seniority level to look up.

    Returns:
        The matching SeniorityInfo.

    Raises:
        LookupError: If no entry exists for the given level.
    """
    info = _SENIORITY_INFO_BY_LEVEL.get(level)
    if info is None:
        logger.warning(
            ROLE_LOOKUP_MISS,
            level=level.value,
            reason="no seniority info in catalog",
        )
        msg = f"No seniority info for level {level!r}; catalog may be incomplete"
        raise LookupError(msg)
    return info

Task

task

Task domain model and acceptance criteria.

AcceptanceCriterion pydantic-model

Bases: BaseModel

A single acceptance criterion for a task.

Attributes:

Name Type Description
description NotBlankStr

The criterion text.

met bool

Whether this criterion has been satisfied.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

description pydantic-field

description

Criterion text

met pydantic-field

met = False

Whether this criterion has been satisfied

Task pydantic-model

Bases: BaseModel

A unit of work within the company.

Represents a task from creation through completion, with full lifecycle tracking, dependency modeling, and acceptance criteria. Field schema matches the Engine design page.

Attributes:

Name Type Description
id NotBlankStr

Unique task identifier (e.g. "task-123").

title NotBlankStr

Short task title.

description NotBlankStr

Detailed task description.

type TaskType

Classification of the task's work type.

priority Priority

Task urgency and importance level.

project NotBlankStr

Project ID this task belongs to.

created_by NotBlankStr

Agent name of the task creator.

assigned_to NotBlankStr | None

Agent ID of the assignee (None if unassigned).

reviewers tuple[NotBlankStr, ...]

Agent IDs of designated reviewers.

dependencies tuple[NotBlankStr, ...]

IDs of tasks this task depends on.

artifacts_expected tuple[ExpectedArtifact, ...]

Artifacts expected to be produced.

acceptance_criteria tuple[AcceptanceCriterion, ...]

Structured acceptance criteria.

estimated_complexity Complexity

Task complexity estimate.

budget_limit float

Maximum spend for this task in the configured currency.

deadline str | None

Optional deadline (ISO 8601 string or None).

max_retries int

Max reassignment attempts after failure (default 1).

status TaskStatus

Current lifecycle status.

parent_task_id NotBlankStr | None

Parent task ID when created via delegation (None for root tasks).

delegation_chain tuple[NotBlankStr, ...]

Ordered agent names of delegators (root first).

task_structure TaskStructure | None

Classification of how subtasks relate to each other (None when not yet classified).

coordination_topology CoordinationTopology

Coordination topology for multi-agent execution (defaults to AUTO).

middleware_override tuple[NotBlankStr, ...] | None

Per-task middleware chain override (None uses company default chain).

metadata dict[str, Any]

Arbitrary key-value metadata for pipeline tracking, labels, and operator-defined context. Deep-copied at construction to prevent external mutation.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _deepcopy_metadata
  • _validate_deadline_format
  • _validate_collections
  • _validate_delegation_fields
  • _validate_assignment_consistency

id pydantic-field

id

Unique task identifier

title pydantic-field

title

Short task title

description pydantic-field

description

Detailed task description

type pydantic-field

type

Task work type

priority pydantic-field

priority = MEDIUM

Task priority

project pydantic-field

project

Project ID this task belongs to

created_by pydantic-field

created_by

Agent name of the task creator

assigned_to pydantic-field

assigned_to = None

Agent ID of the assignee

reviewers pydantic-field

reviewers = ()

Agent IDs of designated reviewers

dependencies pydantic-field

dependencies = ()

IDs of tasks this task depends on

artifacts_expected pydantic-field

artifacts_expected = ()

Artifacts expected to be produced

acceptance_criteria pydantic-field

acceptance_criteria = ()

Structured acceptance criteria

estimated_complexity pydantic-field

estimated_complexity = MEDIUM

Task complexity estimate

budget_limit pydantic-field

budget_limit = 0.0

Maximum spend for this task in the configured currency

deadline pydantic-field

deadline = None

Optional deadline (ISO 8601 string)

max_retries pydantic-field

max_retries = 1

Max reassignment attempts after failure

status pydantic-field

status = CREATED

Current lifecycle status

parent_task_id pydantic-field

parent_task_id = None

Parent task ID when created via delegation

delegation_chain pydantic-field

delegation_chain = ()

Ordered agent names of delegators (root first)

task_structure pydantic-field

task_structure = None

Classification of subtask relationships (None = not classified)

coordination_topology pydantic-field

coordination_topology = AUTO

Coordination topology for multi-agent execution

source pydantic-field

source = None

Origin of this task (internal, client, or simulation)

middleware_override pydantic-field

middleware_override = None

Per-task middleware chain override (None = use company default)

metadata pydantic-field

metadata

Arbitrary key-value metadata for pipeline tracking and labels

with_transition

with_transition(target, **overrides)

Create a new Task with a validated status transition.

Calls :func:~synthorg.core.task_transitions.validate_transition before producing the new instance, ensuring the state machine is enforced. Uses model_validate so all validators run on the new instance.

Parameters:

Name Type Description Default
target TaskStatus

The desired target status.

required
**overrides Any

Additional field overrides for the new task.

{}

Returns:

Type Description
Task

A new Task with the target status.

Raises:

Type Description
ValueError

If the transition is not valid or overrides contain status.

Source code in src/synthorg/core/task.py
def with_transition(self, target: TaskStatus, **overrides: Any) -> Task:
    """Create a new Task with a validated status transition.

    Calls :func:`~synthorg.core.task_transitions.validate_transition`
    before producing the new instance, ensuring the state machine is
    enforced.  Uses ``model_validate`` so all validators run on the
    new instance.

    Args:
        target: The desired target status.
        **overrides: Additional field overrides for the new task.

    Returns:
        A new Task with the target status.

    Raises:
        ValueError: If the transition is not valid or overrides
            contain ``status``.
    """
    if "status" in overrides:
        msg = "status override is not allowed; pass transition target explicitly"
        raise ValueError(msg)
    validate_transition(self.status, target)
    payload = self.model_dump()
    payload.update(overrides)
    payload["status"] = target
    result = Task.model_validate(payload)
    logger.info(
        TASK_STATUS_CHANGED,
        task_id=self.id,
        from_status=self.status.value,
        to_status=target.value,
    )
    return result

Task Transitions

task_transitions

Task lifecycle state machine transitions.

Defines the valid state transitions for the task lifecycle, based on the Engine design page, extended with BLOCKED, CANCELLED, FAILED, INTERRUPTED, SUSPENDED, REJECTED, and AUTH_REQUIRED transitions for completeness::

CREATED -> ASSIGNED | REJECTED
ASSIGNED -> IN_PROGRESS | AUTH_REQUIRED | BLOCKED | CANCELLED
           | FAILED | INTERRUPTED | SUSPENDED
IN_PROGRESS -> IN_REVIEW | AUTH_REQUIRED | BLOCKED | CANCELLED
               | FAILED | INTERRUPTED | SUSPENDED
IN_REVIEW -> COMPLETED | IN_PROGRESS (rework) | BLOCKED | CANCELLED
AUTH_REQUIRED -> ASSIGNED (approved) | CANCELLED (denied/timeout)
BLOCKED -> ASSIGNED (unblocked)
FAILED -> ASSIGNED (reassignment for retry)
INTERRUPTED -> ASSIGNED (reassignment on restart)
SUSPENDED -> ASSIGNED (resume from checkpoint)

COMPLETED, CANCELLED, and REJECTED are terminal states with no outgoing transitions. FAILED, INTERRUPTED, and SUSPENDED are non-terminal (can be reassigned). AUTH_REQUIRED is non-terminal (waiting for authorization).

validate_transition

validate_transition(current, target)

Validate that a state transition is allowed.

Parameters:

Name Type Description Default
current TaskStatus

The current task status.

required
target TaskStatus

The desired target status.

required

Raises:

Type Description
ValueError

If the transition from current to target is not in :data:VALID_TRANSITIONS.

Source code in src/synthorg/core/task_transitions.py
def validate_transition(current: TaskStatus, target: TaskStatus) -> None:
    """Validate that a state transition is allowed.

    Args:
        current: The current task status.
        target: The desired target status.

    Raises:
        ValueError: If the transition from *current* to *target*
            is not in :data:`VALID_TRANSITIONS`.
    """
    _MACHINE.validate(current, target)

transition_path

transition_path(current, target)

Return the shortest valid hop sequence from current to target.

Parameters:

Name Type Description Default
current TaskStatus

The current task status.

required
target TaskStatus

The desired task status.

required

Returns:

Type Description
tuple[TaskStatus, ...] | None

() when already at target; a tuple of intermediate

tuple[TaskStatus, ...] | None

statuses ending in target (each hop individually valid) when

tuple[TaskStatus, ...] | None

a lifecycle path exists; or None when target is

tuple[TaskStatus, ...] | None

unreachable from current (e.g. current is terminal).

Source code in src/synthorg/core/task_transitions.py
def transition_path(
    current: TaskStatus,
    target: TaskStatus,
) -> tuple[TaskStatus, ...] | None:
    """Return the shortest valid hop sequence from *current* to *target*.

    Args:
        current: The current task status.
        target: The desired task status.

    Returns:
        ``()`` when already at *target*; a tuple of intermediate
        statuses ending in *target* (each hop individually valid) when
        a lifecycle path exists; or ``None`` when *target* is
        unreachable from *current* (e.g. *current* is terminal).
    """
    return _MACHINE.path_to(current, target)

Project

project

Project domain model for task collection management.

Project pydantic-model

Bases: BaseModel

A collection of related tasks with a shared goal, team, and deadline.

Projects organize tasks into a coherent unit of work with budget tracking and team assignment. Per the Design Overview glossary and entity relationship tree.

Attributes:

Name Type Description
id NotBlankStr

Unique project identifier (e.g. "proj-456").

name NotBlankStr

Project display name.

description str

Detailed project description.

team tuple[NotBlankStr, ...]

Agent IDs assigned to this project.

lead NotBlankStr | None

Agent ID of the project lead.

task_ids tuple[NotBlankStr, ...]

IDs of tasks belonging to this project.

deadline str | None

Optional deadline (ISO 8601 string or None).

budget float

Total budget in base currency (configurable, defaults to EUR).

status ProjectStatus

Current project status.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_deadline_format
  • _validate_collections

id pydantic-field

id

Unique project identifier

name pydantic-field

name

Project display name

description pydantic-field

description = ''

Detailed project description

team pydantic-field

team = ()

Agent IDs assigned to this project

lead pydantic-field

lead = None

Agent ID of the project lead

task_ids pydantic-field

task_ids = ()

IDs of tasks belonging to this project

deadline pydantic-field

deadline = None

Optional deadline (ISO 8601 string)

budget pydantic-field

budget = 0.0

Total budget in base currency (configurable, defaults to EUR)

status pydantic-field

status = PLANNING

Current project status

Approval

approval

Human approval item domain model.

Represents an action that requires human approval before proceeding. Used by the approval queue API and referenced by engine and security subsystems.

ApprovalItem pydantic-model

Bases: BaseModel

A single item in the human approval queue.

Attributes:

Name Type Description
id NotBlankStr

Unique approval identifier.

action_type NotBlankStr

What kind of action requires approval.

title NotBlankStr

Short summary of the approval request.

description NotBlankStr

Detailed explanation.

requested_by NotBlankStr

Agent or system that requested approval.

risk_level ApprovalRiskLevel

Assessed risk level.

status ApprovalStatus

Current approval status.

created_at AwareDatetime

When the item was created.

expires_at AwareDatetime | None

Optional expiration time for auto-expiry.

decided_at AwareDatetime | None

When the decision was made (set on approve/reject).

decided_by NotBlankStr | None

Who made the decision (set on approve/reject).

decision_reason NotBlankStr | None

Reason for the decision (required on reject).

task_id NotBlankStr | None

Optional associated task identifier.

source ApprovalSource

Origin discriminator fixed at creation. Routes a decided approval deterministically (parked-context resume vs. review gate) without a live parked-context probe. Defaults to REVIEW_GATE; the two park producers (SecOps escalation and the request_human_approval tool) set PARKED_CONTEXT.

metadata dict[str, str]

Additional key-value metadata.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _deep_copy_metadata
  • _validate_decision_fields
  • _validate_expiry

evidence_package pydantic-field

evidence_package = None

Structured evidence for HITL approval

Artifact

artifact

Artifact domain models for task outputs and expected deliverables.

ExpectedArtifact pydantic-model

Bases: BaseModel

An artifact expected to be produced by a task.

Used within task definitions to declare what outputs are expected.

Attributes:

Name Type Description
type ArtifactType

The type of artifact expected.

path NotBlankStr

File or directory path where the artifact should be produced.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

type pydantic-field

type

Type of artifact expected

path pydantic-field

path

File or directory path for the artifact

Artifact pydantic-model

Bases: BaseModel

A concrete artifact produced by an agent during task execution.

Artifacts track the actual work output, linking it back to the originating task and the agent who produced it.

Attributes:

Name Type Description
id NotBlankStr

Unique artifact identifier (e.g. "artifact-abc123").

type ArtifactType

The type of artifact.

path NotBlankStr

File or directory path of the artifact.

task_id NotBlankStr

ID of the task that produced this artifact.

created_by NotBlankStr

Agent ID of the creator.

description str

Human-readable description of the artifact.

content_type str

MIME content type (empty when no content stored).

size_bytes int

Content size in bytes (zero when no content stored).

project_id NotBlankStr | None

ID of the project this artifact belongs to.

created_at AwareDatetime | None

Timestamp when the artifact was created.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

id pydantic-field

id

Unique artifact identifier

type pydantic-field

type

Artifact type

path pydantic-field

path

File or directory path of the artifact

task_id pydantic-field

task_id

ID of the task that produced this artifact

created_by pydantic-field

created_by

Agent ID of the creator

description pydantic-field

description = ''

Human-readable description of the artifact

project_id pydantic-field

project_id = None

ID of the project this artifact belongs to

content_type pydantic-field

content_type = ''

MIME content type (empty when no content stored)

size_bytes pydantic-field

size_bytes = 0

Content size in bytes (zero when no content stored)

created_at pydantic-field

created_at = None

UTC timestamp when the artifact was created

Personality

personality

Personality compatibility scoring.

Computes pairwise and team-level compatibility scores from :class:~synthorg.core.agent.PersonalityConfig profiles.

compute_compatibility

compute_compatibility(a, b)

Compute pairwise compatibility score between two personality profiles.

Parameters:

Name Type Description Default
a PersonalityConfig

First personality profile.

required
b PersonalityConfig

Second personality profile.

required

Returns:

Type Description
float

Score between 0.0 (incompatible) and 1.0 (highly compatible).

Source code in src/synthorg/core/personality.py
def compute_compatibility(a: PersonalityConfig, b: PersonalityConfig) -> float:
    """Compute pairwise compatibility score between two personality profiles.

    Args:
        a: First personality profile.
        b: Second personality profile.

    Returns:
        Score between 0.0 (incompatible) and 1.0 (highly compatible).
    """
    bf_score = _big_five_score(a, b)
    collab_score = _collaboration_score(a.collaboration, b.collaboration)
    conflict_score = _conflict_score(a.conflict_approach, b.conflict_approach)

    result = (
        _WEIGHT_BIG_FIVE * bf_score
        + _WEIGHT_COLLABORATION * collab_score
        + _WEIGHT_CONFLICT * conflict_score
    )
    # Clamp to [0.0, 1.0] for safety.
    result = max(0.0, min(1.0, result))

    logger.debug(
        PERSONALITY_COMPATIBILITY_COMPUTED,
        score=result,
        big_five=bf_score,
        collaboration=collab_score,
        conflict=conflict_score,
    )
    return result

compute_team_compatibility

compute_team_compatibility(members)

Compute average pairwise compatibility for a team.

Parameters:

Name Type Description Default
members tuple[PersonalityConfig, ...]

Tuple of personality profiles for team members.

required

Returns:

Type Description
float

Average pairwise score (1.0 for teams with fewer than 2 members).

Source code in src/synthorg/core/personality.py
def compute_team_compatibility(
    members: tuple[PersonalityConfig, ...],
) -> float:
    """Compute average pairwise compatibility for a team.

    Args:
        members: Tuple of personality profiles for team members.

    Returns:
        Average pairwise score (1.0 for teams with fewer than 2 members).
    """
    team_size = len(members)
    if team_size <= 1:
        logger.debug(
            PERSONALITY_TEAM_SCORE_COMPUTED,
            team_size=team_size,
            score=1.0,
        )
        return 1.0

    pair_count = team_size * (team_size - 1) // 2
    total = sum(
        compute_compatibility(a, b) for a, b in itertools.combinations(members, 2)
    )
    result = total / pair_count

    logger.debug(
        PERSONALITY_TEAM_SCORE_COMPUTED,
        team_size=team_size,
        pair_count=pair_count,
        score=result,
    )
    return result

Resilience Config

resilience_config

Resilience configuration models (retry + rate limiting).

Defined in core/ to avoid circular imports between config.schema and providers.resilience. Both modules import from here.

RetryConfig pydantic-model

Bases: BaseModel

Configuration for automatic retry of transient provider errors.

Attributes:

Name Type Description
max_retries int

Maximum number of retry attempts (0 disables retries).

base_delay float

Initial delay in seconds before the first retry.

max_delay float

Upper bound on computed delay in seconds.

exponential_base float

Multiplier for exponential backoff.

jitter bool

Whether to add random jitter to delay.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_delay_ordering

max_retries pydantic-field

max_retries = 3

Maximum number of retry attempts (0 disables retries)

base_delay pydantic-field

base_delay = 1.0

Initial delay in seconds before the first retry

max_delay pydantic-field

max_delay = 60.0

Upper bound on computed delay in seconds

exponential_base pydantic-field

exponential_base = 2.0

Multiplier for exponential backoff

jitter pydantic-field

jitter = True

Whether to add random jitter to delay

RateLimiterConfig pydantic-model

Bases: BaseModel

Configuration for client-side rate limiting.

Attributes:

Name Type Description
max_requests_per_minute int

Maximum requests per minute (0 means unlimited).

max_concurrent int

Maximum concurrent in-flight requests (0 means unlimited).

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

max_requests_per_minute pydantic-field

max_requests_per_minute = 0

Maximum requests per minute (0 = unlimited)

max_concurrent pydantic-field

max_concurrent = 0

Maximum concurrent in-flight requests (0 = unlimited)

Auth

The auth domain types live in synthorg.core.auth (not synthorg.api.auth) so persistence repositories and engine modules can reference user / session / refresh-record / role models without crossing a layer boundary into the HTTP-coupled API package. The AuthService, controllers, and middleware that bind to Litestar / JWT issuer-audience constants stay under synthorg.api.auth.

config

Authentication configuration.

AuthConfig pydantic-model

Bases: BaseModel

JWT and authentication configuration.

The jwt_secret is resolved at application startup via a priority chain:

  1. SYNTHORG_JWT_SECRET environment variable (for multi-instance deployments sharing a common secret).
  2. Previously persisted secret in the settings table.
  3. Auto-generate a new secret and persist it for future runs.

At construction time the secret may be empty -- it is populated before the first request is served.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _apply_mirrors
  • _validate_secret_length
  • _validate_refresh_expiry
  • _validate_cookie_settings

jwt_secret pydantic-field

jwt_secret = ''

JWT signing secret (resolved at startup). Also used as the HMAC key for API key hash computation -- rotating this secret invalidates all stored API key hashes.

jwt_algorithm pydantic-field

jwt_algorithm = 'HS256'

JWT signing algorithm (HMAC family)

jwt_expiry_minutes pydantic-field

jwt_expiry_minutes = 1440

Token lifetime in minutes (default 24h)

min_password_length pydantic-field

min_password_length = 12

Minimum password length for setup and password change

exclude_paths pydantic-field

exclude_paths = None

Regex patterns for paths excluded from authentication. When None (default), paths are auto-derived from the API prefix (health, auth/setup, auth/login, docs, scalar UI). Use ^ to anchor at the start of the path and add $ when an exact match (rather than a prefix match) is required.

cookie_name pydantic-field

cookie_name = DEFAULT_COOKIE_NAME

Session cookie name

cookie_secure pydantic-field

cookie_secure = True

Secure flag on session cookies (HTTPS-only)

cookie_samesite pydantic-field

cookie_samesite = 'strict'

SameSite attribute for session cookies

cookie_path pydantic-field

cookie_path = '/api'

Path scope for the session cookie (HttpOnly)

csrf_cookie_path = '/'

Path scope for the CSRF cookie (non-HttpOnly). Defaults to / so document.cookie in JavaScript can read it from any SPA route; scoping it under /api (like the session cookie) would hide it from code running on application pages, breaking the double-submit pattern.

cookie_domain pydantic-field

cookie_domain = None

Domain for session cookies (None = current host)

csrf_cookie_name = DEFAULT_CSRF_COOKIE_NAME

CSRF token cookie name (non-HttpOnly, JS-readable)

csrf_header_name pydantic-field

csrf_header_name = DEFAULT_CSRF_HEADER_NAME

Header name for CSRF token submission

max_concurrent_sessions pydantic-field

max_concurrent_sessions = 5

Max concurrent sessions per user (0 = unlimited)

jwt_refresh_enabled pydantic-field

jwt_refresh_enabled = False

Enable refresh token rotation

jwt_refresh_expiry_minutes pydantic-field

jwt_refresh_expiry_minutes = 10080

Refresh token lifetime in minutes (default 7 days)

refresh_cookie_name = DEFAULT_REFRESH_COOKIE_NAME

Refresh token cookie name

refresh_cookie_path = DEFAULT_REFRESH_COOKIE_PATH

Path scope for refresh token cookie (narrow)

lockout_threshold pydantic-field

lockout_threshold = 10

Failed login attempts before account lockout

lockout_window_minutes pydantic-field

lockout_window_minutes = 15

Sliding window for counting failed attempts

lockout_duration_minutes pydantic-field

lockout_duration_minutes = 15

Auto-unlock duration after lockout

with_secret

with_secret(secret)

Return a copy with the JWT secret set.

Parameters:

Name Type Description Default
secret str

Resolved JWT signing secret.

required

Returns:

Type Description
AuthConfig

New AuthConfig with the secret populated.

Raises:

Type Description
ValueError

If the secret is too short.

Source code in src/synthorg/core/auth/config.py
def with_secret(self, secret: str) -> AuthConfig:
    """Return a copy with the JWT secret set.

    Args:
        secret: Resolved JWT signing secret.

    Returns:
        New ``AuthConfig`` with the secret populated.

    Raises:
        ValueError: If the secret is too short.
    """
    _require_valid_secret(secret)
    return self.model_copy(update={"jwt_secret": secret})

models

Authentication domain models.

AuthMethod

Bases: StrEnum

Authentication method used for a request.

OrgRole

Bases: StrEnum

Permission-level role for org configuration access.

Orthogonal to HumanRole (operational persona). HumanRole controls who you are in the org simulation; OrgRole controls what you can do to the org config.

User pydantic-model

Bases: BaseModel

Persisted user account.

Attributes:

Name Type Description
id NotBlankStr

Unique user identifier.

username NotBlankStr

Login username.

password_hash str

Argon2id hash (excluded from repr).

role HumanRole

Access control role.

must_change_password bool

Whether the user must change password.

org_roles tuple[OrgRole, ...]

Permission-level roles for org config access.

scoped_departments tuple[NotBlankStr, ...]

Departments accessible to dept admins.

created_at AwareDatetime

Account creation timestamp.

updated_at AwareDatetime

Last modification timestamp.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_scoped_departments

ApiKey pydantic-model

Bases: BaseModel

Persisted API key (hash-only storage).

Attributes:

Name Type Description
id NotBlankStr

Unique key identifier (UUID).

key_hash NotBlankStr

HMAC-SHA256 hex digest of the raw key.

name NotBlankStr

Human-readable label.

role HumanRole

Access control role.

user_id NotBlankStr

Owner user ID.

created_at AwareDatetime

Key creation timestamp (timezone-aware).

expires_at AwareDatetime | None

Optional expiry timestamp (timezone-aware).

revoked bool

Whether the key has been revoked.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

AuthenticatedUser pydantic-model

Bases: BaseModel

Lightweight identity attached to connection.user.

Populated by the auth middleware after successful authentication.

Attributes:

Name Type Description
user_id NotBlankStr

User's unique identifier.

username NotBlankStr

User's login name.

role HumanRole

Access control role.

auth_method AuthMethod

How the user authenticated.

must_change_password bool

Whether forced password change is pending.

org_roles tuple[OrgRole, ...]

Permission-level roles for org config access.

scoped_departments tuple[NotBlankStr, ...]

Departments accessible to dept admins.

session_id NotBlankStr | None

JWT jti (or None for non-JWT methods). Long-lived connections (WS, SSE) consult session_store.is_revoked(session_id) periodically so an admin revocation kicks the connection out instead of waiting for the access token to expire.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_scoped_departments

session

Session domain model for JWT session tracking.

Session pydantic-model

Bases: BaseModel

An active JWT session.

Each JWT token issued at login/setup creates a Session record. The session_id corresponds to the JWT jti claim, enabling per-token revocation.

Attributes:

Name Type Description
session_id NotBlankStr

JWT jti claim (unique token identifier).

user_id NotBlankStr

Owner's user ID.

username NotBlankStr

Owner's login name (denormalized for display).

role HumanRole

Owner's role at session creation time.

ip_address str

Client IP at login time.

user_agent str

Client User-Agent header at login time (capped at 512 characters).

created_at AwareDatetime

Session creation timestamp.

last_active_at AwareDatetime

Last request timestamp.

expires_at AwareDatetime

JWT expiry timestamp.

revoked bool

Whether the session has been revoked.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

  • session_id (NotBlankStr)
  • user_id (NotBlankStr)
  • username (NotBlankStr)
  • role (HumanRole)
  • ip_address (str)
  • user_agent (str)
  • created_at (AwareDatetime)
  • last_active_at (AwareDatetime)
  • expires_at (AwareDatetime)
  • revoked (bool)

Validators:

  • _validate_temporal_ordering

refresh_record

Refresh-token record model.

Lives outside the persistence layer so protocol modules can depend on the model without importing a backend implementation.

RefreshRejectReason

Bases: StrEnum

Why a consume() call refused to mint a new lease.

The repository captures the reason as a typed enum so the auth service / controller can emit SECURITY_AUTH_REFRESH_REJECTED with the correct reason field instead of folding every miss into a single bucket.

RefreshConsumeOutcome pydantic-model

Bases: BaseModel

Result of a refresh-token consume attempt.

Exactly one of record and reject_reason is populated. The model validator below keeps the discriminator honest.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_discriminator

RefreshRecord pydantic-model

Bases: BaseModel

A stored refresh token record.

Attributes:

Name Type Description
token_hash NotBlankStr

HMAC-SHA256 hash of the opaque token.

session_id NotBlankStr

Associated JWT session (jti).

user_id NotBlankStr

Token owner's user ID.

expires_at AwareDatetime

Expiry timestamp.

used bool

Whether the token has been consumed.

created_at AwareDatetime

Creation timestamp.

Config:

  • frozen: True
  • allow_inf_nan: False
  • extra: forbid

Fields:

Validators:

  • _validate_temporal_order

roles

Recognised human roles for access control.

HumanRole

Bases: StrEnum

Recognised human roles for access control.