Skip to content

The agent's pipeline

How the engine analyses a problem, from the trigger and the context it builds to the provider call, the checked answer, the alert it releases and the prompt, with what is cached, what is limited and what only Sypnia Cloud adds.

Applies to Engine
View as Markdown
On this page
  1. The whole pipeline
  2. Triggers and debouncing
  3. Step 1: collect
  4. Step 2: redact, then fit
  5. Step 3: ask
  6. The provider abstraction
  7. The answer it must return
  8. Step 4: check
  9. Step 5: write, and release the alert
  10. Cost limits and what is cached
  11. The prompt
  12. Pull requests
  13. Weekly suggestions
  14. What changed from the system this comes from
  15. Next

The agent is the part of the engine that reads a problem and writes one sentence about it. This page is how it is built. What it reads and writes, from the reader’s side, is in How the analysis works.

Two facts frame everything here. The agent is off by default in the engine: with ai.provider set to none it makes no call and sends nothing anywhere. And it is mostly not a model: of the five steps, four are fixed rules written in Rust, and one is a single call to a model that has no tools.

The whole pipeline

Figure. One analysis. The model is one message of eleven; everything around it is the engine following fixed rules.
  1. The Fast path writes to Postgres in one transaction: the problem is born, its problem.new alert is held with release_by 100 seconds later, and a job is queued.
  2. The Fast path wakes the agent.
  3. The agent claims the job and reads the problem, its counts and its release.
  4. From the Bucket it takes the source maps of 4f2a91c, the session file and the trace’s segments.
  5. Collect, symbolicate, redact, fit to 24,000 characters. No model yet.
  6. One request to the AI provider: the instructions, and the context as JSON.
  7. The provider answers with JSON.
  8. The agent checks the answer against the context, fills the numbers and sets the confidence by rule.
  9. To Postgres: analysis = ready, the slug pay-button-does-nothing, usage plus one.
  10. The agent releases the alert, with the sentence.
  11. Alerts records it and sends the signed webhook.
Read this diagram as text

A sequence diagram with six lifelines, time going down: Fast path, Postgres, The agent, Bucket, AI provider (yours: off until you set a key) and Alerts. A clock on the left marks 0 s at message 1, 5 s at message 3, 60 s at message 10 and 100 s below. Messages 3 to 10 share one budget: 60 seconds, or what is left of the 100. Under the eleven messages, what happens if the model is slow: when release_by is reached, Postgres releases the alert to Alerts with the technical title; later the sentence arrives on the problem, with the webhook problem.analyzed.

Triggers and debouncing

A job is a row in the jobs table. The fast path inserts it in the same transaction that records the transition, so a problem cannot be born without its job, and a retry cannot create two. How a job is claimed, retried and given up is on What happens when something fails.

TriggerInserted byWhen
The problem is newThe fast pathThe Born transition
The problem came backThe fast pathThe CameBack transition
The problem growsThe fast pathThe Growing transition: twice the people of its last alert, and at least 5. Or its first occurrence in a release it had not been seen in: a ver missing from problems.releases, which the same transaction appends to
You askThe APIPOST /v1/problems/{problem}/analyze, with an admin token. It answers 409 while an analysis of the problem is running, and counts against the limits below
Skipped yesterdayThe first pass of the dayOpen problems whose status is limit_reached, those that hit the most people first

Before a job runs, four gates, in this order. Each one that closes writes its reason on the problem, so the absence of a sentence is never silent.

GateIf closedanalysis.status
A provider is configured and the project has the agent onNothing runs, nothing is sentoff
The problem is not ignoredThe job is droppedunchanged
The problem has fewer than 3 analyses today (ai.max_analyses_per_problem_per_day)The job is droppedunchanged; the last analysis stays
The project has fewer than 100 analyses today (ai.max_analyses_per_day). On Sypnia Cloud: the organization has analyses left this month, and on Free fewer than 10 todayThe job is kept until the count resetslimit_reached

Debouncing. A problem that explodes can grow three times in a minute. Three rules keep that to one call:

  • One job per problem. The jobs table has a unique index on the problem for jobs that are not finished. A second trigger while one is waiting or running does not insert; it sets a flag on the existing job.
  • Run again at most once. When a job finishes and its flag is set, it runs once more, with the newest counts, if the limits still allow.
  • No call for the same input. The redacted context is hashed. If the hash equals the one stored with the last analysis, the stored analysis is kept and no call is made. This is what makes «Analyse again» free when nothing changed.

Step 1: collect

The agent studies one occurrence: the latest one that has both a trace and a session. From it the engine builds exactly what GET /v1/problems/{problem}/context returns.

PartRead fromFixed size
The grouped failureproblems: kind, title, the sample occurrence—
The stack with source linessample.stack_original; the source lines come from the source map’s own sourcesContent8 frames of your code, 5 lines on each side
BreadcrumbsThe session file in the Bucket, events before the failure30
The traceThe segments named by traces.segments, the lines of that trace id40 spans, the failing ones and their parents first
The release and what changedreleases: when it was first seen, commits, changed files, diffs if you sent them10 files, 20,000 characters of diff
The impactproblems, problem_hits, problem_occurrences—

Symbolication runs here, before anything else, because the stack in your own files is the most useful part of the context. Problem grouping describes it.

If a part cannot be built, it is null and missing says why: source_maps_not_uploaded, no_session, no_trace, release_unknown. The agent works with what there is.

Step 2: redact, then fit

Redaction is a function from the full context to a smaller one. It is applied before the size budget, so nothing that must not leave can survive by being «important».

Removed or replacedBy
Person ids, names, e-mails, account ids and names«person 1», «person 2», in order of first appearance
Session ids, trace ids, span ids, device idsShort local labels («session A»); the engine puts the real ids back into the result
Labels of clicked list rows, table cells and free textTheir kind: «a row», «a cell»
Things that look like secrets in messages and paths: long tokens, keys, e-mail addresses, long numbersA marker of their kind
The project’s name and slugNothing
With ai.send_source set to false: source lines and diffsNothing. File names, lines and function names stay

Three things cannot be redacted because they are never there: what a person typed, anything inside a masked element, and replay content. The SDK does not collect the first two, and the agent never opens a replay chunk.

Then the context is fitted to about 24,000 characters.

Figure. When the context is too long, it loses its least useful end first. The failure, its impact and the stack are never cut.
  1. Failure and impact: always whole.
  2. Stack: 8 frames of 11 lines each.
  3. Trace: up to 40 spans. Spans that did not fail and are not parents of one that did go first.
  4. Release: commits and changed file names.
  5. Breadcrumbs: up to 30. The oldest go first.
  6. Diffs: up to 10 files. Diffs of files that are not in the stack go first.
Read this diagram as text

One bar of about 24,000 characters in six parts, in the order they are kept; their rough shares are 6, 22, 12, 8, 12 and 40 percent. Parts 1 and 2 are never cut. The cut starts at the right end: first part 6, then part 5, then part 3. What was cut is listed in the context, so the model knows.

Notice in the excerpt that redact returns a different type from the one it receives. Code that calls a provider can only be given a Redacted context, so sending an unredacted one does not compile.

crates/sypnia-agent/src/context.rs
pub async fn build_context(engine: &Engine, problem: &Problem) -> Result<AgentInput, AgentError> {
    // The latest occurrence that has both a trace and a session; else the latest.
    let occurrence = occurrences::pick(engine, problem).await?;

    // What GET /v1/problems/{problem}/context returns: stack, breadcrumbs, trace, release, impact.
    let mut full = ProblemContext::load(engine, problem, &occurrence).await?;
    if full.stack.as_ref().is_some_and(|s| !s.symbolicated) {
        symbolicate::apply(engine, &mut full).await.ok(); // never fails the analysis
    }

    // People become «person 1»; ids, names and e-mails go; secrets in text are cut.
    let mut redacted: Redacted<ProblemContext> = redact(full, &engine.config.ai);

    // Cut from the least useful end until it fits. Each cut is written down for the model.
    let mut cuts = Vec::new();
    while redacted.chars() > MAX_CONTEXT_CHARS {
        let Some(cut) = redacted.drop_least_useful() else { break };
        cuts.push(cut);
    }
    redacted.note_cuts(&cuts);

    let json = serde_json::to_string(&redacted)?;
    Ok(AgentInput {
        input_hash: sha256_hex(json.as_bytes()), // the same input twice is one call
        restore: redacted.restore_map(),         // «session A» → the real id, for the result
        facts: Facts::from(&redacted),           // what the answer will be checked against
        json,
    })
}

Step 3: ask

One request. The instructions are fixed text that ships with the engine; the context goes as JSON in the user message; the answer must be JSON of a fixed shape. The model has no tools: it cannot browse, run code or ask for more.

The provider abstraction

The engine knows a model only through one trait. Notice how small it is: text in, text out, and the token counts for the usage counters. Everything that knows about problems is on the engine’s side of it.

crates/sypnia-agent/src/provider.rs
/// The one thing the engine needs from a model. Implemented once per wire format.
#[async_trait]
pub trait AiProvider: Send + Sync {
    /// As configured: "openrouter", "openai", "anthropic", "google", "openai-compatible".
    fn name(&self) -> &str;

    async fn complete(&self, request: &CompletionRequest) -> Result<Completion, AiError>;
}

pub struct CompletionRequest {
    pub instructions: &'static str,   // fixed text, shipped with the engine
    pub input: String,                // the redacted context, as JSON
    pub schema: &'static JsonSchema,  // sent to providers that can enforce a JSON shape
    pub max_output_tokens: u32,       // `ai.max_output_tokens`, 2,000 by default
    pub timeout: Duration,            // `ai.timeout_seconds`, or less when an alert is due
}

pub struct Completion {
    pub text: String,
    pub model: String,       // as the provider names it; stored with the analysis
    pub tokens_in: u32,
    pub tokens_out: u32,
}

/// Built once at start. `None` is the default: the agent is off and nothing is ever sent.
pub fn from_config(ai: &AiConfig) -> Result<Option<Arc<dyn AiProvider>>, ConfigError> {
    Ok(match ai.provider {
        Provider::None => None,
        Provider::Anthropic => Some(Arc::new(AnthropicMessages::new(ai)?)),
        // OpenRouter, the OpenAI API, Google's OpenAI-compatible endpoint and any other
        // endpoint that speaks chat completions share one implementation and differ by base URL.
        Provider::OpenRouter | Provider::OpenAi | Provider::Google | Provider::OpenAiCompatible => {
            Some(Arc::new(ChatCompletions::new(ai)?))
        }
    })
}
ai.providerImplementationDefault base URL
none——
openrouterChatCompletionshttps://openrouter.ai/api/v1
openaiChatCompletionshttps://api.openai.com/v1
googleChatCompletionshttps://generativelanguage.googleapis.com/v1beta/openai
openai-compatibleChatCompletionsNone: ai.base_url is required
anthropicAnthropicMessageshttps://api.anthropic.com

Five ways to connect, two implementations. Adding a provider with a third wire format is one file that implements the trait. The settings and how to check each one are on Models and what is sent.

The Sypnia engine and Sypnia Cloud compared
Sypnia engineOpen source, self-hostedSypnia CloudPaid service, with a free tier
Which modelThe one you name in ai.model. The engine has no default model, on purpose.Chosen by Sypnia, reached through OpenRouter, and changed when a better one appears.
Whose keyYours. Until you set one, the agent is off.Sypnia's. Nothing to configure.
Where the context goesFrom your engine to your provider. Nothing goes to Sypnia.From Sypnia Cloud to the provider.

The answer it must return

what the model must return
{
  "sentence": "{people} tried to pay {when} and could not. The Pay button does nothing since {release_when}.",
  "who": "{people}. Two of them tried again and gave up.",
  "doing": "Paying for an order, at the last step of checkout.",
  "since": "{release_when}. It worked before.",
  "cause": {
    "text": "The release renamed the cart's total from cart.total to cart.totalCents. The checkout still reads cart.total, so the payment goes out without an amount and the API answers 400.",
    "blames": "src/checkout/checkout.tsx:142",
    "evidence": [
      { "kind": "release_change", "ref": "release:src/cart/cart.ts", "text": "The release renames `total` to `totalCents` in the Cart type." },
      { "kind": "stack_frame", "ref": "src/checkout/checkout.tsx:142", "text": "confirmPayment() still passes `cart.total` to createPayment()." },
      { "kind": "trace", "ref": "trace A", "text": "POST /api/checkout answered 400 with the code `amount_required`." }
    ]
  },
  "what_to_do": "Read cart.totalCents in confirmPayment(), and show the customer a message when a payment is rejected."
}

Three things about this shape are deliberate.

  • No numbers of its own. The model writes {people}, {sessions}, {occurrences}, {when} and {release_when}; the engine fills them from its counts. «3 people» is never a model’s arithmetic.
  • No confidence. The model is not asked how sure it is. Confidence is set by rule in the next step.
  • cause may be null. The instructions say that naming no cause is a correct answer when the facts do not support one.

Step 4: check

The answer is parsed strictly, then checked against the Facts kept in step 2. Notice that the function below never repairs an answer. It accepts it, or says exactly what is wrong.

crates/sypnia-agent/src/check.rs
pub fn check(answer: &ModelAnswer, facts: &Facts) -> Result<Checked, Vec<Rejection>> {
    let mut rejections = Vec::new();

    if let Some(cause) = &answer.cause {
        // The place it blames must be a frame of the stack or a file the release changed.
        if !facts.has_frame(&cause.blames) && !facts.release_changed(&cause.blames) {
            rejections.push(Rejection::BlamesUnknownPlace(cause.blames.clone()));
        }
        // One to six pieces of evidence, each pointing at something that is in the context.
        if !(1..=6).contains(&cause.evidence.len()) {
            rejections.push(Rejection::EvidenceCount(cause.evidence.len()));
        }
        for item in &cause.evidence {
            if !facts.has_ref(item.kind, &item.reference) {
                rejections.push(Rejection::EvidenceNotInContext(item.reference.clone()));
            }
        }
    }
    // A count written as a digit instead of a placeholder is a count the engine cannot vouch for.
    for field in [&answer.sentence, &answer.who, &answer.since] {
        if states_a_count(field) {
            rejections.push(Rejection::LiteralCount);
        }
    }

    if !rejections.is_empty() {
        return Err(rejections);
    }
    Ok(Checked {
        confidence: answer.cause.as_ref().map(|cause| confidence_by_rule(cause, facts)),
        answer: answer.clone(),
    })
}
OutcomeWhat the engine doesanalysis.status
The answer passesFills the placeholders, puts the real ids back, sets the confidenceready
The answer passes and cause is nullKeeps the sentence, who, doing and since; lists what was missingnot_enough_evidence
The answer fails a checkAsks once more, with the rejections added to the request—
It fails againDrops the cause, keeps what passednot_enough_evidence
The call fails or times outTries again, twice more, with a short wait—
Three failed callsStops. It is tried again when the problem growsfailed

A wrong cause stated with confidence costs more than no cause. That is why the unhappy paths end in «not enough evidence» and never in a guess.

Confidence by rule:

LevelRule
highAt least two kinds of evidence agree, and one of them is a change in the release that touches the code where it fails
mediumThe cause rests on the stack or the trace alone, with source lines
lowThe cause fits the facts and nothing confirms it: a minified stack, or no release information

Step 5: write, and release the alert

One transaction:

  1. problems.analysis gets the analysis as the API returns it, with the provider, the model, the time and the run number.
  2. On the first analysis, the problem gets its readable slug, made from the sentence. The old slug keeps working.
  3. analyses gets one row: the input hash, the token counts, the outcome. Not the context and not the answer.
  4. usage_daily.analyses goes up by one.

Then two things leave the engine: the problem.analyzed webhook, and the alert.

The alert hand-off. The alert was written by the fast path with released_at empty and release_by set to 100 seconds after the failure reached ingest. Whoever gets there first releases it:

WhoWhenThe alert’s title
The agentThe analysis is ready or not_enough_evidence before release_byThe sentence
The agentThe model has not answered at release_by: the agent stops waiting, releases, and keeps the call runningThe technical title
The fast pathThe agent is off, or a gate closedThe technical title, at once
The passSafety net: any alert past release_by that nobody releasedThe technical title

Releasing is one UPDATE … WHERE released_at IS NULL, so two of them racing release it once.

Cost limits and what is cached

WhatRule
Calls a day, per project100 by default (ai.max_analyses_per_day); 0 is no limit. A usage.limit alert at 80 % and at 100 %. Cloud On Sypnia Cloud the plan’s analyses a month for the whole organization replace it, and the Free plan also has 10 a day: Plans and limits
Calls a day, per problem3 (ai.max_analyses_per_problem_per_day)
InputAbout 24,000 characters, a few thousand tokens
Output2,000 tokens (ai.max_output_tokens)
Calls per analysis1 normally; 2 when the first answer fails the check; never more than 3 including failed calls
Same inputNo call: the input_hash matches the last analysis
Source mapsParsed maps are cached in memory: 50 maps or 200 MB
The contextNot stored. It is rebuilt when asked for, from the Bucket and Postgres

The engine records tokens, not money: it does not know your provider’s prices. The arithmetic is yours: one analysis is a few thousand tokens in and at most two thousand out, and a project makes at most 100 a day. Set a spending limit on the key at your provider as well; the engine’s limit counts calls, not what they cost.

The prompt

The prompt for a coding agent is not written by a model. It is a fixed template filled from the analysis and the context, which is why it always has the same shape and exists even when the agent is off.

PartLinesFilled from
The briefWhat happens, Where, Why, Do, CheckThe analysis and the engine’s counts. Without an analysis, Why and Do are left out and the evidence speaks
EvidenceStack, Before the failure, Trace, ReleaseThe same context the agent had, before redaction: it is your data, going to your own agent
RulesA short listFixed text: smallest change, add a test, do not merge, how to mark the problem resolved

It is built when it is asked for, by GET /v1/problems/{problem}/prompt and by the MCP tool problem_prompt, never stored, and cut to 12,000 characters with the same order as the context. The full template is on The prompt.

Pull requests Cloud

The engine stops at the prompt. It has no code that reads a repository, and none that writes to one.

On Sypnia Cloud, the private part listens for the same problem.analyzed event your webhook gets. Pull requests are a project setting, settings.agent.pull_requests, off by default and not part of the Free plan. When a project has turned it on, has the Sypnia GitHub App installed, and someone asks for a fix, or the project set auto_pull_requests to high_confidence, a separate worker:

  1. reads the files the analysis blames, through the GitHub App, with the permissions listed on The GitHub App;
  2. writes the change and a test on a branch sypnia/<problem slug>;
  3. opens a pull request that carries the sentence, the cause and its evidence;
  4. stops. A person reviews and merges.

Its state is the pull_request object on the problem: queued, writing, open, merged, closed or failed. On a self-hosted engine that field is always null, and the way to a fix is the prompt or the MCP server with your own coding agent.

Weekly suggestions

The same provider and the same pattern serve one more job: on Monday at 07:00 UTC, fixed rules over the week’s numbers find pages and routes worth improving, and one model call per page with findings puts them into plain words. It sends counts, routes, selectors and stable labels, never people or sessions. With no provider, the rules still run. ai.weekly_suggestions set to false keeps the rules and makes no call.

What changed from the system this comes from

ThereHereWhy
A weekly job that analysed modules and wrote findingsThe same idea kept as weekly suggestions; and a new per-problem analysis within the 2 minutesThe product’s promise is a sentence about a problem, when it happens
One provider, written into the jobA trait, five ways to connect, off by defaultBrief §5b: the AI provider is a piece you choose
A cost cap per run in moneyLimits in calls per day and characters per callThe engine cannot know every provider’s prices
Findings in one fixed languageThe language of the project (ai.language)Any team

Next

  1. The whole pipeline
  2. Triggers and debouncing
  3. Step 1: collect
  4. Step 2: redact, then fit
  5. Step 3: ask
  6. The provider abstraction
  7. The answer it must return
  8. Step 4: check
  9. Step 5: write, and release the alert
  10. Cost limits and what is cached
  11. The prompt
  12. Pull requests
  13. Weekly suggestions
  14. What changed from the system this comes from
  15. Next

    Search pages, sections and terms