aspace://guide/springai-jev

Spring AI and TypeSafe Jev

A customer writes in. Claude Haiku drafts the reply on a peer that holds no API key, through a model server peer that does. TypeSafe Jev judges the draft on a peer that holds the TypeSafe key, and the judgment is a signed entry in a shared space. This is the Spring blog post on typed judgment, run by a fleet of nine Spring Boot peers on AgentSpaces 0.5.0.

AgentSpaces 0.5.09 Spring Boot peers, one JVM10 agents in 6 classes6 spacesloopback tcp, dev-local profileruns with no keys; two optional
What changed from the postFollow one ticketRun it
aspace://guide/springai-jev/idea · chapter 1

The idea: typed judgment, on a fleet

The Spring AI community project spring-ai-typesafe wraps TypeSafe's Jev API, which answers questions about a piece of text with numbers and generates no text of its own. A Noul returns a truth value, a Choice picks one option and gives a probability for each, and a Score places the text on an ordered rubric. The post Spring AI and TypeSafe Jev: Fast, Cheap, Structured Decisions (spring.io, 2026-09-21) triages a support ticket with those three questions, grades a model's reply with a JevJudge, and retries a failed reply with JevSelfRefineAdvisor, all inside one ChatClient call in one application.

This example keeps the typed questions and moves everything around them onto a fleet. A customer message becomes a Ticket in a shared space. A drafter peer with no API key writes its prompt as an entry, and a model server peer that holds the Anthropic key answers it. A judge peer that holds the TypeSafe key runs the questions and writes the result as a signed Judgment. A failed draft comes back as a new ticket that carries Jev's feedback. A ticket routed to billing goes through an ordered log, so exactly one clerk takes it. A reduce keeps the pass rate per department. Three judge peers each ask Jev one question and vote on whether a very angry customer gets a person.

THE POST: ONE JVM, ONE CALL CHAINTHE FLEET: ENTRIES BETWEEN PEERSChatClient.prompt()the application's one callJevSelfRefineAdvisorjudge, add feedback, call againChatModelClaude Haiku, key in this processJevJudgeTypeSafe Jev, key in this processretryloopboth keys, the judge and the retry live in one processinboxdrafterno keydraftsmodel-requestsmodel-serverAnthropic keyjudgeTypeSafe keyverdictsthe retry is a Ticket(attempt 2, feedback) back into inbox,and each key sits on the one peer that needs it
The post and the fleet. The post builds judgment into one call chain: a ChatClient, an advisor that retries, a model, and a judge, all in one process with both keys. The fleet keeps the same typed questions and turns each stage into a peer that reads and writes entries. The advisor loop becomes a ticket in a space, and each key moves to the one peer that calls that API.

What changed between the post and the fleet

Concern In the post In the fleet
Where the code runsone application and one ChatClient call chain9 Spring Boot peers that read one agentspaces: subtree
Who holds the Haiku keythe application that calls the modelthe model-server peer only. Drafters hold none and send a ModelRequest entry
Who holds the Jev keythe same applicationthe three judge peers only
The retryJevSelfRefineAdvisor loops inside the callthe judge writes Ticket(attempt + 1, feedback) into inbox and any live drafter takes it
What a judgment isa JevVerdict object in memorya signed Judgment entry in verdicts that any peer can read
A worker dies mid-draftthe call fails with the processthe take lease lapses after 20s and another drafter takes the ticket
After the verdictthe post stops at the judge and the retrybilling exactly once, a running score per department, a council vote on very angry customers

The guide follows the order of the work. Chapters 2 to 4 describe the cast, how the fleet forms, and the spaces. Chapter 5 follows one ticket from the inbox to the ledger. Chapters 6 to 11 each take one mechanism: the model server and its lease, the typed questions, the retry, the ordered billing desk, the reduce, and the council. Chapter 12 shows the two fixtures that let the whole fleet run with no keys and what the two live profiles change. Chapter 13 covers failure and chapter 14 covers running and testing.

What needs keysNo part of the example needs a key. FixtureHaiku answers for Claude Haiku and FixtureJev answers for the TypeSafe System One API, so mvn verify runs the whole scenario on a laptop. Set ANTHROPIC_API_KEY to put Haiku on the model-server peer, set TYPESAFE_API_KEY to put Jev on the judge peers, or set both. The two are independent.
aspace://guide/springai-jev/cast · chapter 2

The cast: nine peers, ten agents

Each peer is a separate Spring Boot application with its own identity, its own tcp socket and its own replica of every space. The launcher starts all nine in one JVM, in the order of JevFleet.PEERS, and closing a peer's Spring context is the event the rest of the fleet sees when a process dies.

The fleet has 10 bound agents of 6 classes: two drafters, one judge, one council lead, three councillors, two billing clerks and one quality reducer. The ModelServer is one more worker: a lifecycle bean that the agentspaces-springai library starts on the model-server peer, so it has no @AgentSpec of its own. The Ledger class on the console peer reads the ledger and is not an agent.

ONE GROUP jev-fleet: 9 PEERS, TWO API KEYSmodel-servertcp :7711ModelServer, the library's lifecycle beanserves claude-haiku-4-5-20251001ANTHROPIC keydrafter-atcp :7712Drafter: @SpaceTake on inboxChatClient over FleetChatModelno keydrafter-btcp :7713Drafter: @SpaceTake on inboxChatClient over FleetChatModelno keyjudge-leadtcp :7714Judge: @SpaceNotify on draftscouncil-lead, Councillor (RETENTION)TYPESAFE keyjudge-btcp :7715Councillor (PERSON)@Ballot on councilTYPESAFE keyjudge-ctcp :7716Councillor (RISK)@Ballot on councilTYPESAFE keybilling-atcp :7717billing-clerk: @OrderedTakea seat in the billing Raft logno keybilling-btcp :7718billing-clerk: @OrderedTakea seat in the billing Raft logno keyconsoletcp :7719quality: @SpaceReduce, and Ledgerfleet console on http :7595no keythe model-serve grant names model-server on every peer, so a drafter accepts a model answer from that peer onlymodel-server is the seed: the other eight peers dial 127.0.0.1:7711
Nine peers and two keys. Each peer is a separate Spring Boot application with its own identity. The filled ones hold an API key: the model server holds the Anthropic key and the three judge peers hold the TypeSafe key. No other peer uses either key, and nothing in the fleet sends a key from one peer to another. The demo shares one process environment, so the boundary there is one of configuration, and running each peer as its own process makes it a process boundary.
Agent and class Peers Annotation Reads Writes
model-server
ModelServer from agentspaces-springai
model-servera lifecycle bean, not an annotated agentModelRequest from model-requests (take lease 2m)ModelResponse, ModelAttempt
drafter
Drafter
drafter-a, drafter-b@SpaceTake(inbox, lease 20s, resultSpace drafts, resultLease 12h)TicketDraft; through its ChatClient: ModelRequest, and the ModelResponse it waits for
judge
Judge
judge-lead@SpaceNotify(drafts, resultSpace verdicts, resultLease 24h)DraftJudgment, QualitySample, Reply, Escalation, GaveUp in verdicts; Ticket in inbox; BillingCase in billing
council-lead
Council.Lead
judge-lead@Propose and @OnDecisionEscalation and the votesProposal in council; EscalationDecision in verdicts
councillor
Council.Councillor
judge-lead (RETENTION), judge-b (PERSON), judge-c (RISK)@Ballot(council)Proposal, then the Escalation in verdictsone signed ballot
billing-clerk
Billing.Clerk
billing-a, billing-b@OrderedTake(billing, lease 30s, resultSpace verdicts)BillingCaseBillingReceipt
quality
Quality
console@SpaceReduce(verdicts, key department, lease 30s, idle 7d)QualitySampleDepartmentQuality

The key boundary follows from where each client is built. JevFleet.JudgeConfig builds the TypeSafeClient on the three judge peers only, and the model server builds Spring AI's Anthropic model on the model-server peer only. The test checks the boundary by asking the surviving drafter's Spring context for a FixtureHaiku bean and a FixtureJev bean and finding neither, while the judge-lead peer has the fixture Jev and the model-server peer has the fixture Haiku. The demo runs all nine peers in one JVM, so they share one process environment, and the boundary in the demo is one of configuration: it is what each peer's profiles and beans use, and a peer's code could still read the variable. Run each peer as its own process, set ANTHROPIC_API_KEY only in the model-server process and TYPESAFE_API_KEY only in the judge processes, and the same boundary becomes an operating-system one.

Three councillors sit on three peers because the vote capability counts voters per peer here: the example grants no agent-level vote, so the authorizer answers at peer granularity. The judge-lead peer hosts the Judge, the Council.Lead and one councillor, and the two other judge peers each host one councillor.

aspace://guide/springai-jev/formation · chapter 3

How the fleet forms and how the agents find each other

All nine peers join one group, jev-fleet, with the founding text agentspaces-jev-example-v1. The first peer in PEERS, model-server, is the seed: it binds 127.0.0.1:7711 and the other eight peers dial it. The demo uses ports 7711 to 7719 in that order, and the test asks the operating system for free ports instead. The transport is tcp on loopback under the dev-local security profile, and every peer ticks every 250 ms. The console peer also serves its HTTP page on port 7595.

HOW A PEER JOINS: group jev-fleet, founding text agentspaces-jev-example-v1drafter-adials the seedmodel-serverthe seed, tcp :7711the other peersseven more peers1 dial the seedthe configured seed 127.0.0.1:7711 over tcp2 introducesigned peer ad, group id checked3 membershipthe newcomer is introduced to the members4 cards and adsagents, spaces, capabilities on one gossip stream5 spaces catch updigests, then rumorssecurity profile dev-local on loopback; the tick is 250 ms.The founding is text, so every peer that knows it and dials the seed lands in the same group.
How a peer joins. A new peer needs only a seed to dial. It proves a key, learns the members, hears every card, and its spaces fill from the replicas already there. No peer in the middle admits it and no registry holds it: the group id is the hash of the founding, and membership is what the members agree on. Here all nine peers share one JVM and still behave as nine processes, each with its own socket, key and replicas.
application.yml: the one subtree every peer reads
agentspaces:
  security:
    profile: dev-local                # loopback TCP; mtls in production
    # JevFleet.Fleet.start sets grants.model-serve[0] on every peer from the model-server's pinned
    # identity. A deployment names that peer here instead:
    # grants:
    #   model-serve: [<model-server PeerId>]
  identity:
    agent-keys: subordinate         # every agent signs its own records: AGENT_ATTESTED verdicts, ballots, receipts
  tick-millis: 250
  capabilities:
    votes-space: council
  groups:
    - name: jev-fleet
      founding: agentspaces-jev-example-v1
      seeds: ${example.seeds:}      # the seed peer's address; the launcher sets it on every peer but the seed
      spaces:
        - name: inbox
        - name: drafts
        - name: verdicts
        - name: council
        - name: billing
        - name: model-requests

The base document holds everything the nine peers share: the group, its six spaces, the security profile, the subordinate-key setting that lets every agent sign its own records, and the votes space the council uses. Each peer then adds a role document, and the launcher sets the properties that differ per peer. Spring gives the launcher's SpringApplicationBuilder.properties the lowest priority, so application.yml leaves example.peer-name, example.seeds, example.concern and example.console-port to the launcher.

WHAT ONE PEER READS, HIGHEST PRIORITY FIRSTTHE PROFILES EACH PEER GETSprofile documentsmodel-server, drafter, console; haiku-live, jev-liveapplication.yml, the basegroup, six spaces, dev-local, tick 250 mslauncher default propertiespeer-name, bind, seeds, concern, model-serve grantoverridesoverridesSpringApplicationBuilder.properties sets the lowest-priority source,so application.yml leaves peer-name, seeds and concern to the launchermodel-servermodel-server, plus haiku-live withANTHROPIC_API_KEYdrafter-adrafter-bdrafterjudge-leadjudge-bjudge-cjev-live with TYPESAFE_API_KEY, otherwisenonebilling-abilling-bnone: the desk forms in codeconsoleconsole
Configuration layers and role profiles. All nine peers read one application.yml and differ by profile and by a handful of properties the launcher sets per peer. A live profile switches on only for the peer that holds the matching key, which keeps that key out of every other peer's configuration.
The role documents and the live profiles
spring:
  config:
    activate:
      on-profile: model-server
agentspaces:
  springai:
    model-server:
      enabled: true
      models: ["${example.haiku-model}"]
      lease: 2m

The launcher builds nine peers and one key boundary

The launcher creates the model server's identity first, in a keystore directory, so the model-serve grant can name a peer id before any peer exists. It then starts the peers in order, puts the same grant on every peer, and forms the billing desk once all nine are up.

JevFleet.java: Fleet.start
public static Fleet start(int[] ports, Path keystore, int consolePort, boolean haikuLive, boolean jevLive,
                          Drafter.Hook hook) throws IOException {
    Files.createDirectories(keystore);
    PeerIdentity modelServer = FileKeystore.loadOrCreate(keystore);
    Fleet fleet = new Fleet(modelServer);
    try {
        for (int i = 0; i < PEERS.size(); i++) {
            String name = PEERS.get(i);
            Map<String, Object> extra = new HashMap<>();
            // Only the model-server peer may answer model requests; every peer checks this.
            extra.put("agentspaces.security.grants.model-serve[0]", modelServer.peerId().value());
            if (name.equals("model-server")) {
                extra.put("agentspaces.keystore", keystore.toString());
            }
            if (name.equals("console")) {
                extra.put("example.console-port", consolePort);
            }
            fleet.peers.put(name, JevFleet.start(name, node(name, ports[i], i == 0 ? 0 : ports[0], extra),
                    profiles(name, haikuLive, jevLive), name.startsWith("drafter-") ? hook : null));
        }
        fleet.desk.addAll(Billing.formDesk(List.of(fleet.peer("billing-a"), fleet.peer("billing-b"))));
    } catch (RuntimeException e) {
        fleet.close();
        throw e;
    }
    return fleet;
}

How the agents find each other

Each bound agent publishes a signed card on the gossip stream, and the six card names below are the agent names from the table in chapter 2. No agent in this app reads a card. Every step routes by entry type: the drafter takes Ticket from inbox, the judge reacts to Draft in drafts, the clerk takes BillingCase from billing. A card tells a reader who is in the fleet and leaves the routing to the spaces.

AGENT CARDS (one per bound agent, 15 min TTL, refreshed)drafterdrafter-a, -bjudgejudge-leadcouncil-leadjudge-leadcouncillor3 judge peersbilling-clerkbilling-a, -bqualityconsoleany peerreads the cataloguea carda hint, never a rosterno agent in this app reads a card:every step routes by entry type,so a card only describes who is there
Cards and the catalogue. Every discoverable thing is a signed, typed, time-limited card on one gossip stream. A planner or a console reads the catalogue to learn what exists. The design rule that follows is to route by entry type: a space and a record type deliver the work, and a discovered name only tells a reader where to look.
aspace://guide/springai-jev/spaces · chapter 4

The spaces

The configuration names six spaces and sets no strategy on any of them, so each is LEASE_RACE, the starter's default: a take claims an entry under a lease, and the claim race decides which peer wins. The billing space additionally has an ordered-log coordinator registered over it, and only @OrderedTake takes go through that log. Every record is a plain Java record, so the canonical CBOR codec carries it unchanged, and every record carries the ticket id that each stage joins on.

Space Records and their leases Written by Read or taken by
inboxTicket, 12 hthe console peer (a customer message), the judge (a retry)the drafters, with a take lease of 20s
draftsDraft, 12hthe draftersthe judge, by notification
verdictsJudgment, QualitySample, Reply, Escalation, GaveUp, EscalationDecision and BillingReceipt, each 24h; DepartmentQuality accumulators, 7d idlethe judge, the council lead, the clerks, the reducerthe reducer, the lead, the councillors, the ledger
councilthe vote's proposals and signed ballots, 12 hthe lead and the councillorsevery council member
billingBillingCase, 12 hthe judgethe clerks, through the ordered log
model-requestsModelRequest 45 s (the wait plus 30 s), ModelResponse 10 min, ModelAttempt 10 minthe drafters, the model serverthe model server, the drafters
THE verdicts SPACE: EVERY RECORD IS SIGNED BY THE AGENT THAT WROTE ITJudgmentReplyGaveUpQualitySampleEscalationEscalationDecisionBillingReceiptDepartmentQualityjudgejudge-leadsignscouncil-leadjudge-leadsignsbilling-clerkbilling-a, -bsignsqualityconsolesignsqualitytakes each sample, reducescouncil-lead and councillorsnotified, then readLedger on consolereads all eightevery entry keeps the AgentId of its signer, so the ledger prints judge@peer, council-lead@peer, billing-clerk@peer, quality@peer
One space, eight record types, four signers. The verdicts space is the ledger. Under agent-keys: subordinate each agent signs its own records with its own key, so any peer can check who judged, who voted, who settled and who scored. Two readers act on what they find: the reduce takes the samples and the council lead reacts to the escalation.

The example sets subordinate agent keys for the sake of this ledger. Each record carries the id of the agent that signed it, and the console's Ledger prints that id and the attestation level on every line. It prints one quality line per department, the newest accumulator, which chapter 10 explains.

Ledger.java: one line per signed record
private static String by(Space.Entry<?> entry) {
    return " ยท by " + entry.issuer().localName() + "@" + entry.issuer().peer().display()
            + " (" + entry.attestation() + ")";
}
ONE ENTRY IN THE SPACE verdictsJudgmentticketIdattempturgencydepartmentdepartmentConfidencefrustrationfrustrationLabelpassedsummaryfeedbackjudgedByspace strategyLEASE_RACElease24hsigned bythe judge agent's own key
An entry. Every shared fact in an AgentSpaces app is a typed record in a space. The space's strategy says how a take is decided, the lease says how long the entry lives, tags make it findable, and the signature says which agent wrote it and lets any member check that.
Leases double as cleanupNo peer deletes ledger entries. A judgment lives 24h, a retry ticket and a draft live 12h, and a department's accumulator lapses after 7d without a new sample.
aspace://guide/springai-jev/one-run · chapter 5

One run, end to end

The demo and the test submit the same three customer messages. T-1 is a double charge, and its first draft is generic on purpose, so Jev fails it and the retry path runs. T-2 is a webhook outage routed to technical, judged once and approved. T-3 is a customer who has written three times and is disputing a charge with a bank, so Jev scores the customer as very angry and the council votes.

consolesubmits, reducesdrafter-aor drafter-bmodel-serverAnthropic keyjudge-leadTypeSafe keybilling-aor billing-b1 Ticket, attempt 1inbox2 take, lease 20sfrom inbox3 ModelRequestmodel-requests4 ModelResponsethe take completes5 Draftdrafts6 Jev: triage + verdicttwo System One calls7 Judgment, QualitySampleverdicts8 failed: Ticket attempt 2, feedbackinbox, back to step 29 passed: Reply, BillingCaseverdicts, billing10 ordered take, Receiptverdicts11 reduce: DepartmentQualityverdictsvery angry (frustration >= 1.5): an Escalation too, then the council votes (chapter 11)
One ticket, end to end. T-1, the double charge. Steps 2 to 5 run on whichever drafter takes the ticket. If the draft fails, step 8 puts a new ticket into inbox and the drafters run steps 2 to 7 again. A draft that passes and belongs to billing continues through step 9 to the ordered desk, and every judgment feeds the running score in step 11.

Steps 1 and 2: the ticket and the take

The console peer writes the message into inbox with a 12-hour lease. The drafter's @SpaceTake method takes it under a 20s lease and returns a Draft, and the binder writes that return value into drafts and completes the take in the same step.

Submit, and the drafter
public void submit(String ticketId, String customer, String message) {
    space(Support.INBOX).write(new Ticket(ticketId, customer, message, 1, ""), Lease.of(Duration.ofHours(12)));
}

Steps 5 to 9: the judge decides what the draft implies

One @SpaceNotify method reacts to each draft and returns every entry the judgment implies. Chapters 7 and 8 take it apart. Here the whole method shows how few lines sit between a draft and four different next steps.

Judge.java: judge
@SpaceNotify(space = Support.DRAFTS, lease = "12h", resultSpace = Support.VERDICTS, resultLease = "24h",
        produces = {Judgment.class, QualitySample.class, Reply.class, Escalation.class, GaveUp.class})
public Entries judge(Draft draft) {
    SystemOneResponse answers = jev.systemOne(draft.message(), TRIAGE);
    JevVerdict verdict = judge.judge(draft.message(), draft.reply());

    String department = answers.choiceValue("department");
    double frustration = answers.scoreValue("frustration");
    Judgment judgment = new Judgment(draft.ticketId(), draft.attempt(), answers.noulValue("is_urgent"),
            department, answers.choice("department").confidence(), frustration,
            answers.score("frustration").nearestLabel(), verdict.passed(), verdict.summary(),
            verdict.passed() ? "" : verdict.feedback(), name);

    List<Object> ledger = new ArrayList<>();
    ledger.add(judgment);
    ledger.add(new QualitySample(department, draft.ticketId(), draft.attempt(), verdict.passed(), frustration));
    if (frustration >= Support.VERY_ANGRY) {
        ledger.add(new Escalation(draft.ticketId(), draft.customer(), draft.message(), frustration));
    }
    if (verdict.passed()) {
        ledger.add(new Reply(draft.ticketId(), draft.customer(), draft.reply(), draft.attempt(), department));
        if ("billing".equals(department)) {
            billing.write(new BillingCase(draft.ticketId(), draft.customer(), draft.message(), draft.reply()),
                    Lease.of(Duration.ofHours(12)));
        }
    } else if (draft.attempt() < Support.MAX_ATTEMPTS) {
        // The retry is an entry, so any drafter may take it, and a drafter that dies holding it
        // lets it reappear. No advisor loop, no process that has to stay alive.
        inbox.write(new Ticket(draft.ticketId(), draft.customer(), draft.message(), draft.attempt() + 1,
                verdict.feedback()), Lease.of(Duration.ofHours(12)));
    } else {
        ledger.add(new GaveUp(draft.ticketId(), draft.customer(), draft.attempt(), verdict.feedback()));
    }
    return Entries.of(ledger);
}

What the demo prints

This is the ledger the demo prints at the end of one run on 2026-11-04, taken verbatim after mvn -q compile exec:java. The nine peers' Spring Boot start-up lines between the first line and the ledger are left out. The order of the ledger lines varies from run to run, and so do the peer ids and the commit indexes.

mvn -q compile exec:java, recorded 2026-11-04
jev fleet: haiku fixture, jev fixture, console at http://localhost:7595/

ledger:
  judgment  T-1 attempt 2: urgency 0.92, billing (0.86), frustration 1.0 Frustrated, PASSED ยท by judge@peer:zCfDNj8M4oโ€ฆ (AGENT_ATTESTED)
  judgment  T-3 attempt 1: urgency 0.92, billing (0.86), frustration 2.0 Very angry, PASSED ยท by judge@peer:zCfDNj8M4oโ€ฆ (AGENT_ATTESTED)
  judgment  T-2 attempt 1: urgency 0.92, technical (0.86), frustration 1.0 Frustrated, PASSED ยท by judge@peer:zCfDNj8M4oโ€ฆ (AGENT_ATTESTED)
  judgment  T-1 attempt 1: urgency 0.92, billing (0.86), frustration 1.0 Frustrated, FAILED ยท by judge@peer:zCfDNj8M4oโ€ฆ (AGENT_ATTESTED)
  reply     T-1 attempt 2 to billing: I am sorry your card was charged twice for the same order. I have opened a refund review for the duplicate charge, and the billing team will confirm the refund and its timing with you directly. ยท by judge@peer:zCfDNj8M4oโ€ฆ (AGENT_ATTESTED)
  reply     T-3 attempt 1 to billing: I am sorry this is the third time you have written and nobody has answered. I have flagged your account for a supervisor to review the disputed charge and to cancel the services you named today, and a person will contact you about both. ยท by judge@peer:zCfDNj8M4oโ€ฆ (AGENT_ATTESTED)
  reply     T-2 attempt 1 to technical: I am sorry the webhook integration stopped firing after last night's update. I have opened a priority incident with the integrations team for your stuck orders, and I will send you their findings as soon as they confirm the cause. ยท by judge@peer:zCfDNj8M4oโ€ฆ (AGENT_ATTESTED)
  council   T-3: human {human=3, bot=0} ยท by council-lead@peer:zCfDNj8M4oโ€ฆ (AGENT_ATTESTED)
  receipt   T-1: refund review opened for Dana by billing-a at commit 3 ยท by billing-clerk@peer:z26PTeBiFpโ€ฆ (AGENT_ATTESTED)
  receipt   T-3: refund review opened for Priya by billing-a at commit 2 ยท by billing-clerk@peer:z26PTeBiFpโ€ฆ (AGENT_ATTESTED)
  quality   billing: 3 judged, 2 passed, mean frustration 1.33 ยท by quality@peer:zFtRWC3EiQโ€ฆ (AGENT_ATTESTED)
  quality   technical: 1 judged, 1 passed, mean frustration 1.00 ยท by quality@peer:zFtRWC3EiQโ€ฆ (AGENT_ATTESTED)
✓ fixture Haiku, fixture Jev · 3 tickets · 12 signed records

Read the ledger against the figure. T-1 has two judgments, a failed first attempt and a passed second one, and one reply at attempt 2. T-3 appears once in judgment because it passed on the first draft, and it also carries the council's decision. The two receipts name billing-a as the clerk the log committed, and billing-clerk signs both receipts with its own key. The two quality lines are the reduce's accumulators, one line per department and each the newest accumulator: billing saw three judgments and passed two, technical saw one and passed it.

aspace://guide/springai-jev/model · chapter 6

Claude Haiku through a peer that holds the key

The drafter peers hold no Anthropic key. The app is one Maven module, so the Anthropic auto-configuration is on every peer's classpath, and spring.ai.model.chat: none in the base document keeps it off everywhere except the model-server peer under haiku-live. The drafter's ChatClient is built over FleetChatModel from agentspaces-springai, a Spring AI ChatModel whose provider is the fleet. The call() its advisor chain calls writes a ModelRequest into model-requests and waits for the matching ModelResponse.

The drafter's ChatClient and its configuration
static class DrafterConfig {
    @Bean
    Drafter drafter(FleetChatModel fleetChatModel, FleetTaskScheduler scheduler, Environment env,
                    AgentSpacesSpringAiProperties springAi, ObjectProvider<Drafter.Hook> hook) {
        Duration wait = springAi.modelClient().timeout();
        if (wait.compareTo(Drafter.LEASE) >= 0) {
            throw new IllegalStateException("agentspaces.springai.model-client.timeout (" + wait
                    + ") must be shorter than the ticket's take lease (" + Drafter.LEASE
                    + "): TakeLeaseAdvisor renews the take once before a non-streamed call");
        }
        ChatClient chat = ChatClient.builder(fleetChatModel)
                .defaultAdvisors(new TakeLeaseAdvisor(scheduler.scheduler(), Drafter.LEASE.dividedBy(3)))
                .build();
        return new Drafter(env.getProperty("example.peer-name", "drafter"), chat,
                hook.getIfAvailable(() -> Drafter.Hook.NONE));
    }
}

The round trip

The model-server peer runs ModelServer, which takes ModelRequest entries from model-requests, calls the one ChatModel bean on its peer, and completes the take with a ModelResponse. Because the response is a signed entry, the drafter can ask who wrote it. The check is the authenticity step of the round trip: the drafter accepts the answer only when the signer's peer is one the model-serve grant names, and it ignores an answer from any other peer.

drafter-aFleetChatModelmodel-requeststhe spacemodel-serverModelServerAnthropic APIthe key lives here1 notify ModelResponse by requestIda subscription, before anything is written2 write ModelRequestlease 45 s: the wait + 30 s3 take (LEASE_RACE, lease 2m)by model name; writes a ModelAttempt4 ChatModel.call(prompt)the one place the key is used5 the model's reply6 complete the take with ModelResponseanswer and removal land together7 event: ModelResponse8 trusted(issuer, MODEL_SERVE)the model-serve grant names model-server9 retire the response, return to ChatClientservedBy and attempt in the metadatawhile the provider works, the server renews its takeevery 40 s (lease 2m / 3); a response from any peer the grantdoes not name is ignored, never accepted
The model-server round trip. A drafter writes its prompt as a ModelRequest. The one model server takes it, calls Claude Haiku with the key it alone holds, and completes the take with a ModelResponse. The drafter checks that the signer of the response is a peer the model-serve grant names before it accepts the text.
agentspaces-springai: FleetChatModel and ModelServer
public ChatResponse call(Prompt prompt) {
    ModelRequest request = request(prompt, false);
    return observation(request).observe(() -> {
        Template<ModelResponse> template = responses(request.requestId());
        CompletableFuture<ModelResponse> answer = new CompletableFuture<>();
        try (Subscription subscription = space.notify(template, (SpaceEvent<ModelResponse> event) -> {
            if (event.kind() == SpaceEvent.Kind.WRITTEN && trusted(event.issuer(), event.entry())) {
                answer.complete(event.entry());
            }
        }, Lease.of(timeout.plusMinutes(1)))) {
            space.write(request, Lease.of(timeout.plusSeconds(30)));
            ModelResponse response = await(answer, template, Instant.now().plus(timeout))
                    .orElseThrow(() -> new FleetModelException("no trusted model server answered request "
                            + request.requestId() + " (model '" + request.model() + "') within " + timeout));
            retire(template);
            if (response.error() != null) {
                throw new FleetModelException("model server " + response.servedBy() + " failed: "
                        + response.error());
            }
            return WireMapping.toResponse(response.generations(), response.usage(), response.model(),
                    response.requestId(), java.util.Map.of(SERVED_BY_KEY, response.servedBy(),
                            ATTEMPT_KEY, response.attempt()));
        }
    });
}
✓ library code, agentspaces-springai 0.5.0

The grant that names the model server

The grant is a list of peer ids under agentspaces.security.grants.model-serve. The launcher builds it from the model server's pinned identity and sets it on every peer, including the model server itself, which would otherwise log a warning that callers will ignore its answers. Under the dev-local profile the grant is part of the membership authorizer, so the setting is enforced here and not only documented.

JevFleet.java: the grant
// Only the model-server peer may answer model requests; every peer checks this.
extra.put("agentspaces.security.grants.model-serve[0]", modelServer.peerId().value());

The lease follows the work, and the wait ends inside it

Two takes are in flight during one draft. The drafter holds a take on the Ticket with a 20s lease, and the model server holds a take on the ModelRequest with a 2m lease. The TakeLeaseAdvisor sits on the drafter's ChatClient and renews the ticket's take, by the binding's lease and counted from now, once before each non-streamed model call. This drafter makes one call per draft, so the call has the lease's 20s. The model client's wait is 15s, which leaves 5 seconds of margin, so a call either answers inside the take or fails before the take lapses. The model server renews its own take every 40 seconds, a third of its lease, while the provider works.

THE DRAFTER: ITS TICKET TAKE AND ITS MODEL WAIT, IN SECONDSTicket take (drafter)lease 20s, renewed once, before the model callFleetChatModel waittimeout 15s: the call has failed by here at the latestrenew5 s of margin05101520THE MODEL SERVER'S SIDE OF THE SAME ROUND TRIP, IN SECONDSModelRequest entrytimeout + 30 sModelRequest take (server)lease 2mrenewed every 40 srenew at 40srenew at 80s020406080100120140160
The wait ends inside the take. The ticket's take is short on purpose, so a dead drafter loses it 20 s later. TakeLeaseAdvisor renews it once, before the model call, and this drafter makes one call per draft, so the call has the lease's 20 s. The model client's wait is 15 s, so a slow call fails 5 s before the take lapses and the ticket reappears for the other drafter. The model server renews its own, longer take while the provider works.
Drafter.java: the one lease the annotation and the check share
/** The take lease on a ticket, in seconds. */
static final int LEASE_SECONDS = 20;

/**
 * The take lease on a ticket. {@code TakeLeaseAdvisor} renews it by this much, from now, once
 * before each non-streamed model call, so one call has this long. {@code JevFleet.DrafterConfig}
 * refuses to build the drafter when {@code agentspaces.springai.model-client.timeout}, the
 * longest the call can wait, is not shorter than this.
 */
static final Duration LEASE = Duration.ofSeconds(LEASE_SECONDS);
TakeLeaseAdvisor: renewal before each call
public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) {
    current.get().ifPresent(TakeLeaseAdvisor::renew);
    return chain.nextCall(request);
}
✓ library code, agentspaces-springai 0.5.0
What to watch forThe advisor renews once before each non-streamed round trip, so the take outlives the call only when the call waits less than the lease. The library's own default wait is 120 seconds, which is longer than this drafter's 20s take, so the example sets agentspaces.springai.model-client.timeout to 15s, and the JevFleet.DrafterConfig shown earlier checks at start that the wait stays shorter than Drafter.LEASE. A call that waits the 15s out throws, the binder logs the failure, the take lapses 5 seconds later, and the other drafter takes the ticket. A deployment with slower models lengthens the lease on @SpaceTake and the timeout together and keeps the wait the shorter, at the price of slower recovery from a dead drafter. The model server is a single instance: with a second model-server peer, a request whose server dies reappears and the next server serves it with the next attempt number.
aspace://guide/springai-jev/judgment · chapter 7

Jev's typed questions, on the judge peer

The judge peer builds the same objects the post builds. A Map holds the three triage questions of the post's support-ticket example, asked in one System One request over the customer's message. A JevJudge with three criteria grades the reply, and the judge asks it with the message and the reply, which is a second System One request. The TypeSafeClient the starter or the fixture contributes is the only object that talks to Jev, so the questions, the judge and the answer types are the real classes either way.

Judge.java: the questions and the judge
private static Map<String, Question> triage() {
    Map<String, Question> questions = new LinkedHashMap<>();
    questions.put("is_urgent", Noul.of("Does this message convey urgency?"));
    questions.put("department", Choice.builder()
            .instructions("Which team should handle this?")
            .option("billing", "Payments, invoicing, refunds, charges")
            .option("technical", "Bugs, outages, integrations")
            .option("sales", "Pricing, upgrades, new accounts")
            .build());
    questions.put("frustration", Score.of("How frustrated is the customer?", "Calm", "Frustrated", "Very angry"));
    return Map.copyOf(questions);
}
Draftmessage and replySYSTEM ONE 1: TRIAGE, OVER THE MESSAGEis_urgent: Noula truth value, 0 to 1department: Choicebilling, technical or sales, with confidencefrustration: ScoreCalm, Frustrated, Very angry: 0 to 2SYSTEM ONE 2: THE JUDGE, OVER THE REPLYaddresses_issue: Noulpasses at 0.7 or moreno_unconfirmed_promise: Noulpasses at 0.7 or moretone: ScoreCurt, Neutral, Courteous: passes at 1.0Judgmentverdictsurgency, department + confidencefrustration + rubric labelpassed, summary, feedbackjudgedByfrustration >= 1.5 also writes an Escalationpassed also writes a Replypassed and billing also writes a BillingCasea failure also writes the retry Ticketthe verdict's feedback() text rideson that retry Ticket
Two typed requests per draft. The judge asks Jev two things. The triage request puts three typed questions to the customer's message. The JevJudge request grades the reply against three criteria, each with its own threshold. The answers become one signed Judgment, and what the judgment implies decides which other entries the same method writes.

Each answer carries what the post describes: the Noul is a truth value, the Choice names an option and gives a probability per option, and the Score gives a value on the rubric and the nearest label. The judge copies those numbers into the Judgment, adds the verdict's passed, summary and feedback, and signs the whole record. The criteria have thresholds, so addresses_issue and no_unconfirmed_promise pass at 0.7 or more, and tone passes at 1.0 or more.

The test counts the cost: over the whole scenario the three judge peers make 11 System One requests, four judgments at two requests each and three council ballots at one each.

Why two requestsThe triage questions run over the customer's message and the judge's criteria run over the message and the reply, so one request cannot hold both. The judge makes the two calls in sequence and writes one Judgment.
aspace://guide/springai-jev/retry · chapter 8

A failed draft is a ticket

In the post, JevSelfRefineAdvisor retries inside one process: it judges, appends the failing criteria to the prompt, and calls the model again up to maxRepeatAttempts times. The app drops that advisor deliberately. The judge writes the next attempt as an entry, and any live drafter takes it. The ticket carries the judge's feedback(), and Drafter.prompt adds it to the next prompt under the line "A reviewer rejected the previous draft."

The judge writes the next step
if (verdict.passed()) {
    ledger.add(new Reply(draft.ticketId(), draft.customer(), draft.reply(), draft.attempt(), department));
    if ("billing".equals(department)) {
        billing.write(new BillingCase(draft.ticketId(), draft.customer(), draft.message(), draft.reply()),
                Lease.of(Duration.ofHours(12)));
    }
} else if (draft.attempt() < Support.MAX_ATTEMPTS) {
    // The retry is an entry, so any drafter may take it, and a drafter that dies holding it
    // lets it reappear. No advisor loop, no process that has to stay alive.
    inbox.write(new Ticket(draft.ticketId(), draft.customer(), draft.message(), draft.attempt() + 1,
            verdict.feedback()), Lease.of(Duration.ofHours(12)));
} else {
    ledger.add(new GaveUp(draft.ticketId(), draft.customer(), draft.attempt(), verdict.feedback()));
}
Ticketinboxattempt nfeedbackDraftdraftsattempt nreplyJudgmentverdictsattempt npassed, feedbackDrafterJudgeReplypassedGaveUpfailed, n = 2failed and n < 2: Ticket(attempt n + 1, feedback)written by the judge into inbox, with a 12 h leasethe drafter's next prompt reads:"A reviewer rejected the previous draft. Feedback: ..."JevSelfRefineAdvisor would loop inside one process;a Ticket lets any live drafter take the next attemptthe limit is Support.MAX_ATTEMPTS = 2: after thesecond failed draft the ledger gets a GaveUp
The retry loop is a ticket. Each attempt is three entries in three spaces. A failed judgment writes the next ticket and the loop continues, whichever drafter is alive. The attempt number rides on every record, so the ledger shows both drafts and both judgments of one ticket side by side.

The loop ends after 2 drafts. Support.MAX_ATTEMPTS stops the retry and the ledger gets a GaveUp that names the last feedback, so a person knows the ticket needs hand writing. In the demo and the test, FixtureHaiku's first answer to the double charge is generic, FixtureJev fails it because it shares fewer than two content words with the message, and the retry prompt, which mentions the feedback, gets a specific answer that passes.

What the test assertsT-1 attempt 1 is FAILED with addresses_issue=FAILED and a non-blank feedback, attempt 2 is PASSED, the drafts has two Draft entries with attempts 1 and 2, and the Reply is at attempt 2.
aspace://guide/springai-jev/billing · chapter 9

Exactly once: the ordered billing desk

A passed draft that Jev routed to billing becomes a BillingCase in the billing space, and the case must reach exactly one clerk. Two clerks race for every case, one on billing-a and one on billing-b. A plain lease race could hand one case to both if a partition split them, so the clerks use @OrderedTake, which routes the take through a Raft log. Each clerk submits a signed claim as a log command, every member applies the log in the same order, and the first committed claim for an entry takes it.

judge-leadwrites BillingCaseBillingCasebillingticketId, customermessage, replyTHE DESK: billing-a AND billing-b, ONE RAFT LOGbilling-abilling-clerkclaimbilling-bbilling-clerkclaimTHE LOGclaim by billing-aclaim by billing-bthe first committed claimper entry takes itmembers: [billing-a, billing-b]Billing.formDesk runs once all peers are up:each peer registers the coordinator, then binds its clerkRaft commits on a majority: two members need both up.A third clerk would let one die; this example keeps two.BillingReceiptverdictsticketId, actionhandledBycommitIndexthe losing claim findsthe entry already taken:no second receipt
The ordered billing desk. A billing case sits in the replicated billing space. Both clerks submit a signed take claim as a command in the Raft log, every member applies the log in the same order, and the first committed claim wins. The winner runs the method and completes the take with a BillingReceipt that names the clerk and the commit index.
Billing.java: the clerk and the desk
@AgentSpec(name = CLERK, description = "Opens the refund review for a billing ticket, exactly once",
        goals = {"settle billing cases"})
public static final class Clerk {
    private final String name;
    private final OrderedTakes desk;

    public Clerk(String name, OrderedTakes desk) {
        this.name = Objects.requireNonNull(name, "name");
        this.desk = Objects.requireNonNull(desk, "desk");
    }

    @OrderedTake(space = Support.BILLING, lease = "30s", pollTimeout = "1s",
            resultSpace = Support.VERDICTS, resultLease = "24h")
    public BillingReceipt settle(BillingCase billingCase) {
        return new BillingReceipt(billingCase.ticketId(), "refund review opened for " + billingCase.customer(),
                name, desk.raft().commitIndex());
    }
}

The starter binds every annotated bean as an ordinary Spring bean, but it cannot infer an ordered log's member set. Billing.formDesk therefore runs once after all nine peers are up. It reads the two billing peers' ids, builds one OrderedTakes per peer over the clerk's own attested identity, registers it with group.ordered, and then binds the clerk, which lets @OrderedTake bind on that peer.

The receipt records handledBy and the log's commit index, and the clerk that produced it signs it as billing-clerk. The demo run above committed T-1 at index 3 and T-3 at index 2, and the test run committed T-1 at 1 and T-3 at 4, so the index belongs to the log and does not count cases. The test waits three seconds after the last receipt and asserts that T-1 and T-3 each have exactly one.

What to watch forRaft commits on a majority of its members, and a desk of two has a majority of two. The desk therefore commits only while both billing peers are up: if either clerk dies, the survivor cannot commit a take and the cases wait. The option is a third clerk, a third billing peer in the member list that Billing.formDesk builds, which lets one of the three die; this example keeps two. The ordered log buys exactly-once at the price of that quorum, which is why only the billing case, the one step with money in it, goes through it.
aspace://guide/springai-jev/reduce · chapter 10

A reduce keeps the score

Every judgment also writes a QualitySample, and @SpaceReduce on the console peer folds each sample into its department's running score. The method takes the current accumulator, which is null on a key's first step, and one sample, and it returns the new accumulator.

Quality.java, and the two readers of the score
@SpaceReduce(space = Support.VERDICTS, name = NAME, key = "department", lease = "30s", accumulatorLease = "7d")
public DepartmentQuality score(DepartmentQuality current, QualitySample sample) {
    DepartmentQuality so_far = current == null ? new DepartmentQuality(sample.department(), 0, 0, 0.0) : current;
    return new DepartmentQuality(so_far.department(), so_far.judged() + 1,
            so_far.passed() + (sample.passed() ? 1 : 0), so_far.frustrationSum() + sample.frustration());
}
ELEMENTS: QualitySample, ONE PER JUDGMENTT-2 a1 technical passedfrustration 1.0T-1 a1 billing failedfrustration 1.0T-3 a1 billing passedfrustration 2.0T-1 a2 billing passedfrustration 1.0SpaceReduce, key = departmenttechnicalone ticket per key serializes its stepsstep 1: 1 judged, 1 passedAt a handoff two accumulators are visible:Reductions.current returns the newer.billingtake the sample, fold, complete: one atomic stepstep 1: 1 judged, 0 passedstep 2: 2 judged, 1 passedstep 3: 3 judged, 2 passedbilling: frustration sum 4.0, mean 1.33the accumulator is an entry: any peer reads it
A reduce keeps the score. Each judgment writes one sample. The reduce folds a sample into its department's accumulator and completes the sample in the same step, so no sample counts twice and no update is lost. The numbers are the ones the test asserts and the recorded run prints: billing 3 judged and 2 passed, technical 1 and 1. The ledger and the JevFleet.quality helper read a department's score through Reductions.current, so a handoff never shows two.

The binder takes a sample under the 30s lease, calls the method, and completes the sample with the new accumulator in one atomic step, so a sample never folds twice. A join ticket per key serializes the steps of one department, so two reducers cannot overwrite each other, and the accumulator's 7d lease is the key's idle timeout. Because the accumulator is an entry in verdicts, any peer reads it with a plain read, and the ledger prints it with the console peer's signature.

What to watch forBetween a successor's write and the predecessor's retirement two accumulators are visible, and a plain read can return the older one. The library's Reductions.current picks the highest step count from the entry tags, and both readers of the score use it. JevFleet.quality reads one department through it, and the console's Ledger collects the departments that have an accumulator and prints one quality line for each, so a handoff never puts two lines for one department in the ledger.
aspace://guide/springai-jev/council · chapter 11

Three judges, three questions, one vote

When the frustration score reaches 1.5, the judge writes an Escalation next to the Judgment. The council lead's @Propose turns each escalation into a vote with a fixed shape: the options human and bot and a quorum of three. Three councillors, one on each judge peer, read the escalation, ask Jev one Noul from their own concern, and cast a signed ballot. The lead's @OnDecision runs once when the third ballot closes the vote and writes the decision.

Council.java
@AgentSpec(name = "council-lead", description = "Puts very angry customers to the council and records its decision",
        goals = {"open votes", "record decisions"})
public static final class Lead {

    @Propose(space = Support.VERDICTS, vote = Support.COUNCIL, prefix = PREFIX, key = "ticketId",
            options = {"human", "bot"}, quorum = 3, lease = "12h", subscriptionLease = "12h")
    public String open(Escalation escalation) {
        return "Customer " + escalation.customer() + " scored " + escalation.frustration()
                + " on the frustration rubric. Should a person take over ticket " + escalation.ticketId() + "?";
    }

    @OnDecision(space = Support.COUNCIL, prefix = PREFIX, resultSpace = Support.VERDICTS, resultLease = "24h")
    public EscalationDecision record(VoteCapability.Decision decision) {
        return new EscalationDecision(decision.proposalId().substring(PREFIX.length()), decision.winner(),
                decision.tally().toString());
    }
}
judge-leadJudge, council-leadcouncilthe vote spacejudge-leadCouncillor RETENTIONjudge-bCouncillor PERSONjudge-cCouncillor RISK1 Escalation into verdictsfrustration >= 1.52 @Proposehuman:T-3, 2 options3 the proposal reaches every councillorretentionasks_for_personrisk4 each asks Jev one Noul over the customer's message5 signed @Ballot: human if the truth is 0.5 or more6 @OnDecisionthird ballot closes the voteEscalationDecision(T-3, human, {human=3, bot=0}) into verdicts
Three judges, three questions, one vote. The lead opens one vote per escalation with a fixed shape: two options and a quorum of three. Each councillor reads the escalation, asks Jev one question from its own concern, and signs one ballot. The tally and the three signatures stay in the council space, and the lead writes the decision once.

The three concerns are three different readings of the same message: whether the customer threatens to leave or dispute a charge, whether the customer asks for a person or complains that nobody answers, and whether the message mentions legal action, a bank dispute or harm. Each is a Noul with a truth value, and a councillor votes human at 0.5 or more. The ballots stay in the council space, signed by the three councillor agents on three peers, so anyone can recount them. The decision for T-3 is human with the tally {human=3, bot=0}, and the test asserts that it appears once.

What to watch forA councillor that cannot read the escalation within ten seconds returns null and abstains. With a quorum of three and three councillors, one abstention leaves the vote open, so the lead's decision waits. The record of the open vote stays in the council space for 12 h.
aspace://guide/springai-jev/fixtures · chapter 12

Running with no keys, and what the live profiles change

Both fixtures sit at the bottom of their stacks and replace one thing each. FixtureHaiku is a ChatModel, and the ModelServer calls it through exactly the path a live model uses: the drafter writes a ModelRequest entry, the server takes it, calls this bean, and returns the response as an entry. FixtureJev extends TypeSafeApi and answers systemOne in memory, so the real TypeSafeClient, the real JevJudge and the real question and answer types run unchanged above it.

THE MODEL-SERVER PEER: WHAT STANDS BEHIND ModelServerModelServertakes requests, calls one ChatModelChatModel beanthe only provider beanFixtureHaikuno profile: keyword replies, no keyAnthropicChatModelhaiku-live: ANTHROPIC_API_KEYthe bean name is haiku; with haiku-live theAnthropic auto-configuration supplies itTHE JUDGE PEERS: WHAT STANDS BEHIND Judge AND CouncillorJudge, Councillorask typed questionsJevJudgethe real classTypeSafeClientthe real clientFixtureJevno profile: TypeSafeApi in memorySystem One over HTTPjev-live: TYPESAFE_API_KEYonly the HTTP call is replaced: the questions,the judge and the answer types run unchangedthe two live profiles are independent: any mix of fixture and live
Where the fixtures sit. Each fixture replaces one thing at the very bottom of its stack: the provider's chat model on the model server, and the HTTP transport under the TypeSafe client on the judge peers. Everything above that seam, the fleet's model path, the typed questions, the judge, the spaces, runs the same code with keys and without.
Which bean each peer gets
@Configuration(proxyBeanMethods = false)
@Profile("!haiku-live")
static class FixtureHaikuConfig {
    @Bean
    ChatModel haiku() {
        return new FixtureHaiku();
    }
}

The fixtures use keyword rules so the scenario repeats. FixtureHaiku gives a double charge a generic first draft and a specific one when the prompt contains feedback:. In FixtureJev, a reply that shares fewer than two content words with the customer's message fails addresses_issue, a message containing third time, nobody, disputing or cancel everything scores as very angry, and a webhook complaint routes to technical.

The fixtures' rules
private static String reply(String text) {
    boolean retry = text.contains("feedback:");
    if (text.contains("charged twice") && !retry) {
        return "Thanks for reaching out. We will look into it and get back to you as soon as we can.";
    }
    if (text.contains("charged twice")) {
        return "I am sorry your card was charged twice for the same order. I have opened a refund review"
                + " for the duplicate charge, and the billing team will confirm the refund and its timing"
                + " with you directly.";
    }
    if (text.contains("webhook")) {
        return "I am sorry the webhook integration stopped firing after last night's update. I have opened"
                + " a priority incident with the integrations team for your stuck orders, and I will send"
                + " you their findings as soon as they confirm the cause.";
    }
    if (text.contains("third time") || text.contains("disputing")) {
        return "I am sorry this is the third time you have written and nobody has answered. I have flagged"
                + " your account for a supervisor to review the disputed charge and to cancel the services"
                + " you named today, and a person will contact you about both.";
    }
    return "Thank you for your message. I have passed it to the right team and will follow up with you.";
}

What the live profiles change

  • haiku-live on the model-server peer sets spring.ai.model.chat: anthropic and the Anthropic key, so Spring AI's Anthropic auto-configuration supplies the ChatModel bean in place of FixtureHaiku. The model is claude-haiku-4-5-20251001 with max-tokens of 400.
  • jev-live on the three judge peers sets spring.ai.typesafe.api-key, so the spring-ai-starter-typesafe starter contributes the TypeSafeClient and FixtureJevConfig drops out.
  • The launcher reads ANTHROPIC_API_KEY and TYPESAFE_API_KEY, and adds a live profile only to the peers that hold that key. The drafters, the clerks and the console get no profile that mentions either variable, and the test runs both fixtures.
  • Everything above the seam is the same code with and without keys: the model-requests path, the typed questions, the signed ledger and the council. Live runs change the answers and the latency, and the shape of the flow stays the same.
aspace://guide/springai-jev/dies · chapter 13

When something dies

The test tells one failure story, and it tells it with the real take lease. A CrashSwitch arms a crash: the first drafter that takes T-1 holds the take and waits. The test then closes that drafter's Spring context, which is the event the fleet sees when a process dies. Nothing renews the take, so the ticket reappears after 20s and the surviving drafter takes it.

ACT ONE, T-1: THE FIRST DRAFTER TO TAKE THE TICKET DIES HOLDING IT (NOT TO SCALE)drafter-adrafter-bmodel-serverjudge-leadbilling-a/btakes T-1closedtakes T-1serves 1draft 1FAILEDtakes #2serves 2draft 2PASSEDreceiptlease 20s lapses
A drafter dies holding a ticket. drafter-a takes T-1 and the test closes its Spring context, which is the event the fleet sees when a process dies. Nothing renews the lease, so the ticket reappears after 20s and drafter-b takes it. Every step after that is the ordinary path: the judge fails the generic draft, the retry ticket goes to the surviving drafter, and the second draft passes.
JevFleetTest.java: act one
// Act one: a double charge. The first drafter to take it dies holding it; the ticket
// reappears when its lease lapses and the other drafter writes the draft.
fleet.submit("T-1", "Dana", "My card was charged twice for the same order and I want the duplicate refunded.");
assertThat(crash.awaitTake(Duration.ofSeconds(60))).as("a drafter took T-1").isTrue();
String victim = crash.victim();
String survivor = victim.equals("drafter-a") ? "drafter-b" : "drafter-a";
crash.kill();
fleet.kill(victim);

Draft firstDraft = JevFleet.await(() -> JevFleet.first(drafts, Draft.class, "T-1"), Duration.ofSeconds(120))
        .orElseThrow();
assertThat(firstDraft.draftedBy()).as("the surviving drafter finished the job").isEqualTo(survivor);
assertThat(firstDraft.attempt()).isEqualTo(1);

The victim never reaches the model, which is why the model server answers four requests and the killed drafter contributes none: T-1 attempt 1, T-1 attempt 2, T-2 and T-3. The whole scenario takes about 33 seconds, and at least 20 of those are the lease running out. Everything after the lapse is the ordinary path, and the judge never learns a process died.

A model call that is too slow

A drafter can also lose a ticket without dying: its model call can run long. The test does not exercise this, and the code answers it by construction. The wait is 15s and the take is 20s, and TakeLeaseAdvisor renews the take once, before the call, so the call fails 5 seconds before the take would lapse. The failed call throws FleetModelException out of the draft method, the binder logs the failure and does not complete the take, and the ticket reappears for whichever drafter is alive. The slow drafter has stopped working on the ticket by then, so two drafters never draft it together. Chapter 6 shows the check that keeps the wait shorter than the take.

The other peers

The test kills a drafter because the lease race alone protects that role. The table says what the death of each peer means in this fleet, as far as the code in the chapters above shows.

Peer Instances If it dies
drafter-a, drafter-b2the ticket reappears after 20s and the other drafter takes it. This is the tested path.
model-server1no draft completes, because it is a single instance. A second server peer would take a waiting request after the dead server's 2m take lapses, with the next attempt number. With one server, nothing is answered until it returns.
billing-a, billing-b2a desk of two commits only while both are up, because Raft commits on a majority, so billing cases wait until the dead clerk returns. A third clerk is the option, as chapter 9 explains.
judge-lead1a single instance that hosts the judge, the council lead and one councillor, so judging stops and no vote can reach a quorum of three until it returns.
console1a single instance: the reducer and the ledger view stop. The entries in the spaces stay.
aspace://guide/springai-jev/running · chapter 14

Running and testing it

Every dependency resolves from Maven Central, so the first mvn needs the network and no checkout of the core. The pom pins the library version once and imports the published BOM.

pom.xml: the coordinates
<properties>
  <maven.compiler.release>21</maven.compiler.release>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <agentspaces.version>0.5.0</agentspaces.version>
  <spring-ai.version>2.0.1</spring-ai.version>
  <spring-boot.version>4.1.1</spring-boot.version>
  <typesafe.version>0.1.0</typesafe.version>
  <jackson.version>2.21.7</jackson.version>
  <jackson3.version>3.1.7</jackson3.version>
  <junit.version>5.13.4</junit.version>
  <assertj.version>3.27.7</assertj.version>
  <example.main>ai.badmonkey.agentspaces.examples.jev.JevFleet</example.main>
</properties>
mvn -q verify                                    # the fleet test on the fixture model and the fixture Jev
mvn -q compile exec:java                         # the demo: nine peers, three tickets, the ledger, console at http://localhost:7595/
ANTHROPIC_API_KEY=... TYPESAFE_API_KEY=... mvn -q compile exec:java    # live: Claude Haiku on the model server, Jev on the judges

The test is one method, typedJudgmentRunsAcrossTheFleetWithRetriesExactlyOnceBillingAndACouncil, and it runs the nine peers over tcp on free ports with both fixtures. It takes about half a minute because it waits out the 20s lease of the killed drafter. It needs no keys and no network once the dependencies are in the local repository. This is the run of 2026-11-04, with the numbers the test prints at its end.

mvn verify, recorded 2026-11-04
[INFO] Running ai.badmonkey.agentspaces.examples.jev.JevFleetTest

measured on the fixture path:
  fleet of 9 peers started in 1539 ms
  T-2 (one draft, one judgment) from inbox to approved reply: 928 ms
  model requests served by the model-server: 4 (fixture Haiku calls 4)
  System One requests across the three judge peers: 11
  whole scenario, including the 20 s lease lapse of the killed drafter: 32764 ms
  ledger lines: 12

[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 32.81 s -- in ai.badmonkey.agentspaces.examples.jev.JevFleetTest
[INFO] BUILD SUCCESS
✓ 1 test · 32.81 s · fixture Haiku, fixture Jev

What the test asserts, requirement by requirement

Requirement What the test asserts
JV-01The drafter holds no model credential; only the model-server peer answers model requestsThe survivor drafter's context has no FixtureHaiku bean and the model-server's has one. The launcher sets grants.model-serve on every peer in code; the test prints ModelServer.served() and the fixture's call count and does not assert them
JV-02The judge runs the three typed questions and a JevJudge verdict per draftT-1 attempt 1 carries department billing, frustration label Frustrated, and a verdict summary with addresses_issue=FAILED; T-3 carries frustration label Very angry
JV-03Judgments are signed, leased entries any peer readsThe ledger, read on the console peer, lists every record with its issuer (ยท by), and the judgment, council and receipt lines name judge@, council-lead@ or billing-clerk@. The AGENT_ATTESTED level is printed in each line and not asserted
JV-04A failed draft reappears for a second attempt with the feedback, through the spaceT-1 attempt 1 FAILED with addresses_issue=FAILED and non-empty feedback; attempt 2 PASSED; two Draft entries, attempts 1 and 2; one Reply at attempt 2
JV-05A drafter killed mid-draft loses its lease and the other drafter finishes the ticket; a slow model call cannot outlive the takeThe first taker is closed while holding T-1; the Draft is by the survivor. The drafters start only because the model wait (15 s) is shorter than the take lease (20 s), which the drafter bean checks; a longer wait fails the fleet's start
JV-06A ticket routed to billing is taken exactly onceOne BillingReceipt for T-1 and one for T-3 after a settle, by a clerk on billing-a or billing-b
JV-07A running quality score per departmentDepartmentQuality billing: 3 judged, 2 passed; technical: 1 judged, 1 passed, each read with Reductions.current, the newest accumulator. The ledger prints one quality line per department
JV-08A council of three judge peers decides whether a very angry customer gets a personT-3 scores Very angry; EscalationDecision is human with tally human=3, exactly once
JV-09The TypeSafe key lives on the judge peers onlyThe survivor drafter's context has no FixtureJev bean; the judge-lead's has one
JV-10No keys needed; live when setThe test runs both fixtures; JevFleet.main adds the live profiles when the environment variables are set (not asserted)

The timings vary with the machine and its load. The counts do not: four model requests served, eleven System One requests, twelve ledger lines, and exactly one receipt per billing case.

Going liveWith ANTHROPIC_API_KEY set, Haiku drafts on the model-server peer and the drafters stay keyless. With TYPESAFE_API_KEY set, the three judge peers call Jev and the fixture drafts. The pom uses version 0.1.0 of the TypeSafe starter and library, the version the post names. The project's newest release is 0.4.0, and the test passes against it with -Dtypesafe.version=0.4.0. Everything else, Spring Boot 4.1.1 and Spring AI 2.0.1 included, is pinned in the pom.
aspace://guide/springai-jev/next

Where to go next

THE FIVE LAYERS, AND WHAT SPRING AI AND JEV STANDS ONagents and the binderten bound agents in six classes, one binder per peerLayer 4 capabilitiesvote, ordered log, aggregate, content, remote actionsSpring AI and Jevvote on council, ordered log on billingLayer 3 spacesreplicated tuple spaces, leases, strategiesSpring AI and Jevsix spaces: leased takes, notify, reduce, retry ticketsLayer 2 discoverycards, advertisements, locatorsSpring AI and Jevagent cards on gossip, no agent reads themLayer 1 peeringmembership, gossip, transportsSpring AI and Jevnine peers over loopback tcp, tick 250 msLayer 0 identityEd25519 keys, signed documents, groupsSpring AI and Jevan Ed25519 key per peer and per agent, one grant
The layers under the app. Each layer rests on the one below. A highlighted layer is one the app uses directly; the rest still run beneath it and need no configuration here.