Technical Product Specification • Section 6-12

WorkAgent OS Architecture

A decoupled, modular execution engine designed from the ground up for strict multi-tenant boundaries, verifiable tool orchestration, and model-agnostic reasoning.

Platform Infrastructure

The 6-Layer Platform Architecture

WorkAgent OS decouples interchangeable reasoning models from business rules, persistence, and tool integrations. The 6-Layer Platform Architecture provides the multi-tenant infrastructure host, while the 8-Layer Execution Model governs each agent action lifecycle.

Platform Hierarchy (System Infrastructure)
Layer 1

Presentation & Workspace Layer

Modern Next.js 16 web application, role-based Employee Workspace, Admin Console, and Human-in-the-Loop review portals.

Layer 2

API Gateway & Security Boundary

Enterprise gateway (SPEC) designed for authentication, request-signature validation where applicable, tenant isolation, and rate limiting. Request-signature checks (e.g. JWT or webhook verification) are distinct from action payload hashes.

Layer 3

Agent Runtime & Execution Engine

The core reasoning engine. Features modular LLM adapters (Claude, GPT, DeepSeek), 9-step Context Engine, Dynamic Risk Engine, and State Verification.

Layer 4

MCP-Compatible Tool Gateway

Bi-directional connector gateway providing tenant-scoped, permission-controlled tool access to enterprise SaaS and internal databases.

Layer 5

Enterprise Multi-Tenant Storage Layer

Strictly segregated multi-tenant persistence layer combining relational data, vector embeddings, and tamper-evident audit logging.

Layer 6

Observability, Cost & Evaluation Layer

Full OpenTelemetry-compliant execution tracing, real-time cost accounting, and automated regression evaluation suites.

Recommended Enterprise Production Stack:
Next.js 16 (TypeScript)FastAPI / Python RuntimePostgreSQL + pgvectorRedis Pub/Sub & CacheS3-Compatible Object StoreDocker / Containerized WorkersOpenTelemetry Tracing
Layer Inspector: Layer 3

Agent Runtime & Execution Engine

Isolation Scope: Strict Tenant RLS

The core reasoning engine. Features modular LLM adapters (Claude, GPT, DeepSeek), 9-step Context Engine, Dynamic Risk Engine, and State Verification.

Core Modules & Protocols:

9-Stage Context Resolution

Context resolution stages: Identity, Tenant, User, Task, Conversation, Org, Memory, Tool, Policy. Retrieval and ranking (structured fetch, semantic search, relevance, source authority, recency, dedup, budget, citations) run as a separate pipeline.

Planning & Tool Router

Decomposes requests into step-by-step DAGs, selects verified tools, validates JSON schemas.

Policy & Risk Engine

Normalized formula: Impact × Irreversibility × Externality × Sensitivity × Uncertainty × 100. 0-100 tiered action gates.

State Verification & Recovery

Re-reads external state post-execution, verifies outcome schema against expected entity, and triggers compensation, retry, reconciliation, or escalation depending on connector capability.

Deterministic Zero-Trust Protocol
spec_ref: Section 6 System Architecture
Section 8 Specification

The Agent Runtime Algorithm

Every run is designed to follow a fixed, verifiable execution algorithm. The model never communicates directly with raw databases or unverified APIs; every action is mediated by the Policy Engine, Risk Scorer, and Verifier.

01.Authorize session user under current Tenant RLS scope
02.Assemble minimal necessary context via Context Builder
03.Classify task and compile execution DAG plan
04.Evaluate ABAC/RBAC permissions and calculate quantitative risk
05.Pause and demand Human Approval for high-risk write tools
06.Verify post-execution external state against expected schema
07.Record OpenTelemetry trace and persist memory
agent_runtime.py (Core Execution Kernel)
Reference Runtime Pseudocode
function run_agent(request, user, tenant):
    # Step 1: Authentication & Tenant Resolution
    authorize_user(user, tenant)
    
    # Step 2: Context Retrieval & Filtering
    context = build_context(user_profile, history, memory, sources, request)
    policy = load_policy(tenant, agent_type)
    validate_context_access(context, policy)
    
    # Step 3: Planning & Decomposition
    task = classify_task(request)
    plan = model.plan(task, context, available_tools)
    
    # Step 4: Step-by-Step Tool Execution Loop
    for step in plan:
        tool = resolve_tool(step)
        if not policy.allows(tool, user, context):
            return blocked("permission_denied")
            
        risk = risk_engine.assess(step, tool, context)
        if risk.requires_human_approval:
            approval = request_approval(step, risk)
            if not approval.granted:
                audit("approval_denied")
                continue
                
        result = execute_tool(tool, step.parameters)
        
        # Step 5: Verification & State Recovery
        if not verifier.validate(result, step.expected_outcome):
            recovery = planner.replan(step, result)
            if recovery.available:
                continue
            return safe_failure()
            
        write_trace(step, result)
        update_short_term_memory(step, result)
        
    persist_relevant_long_term_memory()
    return final_response()
Section 9 Specification

The 9-Step Context Engine Pipeline

AI agents should never be flooded with indiscriminate data dumps. The Context Builder applies rigorous semantic, temporal, and authority filters to curate the exact minimum required tokens.

Step 01

Intent & Entity Decomposition

Parses prompt for core intent, entity references, and relevant time window.

Step 02

Tenant Permission Scoping

Defines strict tenant and department boundaries before any database querying.

Step 03

Structured Deterministic Fetch

Queries deterministic sources: Calendar attendees, CRM opportunities, user profile.

Step 04

Semantic Vector Search

Performs pgvector cosine similarity search across Drive docs and past emails.

Step 05

Multi-Factor Scoring

Calculates composite score: Recency (30%) + Semantic Relevance (40%) + Source Authority (30%).

Step 06

Deduplication & Noise Pruning

Discards redundant email chains and low-confidence document fragments.

Step 07

Context Budget Allocation

Caps assembled context within the pre-allocated token budget (e.g. 8,000 tokens).

Step 08

Citation Metadata Tagging

Attaches persistent source IDs and timestamps to each context fragment.

Step 09

Prompt Context Delivery

Transmits verified, citation-backed context payload to the model reasoning adapter.

Section 16 Specification

Verification & Self-Healing Recovery

Traditional agents assume tool execution succeeded if an HTTP 200 was returned. WorkAgent OS enforces active state verification: reading back the external resource to confirm changes took effect.

Define expected state outcome prior to executing tool call
Execute tool through MCP Gateway with unique idempotency_key
Validate JSON response schema against tool definition
Re-read external state directly (e.g. query Jira issue status)
Compare actual state against expected outcome
On failure: exponential-backoff retry with jitter
On repeated failure: retry, compensation, reconciliation, or escalation depending on connector capability
verifier_flow.jsonSelf-Healing Active
[1] Tool Execution:
POST /jira/rest/api/3/issue (idempotency: 77a1bc)
[2] Independent State Re-read:
GET /jira/rest/api/3/issue/ENG-4821
[3] State Comparison Verified:
Status == "OPEN" & Assignee == "[email protected]" ✓
Section 16 Specification • Connector Verification Matrix

Connector Verification & Recovery Capabilities

The specification classifies each external connector by its independent read-back verification rule, proposed retry policy, compensating capability, and reconciliation audit. These are design examples — provider behavior must be verified per deployment.

ConnectorRead Verification StrategyRetry StrategyRollback CapabilityCompensation MechanismReconciliation Audit
Google CalendarGET event by ID verify status === 'confirmed' and start/end matchesProposed: exponential backoff (3 attempts, max 10s)CompensatingCompensating action: delete created event ID or restore previous event payload snapshotEtag comparison against audit log snapshot
GmailVerify draft ID exists or sent message ID in sent folderProposed: linear retry on 429 / 503 (max 2 attempts)None (Manual)Irreversible external send; pre-execution hash approval required; send follow-up cancellation if configuredMessage-ID and thread-ID logged in append-only audit chain
Jira / LinearGET issue by issue_key verify fields, status, and assigneeProposed: exponential backoff on 429 rate limit (3 attempts)Partial / CompensatingTransition issue to 'Cancelled' or revert custom fields to cached pre-execution stateChangelog API diff comparison against execution intent
Slackconversations.history by message ts verify text and attachmentsProposed: exponential backoff with jitter on HTTP 429CompensatingCompensating action: chat.delete by channel and ts or chat.update with redaction noticeMessage timestamp and channel ID mapped in execution store
Salesforce / CRMSOQL query by record ID verify updated field values and SystemModstampProposed: exponential backoff on transient network / lock errors (3 attempts)Partial / CompensatingRevert updated fields to snapshot state captured in pre-execution contextField history tracking cross-checked against audit store

Risk Scoring Specification

SPEC

Illustrative scoring model — policies, tenant configuration, and scope checks can still deny low-scoring actions. The canonical formula multiplies five normalized factors:

RiskScore = Impact × Irreversibility × Externality × Sensitivity × Uncertainty × 100
FactorRangeMeaning
Impact0.0 – 1.0Blast radius of the action if executed wrongly
Irreversibility0.0 – 1.0Cost/difficulty of undoing the effect
Externality0.0 – 1.0Effect on parties/systems outside the tenant
Sensitivity0.0 – 1.0Data-classification level touched
Uncertainty0.0 – 1.0Model/policy confidence margin
ScoreTierBehavior
0 – 20Auto ExecutionEligible for autonomous execution in the illustrative model — still subject to policy, tenant, and scope checks.
21 – 50ABAC / Policy CheckPolicy evaluation before execution.
51 – 80Human Approval GateRequires hash-bound human approval.
81 – 100Deny / Elevated ApprovalDenied or routed to elevated approval.
Enterprise Architecture Blueprint

Enterprise Trust Zones & Data Flow Topology

A simplified perspective for enterprise security architects showing how user requests flow safely from identity providers into policy-bounded agent runtimes and external enterprise SaaS tools.

Zone 1

Human & Identity Scope

Enterprise SSO (SAML/OIDC), session resolution, and delegated execution authority binding (Tenant → User → Agent).

Zone 2

Policy & Risk Kernel

Deterministic ABAC/RBAC rules, Quantitative Risk Formula (0–100), and canonical SHA-256 action hash approval gates.

Zone 3

Context Engine & Memory

PostgreSQL RLS, pgvector semantic search, working memory, and token budget allocation with source citations.

Zone 4

Model-Agnostic Adapter

Stateless commercial foundation model inference (target); retention terms depend on the provider contract.

Zone 5

MCP Tool Gateway & Vault

Credential isolation inside Vault, idempotency control, external state read-back, and append-only audit ledger commit.