diff --git a/docs/authors.json b/docs/authors.json
index 01f374a8a0..c65662ff44 100644
--- a/docs/authors.json
+++ b/docs/authors.json
@@ -89,5 +89,12 @@
"url": null,
"image_url": "https://ravendb.net/wp-content/uploads/2024/11/Default-author-thumbnail-150x150.png",
"socials": { "linkedin": "https://www.linkedin.com/in/mateusz-ziemiewicz-2883211b3/" }
+ },
+ "Federico Lois": {
+ "name": "Federico Lois",
+ "job_title": "Senior Performance Engineer",
+ "url": null,
+ "image_url": "https://ravendb.net/wp-content/uploads/2024/11/Default-author-thumbnail-150x150.png",
+ "socials": {}
}
}
diff --git a/guides/assets/gated-consensus-1.webp b/guides/assets/gated-consensus-1.webp
new file mode 100644
index 0000000000..c2b9017116
Binary files /dev/null and b/guides/assets/gated-consensus-1.webp differ
diff --git a/guides/assets/gated-consensus-2.webp b/guides/assets/gated-consensus-2.webp
new file mode 100644
index 0000000000..506f47463b
Binary files /dev/null and b/guides/assets/gated-consensus-2.webp differ
diff --git a/guides/assets/gated-consensus-3.webp b/guides/assets/gated-consensus-3.webp
new file mode 100644
index 0000000000..d3feb46300
Binary files /dev/null and b/guides/assets/gated-consensus-3.webp differ
diff --git a/guides/handling-model-uncertainty-with-gated-consensus.mdx b/guides/handling-model-uncertainty-with-gated-consensus.mdx
new file mode 100644
index 0000000000..cde625a5f5
--- /dev/null
+++ b/guides/handling-model-uncertainty-with-gated-consensus.mdx
@@ -0,0 +1,734 @@
+---
+title: "Gated Consensus: Handling Model Uncertainty with RavenDB AI Capabilities"
+tags: [ai, architecture, deep-dive, use-case]
+icon: "genai"
+description: "A model's answer carries no sign of whether to trust it. Gated consensus measures agreement between independent GenAI tasks and lets an index decide how much human attention each case gets, built step by step on the Claims Desk sample."
+published_at: 2026-12-03
+see_also:
+ - title: "GenAI Integration Overview"
+ link: "ai-integration/gen-ai-integration/overview"
+ source: "docs"
+ path: "AI Integration > GenAI Integration"
+ - title: "Process Attachments: API"
+ link: "ai-integration/gen-ai-integration/process-attachments/processing-attachments_api"
+ source: "docs"
+ path: "AI Integration > GenAI Integration"
+ - title: "Embeddings Generation Task"
+ link: "ai-integration/generating-embeddings/embeddings-generation-task"
+ source: "docs"
+ path: "AI Integration > Generating Embeddings"
+ - title: "Indexing Related Documents"
+ link: "indexes/indexing-related-documents"
+ source: "docs"
+ path: "Indexes"
+author: "Federico Lois"
+proficiency_level: "Expert"
+---
+
+import Admonition from '@theme/Admonition';
+import Image from "@theme/IdealImage";
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+Ask a model to sort a support ticket, read the total off an invoice, rate the risk in a contract clause or grade the damage in a photo, and it answers. It answers the same way whether the case is easy or beyond what it can judge: well-formed output, a value from the allowed set, a reason that sounds sure of itself. What the answer doesn't carry is any sign of whether it's one to trust.
+
+That's the hard part of putting a model's output in front of a business decision. The output always looks finished. Asking the model how confident it is returns a number, but that number comes from the same call that may be wrong, so it fails in exactly the cases it's meant to catch. It's worse than that: ask the same question twice and the answer can change, with each version just as sure as the other. A single call is one draw from the answers the model might give, and nothing in it shows how far the next draw could land. Having a person redo every answer is safe, and it gives up most of the reason for using a model in the first place.
+
+Gated consensus measures uncertainty instead of asking for it. Several independent assessments of the same input either agree or they don't, and disagreement is a signal that no single answer carries. A gate, a plain rule that runs outside the model, then looks at that agreement and at what's at stake, and decides how much human attention each case gets.
+
+This guide builds the pattern inside RavenDB 7.2, following the [Claims Desk sample](https://github.com/ravendb/samples-auto-tagger): a motor insurer's desk where a customer reports damage with one photo. Every model call runs in a GenAI task, the gate is a static index, and the backend only saves documents and runs queries. The insurance domain is incidental. What matters is how the features interlock, and why each piece sits where it does.
+
+
+
+- The [samples-auto-tagger repository](https://github.com/ravendb/samples-auto-tagger), with its C#, Python and Node.js backends. The GenAI scripts and queries in this guide are the same in all three, and code that differs comes with a tab per backend.
+- A RavenDB license. GenAI tasks need one, and a free [developer license](https://ravendb.net/license/request/dev) works.
+- A chat model that accepts images. The sample defaults to OpenAI `gpt-4o-mini`. The observations in this guide come from our runs with Qwen3-VL-30B-A3B served locally.
+
+
+
+## The pipeline at a glance
+
+A claim is one document in the Claims collection, with the photo as its attachment. Everything that happens to it is a write to that document:
+
+1. The backend saves the claim and its photo in one batch.
+2. Three assessor tasks each look at the photo and write `Assessments.`: a severity and the damaged parts.
+3. The judge task waits for all three, looks at the photo and their answers, and writes `Decision`, including how many assessors back its severity.
+4. The ruling search task looks for the adjuster ruling closest to the damage and writes its id to `Candidate`.
+5. The ruling check task decides whether that ruling's condition holds on the photo and writes `Check`.
+6. The `Claims/Desk` index reads `Decision`, `Check`, `Review` and the routing rules, and gives the claim a status: Assessing, FastTracked, CloserLook or Dispatched.
+7. An adjuster verifies the claim, revising it or not, and dispatches it. The review can save a new ruling.
+
+
+
+Nothing in that list calls anything else. Steps 2 to 5 are GenAI tasks that RavenDB runs whenever the claim changes, step 6 is an index that RavenDB keeps up to date, and the backend's part ends at step 1 until an adjuster acts.
+
+Two terms carry the rest of the guide. Consensus is what the assessors and the judge produce together: an answer plus the number of independent assessments behind it. The gate is what the index does with that number.
+
+One thing the gate doesn't decide is whether a person looks at the claim. On this desk an adjuster verifies every claim. The gate decides how much of the adjuster's attention a claim needs: a fast-tracked claim can be verified at a glance, and any other claim comes with the reason it needs a closer look.
+
+
+
+## Consensus: three assessors, three trades
+
+### Independent enough to disagree
+
+Asking one model the same question three times does show some spread, but all three answers share one framing, so a mistake that framing invites tends to come back in every one. The three assessors in Claims Desk look at the photo from three trades instead, each with its own prompt. Each prompt ends with the same rules about part names and the severity scale:
+
+
+
+
+```csharp
+public static readonly Dictionary Assessors = new()
+{
+ ["adjuster"] = $"You are a motor claims adjuster. A customer sent this photo with a claim. Which parts of the vehicle are damaged, and how serious is it?\n{Rules}",
+ ["estimator"] = $"You are a body shop estimator. Which parts of this vehicle would you have to repair or replace, and how big is the job?\n{Rules}",
+ ["inspector"] = $"You inspect vehicles after accidents. Is this car still safe to drive? Name each damaged part and judge how serious the damage is.\n{Rules}",
+};
+```
+
+
+
+
+```python
+ASSESSORS = {
+ "adjuster": "You are a motor claims adjuster. A customer sent this photo with a claim. Which parts of the vehicle are damaged, and how serious is it?\n" + RULES,
+ "estimator": "You are a body shop estimator. Which parts of this vehicle would you have to repair or replace, and how big is the job?\n" + RULES,
+ "inspector": "You inspect vehicles after accidents. Is this car still safe to drive? Name each damaged part and judge how serious the damage is.\n" + RULES,
+}
+```
+
+
+
+
+```typescript
+const ASSESSORS = {
+ adjuster: `You are a motor claims adjuster. A customer sent this photo with a claim. Which parts of the vehicle are damaged, and how serious is it?\n${RULES}`,
+ estimator: `You are a body shop estimator. Which parts of this vehicle would you have to repair or replace, and how big is the job?\n${RULES}`,
+ inspector: `You inspect vehicles after accidents. Is this car still safe to drive? Name each damaged part and judge how serious the damage is.\n${RULES}`,
+};
+```
+
+
+
+
+Each question pulls a different reading out of the same pixels: the adjuster thinks about the claim, the estimator about the repair, the inspector about safety. When the photo is clear, they land on the same severity. When it's ambiguous, they drift apart, and that drift is the signal.
+
+They may still run on one model, and then some of their mistakes match. Each assessor has its own connection string, named after its task (`assessor-adjuster-model` and so on), so one of them can move to another model or provider in Studio without touching the others. Agreement across different models is a stronger signal than agreement across three prompts on one model. The sample leaves that choice to configuration.
+
+### The photo and nothing else
+
+An assessor's context script builds what the model sees. In Claims Desk, that's the photo alone:
+
+```javascript
+// An assessor sees the photo of the claim and nothing else.
+withPhoto(this, ai.genContext({ Task: 'Assess the damage in the attached photo.' }));
+
+// Adds the photo of the claim to what the model sees, in the photo's own image format.
+function withPhoto(claim, context) {
+ const photo = claim['@metadata']['@attachments'][0];
+ const image = loadAttachment(photo.Name);
+ return photo.ContentType === 'image/png' ? context.withPng(image) : context.withJpeg(image);
+}
+```
+
+`ai.genContext` creates the context object that the model receives, `loadAttachment` reads the photo stored with the claim, and `withJpeg` or `withPng` sends it to the model as an image. [Processing attachments in GenAI tasks](https://docs.ravendb.net/ai-integration/gen-ai-integration/process-attachments/processing-attachments_api) covers these methods in full. The backend stores the claim and its photo in the same session, so no assessor ever runs on a claim without its photo.
+
+What's left out matters as much. The claim also holds the customer's statement ("Our delivery van hit a concrete barrier while parking at the depot"), and no context script reads it. Given the statement, all three assessors would anchor on the same story, and their agreement would measure the statement rather than the damage. Keeping every model on the pixels is what keeps the votes independent.
+
+### Names that can be counted
+
+Votes only work when every assessor names a part the same way. The prompt gives the list of allowed names, and the update script, which RavenDB runs on the model's answer, holds the answer to that list. Here's the adjuster's:
+
+```javascript
+// Writes the answer under Assessments.adjuster, keeping only what the desk knows:
+// a part from the list, each part once, and a severity from the scale.
+const PARTS = ["front bumper", "rear bumper", "hood", "trunk", "roof", "windshield", "side window", "rear window", "door", "fender", "headlight", "taillight", "grille", "side mirror", "wheel"];
+const SEVERITIES = ["minor", "moderate", "severe"];
+
+const parts = [];
+for (const { Part, Reason } of $output.Parts) {
+ const part = clean(Part);
+ if (PARTS.includes(part) && parts.every(p => p.Part !== part))
+ parts.push({ Part: part, Reason });
+}
+const severity = clean($output.Severity);
+
+this.Assessments = this.Assessments || {};
+this.Assessments.adjuster = {
+ Severity: SEVERITIES.includes(severity) ? severity : null,
+ SeverityReason: $output.SeverityReason,
+ Parts: parts,
+ At: new Date().toISOString()
+};
+
+function clean(text) {
+ return String(text).toLowerCase().trim();
+}
+```
+
+`$output` is the model's answer, shaped like the sample object that the task defines, and `this` is the claim. Whatever the script writes is saved as an ordinary change to the document. A part name outside the list is dropped, a repeated part is kept once, and an unknown severity is stored as `null`, which never counts as a vote later.
+
+The list holds only outside parts. A photo of the outside can't show the cabin, and in our runs a model asked about inside parts named ones it couldn't see.
+
+## The judge: a model weighs, a script counts
+
+### Waiting for three answers
+
+The judge's context script starts by checking that every assessor has answered:
+
+```javascript
+// The judge waits for every assessor. A script that creates no context skips the claim,
+// and RavenDB runs it again when the claim changes.
+const assessors = ["adjuster", "estimator", "inspector"];
+const assessments = this.Assessments || {};
+if (assessors.some(name => !assessments[name]))
+ return;
+
+// The judge sees the photo and what each assessor wrote. It never sees an adjuster's ruling.
+withPhoto(this, ai.genContext({
+ Assessments: assessors.map(name => {
+ const { Severity, SeverityReason, Parts } = assessments[name];
+ return { Assessor: name, Severity, SeverityReason, Parts };
+ })
+}));
+```
+
+A context script that returns without calling `ai.genContext` produces nothing to send, so the task skips the claim. Each assessor's write is a new change to the claim, the judge's script runs again on it, and the third write is the one that gets through. There's no barrier, counter or callback: the judge waits by finding its inputs missing.
+
+### Rules in the script, not the prompt
+
+The judge model looks at the photo and the three assessments, picks a severity, and gives a keep-or-drop verdict for each part an assessor proposed. Its update script then decides what that answer is allowed to change:
+
+```javascript
+const SEVERITIES = ["minor", "moderate", "severe"];
+const assessments = Object.values(this.Assessments);
+
+// How many assessors named each part.
+const votes = {};
+for (const { Parts } of assessments)
+ for (const { Part } of Parts)
+ votes[Part] = (votes[Part] || 0) + 1;
+
+// One verdict for every part an assessor named. A part that only the judge named is ignored.
+const parts = Object.keys(votes).map(part => {
+ const verdict = $output.Parts.find(p => clean(p.Part) === part);
+ const majority = votes[part] * 2 > assessments.length;
+ // ... builds the reason shown for the part
+ return {
+ Part: part,
+ Keep: majority && verdict !== undefined && verdict.Keep === true,
+ Reason: reason,
+ Votes: votes[part]
+ };
+});
+
+// An unknown severity counts as none. The votes are the assessors that gave the judge's severity.
+const answer = clean($output.Severity);
+const severity = SEVERITIES.includes(answer) ? answer : null;
+const severityVotes = severity ? assessments.filter(a => a.Severity === severity).length : 0;
+
+this.Decision = {
+ Severity: severity,
+ SeverityReason: $output.SeverityReason,
+ SeverityVotes: severityVotes,
+ Parts: parts,
+ At: new Date().toISOString()
+};
+```
+
+This split is the core of the pattern. The model does what only a model can do: look at the photo and weigh three sets of reasons. The script does what a model can't be relied on to do every time: count. A rule in a prompt is a request, while the same rule in an update script holds on every claim, whatever the model answered. The judge can't add a part that no assessor proposed, and it can't keep a part that only one assessor named, however good its reason sounds.
+
+`SeverityVotes` is the uncertainty measure that the gate uses. It's the number of assessors that gave the severity the judge chose: 3 when everyone agreed, 2 when the judge sided with the majority, 1 when it sided with a lone assessor, and 0 when it picked a severity nobody proposed. The judge is free to overrule the assessors, and the vote count records that it did.
+
+The script also appends the decision to a `History` array on the claim. The review step uses that array later.
+
+## The gate: an index decides the route
+
+### Why an index
+
+The gate could be an `if` in the backend. In Claims Desk it's the `Claims/Desk` static index, and that one choice settles three things:
+
+- The rule runs on the server, next to the data, with no model involved: the same claim under the same rules always gets the same route.
+- RavenDB re-indexes a claim every time it changes, so a claim moves from Assessing to its route as soon as the last task writes, with no code watching for that moment.
+- The routing rules are a document that the index loads, so changing them re-routes every claim.
+
+Here's the map, with its comments shortened. The C# and Python backends write it in LINQ and the Node.js backend in JavaScript, and the server runs it in every case:
+
+
+
+
+```csharp
+Map = claims =>
+ from claim in claims
+ let routing = LoadDocument("settings/routing")
+ let assessed = claim.Decision != null && claim.Check != null
+ // The ruling that the check applied to this claim, if any.
+ let ruling = claim.Check != null && claim.Check.Applies ? claim.Check.Ruling : null
+ // The proposed severity: the applied ruling's, else the judge's.
+ let proposed = ruling != null ? claim.Check.Severity : claim.Decision != null ? claim.Decision.Severity : null
+ let rank = proposed == "minor" ? 1 : proposed == "moderate" ? 2 : 3
+ // The highest severity that is still fast tracked.
+ let limit = routing.FastTrackUpTo == "minor" ? 1 : 2
+ let reason = assessed == false ? null
+ : ruling == null && claim.Decision.SeverityVotes < routing.MinAgreement ? "Assessors disagree"
+ : rank > limit ? (proposed == "severe" ? "Possible total loss" : "Above the fast-track limit")
+ : null
+ let status = claim.Review != null ? "Dispatched" : assessed == false ? "Assessing" : reason != null ? "CloserLook" : "FastTracked"
+ select new
+ {
+ claim.Holder,
+ claim.Vehicle,
+ claim.Reported,
+ Status = status,
+ Reason = reason,
+ Severity = claim.Review != null ? claim.Review.Severity : proposed,
+ Ruling = ruling,
+ Checked = claim.Check != null ? claim.Check.Ruling : null,
+ Rank = status == "CloserLook" ? 0 : 1,
+ };
+```
+
+
+
+
+```python
+self.map = "\n".join([
+ 'from claim in docs.Claims',
+ 'let routing = LoadDocument("settings/routing", "Settings")',
+ 'let assessed = claim.Decision != null && claim.Check != null',
+ # The ruling that the check applied to this claim, if any.
+ 'let ruling = claim.Check != null && claim.Check.Applies == true ? claim.Check.Ruling : null',
+ # The proposed severity: the applied ruling's, else the judge's.
+ 'let proposed = ruling != null ? claim.Check.Severity : claim.Decision != null ? claim.Decision.Severity : null',
+ 'let rank = proposed == "minor" ? 1 : proposed == "moderate" ? 2 : 3',
+ # The highest severity that is still fast tracked.
+ 'let limit = routing.FastTrackUpTo == "minor" ? 1 : 2',
+ 'let reason = assessed == false ? null',
+ ' : ruling == null && (int)claim.Decision.SeverityVotes < (int)routing.MinAgreement ? "Assessors disagree"',
+ ' : rank > limit ? (proposed == "severe" ? "Possible total loss" : "Above the fast-track limit")',
+ ' : null',
+ 'let status = claim.Review != null ? "Dispatched" : assessed == false ? "Assessing" : reason != null ? "CloserLook" : "FastTracked"',
+ 'select new',
+ '{',
+ ' claim.Holder,',
+ ' claim.Vehicle,',
+ ' claim.Reported,',
+ ' Status = status,',
+ ' Reason = reason,',
+ ' Severity = claim.Review != null ? claim.Review.Severity : proposed,',
+ ' Ruling = ruling,',
+ ' Checked = claim.Check != null ? claim.Check.Ruling : null,',
+ ' Rank = status == "CloserLook" ? 0 : 1',
+ '}',
+])
+```
+
+
+
+
+```typescript
+this.map("Claims", (claim) => {
+ const decision = claim.Decision;
+ const check = claim.Check;
+ const review = claim.Review;
+ const routing = load("settings/routing", "Settings");
+ const assessed = decision != null && check != null;
+
+ // The ruling that the check applied to this claim, if any, and the proposed severity: that ruling's, else the judge's.
+ let ruling = null;
+ let proposed = decision != null ? decision.Severity : null;
+ if (check != null && check.Applies && check.Ruling != null) {
+ ruling = check.Ruling;
+ proposed = check.Severity;
+ }
+ const rank = proposed === "minor" ? 1 : proposed === "moderate" ? 2 : 3;
+ // The highest severity that is still fast tracked.
+ const limit = routing.FastTrackUpTo === "minor" ? 1 : 2;
+
+ let reason = null;
+ if (assessed) {
+ if (ruling == null && decision.SeverityVotes < routing.MinAgreement) reason = "Assessors disagree";
+ else if (rank > limit) reason = proposed === "severe" ? "Possible total loss" : "Above the fast-track limit";
+ }
+ const status = review != null ? "Dispatched" : !assessed ? "Assessing" : reason != null ? "CloserLook" : "FastTracked";
+
+ return {
+ Holder: claim.Holder,
+ Vehicle: claim.Vehicle,
+ Reported: claim.Reported,
+ Status: status,
+ Reason: reason,
+ Severity: review != null ? review.Severity : proposed,
+ Ruling: ruling,
+ Checked: check != null ? check.Ruling : null,
+ Rank: status === "CloserLook" ? 0 : 1,
+ };
+});
+```
+
+
+
+
+Read top to bottom, it's the whole routing policy:
+
+- A claim is Assessing until both the judge's `Decision` and the ruling check's `Check` exist.
+- With no ruling applied, fewer than `MinAgreement` votes behind the judge's severity sends the claim for a closer look, with the reason "Assessors disagree". The default is 2 of 3.
+- A proposal above `FastTrackUpTo`, by default `moderate`, also needs a closer look. `limit` never goes above 2, so a severe proposal is never fast tracked, whatever the agreement: "Possible total loss".
+- Everything else is FastTracked, and a reviewed claim is Dispatched.
+
+Both halves of the gate are there: agreement, in `MinAgreement`, and stakes, in `FastTrackUpTo` and the fixed rule for severe proposals. Agreement can lower the attention a claim needs, but never for a possible total loss. The reason comes from the proposal and not from the review, so a dispatched claim keeps the reason it was routed for.
+
+### Rules as a document
+
+`LoadDocument` makes `settings/routing` a related document of every claim. When it changes, RavenDB re-indexes the claims that load it, so raising `MinAgreement` to 3 in Studio moves every split claim off the fast track, with no deploy and no migration. The sample's settings endpoint writes the same document. The mechanism is described in [indexing related documents](https://docs.ravendb.net/indexes/indexing-related-documents).
+
+The cost comes with it: every claim loads that one document, so every change to it re-indexes every claim. For rules that change a few times a day, that's nothing. Rules that change often, or differ per customer segment, would need one document per segment, so a change touches only the claims that load it.
+
+### The desk is one query
+
+The index stores `Status`, `Reason`, `Severity`, `Ruling` and `Checked` and indexes them as exact values, so the desk reads the computed route straight from the index:
+
+```sql
+from index 'Claims/Desk'
+where Status = $status
+order by Rank, Reported desc
+select id() as Id, Holder, Vehicle, Reported, Status, Reason, Severity, Ruling
+```
+
+The counts at the top of the desk come from a [faceted search](https://docs.ravendb.net/indexes/querying/faceted-search) over `Status` and `Severity` on the same index. Exact indexing keeps the facet values as written: `FastTracked`, not `fasttracked`. None of the backends has routing code. They query the index.
+
+## Rulings: when the adjuster disagrees
+
+### Knowledge that would otherwise vanish
+
+An adjuster who revises a proposal knows something the models don't. If that knowledge stays inside one review, the next photo like it gets the same wrong proposal. So the review form takes an optional condition: a sentence describing where the damage is, such as "All the damage is at the front of the car." Saved with the review, the condition and the adjuster's severity become a document in the Rulings collection.
+
+From then on, a claim whose photo matches the condition gets the adjuster's severity as its proposal. Matching takes three pieces: an embeddings task, a search task and a check task.
+
+The embeddings task is the simple one. An [embeddings generation task](https://docs.ravendb.net/ai-integration/generating-embeddings/embeddings-generation-task) turns the `Condition` of each ruling into a vector, using the [embedding model built into RavenDB](https://docs.ravendb.net/ai-integration/connection-strings/embedded), so there's no embedding service to call. The task embeds each new ruling shortly after it's saved.
+
+### Search and check are separate tasks
+
+Two constraints shape the rest. A GenAI task can run a query, but only as part of a model call. And everything in a task's context reaches the model as text. If one task both searched with the assessors' answers and judged the ruling, the model judging the ruling would also read what the assessors said. So the work is split:
+
+- The ruling search sees the assessments, because it needs them to search, and its model does nothing but copy the id of the ruling that the search found.
+- The ruling check sees the photo and that ruling's condition, and nothing the assessors wrote.
+
+The search context waits for the three assessments, the same way the judge does, then turns them into a sentence:
+
+```javascript
+// Describes the damage in words: every part and every severity that an assessor reported.
+const reports = assessors.map(name => assessments[name]);
+const parts = new Set(reports.flatMap(report => report.Parts.map(p => p.Part)));
+const severities = new Set(reports.map(report => report.Severity).filter(Boolean));
+const query = 'Damaged: ' + [...parts].sort().join(', ') + '. Rated ' + [...severities].sort().join(' or ') + '.';
+
+// The query tool runs its vector search with this query before the model answers.
+// Recheck is part of the context, so raising it makes RavenDB search again.
+ai.genContext({ Recheck: this.Recheck || 0, query });
+```
+
+The task's query tool runs a vector search with that sentence:
+
+```sql
+from 'Rulings'
+where vector.search(embedding.text(Condition, ai.task('ruling-embeddings')), $query)
+select id() as Id, Condition
+limit 1
+```
+
+Setup registers the tool on the task with two options, through a small helper in each backend:
+
+
+
+
+```csharp
+var search = GenAiTask("ruling-search", Tasks.SearchPrompt, Tasks.SearchShape, Tasks.SearchContext, Tasks.SearchUpdate);
+search.Queries = [InitialQuery("find_ruling", "Finds the adjuster ruling closest to the damage that the assessors reported.", Tasks.SearchQuery)];
+
+static AiAgentToolQuery InitialQuery(string name, string description, string query) => new()
+{
+ Name = name,
+ Description = description,
+ Query = query,
+ ParametersSampleObject = "{}",
+ Options = new AiAgentToolQueryOptions { AllowModelQueries = false, AddToInitialContext = true },
+};
+```
+
+
+
+
+```python
+find = initial_query("find_ruling", "Finds the adjuster ruling closest to the damage that the assessors reported.", tasks.SEARCH_QUERY)
+search = gen_ai_task("ruling-search", tasks.SEARCH_PROMPT, tasks.SEARCH_SHAPE, tasks.SEARCH_CONTEXT, tasks.SEARCH_UPDATE, [find])
+
+def initial_query(name, description, query):
+ options = AiAgentToolQueryOptions(allow_model_queries=False, add_to_initial_context=True)
+ return AiAgentToolQuery(name=name, description=description, query=query, parameters_sample_object="{}", options=options)
+```
+
+
+
+
+```typescript
+const search = genAiTask("ruling-search", tasks.SEARCH_PROMPT, tasks.SEARCH_SHAPE, tasks.SEARCH_CONTEXT, tasks.SEARCH_UPDATE);
+search.queries = [initialQuery("find_ruling", "Finds the adjuster ruling closest to the damage that the assessors reported.", tasks.SEARCH_QUERY)];
+
+function initialQuery(name: string, description: string, query: string) {
+ return { name, description, query, parametersSampleObject: "{}", options: { allowModelQueries: false, addToInitialContext: true } };
+}
+```
+
+
+
+
+With `AllowModelQueries` off, the model can't call the query on its own. With `AddToInitialContext` on, RavenDB runs the query before the model answers and puts the result at the start of the conversation. The query's parameters come from the context's fields, so `$query` is the sentence built above.
+
+The search's update script takes the id the model copied, and checks it:
+
+```javascript
+// The model copied the id of the closest ruling, or left it empty.
+const ruling = $output.Id ? load($output.Id) : null;
+if (ruling !== null && ruling['@metadata']['@collection'] === 'Rulings') {
+ // The ruling check takes the candidate from here.
+ this.Candidate = $output.Id;
+} else {
+ // With no ruling to check, the check is settled at once.
+ this.Candidate = null;
+ this.Check = { Ruling: null, Applies: false, At: new Date().toISOString() };
+}
+```
+
+The model's answer counts only as far as `load` confirms it: an id the model made up, or one from another collection, counts as no ruling. With no ruling, the script settles `Check` right away, which is what lets the index stop showing the claim as Assessing.
+
+### The blind check
+
+The check task's context holds the photo and the candidate's id:
+
+```javascript
+// The ruling check runs only for a claim that the ruling search gave a candidate.
+if (!this.Candidate)
+ return;
+
+withPhoto(this, ai.genContext({ Ruling: this.Candidate }));
+```
+
+Its query tool, registered with the same two options, reads the condition:
+
+```sql
+from 'Rulings' where id() = $Ruling select id() as Id, Condition
+```
+
+The prompt asks the model to split the condition into its statements and decide, for each one, whether the photo shows it's true. The update script then decides whether the ruling applies:
+
+```javascript
+// $input is the context the model answered, so the check names the ruling it judged.
+const ruling = load($input.Ruling);
+const statements = $output.Statements || [];
+
+// The ruling applies only when the photo shows every statement of its condition.
+// The outcome is copied from the ruling, as the adjuster decided it.
+this.Check = {
+ Ruling: $input.Ruling,
+ Condition: ruling ? ruling.Condition : null,
+ Severity: ruling ? ruling.Severity : null,
+ Applies: ruling !== null && statements.length > 0 && statements.every(s => s.Holds === true),
+ Statements: statements,
+ At: new Date().toISOString()
+};
+```
+
+The model never produces a severity here. It says whether each statement holds, the script requires all of them to, and the severity is copied from the ruling as the adjuster wrote it.
+
+### What it took to make the check reliable
+
+The check took more iterations than any other task, and each of its rules answers a failure we saw. With Qwen3-VL-30B-A3B on RavenDB 7.2:
+
+- Shown the ruling's outcome, the model argued with the adjuster's severity instead of judging the photo. So the check never sees the outcome, or the assessments.
+- Asked for one verdict on the whole condition, the model approved photos of wrecks. One verdict per statement, combined by the script, rejected them.
+- Given the condition as a field in the context, the model accepted it even for wrecks. Delivered as a query result, the condition was actually judged.
+- Given several rulings in one call, the model accepted rulings for wrecks. One ruling per call didn't, which is why the search returns only the closest ruling.
+- Conditions that say where the damage is worked. Conditions written as a list of parts didn't.
+
+These are observations about one model, not laws. The structure costs little with a stronger model, so the sample keeps it for every model. Even so, the check isn't perfect: a few photos in our runs still passed conditions they shouldn't have, which is one more reason a person verifies every claim.
+
+### The index applies the ruling
+
+No task applies a ruling. The index does, in the `ruling` and `proposed` lines of the map. When `Check.Applies` is true, the proposal becomes the ruling's severity, and the agreement rule is skipped, since a person has already settled this kind of damage. The severity limit still holds, so a ruling that says severe still sends the claim for a closer look.
+
+A ruling outranks the models, even unanimous ones. In the claim below, all three assessors rated the van severe, the condition of Ruling 1 held on the photo, and that ruling's outcome is moderate, so the claim is on the fast track with a moderate proposal. The claim page shows both proposals, and the adjuster picks one.
+
+
+
+## Order without an orchestrator
+
+Six GenAI tasks, an embeddings task and an index work on the same document in a fixed order, and nothing schedules them. Three mechanisms do the work.
+
+Inputs gate each task. Every context script returns early until the fields it reads exist: the judge and the search wait for three assessments, and the check waits for `Candidate`. Each update script writes a field of its own, and that write is the change that wakes the next task.
+
+The context hash stops the loop. Every write to the claim makes RavenDB look at it again for every task, the assessors included. What keeps them from calling the model again is a hash that each task stores in the document's metadata, computed from the context and the task's configuration, as the [GenAI integration overview](https://docs.ravendb.net/ai-integration/gen-ai-integration/overview) describes. When the judge writes `Decision`, the assessors' context, the photo, hasn't changed, so they're skipped without a model call. That matters beyond cost: a second call could come back with a different severity, and an answer that was drawn again on every save would never settle.
+
+A counter in the context reruns a task on purpose. The search context includes `Recheck: this.Recheck || 0`. Raising `Recheck` changes the context, so the hash differs and the search runs again, against rulings that didn't exist the first time. The review step relies on exactly that.
+
+Two settings from setup matter as well. Each task runs at most two model calls in parallel (`MaxConcurrency = 2`), so a burst of claims doesn't flood the model server. And setup adds each GenAI task with the beginning of time as its starting point.
+
+
+
+In our runs on RavenDB 7.2.0 and 7.2.7, a GenAI task created with the default starting point processed only documents written after it existed. Claims Desk passes the beginning of time as the starting point to `AddGenAiOperation`, so claims saved before setup are assessed too:
+
+
+
+
+```csharp
+await store.Maintenance.SendAsync(new AddGenAiOperation(task, StartingPointChangeVector.BeginningOfTime));
+```
+
+
+
+
+```python
+store.maintenance.send(AddGenAiOperation(task, StartingPointChangeVector.BEGINNING_OF_TIME))
+```
+
+
+
+
+```typescript
+await store.maintenance.send(new AddGenAiOperation(task, StartingPointChangeVector.BeginningOfTime));
+```
+
+
+
+
+
+
+## The review: the person's decision is the last write
+
+### Reviewing the state that was shown
+
+An adjuster reviews what the claim page showed, but the claim can change underneath: a recheck can apply a new ruling while the page is open. A review saved over a state the adjuster never saw would verify a proposal nobody looked at. Claims Desk guards against that twice.
+
+The page carries a token: the number of entries in the claim's `History`. Every automated assessment, ruling check and review appends an entry, so the count names the state that was on screen. The review endpoint compares the token with the stored history and answers 409 when they differ.
+
+The save itself carries the change vector that the endpoint just read. The review is a patch, and a new ruling, when the adjuster wrote a condition, is stored in the same session. Here's the save from the review endpoint:
+
+
+
+
+```csharp
+using (var session = store.OpenAsyncSession())
+{
+ if (rule != "")
+ {
+ var entity = new Ruling(rule, body.Severity, claimId, at);
+ await session.StoreAsync(entity);
+ ruling = session.Advanced.GetDocumentId(entity);
+ }
+
+ session.Advanced.Defer(new PatchCommandData(claimId, (string?)doc["@metadata"]!["@change-vector"], new PatchRequest
+ {
+ Script = Tasks.ReviewPatch,
+ Values = new()
+ {
+ ["severity"] = body.Severity,
+ ["parts"] = body.Parts.Distinct().ToArray(),
+ ["note"] = body.Note?.Trim() ?? "",
+ ["ruling"] = ruling,
+ ["at"] = at,
+ },
+ }));
+
+ try
+ {
+ await session.SaveChangesAsync();
+ }
+ catch (ConcurrencyException)
+ {
+ return Results.Conflict(new { error = Stale });
+ }
+}
+```
+
+
+
+
+```python
+with store.open_session() as session:
+ if rule:
+ entity = Ruling(rule, severity, id, at)
+ session.store(entity)
+ ruling = session.advanced.get_document_id(entity)
+
+ values = {"severity": severity, "parts": list(dict.fromkeys(parts)), "note": (note or "").strip(), "ruling": ruling, "at": at}
+ session.advanced.defer(PatchCommandData(id, doc["@metadata"]["@change-vector"], PatchRequest(REVIEW_PATCH, values)))
+
+ try:
+ session.save_changes()
+ except ConcurrencyException:
+ raise HTTPException(409, STALE)
+```
+
+
+
+
+```typescript
+const session = store.openSession();
+try {
+ if (rule) {
+ const entity = new Ruling(rule, severity, id, at);
+ await session.store(entity);
+ ruling = session.advanced.getDocumentId(entity);
+ }
+
+ const patch = PatchRequest.forScript(REVIEW_PATCH);
+ patch.values = { severity, parts: [...new Set(parts)], note: (note ?? "").trim(), ruling, at };
+ session.advanced.defer(new PatchCommandData(id, doc["@metadata"]["@change-vector"], patch));
+
+ await session.saveChanges();
+} catch (e: any) {
+ if (e?.name !== "ConcurrencyException") throw e;
+ return c.json({ error: STALE }, 409);
+} finally {
+ session.dispose();
+}
+```
+
+
+
+
+If anything writes the claim between the read and the save, the whole batch fails, the new ruling included, and the adjuster gets the fresh state instead. The token catches most of these cases before anything is written, and the change vector closes the gap between that check and the save. The patch script sets `Review` and appends an `Adjuster` entry to `History`, atomically on the server. `Review` is what the index reads to mark the claim Dispatched.
+
+### Letting a new ruling reach waiting claims
+
+A new ruling should help the claims already waiting, not only the ones that arrive later. That takes two steps, and it's the only sequencing the backend does.
+
+The ruling has to be searchable first, which happens once the embeddings task has embedded it. The backend runs a vector search for the ruling's own condition every 500 ms, for up to 30 seconds, until the new ruling comes back as the nearest match. Then a [patch by query](https://docs.ravendb.net/documents/patching-documents/patch-multiple-documents/client-api) raises `Recheck` on the claims that could use it:
+
+```sql
+from index 'Claims/Desk'
+where Status = 'CloserLook' and Ruling = null and id() != $claim
+update { this.Recheck = (this.Recheck || 0) + 1; }
+```
+
+On each of those claims the search context changes, so the ruling search runs again. If the new ruling is now the closest, the check judges it on that claim's photo. A claim that a ruling already applies to is left alone: a later ruling never replaces an earlier one that held.
+
+## What the pattern costs
+
+- Model calls. Each claim takes six: three assessors and the judge with the photo, the search with a short text, and the check with the photo again. That's six times the cost of asking once, and a claim is assessed within about a minute rather than seconds.
+- Agreement isn't correctness. Three assessors can agree and be wrong, and on one shared model they're more likely to. That's why a severe proposal never takes the fast track and why a person verifies every claim. The gate reduces the attention a claim needs; it doesn't replace it.
+- Rulings carry weight. A ruling outranks the models even when all three agree, and that can put a claim the models rated severe on the fast track. The claim page flags it, and the adjuster still verifies. Rulings are never edited in the sample, so a production desk would also need a way to retire one.
+- One rules document. Every claim loads `settings/routing`, so each change to it re-indexes every claim.
+- Outside photos only. The part list stops at what a photo of the outside can show.
+
+## Summary
+
+Gated consensus turns uncertain model answers into decisions without asking any model how sure it is: it measures agreement and lets a rule outside the model act on it. In Claims Desk:
+
+- Three assessors look at the photo from different trades and see nothing else, so their agreement measures the damage rather than a shared story.
+- The judge's update script counts the votes and enforces the majority rule, so the model weighs the evidence but can't change the arithmetic.
+- `SeverityVotes` is the uncertainty measure, and the `Claims/Desk` index gates on it together with the stakes, so a severe proposal always gets a closer look.
+- The routing rules are a document that the index loads, so changing a threshold re-routes every claim without a deploy.
+- Adjuster rulings carry forward through an embeddings task and vector search, and a blind check with one verdict per statement decides whether a ruling holds on a new photo.
+- Fields drive the order of the tasks, and the GenAI context hash keeps the chain of writes from looping, so the backend needs no orchestrator.
+- The review is guarded by a history token and the claim's change vector, so a person's decision always applies to the state they saw.