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.
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 runs | one application and one ChatClient call chain | 9 Spring Boot peers that read one agentspaces: subtree |
| Who holds the Haiku key | the application that calls the model | the model-server peer only. Drafters hold none and send a ModelRequest entry |
| Who holds the Jev key | the same application | the three judge peers only |
| The retry | JevSelfRefineAdvisor loops inside the call | the judge writes Ticket(attempt + 1, feedback) into inbox and any live drafter takes it |
| What a judgment is | a JevVerdict object in memory | a signed Judgment entry in verdicts that any peer can read |
| A worker dies mid-draft | the call fails with the process | the take lease lapses after 20s and another drafter takes the ticket |
| After the verdict | the post stops at the judge and the retry | billing 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.
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.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.
| Agent and class | Peers | Annotation | Reads | Writes |
|---|---|---|---|---|
model-serverModelServer from agentspaces-springai | model-server | a lifecycle bean, not an annotated agent | ModelRequest from model-requests (take lease 2m) | ModelResponse, ModelAttempt |
drafterDrafter | drafter-a, drafter-b | @SpaceTake(inbox, lease 20s, resultSpace drafts, resultLease 12h) | Ticket | Draft; through its ChatClient: ModelRequest, and the ModelResponse it waits for |
judgeJudge | judge-lead | @SpaceNotify(drafts, resultSpace verdicts, resultLease 24h) | Draft | Judgment, QualitySample, Reply, Escalation, GaveUp in verdicts; Ticket in inbox; BillingCase in billing |
council-leadCouncil.Lead | judge-lead | @Propose and @OnDecision | Escalation and the votes | Proposal in council; EscalationDecision in verdicts |
councillorCouncil.Councillor | judge-lead (RETENTION), judge-b (PERSON), judge-c (RISK) | @Ballot(council) | Proposal, then the Escalation in verdicts | one signed ballot |
billing-clerkBilling.Clerk | billing-a, billing-b | @OrderedTake(billing, lease 30s, resultSpace verdicts) | BillingCase | BillingReceipt |
qualityQuality | console | @SpaceReduce(verdicts, key department, lease 30s, idle 7d) | QualitySample | DepartmentQuality |
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.
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.
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.
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.spring: config: activate: on-profile: model-server agentspaces: springai: model-server: enabled: true models: ["${example.haiku-model}"] lease: 2m
spring: config: activate: on-profile: drafter agentspaces: springai: model-client: enabled: true model: ${example.haiku-model} # Shorter than the drafter's 20 s ticket take (Drafter.LEASE). TakeLeaseAdvisor renews the take # once before the call, so a call that waited longer could outlive it and let the other drafter # claim the ticket. A wait that runs out fails the draft, and the ticket reappears. timeout: 15s
spring: config: activate: on-profile: haiku-live ai: model: chat: anthropic anthropic: api-key: ${ANTHROPIC_API_KEY} chat: options: model: ${example.haiku-model} max-tokens: 400
spring: config: activate: on-profile: jev-live ai: typesafe: api-key: ${TYPESAFE_API_KEY}
spring: config: activate: on-profile: console agentspaces: console: enabled: true port: ${example.console-port:7595} fleet-name: jev-fleet
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.
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; }
public static Map<String, Object> node(String name, int port, int seedPort, Map<String, Object> extra) { Map<String, Object> properties = new HashMap<>(Map.of( "example.peer-name", name, "agentspaces.bind", "127.0.0.1:" + port)); if (seedPort > 0) { // A list bound from a higher-priority source replaces the YAML's list wholesale, so the // seed travels as a scalar the YAML's seeds entry expands. properties.put("example.seeds", "127.0.0.1:" + seedPort); } if (name.startsWith("judge-")) { properties.put("example.concern", switch (name) { case "judge-lead" -> "RETENTION"; case "judge-b" -> "PERSON"; default -> "RISK"; }); } properties.putAll(extra); return properties; }
public static List<String> profiles(String name, boolean haikuLive, boolean jevLive) { List<String> profiles = new ArrayList<>(); switch (name) { case "model-server" -> { profiles.add("model-server"); if (haikuLive) { profiles.add("haiku-live"); } } case "drafter-a", "drafter-b" -> profiles.add("drafter"); case "judge-lead", "judge-b", "judge-c" -> { if (jevLive) { profiles.add("jev-live"); } } case "console" -> profiles.add("console"); default -> { } } return profiles; }
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.
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 |
|---|---|---|---|
inbox | Ticket, 12 h | the console peer (a customer message), the judge (a retry) | the drafters, with a take lease of 20s |
drafts | Draft, 12h | the drafters | the judge, by notification |
verdicts | Judgment, QualitySample, Reply, Escalation, GaveUp, EscalationDecision and BillingReceipt, each 24h; DepartmentQuality accumulators, 7d idle | the judge, the council lead, the clerks, the reducer | the reducer, the lead, the councillors, the ledger |
council | the vote's proposals and signed ballots, 12 h | the lead and the councillors | every council member |
billing | BillingCase, 12 h | the judge | the clerks, through the ordered log |
model-requests | ModelRequest 45 s (the wait plus 30 s), ModelResponse 10 min, ModelAttempt 10 min | the drafters, the model server | the model server, the drafters |
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.
private static String by(Space.Entry<?> entry) { return " ยท by " + entry.issuer().localName() + "@" + entry.issuer().peer().display() + " (" + entry.attestation() + ")"; }
public record Judgment(String ticketId, int attempt, double urgency, String department, double departmentConfidence, double frustration, String frustrationLabel, boolean passed, String summary, String feedback, String judgedBy) { }
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.
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.
public void submit(String ticketId, String customer, String message) { space(Support.INBOX).write(new Ticket(ticketId, customer, message, 1, ""), Lease.of(Duration.ofHours(12))); }
@SpaceTake(space = Support.INBOX, lease = LEASE_SECONDS + "s", pollTimeout = "300ms", resultSpace = Support.DRAFTS, resultLease = "12h") public Draft draft(Ticket ticket) { hook.beforeDrafting(name, ticket); String reply = chat.prompt().system(SYSTEM).user(prompt(ticket)).call().content(); if (reply == null || reply.isBlank()) { throw new IllegalStateException("the model returned no reply for " + ticket.ticketId()); } return new Draft(ticket.ticketId(), ticket.customer(), ticket.message(), reply.strip(), ticket.attempt(), name); }
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.
@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.
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)
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.
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.
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)); } }
spring: config: activate: on-profile: drafter agentspaces: springai: model-client: enabled: true model: ${example.haiku-model} # Shorter than the drafter's 20 s ticket take (Drafter.LEASE). TakeLeaseAdvisor renews the take # once before the call, so a call that waited longer could outlive it and let the other drafter # claim the ticket. A wait that runs out fails the draft, and the ticket reappears. timeout: 15s
spring: config: activate: on-profile: model-server agentspaces: springai: model-server: enabled: true models: ["${example.haiku-model}"] lease: 2m
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.
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.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())); } }); }
private boolean trusted(AgentId issuer, ModelResponse response) { return issuer != null && authorizer.permits(issuer, Authorizer.Operation.MODEL_SERVE, response.model() == null ? "" : response.model()); }
private void loop(Template<ModelRequest> template) { while (running) { Optional<TakenEntry<ModelRequest>> taken; try { taken = space.take(template, Lease.of(settings.lease()), Duration.ofSeconds(1)); } catch (RuntimeException e) { if (!running) { return; } LOG.log(System.Logger.Level.WARNING, "model-server: take failed", e); continue; } taken.ifPresent(this::serve); } }
private void answer(TakenEntry<ModelRequest> taken, ModelResponse response) { space.complete(taken, response, Lease.of(settings.responseLease())); served.incrementAndGet(); }
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.
// 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.
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.public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) { current.get().ifPresent(TakeLeaseAdvisor::renew); return chain.nextCall(request); }
public static final int ORDER = ToolCallingAdvisor.DEFAULT_ORDER + 100;
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.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.
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); }
public Judge(String name, TypeSafeClient jev) { this.name = Objects.requireNonNull(name, "name"); this.jev = Objects.requireNonNull(jev, "jev"); this.judge = JevJudge.builder(jev) .noul("addresses_issue", Noul.of("Does the answer address the specific problem the customer raised?"), 0.7) .noul("no_unconfirmed_promise", Noul.of("Does the answer avoid promising a specific outcome the company has not confirmed?"), 0.7) .score("tone", Score.of("What is the tone of the answer?", "Curt", "Neutral", "Courteous"), 1.0) .build(); }
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.
Judgment.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."
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())); }
static String prompt(Ticket ticket) { String prompt = "Customer " + ticket.customer() + " wrote: " + ticket.message(); if (ticket.attempt() > 1) { prompt += "\n\nA reviewer rejected the previous draft. Feedback: " + ticket.feedback() + "\nWrite a new reply that fixes this."; } return prompt; }
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.
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.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.
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.@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()); } }
/** * Forms the desk over the billing peers. The starter cannot infer an ordered log's * member set, so this runs once all the billing peers are up: each registers the * coordinator for the billing space with the same fixed member list, taking under the * clerk's own attested identity, and then binds its clerk, which is what lets * {@code @OrderedTake} bind on that peer. * * @param billingPeers the billing peers' application contexts, in a stable order * @return the seats, one per peer */ public static List<Seat> formDesk(List<ConfigurableApplicationContext> billingPeers) { List<PeerId> members = billingPeers.stream() .map(context -> context.getBean(PeerIdentity.class).peerId()).toList(); List<Seat> seats = new ArrayList<>(); long seed = 4100L; for (ConfigurableApplicationContext context : billingPeers) { AgentSpaces.GroupContext group = context.getBean(AgentSpaces.class).group(Support.GROUP); PeerIdentity identity = context.getBean(PeerIdentity.class); String name = context.getEnvironment().getProperty("example.peer-name", "billing"); ReplicatedSpace billing = (ReplicatedSpace) group.space(Support.BILLING); AgentIdentity clerk = context.getBean(AgentIdentityFactory.class).identityFor(CLERK); OrderedTakes desk = OrderedTakes.over(group.pipes(), CborCodec.defaultCodec(), identity, clerk, members, InstantSource.system(), seed++, billing); group.ordered(Support.BILLING, desk); seats.add(new Seat(name, desk, group.bind(new Clerk(name, desk)))); } return seats; }
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.
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.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.
@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()); }
/** * The current quality score of a department: the accumulator with the most steps. Between a * successor's write and its predecessor's retirement two are visible, and {@code Reductions.current} * returns the newer. */ public static Optional<DepartmentQuality> quality(Space verdicts, String department) { return Reductions.current(verdicts, DepartmentQuality.class, Quality.NAME, department) .map(Space.Entry::value); }
// One score per department: between a successor's write and its predecessor's retirement a // reduce shows two accumulators, and Reductions.current returns the newer. new TreeSet<>(verdicts.readAll(Template.of(DepartmentQuality.class), 100).stream() .map(DepartmentQuality::department).toList()).forEach(department -> Reductions.current(verdicts, DepartmentQuality.class, Quality.NAME, department).ifPresent(e -> lines.add( String.format(Locale.ROOT, "quality %s: %d judged, %d passed, mean frustration %.2f%s", e.value().department(), e.value().judged(), e.value().passed(), e.value().judged() == 0 ? 0.0 : e.value().frustrationSum() / e.value().judged(), by(e)))));
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.
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.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.
@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()); } }
@Ballot(space = Support.COUNCIL, prefix = PREFIX, lease = "12h") public String vote(VoteCapability.Proposal proposal) { String ticketId = proposal.proposalId().substring(PREFIX.length()); Escalation escalation = verdicts.read(Template.of(Escalation.class).where("ticketId", eq(ticketId)), Duration.ofSeconds(10)).orElse(null); if (escalation == null) { return null; // nothing on the record: abstain } double truth = jev.systemOne(escalation.message(), Map.of(concern.question, Noul.of(concern.text))) .noulValue(concern.question); return truth >= 0.5 ? "human" : "bot"; }
public enum Concern { RETENTION("retention", "Is the customer threatening to leave, cancel, or dispute a charge?"), PERSON("asks_for_person", "Is the customer asking for a person, or complaining that nobody has answered?"), RISK("risk", "Does the message mention legal action, a bank dispute, or harm?"); final String question; final String text; Concern(String question, String text) { this.question = question; this.text = text; } }
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.
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.
@Configuration(proxyBeanMethods = false) @Profile("!haiku-live") static class FixtureHaikuConfig { @Bean ChatModel haiku() { return new FixtureHaiku(); } }
@Configuration(proxyBeanMethods = false) @Profile("!jev-live") static class FixtureJevConfig { @Bean FixtureJev fixtureJev() { return new FixtureJev(); } @Bean TypeSafeClient typeSafeClient(FixtureJev fixture) { return fixture.client(); } }
public static List<String> profiles(String name, boolean haikuLive, boolean jevLive) { List<String> profiles = new ArrayList<>(); switch (name) { case "model-server" -> { profiles.add("model-server"); if (haikuLive) { profiles.add("haiku-live"); } } case "drafter-a", "drafter-b" -> profiles.add("drafter"); case "judge-lead", "judge-b", "judge-c" -> { if (jevLive) { profiles.add("jev-live"); } } case "console" -> profiles.add("console"); default -> { } } return profiles; }
boolean haikuLive = System.getenv("ANTHROPIC_API_KEY") != null && !System.getenv("ANTHROPIC_API_KEY").isBlank(); boolean jevLive = System.getenv("TYPESAFE_API_KEY") != null && !System.getenv("TYPESAFE_API_KEY").isBlank();
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.
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."; }
private static Answer answer(String name, Question question, String message, String reply) { return switch (name) { // The triage questions of the original post, over the customer's message. case "is_urgent" -> noul(any(message, "stuck", "third time", "failing", "twice", "stopped")); case "department" -> department(message); case "frustration" -> frustration((Score) question, message); // The judge's criteria, over the reply. case "addresses_issue" -> noul(sharedWords(message, reply) >= 2); case "no_unconfirmed_promise" -> noul(!any(reply, "guarantee", "refunded today", "immediately refund")); case "tone" -> score((Score) question, any(reply, "sorry") ? 2.0 : 1.0); // The council's concerns, over the customer's message. case "retention" -> noul(any(message, "cancel", "leave", "disputing", "switch")); case "asks_for_person" -> noul(any(message, "nobody answers", "third time", "speak to", "a person")); case "risk" -> noul(any(message, "legal", "bank", "disputing", "lawyer")); default -> switch (question) { case Noul n -> new NoulAnswer(0.5); case Choice c -> choice(c.criteria().keySet().iterator().next(), c, 0.5); case Score s -> score(s, 0.0); default -> throw new IllegalArgumentException("unknown question type " + question.typeName()); }; }; }
What the live profiles change
haiku-liveon the model-server peer setsspring.ai.model.chat: anthropicand the Anthropic key, so Spring AI's Anthropic auto-configuration supplies theChatModelbean in place ofFixtureHaiku. The model isclaude-haiku-4-5-20251001withmax-tokensof 400.jev-liveon the three judge peers setsspring.ai.typesafe.api-key, so thespring-ai-starter-typesafestarter contributes theTypeSafeClientandFixtureJevConfigdrops out.- The launcher reads
ANTHROPIC_API_KEYandTYPESAFE_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.
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: 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);
public void beforeDrafting(String worker, Ticket ticket) { synchronized (this) { if (victim != null) { return; } victim = worker; } armed.countDown(); long deadline = System.nanoTime() + Duration.ofSeconds(60).toNanos(); while (!killed && System.nanoTime() < deadline) { try { Thread.sleep(50); } catch (InterruptedException e) { // The binder interrupts its worker when the peer closes: that is the death. Thread.currentThread().interrupt(); killed = true; } } if (killed) { throw new IllegalStateException(worker + " died mid-draft"); } }
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-b | 2 | the ticket reappears after 20s and the other drafter takes it. This is the tested path. |
model-server | 1 | no 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-b | 2 | a 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-lead | 1 | a 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. |
console | 1 | a single instance: the reducer and the ledger view stop. The entries in the spaces stay. |
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.
<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>
<!-- The published AgentSpaces BOM. --> <dependency> <groupId>ai.badmonkey.agentspaces</groupId> <artifactId>agentspaces-dependencies</artifactId> <version>${agentspaces.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies>
<!-- AgentSpaces: the Spring Boot starter wires the peer from application.yml and binds the annotated beans; the capabilities module supplies the ordered log the billing desk forms in code; the console serves the ledger. Versions come from the BOM. --> <dependency><groupId>ai.badmonkey.agentspaces</groupId><artifactId>agentspaces-spring-boot-starter</artifactId></dependency> <dependency><groupId>ai.badmonkey.agentspaces</groupId><artifactId>agentspaces-capabilities</artifactId></dependency> <dependency><groupId>ai.badmonkey.agentspaces</groupId><artifactId>agentspaces-console</artifactId></dependency> <!-- AgentSpaces for Spring AI: FleetChatModel on the drafters, ModelServer on the model-server peer, TakeLeaseAdvisor on every worker. --> <dependency> <groupId>ai.badmonkey.agentspaces</groupId> <artifactId>agentspaces-springai</artifactId> <version>${agentspaces.version}</version> </dependency>
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.
[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
What the test asserts, requirement by requirement
| Requirement | What the test asserts | |
|---|---|---|
| JV-01 | The drafter holds no model credential; only the model-server peer answers model requests | The 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-02 | The judge runs the three typed questions and a JevJudge verdict per draft | T-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-03 | Judgments are signed, leased entries any peer reads | The 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-04 | A failed draft reappears for a second attempt with the feedback, through the space | T-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-05 | A drafter killed mid-draft loses its lease and the other drafter finishes the ticket; a slow model call cannot outlive the take | The 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-06 | A ticket routed to billing is taken exactly once | One BillingReceipt for T-1 and one for T-3 after a settle, by a clerk on billing-a or billing-b |
| JV-07 | A running quality score per department | DepartmentQuality 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-08 | A council of three judge peers decides whether a very angry customer gets a person | T-3 scores Very angry; EscalationDecision is human with tally human=3, exactly once |
| JV-09 | The TypeSafe key lives on the judge peers only | The survivor drafter's context has no FixtureJev bean; the judge-lead's has one |
| JV-10 | No keys needed; live when set | The 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.
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.Where to go next
- The developer guide explains each primitive this app uses:
@SpaceTake,@SpaceNotify,@OrderedTake,@SpaceReduce,@Propose, and the Spring AI chapter, including the model split that FleetChatModel and ModelServer implement. - The workflow guide names the patterns in this app: exactly once, decide by vote, and join and reduce.
- The security chapter covers the profiles behind
dev-localand themodel-servegrant. - Other example guides: Party Bus uses the same mechanisms across 21 peers, and Superfriends mixes three model frameworks in one fleet.
- The app's own
BLOG-DRAFT.mddraft turns this walk-through into a post for Spring developers.