Skip to main content

Sentin8:AI - Detailed Design Document

1. Scope & Context​

Sentin8:AI owns the platform's AI plane: prompt assets (versioned, immutable), provider routing (openai / anthropic / ollama / vllm adapters with normalised tool-call support), synchronous inference (buffered + streamed), multi-turn agent conversations with a bounded tool-calling loop, vector + keyword retrieval, async AI jobs (embeddings, summaries, classifications, document pipelines), budgets, evaluations, output filters, traces/costs, and its dead-letter queue.

  • Owns (schema ai, database sentin8): prompts, providers, embeddings, traces, embedding_registry, dlq, budgets, evaluations, filters, and the agent plane - agents, tools, conversations, messages, runs, tool_calls, approvals, agent_policies - plus outbox (DBX) and audit_journal (DBX); the stream family ai; the three direct-consumer groups on it.
  • Does NOT own: model credentials (secret references resolved via Sentin8:Secrets / env backend), long-running side effects of agent tools (Sentin8:Flow workflows, Sentin8:Func modules), scheduling (Sentin8:Cron), document blobs (Sentin8:Storage), spend analytics (Sentin8:Stat), identity issuance (Sentin8:Auth - AI only requests agent tokens).
  • Agent plane boundary: the model loop (context assembly, provider iteration, tool dispatch, guards) is AI's. The work a tool performs belongs to the owning service and is reached through the tool gateway (sys.service_actions, Flow, Func) - AI never reads another service's tables and never executes domain logic itself.

2. Runtime Architecture​

Request lifecycle - buffered inference (POST /v1/chat):

Error branches: terminal provider error (4xx/auth/schema) → 422; retries exhausted → 502; moderation failure → 422 with filter name.

Request lifecycle - one agent turn (POST /v1/conversations/{id}/turns):

A turn is the unit of multi-turn behaviour: it appends the user message, runs the bounded loop, persists every tool exchange, and returns the final assistant message. Everything the loop decided is recorded, so a turn is reproducible from ai.runs.context_plan.

Loop guards are mandatory and each one is recorded on the run: max_turns (agent policy), token + cost budget (decremented before each provider call), and a wall-clock deadline for the whole turn. Stop reasons are a closed set: completed, max_turns, budget, cancelled, awaiting_approval, error.

3. Data Model​

  • RLS: every table ENABLE+FORCE, per-op policies keyed on sentin8_current_env_id() = env_id; outbox/journal policies additionally require sentin8_context_initialized().
  • Holder-scoped RLS on conversations (§4.3c): ai.conversations select/update admit the owner_sub row only (plus env/org admins through the context-stamped flags). ai.messages, ai.runs, ai.tool_calls and ai.approvals inherit the scope through their parent conversation - a policy that joins the parent is the only permitted shape; there is no org-wide visibility tier on agents.
  • ai.tools and ai.agents are tenant-authorable (origin-less: every row is tenant-owned; the platform seeds none). ai.agent_policies is the per-env bounds document (models, turn caps, tool classes, retention) - an agent's effective policy is its referenced policy or the env default.
  • ai.traces gains run_id so an inference is attributable to the turn that caused it; the conversation key never lives on the trace (the trace stays a metrics row).
  • Secrets: providers.credential_ref holds a secret reference - material never lands in application tables (resolved via Secrets or the env backend SENTIN8_AI_PROVIDER_KEY_*).
  • Indexes: HNSW cosine on ai.embeddings.embedding (pgvector-guarded), GIN on to_tsvector('simple', chunk_text), partial unrelayed indexes on outbox/audit_journal; helper ai.ai_monthly_tokens(env, feature); UNIQUE (conversation_id, seq) on ai.messages (turn ordering and idempotent append), UNIQUE (env_id, name) on ai.tools and ai.agents, partial ai.approvals_pending_idx on (run_id) WHERE state='pending'.

Prompt lifecycle:

Agent plane lifecycles:

  • Run records are append-only apart from the terminal stop_reason and usage counters. A resumed approval never rewrites history: it opens the next iteration of the same run so the transcript stays linear.

3.9 Capability tables (AI-first programme)​

The tables below extend the model for the capabilities described in §4.7-§4.13 and §5. They follow the same rules as every other ai table: env_id is the sole tenant key, RLS is forced, and a holder-scoped table stamps owner_sub.

TableTierNotes
ai.mcp_serversenv-scopedCredential is a reference; streamable_http is the only accepted transport; the URL is scheme-checked at registration, never at dispatch
ai.mcp_toolsenv-scopedexposed_name is UNIQUE (env_id, exposed_name) so two servers cannot both own search
ai.memoriesholder-scopedowner_sub + sentin8_current_subject_id(); region records where the content originated
ai.cost_ledgerenv-scopedAppend-only; settled flips when bill8 acknowledges, never on push attempt
ai.eval_baselinesenv-scopedOne row per (prompt, version, metric); the gate compares against the previous version's row

Two capabilities deliberately add no table:

  • Residency is a column on ai.providers (region) plus a list on ai.agent_policies (allowed_regions). A separate rates table would be a second place the truth could live, and the Shield context builder needs both values as attributes, not as a join.
  • A2A is a projection: an external task is an ai.runs row, and its state is the run's stop_reason. Materialising a parallel a2a_tasks table would give the platform two owners of one lifecycle.

Why the MCP tool row is materialised, not discovered at dispatch. The residency rule (§5) forbids a handler from making a cross-service call to answer a request, and the same reasoning governs tools: the model's tool list is assembled from local state. Discovery writes ai.mcp_tools on registration and on a TTL refresh; a dispatch reads the cached row and calls the server with the row's timeout. A server that dies therefore fails one dispatch, not every listing.

Why memory carries region. A memory extracted from an EU conversation must not be retrieved into a call routed to a US provider (§5). Storing the origin region on the row makes that a predicate in the retrieval query rather than an inference from source_run_id, whose run may itself have been deleted by retention.

4. API Surface​

4.1 Endpoint groups​

Groups (every route: bearer verify → Shield require_policy, target env required for data surfaces, no in-handler scope checks):

GroupEndpointsGate actionEvents
promptsPOST/GET /v1/prompts, DELETE /v1/prompts/{name}/{version}ai:prompt:write / ai:prompt:readsentin8:ai:prompt:updated
inferencePOST /v1/chat, /v1/completions, /v1/chat/stream (ndjson)ai:chat:write / ai:completion:writetrace rows + Stat
vectorsPOST /v1/embeddings, POST /v1/retrieval, /v1/documents/ingest, GET/PUT /v1/registryai:embedding:write / ai:retrieval:readsentin8:ai:document:ready
ops/v1/budgets/{feature}, /v1/dlq[/replay], /v1/evaluations/run, /v1/costs, /v1/tracesprompt scopessentin8:ai:{job_type}:job (replay)
conversationsPOST/GET /v1/conversations, GET /v1/conversations/{id}, PUT /v1/conversations/{id}, GET /v1/conversations/{id}/messages?after_seq=ai:conversation:read / ai:conversation:writesentin8:ai:conversation:created, :archived
turnsPOST /v1/conversations/{id}/turns, GET /v1/runs/{id}, POST /v1/runs/{id}/cancelai:agent:runsentin8:ai:run:completed, sentin8:ai:turn:delta (SSE)
toolsPOST/GET /v1/tools, GET /v1/tools/{name}, PUT/DELETE /v1/tools/{name}ai:tool:read / ai:tool:writesentin8:ai:tool:updated
agentsPOST/GET /v1/agents, PUT/DELETE /v1/agents/{name}, POST/GET /v1/agent-policiesai:agent:write / ai:agent:readsentin8:ai:agent:updated
approvalsGET /v1/approvals?state=pending, POST /v1/approvals/{id}/decideai:agent:approvesentin8:ai:approval:decided
internal/v1/internal/traces/archive (Cron proxy-back), /v1/internal/schedules/run (stale re-embed scan)ai:embedding:writearchive events
admin/SDUI/v1/admin/ui/{page}, /v1/admin/{resource}, shared policy adminShield-
healthGET /v1/healthnone-

Event flow (outbox → Bus → trigger):

Registration-declared triggers: *:document:uploaded → document-pipeline; sentin8:ai:trace:archive (cron ai-trace-archive); sentin8:ai:embedding:stale (cron ai-reembed-stale); sentin8:ai:agent:turn_requested → {"kind": "agent", "agent_name": ...} (an inbound event opens a turn instead of a job).

4.2 Tool gateway contract​

A tool is a tenant-authored row, not a code path. Dispatch is uniform, so adding a capability never edits AI:

  • http_action resolves through sys.service_actions - the same registry the BFF's /bff/action/{action} uses. No URL is ever stored on a tool row; the tool names an action, enroll published the mapping. This also gives discovery for free: the candidate tool set for an env is the actions its scopes admit.
  • side_effect is the confirmation axis: read and write execute inline; irreversible always pauses for POST /v1/approvals/{id}/decide before dispatch. The class is on the tool row, so a tenant can declare their own tool irreversible.
  • rate_limit_per_min is enforced at the gateway: a fixed one-minute INCR/EXPIRE window keyed (env, tool) in Valkey (ai rate_limit.rs), with a process-local minute window as the degraded mode - a Valkey outage tightens to the local bound, it never fails open and never blocks a tool outright. A refused call is a model-visible denied with the reason.
  • Tool results are sanitized before they re-enter the transcript: capped to the row's max_response_bytes, then deny-list PII keys are removed RECURSIVELY (a tool result nests; the shared top-level strip_pii used by traces is not enough for this path). The sanitizer is sanitize_tool_result in agent_gateway.rs, pinned by an integration test.
  • Approval EXECUTES the tool: an approved decision reopens the run, re-validates the arguments and the APPROVER's scope (approval never bypasses the gates), dispatches under the approver's authorization, appends the sanitized result to the transcript, and re-closes the run. A denial fails it. The decision commits first, so an approval is never re-decidable.
  • Arguments never reach a target unvalidated. The schema check happens in the gateway, not in the target, and arguments_hash lands in audit so a mutation is provable after the fact.
  • Results are bounded and filtered before they re-enter the transcript: max_response_bytes truncation plus the env PII deny-list, so a large or sensitive tool payload cannot bloat context or leak into a message row.
  • Tool execution authority is the caller's, never AI's: the agent token carries the conversation owner plus the act chain (see §5), and Shield evaluates it. A tool cannot escalate beyond what the requesting user could do directly.

4.3 Provider tool-call normalisation​

The adapters convert each provider's native shape into one ToolCall ({id, name, arguments}) plus a normalized FinishReason (stop | tool_calls | length | content_filter):

ProviderRequestResponse
OpenAI / vLLM / Ollamatools[] + tool_choicechoices[].message.tool_calls[], finish_reason
Anthropictools[] (added - the body previously had none) + tool_choicecontent[] blocks of type: "tool_use" (id, name, input), stop_reason
Assistant echorole: tool + tool_call_id replayed as the provider expects (tool role on OpenAI family, tool_result block on Anthropic)-

The JSON-intent contract ({action, params, requires_confirmation}) is retained as an explicit JSON-output mode for deterministic classification prompts - a prompt may declare it, and parse_intent remains the fail-closed parser for that mode. It is no longer the only path: the default agent path is native tool calling.

4.4 Edge-function inference (ai_infer)​

Sentin8:Func modules reach inference through a host builtin that AI serves on its normal inference surface - no per-service passthrough endpoint exists anywhere in the platform.

  • Identity is the module's workload certificate, not the caller's bearer: the Func runtime holds a sentin8:ai:infer:write grant (narrower than chat:write - inference only, no prompt or tool administration).
  • Multi-turn inside a stateless sandbox: the request may carry conversation_id; AI loads history, runs the turn, and persists it. The module stays fuel-bounded and state-free, which is the only shape the sandbox permits.
  • The module cannot outspend its env: AI's budget gate applies unchanged, and the model choice comes from the env's provider routes (§4.4), not from anything the module sends.
  • Bounded: the same 1 MiB response cap as every proxy-back, and a provider timeout that aborts the host call rather than the module (the module sees an error and decides).

4.5 Provider routes are tenant-scoped and live​

Routes resolve per request from the caller's env, not from a boot-time snapshot of sys/ops:

  • A tenant registering ai.providers takes effect on the next request. put_provider/delete_provider write an outbox row (sentin8:ai:provider:updated) in the same transaction and invalidate the local entry, so the change is immediate on the writing instance and propagates to the fleet through the Bus relay; the (env, provider) cache entry also expires on its 5-minute TTL as the backstop for a missed event.
  • The route load runs inside a tenant transaction. ai.providers is FORCE ROW LEVEL SECURITY, so a pool-level SELECT carries no sentin8_current_env_id() and is filtered to zero rows - the route would never resolve and the caller would see "provider not configured" for an env that configured it. ProviderRouteCache::load therefore sets the context for the env it is resolving on the same connection before reading (§3, and the platform rule that the context is transaction-local).
  • Credential resolution stays secret-reference-only; the cache holds the resolved adapter and a short-lived credential, never plaintext at rest.
  • An env with no provider row falls back to the platform (sys/ops) route only for platform-origin prompts; a tenant prompt with no tenant route is a 422 naming the env, never a silent platform charge.

4.6 Provider credentials resolve through Sentin8:Secrets​

ai.providers.credential_ref is a reference, never material. Resolution is delegated per environment to the fleet's secret store:

Four backend forms are accepted by credential_from_ref:

credential_refBackendPosture
secrets://ai/<name>Sentin8:Secrets over the AI workload certificateProduction - the only supported path
service://ai/<name>alias of the aboveProduction
env://<name>SENTIN8_AI_PROVIDER_KEY_<NAME> in the AI process envDev bootstrap only
file://<path>a local fileDev bootstrap only

The secrets path is the only one that satisfies the platform's secret-reference rule (principles "secret references only"), because the value lives encrypted in the secret store and is decrypted per use under the service's own identity. It depends on exactly one grant: the ai workload holds sentin8:secrets:secret:read, declared in this service's m2m_grants and provisioned by vertical enroll (DCR is dynamic - no static row is seeded anywhere). Without that grant the resolution returns None, the provider is reported as unconfigured, and the caller gets a 422 naming the env - it never silently falls back to another backend.

The workload name in that grant is the one whose certificate is presented. This service authenticates as ai (the certificate its Bus consumer and its Secrets resolve both load), so a grant on any other slug - including the fuller sentin8:ai identity - is inert for this edge: the certificate IS the identity, and the scopes that authorize the call are read from the workload map row for the presented certificate's subject. A running instance reads the map at boot, so changing the grant requires a restart (or the map's TTL) before the new scopes apply.

The env:// and file:// forms exist so a developer can smoke-test without a secret store; both keep material outside the database but inside a process's reachable surface, so neither is a production posture.

4.7 MCP egress - external tool servers as tools​

The tool registry accepts a fifth kind: mcp_server. An env registers an external Model Context Protocol server once, and its tools become available to every agent bound to them, with the same validation, rate-limit, PII-stripping, and audit treatment as a native tool.

Decisions and their reasons.

  • Namespacing is mandatory. An MCP server's tool names are local to that server; two servers both exposing search is the normal case. The exposed name is {server}__{tool}. Collisions are rejected at registration by UNIQUE (env_id, exposed_name), not resolved by last-write-wins.
  • Discovery is cached, never on the request path. tools/list runs on registration and on a TTL; the rows are what dispatch reads. This is the AGENTS.md rule-3 pattern applied to a tool catalogue: the handler serves from local state.
  • The credential is a reference. auth_ref is secrets://..., resolved through the same path as a provider key (§4.6) and never persisted.
  • A tool-level error is not a platform error. Per the MCP contract, a server that ran and failed returns content the model should see; a transport failure is DispatchOutcome::Error. Collapsing the two would either hide recoverable information from the model or feed transport noise into the transcript.
  • Sanitisation is unchanged. cap_result then strip_pii_deep, exactly as for native tools: an MCP server is a third-party data source and the least trustworthy hop in the loop.
  • stdio transport is not offered to tenants. A tenant-authored MCP server would be arbitrary process execution inside a platform service. Only streamable_http is accepted; stdio exists solely for platform-internal modules, which are not tenant-registerable. This is a security boundary, not a missing feature.

Schema dialect. MCP inputSchema is JSON Schema 2020-12; tools:: validate_arguments already implements the subset the platform honours (type, required, properties, additionalProperties, array items). A schema using a construct outside that subset is rejected at registration with a message naming the construct, rather than silently under-validating at dispatch.

Endpoint group.

EndpointGateNotes
PUT /v1/mcp/servers/{name}ai:tool:writeRegisters server + triggers discovery
GET /v1/mcp/serversai:tool:readMetadata only, never credentials
DELETE /v1/mcp/servers/{name}ai:tool:writeDisables server and its tools
POST /v1/mcp/servers/{name}/refreshai:tool:writeSynchronous re-discovery (explicit operator action)

Registration emits sentin8:ai:mcp:server:updated on the outbox so every instance drops its tool cache.

4.8 Structured output on the agent path​

/v1/chat validates the response against the prompt's output_schema; the agent loop does not. That asymmetry is a defect, and it is worse than an absent feature because the tenant configured a contract that is silently ignored.

The fix is not a bare validate_schema call on free text - a model answering a schema-constrained prompt still returns prose or a fenced code block, so naive validation fails most of the time. The sequence is:

Decisions and their reasons.

  • response_format first. Asking the provider for JSON is strictly better than asking for prose and then complaining: it removes most failures instead of handling them.
  • One repair attempt, then fail. Unbounded repair loops are how a schema-constrained agent becomes an infinite loop. One retry with the exact validation error appended to the transcript is the maximum that earns its cost; failure is an explicit StopReason::Error, not a silent pass-through.
  • Reuse tools::validate_arguments. There is exactly one JSON Schema validator in this service, and it is the subset engine the tool gateway uses. A second validator would drift from it.
  • Validation happens on the final iteration only. Intermediate iterations produce tool calls, not the deliverable; validating them would fail correctly formed tool-calling responses.
  • The parsed object is what the transcript stores when the schema is present, so a downstream consumer reads structured data rather than a string to re-parse.

4.9 Data residency per provider​

A provider row declares where inference physically happens; a request declares what it is allowed to accept. The decision is Shield's, not a handler's.

ColumnTableMeaning
regionai.providersPhysical region the provider endpoint serves (eu, us, uk, ca)
in_region_onlyai.residency_ratesThe provider will not serve a request whose data must stay in its region
allowed_regionsai.agent_policiesRegions this agent's prompts may be routed to; empty = no constraint

Decisions and their reasons.

  • Residency is a policy attribute, not an if in turn.rs. The platform law is that authorization is Shield's and roles/scopes are resolved live (principles §5.2). A residency check written inline in the service would be unauditable, untunable by a tenant, and invisible to the policy admin surface.
  • The fallback chain obeys the same gate. route_for_env resolves a fallback provider; a fallback that crosses a border is a silent violation of the primary's constraint, and it is the most likely place for this rule to be broken. The gate runs per resolved route, not once per request.
  • Fail closed. A provider with no region is treated as unable to satisfy a constrained policy. Missing data must not widen an obligation.
  • Memory inherits the constraint (§4.11): retrieval filters on the row's origin region, so a residency-scoped agent cannot be handed content that originated outside its permitted set.

Endpoint. PUT /v1/providers/{provider} gains region; the value is validated against a closed set so a typo cannot silently create a new jurisdiction.

4.10 Evaluation as a practice, not a demo​

ai.evaluations scores cases by exact match or substring containment. That is sufficient to prove a prompt runs and insufficient to decide whether a prompt change is safe to ship.

Two additions, both reusing the inference plane:

(a) Judge metrics. A metric is a rubric prompt evaluated by a model:

ai.eval_metrics(env_id, name, kind, rubric, model, threshold)
kind = 'judge' | 'exact' | 'contains' | 'regex' | 'trajectory'

A judge metric runs run_inference with the rubric and the case, and returns {score, reason}. Because it is an ordinary inference call it inherits budgets, traces, moderation, and the residency gate - none of which a Python-side evaluator would honour.

trajectory metrics score the path, not the answer: the ordered list of ai.tool_calls for the run. This is what makes an agent change reviewable - "it still answers correctly" is weaker than "it still calls the same tools in a sane order".

(b) Regression baseline and promotion gate.

  • ai.eval_baselines stores one row per (prompt, version, metric).
  • POST /v1/prompts/{name}/{version}/promote compares the candidate's score against the baseline and refuses when the delta is worse than the policy's eval_regression_tolerance.
  • A prompt version with no baseline cannot be promoted; it must be evaluated first.

Decisions and their reasons.

  • The judge lives in the service, not in an external harness. An external evaluator that calls the provider directly would bypass budgets, residency, and moderation - the three things that make AI spend and data handling governable. run_inference is the only sanctioned path to a model.
  • promptfoo and DeepEval are used as CI drivers, not as runtime. Both can target an HTTP endpoint. Pointing promptfoo at /v1/chat with a tests: file gives red-teaming and model comparison without embedding an external evaluation stack inside the service. The system of record stays ai.evaluations.
  • Exact match is retained for deterministic prompts (classification, extraction). Judge scoring is not a replacement for a case that has one correct answer.

4.11 Long-term memory​

A conversation summariser exists (jobs::spawn_summary_consumer); recall across conversations does not. Memory is the difference between an assistant that remembers you and one that meets you again every session.

Implementation. jobs::spawn_memory_consumer subscribes to the ai stream family as the sentin8-ai-memory consumer group; the trigger is declared in the registration (event_triggers), so enroll provisions it. memory_consumer::extract_for_run does the work: it reads the agent policy (memory_enabled, memory_retention_days), loads the run's user turns (extracting from our own assistant text would confirm a hallucination into memory), calls the same ProviderRouter a turn uses so extraction inherits budgets, moderation, and the residency gate, then admits candidates through memory_consumer::admit and inserts them under ON CONFLICT (env_id, owner_sub, agent_id, kind, content) DO NOTHING so a replayed event is a no-op. expires_at is stamped from memory_retention_days; the extraction rubric (EXTRACTION_RUBRIC) is fixed wording and states that the transcript is data, not instructions.

Decisions and their reasons.

  • Write is event-driven, read is synchronous and local. Extraction runs on run:completed through the Bus (AGENTS.md rule 3: an event can carry this work). Retrieval is a local query in the existing context-assembly transaction - a handler may not call out to answer.
  • Memory is holder-scoped, not env-scoped. A memory belongs to a subject, under the same owner_sub rule as conversations. An env admin may read for support (context-stamped flag); a peer may not.
  • Provenance is recorded. source_run_id makes a memory explicable ("this is why the agent believed that") and removable when a run is purged.
  • Residency is a retrieval predicate. The row carries region; retrieval filters on it. Memory is exactly the capability that would otherwise smuggle data across a border that §4.9 just closed.
  • Extraction must not be a second injection vector. The extractor's input is a summary that has already been moderated; its output is text, not instructions, and it enters the transcript as a labelled memory block, never as a system instruction.
  • Bounded by policy. ai.agent_policies gains memory_enabled and memory_retention_days; a disabled agent neither writes nor reads memory.

4.12 Multi-agent composition​

An agent delegating to another agent is the expected enterprise shape. The platform expresses it in two places, deliberately distinct:

(a) Internal composition uses sentin8:flow. A sub-agent invocation is a flow step kind agent_turn:

{ "kind": "agent_turn", "agent_name": "researcher", "input": "$.task",
"output": "$.research", "budget_ref": "$.budget" }

The step calls POST /v1/conversations/{id}/turns on this service. Consequences that make this the right shape:

  • One transcript owner per conversation; no nested-loop ambiguity.
  • The parent's budget tree includes the child's spend because the child is an ordinary turn against the same budget.
  • Flow already owns retries, step state, and the proxy-back contract.

(b) A2A is the external facade. Another organisation's agent is an opaque peer, not a flow step. That is a protocol boundary, and the platform's A2A surface is specified separately (§4.13).

What is explicitly rejected: a bespoke multi-agent DSL with its own planner. The platform already has a durable step engine with retries, and a second orchestration model would fork the failure semantics that Flow, Cron, and Func share.

4.13 Agent interop (A2A)​

An A2A facade lets an external agent discover this platform's agents, send them tasks, and stream results. It is a projection of the run model, not a second engine:

A2A conceptExisting primitive
AgentCard (skills, capabilities, security)ai.agents + policy + provider capabilities
Taskai.runs
TaskStateStopReason
Message.parts[]ai.messages
Artifacttool results / Storage objects
contextIdconversation_id
TASK_STATE_INPUT_REQUIREDAwaitingApproval
TASK_STATE_AUTH_REQUIREDapproval pending
securitySchemes.mtlsthe platform workload certificate

Scope of the facade. The HTTP+JSON binding only: POST /message:send, POST /message:stream, GET /tasks/{id}, POST /tasks/{id}:cancel, GET /.well-known/agent-card.json. gRPC is deliberately not offered: it duplicates the surface for no capability this platform needs.

Decisions and their reasons.

  • The Agent Card is generated, never hand-written. It is derived from the agent row, its bound tools, and the provider's declared capabilities, so it cannot drift from what the agent actually does. A card that advertises a skill the agent cannot perform is worse than no card.
  • Signing uses sentin8:sign. A2A allows JWS over a canonicalised card (RFC 8785). The platform already owns a signing service with ML-DSA-65; a hand-rolled signature would be the one place the platform's post-quantum posture lapsed.
  • TASK_STATE_AUTH_REQUIRED maps to the existing approval gate. This is the strongest mapping in the table: human oversight is enforced at runtime, so an external peer sees a real pause with a real approver, not a status string.
  • A2A traffic is a first-class authorized principal. An external agent presents a workload certificate; it is authorized by Shield like any other caller, and its tool calls land in ai.tool_calls with its identity. This is the platform's differentiator expressed on a standard wire protocol.

5. Cross-Cutting Concerns​

  • Auth: every route verify_bearer_token → Shield require_policy (live roles/scopes from auth); step 5 is the only gate - no handler scope checks.
  • Tenant resolution: target_env_id query REQUIRED on admin/data endpoints (no fallback to token env - rejects with 400).
  • RLS context: transaction-local sentin8_set_tenant_context on the caller's env inside each write transaction; trace insert shares the request's transaction. Every tenant read runs in a tenant transaction too: ai.* tables are FORCE ROW LEVEL SECURITY, so a pool-level SELECT has no sentin8_current_env_id() and returns zero rows - the list endpoints would answer [] for an env holding data, and route resolution would find no provider. The regression test tenant_reads_require_the_rls_context pins both halves (context-less read sees nothing, context-scoped read sees the row).
  • Idempotency: ai:idem:{env}:{key} (24h TTL) replays full response for retried inference calls; job consumers dedupe on job_id. A turn is idempotent on the caller-supplied turn_id (a partial unique index on (conversation_id, turn_id) WHERE role='user'): a retried turn returns the stored assistant message instead of appending a second one.
  • Turn serialisation is structural: ai.runs carries UNIQUE (conversation_id, turn), so a concurrent duplicate turn is rejected by the index (409) rather than by a lock some path forgets to release. There is no advisory lock in the turn path. The number itself is allocated from MAX(ai.runs.turn) + 1 - the authoritative allocator - not from conversations.turn_count: the counter is a roll-up, and a run that closes early (provider failure, moderation block) must not be able to wedge the conversation on the same number forever. Every exit path rolls the conversation up (ai.ai_conversation_touch) so the counter and the run table stay consistent. That function declares p_cost numeric, so callers bind a numeric-coercible value (a float bind is double precision, which PostgreSQL does not implicitly cast).
  • The loop runs in SHORT transactions: setup, each provider iteration, each tool dispatch, and the close each commit separately - a crash loses at most the in-flight provider call, never a partial transcript.
  • Moderation: input stage before provider call; buffered output stage after; streaming moderation on an accumulated buffer per delta (mid-stream violation aborts with an error frame). Agent turns moderate both directions of every hop: the user message on entry, each assistant message on arrival, and each tool result before it re-enters the transcript - a tool returning injected text is the primary prompt-injection channel in an agent loop.
  • Budgets: env-wide '*' fallback + per-feature caps; reject → 429, degrade/queue → cost-labelled traces ({feature}:cost-{mode}). A turn charges feature = agent:{agent_name} and the env '*' budget; the check runs before each provider call inside the loop, so a long tool chain cannot overspend a cap it already crossed.
  • Agent identity: the run executes under the caller's token - the run records that token's jti (runs.agent_token_jti) and the audit chain carries the caller's claims (sub, jti, email, env_id). No new token is minted for the agent, so there is nothing extra to leak, expire, or revoke: revoking the caller's token revokes the run's authority on the next request, and one run remains traceable end to end by its jti.
  • The model reaches the provider in WIRE form: ai.prompts.model_primary carries the registry's provider/model value, but the provider is selected from the route registry separately, so the request body must send only the part after the slash - forwarding ollama/<model> asks the provider for a model literally named that and fails with 404. This is the same rule /v1/chat follows.
  • Audit journaling: agent runs, tool calls, approvals, DLQ writes, and every inference land in ai.audit_journal (pushed to the shared audit ingest). A tool call row carries run_id, tool_name, arguments_hash, status, approval_by, duration_ms - enough to reconstruct what the agent did without replaying the model. The inference row carries cache provenance - cache: "hit"|"miss" plus the prompt-hash key - so a replay is distinguishable from a fresh generation.
  • Context assembly is recorded, not implicit: runs.context_plan stores the window boundary, the summary message id (when history was summarised), and the retrieval chunk ids that were injected. Two runs of the same turn over the same history produce the same plan, which is what makes an agent turn reproducible and auditable.
  • Retention: ai.agent_policies.retention_days bounds conversation history; the sweep archives messages beyond the window into Storage and keeps the conversation skeleton (the same archive pattern as traces).
  • Graceful drain: shell-owned graceful shutdown; relay fail-open. An in-flight turn finishes or fails with stop_reason=error; it never leaves a half-written transcript because messages and the run update commit together.
  • Turn streaming to the client: each iteration emits sentin8:ai:turn:delta through the outbox. The payload is iteration-level (the provider adapter is non-streaming), and it carries the conversation OWNER in user_id plus run_id, conversation_id, iteration, a kind (delta | tool_call), the content, and the token counts. Delivery is the BFF's GET /subscribe SSE hop (§4 subscription table in the BFF design). The publisher stamps user_id because the BFF's per-session filter keys on it and its fallback for a missing claim is tenant-wide fan-out: the BFF holds no grant on the ai schema, so it cannot resolve the owner itself (owner-first, principles §6.6a), and a frame without the claim is dropped rather than broadcast. Token-level deltas require a streaming adapter method and are a separate change (§10 Open Questions).
  • Observability: spans mirror the data model rather than inventing a second one - ai.conversation.turn (run_id, conversation_id, turn) with ai.provider.call (model, tokens, latency) and ai.tool.call (tool, side effect, duration) children. Every attribute is already a column in ai.runs, ai.traces, and ai.tool_calls. Attributes follow the OpenTelemetry GenAI conventions (gen_ai.*) where a name exists and the sentin8.* namespace otherwise. Export is off unless SENTIN8_OTEL_ENDPOINT is set.
  • Cost attribution: a run's charge lands in ai.cost_ledger in the same transaction that closes the run, priced from ai.price_book. Settlement is a Bus consumer on sentin8:ai:run:completed posting to Bank8:Bill's public API - never a call from a handler, and settled flips only on acknowledgement so a billing outage does not lose a charge.
  • Injection defence is layered, and the structural layer is the load-bearing one: tool results are capped, PII-stripped recursively, and re-enter as role: "tool" data inside a labelled envelope; a tool result may never grant the run a new tool; the input deny-list is a coarse first filter, not the defence. Red-team suites run in CI against the public endpoint rather than relying on the phrase list.
  • Regulatory evidence is queryable, not authored. GET /v1/compliance/ai-act/{env} assembles the Annex-IV view from live rows: intended purpose (agent + prompt), model identity and region (provider), data governance (filters, PII rules), human oversight (policy + approval log), accuracy (evaluations + baselines), logging (audit references). A model card per agent is stored as ai.agents.model_card and is the only hand-authored part.

6. Failure Modes & Recovery​

  • Valkey down: idempotency + cache degrade to direct execution (best-effort paths never fail the request). The tool rate-limit bucket degrades to process-local counting - a Valkey outage weakens rate limiting, it never blocks tool execution.
  • Bus down: outbox relay persists rows in ai.outbox (5s safety poll); consumer loops retry their connections.
  • Stat/Flow/Cron/Storage outages: log-only degradations (trace row still carries spend; a flow_workflow tool returns error while the turn continues; cron registration skipped; archive retains hot rows).
  • Credential loss: secret ref unresolvable → provider disabled at routing time (422 to caller or stop_reason=error inside a turn, no crash loop).

Agent-loop failure paths:

  • A failing tool does not fail the turn. The error becomes a tool message so the model can recover, change approach, or explain. The turn fails only when the model cannot continue (provider terminal, guards).
  • A denied tool is a model-visible fact, not a silent drop: the model sees denied: <reason> and the audit row carries the same reason. A silent drop makes an agent loop look like it succeeded when it did not.
  • Crash mid-turn: the run row holds stop_reason unset and the last committed message seq; the next request resumes context from the last committed seq. Committing messages and the run update in one transaction bounds the loss to the in-flight provider call.
  • Approval expiry: a pending approval past its deadline transitions to expired and the run to error - an agent never parks forever.

7. Concurrency & Performance Model​

  • Turns are not background tasks. A turn runs inside its request (bounded by the wall-clock guard), so no unbounded tokio task is spawned per conversation and a crashed instance loses at most one in-flight call.
  • One turn per conversation at a time: an advisory lock keyed (env_id, conversation_id) serialises concurrent turn requests, which is what makes seq assignment and turn_count correct under retries.
  • Tool dispatch is sequential within a turn. Parallel tool execution is deliberately not done: the transcript ordering must stay deterministic and an irreversible tool must not race a read.
  • Pool capped (sentin8_config::pg_pool::connect, max 3 default) - inference trace writes, job upserts and turn commits share the cap; the budget check runs once per provider call inside the loop.
  • Retrieval top_k clamped 1-100; archives bounded (LIMIT 10000); trace lists 1-500; DLQ listing 200; message pages 1-200 (default 50).
  • Hot paths cached: exact-match response cache (1h TTL; the key covers env, model, messages, temperature, max_tokens, and the tool set - hashed to a bounded sha256 prompt-hash, so a near-hit can never replay a response generated under different sampling params) - bypassed for conversation turns, because a dialog key never repeats and a hit would replay a stale answer; embeddings via HNSW; keyword via GIN tsvector.

8. Invariants, Insecure-Defaults Rejected, Unsafe Rationale​

  1. Prompt versions immutable - an update creates a new version; 409 on duplicate (env_id, name, version); origin platform rows are enroll-owned, tenant rows never touched by enroll.
  2. target_env_id REQUIRED on data endpoints - no silent fallback to the token env (cross-tenant read guard).
  3. Credential references only - provider keys never stored in ai.providers; resolution order: Secrets ref → env backend.
  4. Filters run both directions (input + output) with a persistent PII deny-list; output moderation cannot be skipped by model_override.
  5. Budget checks precede provider spend - a rejected request never reaches a provider.
  6. DLQ replay is manual - failed jobs never auto-retry past the consumer redelivery; malformed payloads are acked (poison-pill guard).
  7. Traces insert in the same transaction as the response decision - a trace row exists for every completed or failed inference.
  8. No unsafe blocks in the service.
  9. The model never executes. It emits tool calls; the gateway validates the arguments, checks the scope, applies the confirmation class, and only then dispatches. There is no code path from model output to execution that skips the gateway.
  10. Conversation history lives only in AI. No Func module, Flow workflow, or client holds authoritative transcript state; each addresses a conversation by id. History is therefore bounded, auditable, and tenant-deletable in one place.
  11. Every loop is bounded and the bound is recorded - max_turns, token + cost budget, wall-clock deadline. A turn always terminates with a stop reason from the closed set.
  12. No tool executes on an unvalidated argument set, and every executed call carries arguments_hash in audit.
  13. Tool authority is the caller's, never AI's: the per-run agent token carries the owner and the act chain, and Shield evaluates it. AI holds no scope that a tool target honours on its own behalf.
  14. A tool result is re-moderated before it enters the transcript - tool output is untrusted model input and is the primary injection channel.
  15. Turns bypass the exact-match cache; prompt-only inference keeps it.
  16. Provider credentials are references, never material. The production form is secrets://ai/<name>, decrypted per use over the AI workload certificate. A missing sentin8:secrets:secret:read grant is a hard unconfigured state (422 naming the env), never a silent fallback to an env var or a file.

9. Testing Strategy​

  • tests/integration.rs: adapters (openai/anthropic/ollama/vllm mock round-trips including tool-call responses), error taxonomy (429 transient, 401 terminal), retry + fallback routing, DB RLS isolation, version immutability, filter load per env, chunk persistence, credential-ref resolution, registration identity/scopes, policy boot.
  • Agent suite (same file, DB-gated): a multi-iteration turn against a scripted mock provider (model calls a tool, receives the result, answers); each guard tripping to its expected stop reason; schema-invalid arguments denied without dispatch; out-of-scope tool denied; irreversible tool pausing then resuming on approval; turn_id replay returning the stored message; conversation visibility isolation between two users in one env.
  • tests/live_provider.rs (opt-in, real provider): the only layer that answers "does an agent work on this fleet". It spans four layers that are each tested separately and were never tested together - the ai.providers row, the credential_ref resolution, the adapter's wire shape, and the request the turn loop builds. Gated on SENTIN8_AI_LIVE_PROVIDER=1 and bounded to 16 max_tokens, so a plain cargo test stays green and offline. The credential is resolved through the service's own resolver, never by reading the file in the test: re-implementing the file:///env:/// secrets:// chain would let a ref-format regression pass the test and fail in production.
  • Deliberately not unit-tested: provider HTTP correctness (mocked), Stat emission, cron registration (e2e/platform layer), real model quality (that is the evaluations surface).

9.1 Providing a real model (operator path)​

Three pieces make a live agent work; each fails with a different, misleading symptom when missing.

  1. The credential. Store the provider key in a file outside any tracked tree, mode 0600:

    mkdir -p <tree>/.run/secrets/ai
    printf '%s' '<key>' > <tree>/.run/secrets/ai/ollama-cloud.key
    chmod 600 <tree>/.run/secrets/ai/ollama-cloud.key

    A trailing newline is the most common mistake: the resolver returns the bytes verbatim, so the adapter sends Authorization: Bearer <key>\n and the provider answers 401 with no useful message. The live test asserts this directly rather than leaving it to a support ticket.

  2. The provider row. base_url is the OpenAI-compatible endpoint (Ollama Cloud: https://ollama.com), and credential_ref is file://<abs path> for a single-host deployment or secrets://<name> in production:

    INSERT INTO ai.providers (provider, base_url, credential_ref, models, status, env_id)
    VALUES ('ollama', 'https://ollama.com',
    'file:///<tree>/.run/secrets/ai/ollama-cloud.key',
    '["deepseek-v4.1-flash"]', 'active',
    '00000000-0000-0000-0000-000000000002')
    ON CONFLICT (env_id, provider) DO UPDATE
    SET base_url = EXCLUDED.base_url,
    credential_ref = EXCLUDED.credential_ref,
    models = EXCLUDED.models,
    status = 'active';

    Routes resolve per request with a cache (provider_routes::resolve), and the platform env (sys/ops) is the fallback for every tenant, so this one row serves the whole fleet until a tenant registers its own.

  3. The agent's three rows. A prompt pins the model in registry form (provider/wire-model), a policy must ALLOW that same string, and an agent binds the two. A mismatch is the "agent exists but every turn 422s" class: the policy check and the route lookup fail differently, and neither message names the disagreement. The live test's assembly check reads all three rows through one join so the disagreement surfaces before a turn is attempted.

file:// is deliberately preferred over an environment variable for a single-host deployment: provider env vars pass through captain's allowlist (catalog.rs), which is a security boundary that should not be widened for a credential. secrets:// remains the production path (cert-bound sentin8:secrets:secret:read on the ai workload).

10. Open Questions​

  • SSE transport for POST /v1/chat/stream is already aligned: the transport rule (principles §4.7a) governs, not a per-endpoint choice.
  • Token-accurate streaming accounting adopts the approximation the normalization already performs (estimate from the terminal frame).
  • Embedding model versioning is live (AI-2): ai.embeddings.model_version stamps every write with the registry-active version (ai_version_for); the Cron model_migration sweep (POST /v1/internal/schedules/run) re-enqueues jobs for rows trailing the registry - the dual-read discriminator. Per-model DIMENSIONS remain a pgvector-typmod concern: changing the pinned dimension is a greenfield re-init (the registry row
    • version sweep govern which rows are current).
  • Context compression strategy is deliberately coarse: a conversation beyond the model window is summarised once at a recorded boundary rather than continuously re-summarised. Token-exact budgeting per model family is deferred; the guard uses provider-reported usage where available and the existing char/4 estimate otherwise (usage_estimated flags it).
  • Parallel tool execution is not implemented. If a concrete workload needs it, it must arrive with a deterministic transcript ordering rule (a batch id per assistant message) rather than ad-hoc concurrency.
  • Multi-agent orchestration (an agent delegating to another agent) is out of scope here: it composes as a tool of kind flow_workflow whose logic calls POST /v1/conversations/{id}/turns, which keeps one transcript owner per conversation and avoids nested-loop guard ambiguity. If that proves insufficient, the design change is an explicit sub_agent tool kind with a shared budget tree - not a new execution engine. The flow step kind agent_turn (§4.12) is the concrete form; the A2A facade (§4.13) is the cross-organisation boundary. Neither adds an execution engine.
  • Model routing per turn (cheap model for tool selection, strong model for synthesis) is expressible today as a per-prompt model_primary on different prompts; a first-class per-iteration routing policy is deferred until a tenant asks for it.
  • Token-level streaming on the agent path. The turn event is iteration-level because CompletionProvider::complete is buffered. Real token deltas need complete_stream() returning a chunk stream, wired for the final iteration only (tool-calling iterations still need the complete response to parse tool_calls). Deferred until the BFF SSE hop ships and a client needs the latency improvement; the iteration-level event is sufficient for progress and approvals.
  • MCP stdio transport for tenant servers is deliberately unsupported (§4.7): it is arbitrary process execution inside a platform service. If a tenant needs a local server, the shape is a platform-internal module, not a tenant registration.
  • A2A gRPC binding is not offered (§4.13). HTTP+JSON covers the capability; a second binding doubles the conformance surface without adding behaviour.
  • Memory consolidation across kinds (merging a preference into a fact, or superseding a contradicted memory) is deferred. The first version inserts and retrieves with similarity dedupe; a contradiction-resolution policy needs a real corpus to tune against.

Architecture & Design: sentin8:ai and its underlying concepts were designed by Hamid Jahanzad.