aspace://guide/code-fleet

Code Fleet

A repository's issues become task entries and a fleet of coding agents bids for them through the AUCTION strategy. Each coder prices an issue from its declared expertise and cost, the lowest bid keeps the claim, and review agents take the finished changes and report CI. A worker that dies mid-task lets its lease lapse, and the work comes back for someone else. The guide slices every code window from the app's sources.

agentspaces-code-fleet 0.6.0AgentSpaces 0.6.0SPEC v0.1.33Java 216 peers · 5 agents · 2 spacesone JVM, real TCP on loopbackno keys, no modelApache 2.0
The auctionWhen a worker diesRun it
aspace://guide/code-fleet/the-idea · chapter 1

The idea: work that bids for itself

Code Fleet is the coding-swarm scenario in one 443-line class. A repository's issues become Issue entries in a replicated space. Three coding agents, each on a peer of its own, price every issue with a cost model and claim the one they can do most cheaply. The space keeps the lowest bid, the winning coder does the work, and two review agents take the finished changes and report CI. The app contains no dispatcher, no queue broker and no scheduler: the allocation falls out of three bid functions and the claim rule the space applies to them.

The economics make the result easy to read. The two specialists price their own area at 3 per unit of difficulty and everything else at 9. The sweeper has no specialty and bids 6 per unit on every issue, so it takes the mechanical infra work while the specialists take their own areas. The demo then kills the sweeper on its third take. Its lease lapses after 5 seconds, the issue comes back, and the two specialists, the only bidders left, take it at 36, three times their own rate.

Three things make the example worth reading. Capacity routes itself to the work it fits, which is the point of the AUCTION strategy. The work survives its workers, because a take is a lease and a lapsed lease sends the entry back. And the whole allocation stays legible afterwards: every winner writes its result into the issues space under its own key, so the space is the ledger of who did what at what price.

THE FIVE LAYERS, AND WHAT CODE FLEET STANDS ONagents and the binder3 coders and 2 reviewers: @BidFunction, @SpaceTake, @SpaceRef on plain classesLayer 4 capabilitiesvote, ordered log, aggregate, content, remote actionsLayer 3 spacesreplicated tuple spaces, leases, strategiesCode Fleetissues (AUCTION), changes (LEASE_RACE), per-agent viewsLayer 2 discoverycards, advertisements, locatorsLayer 1 peeringmembership, gossip, transportsCode Fleet6 peers over TCP, one seed dial, a 250 ms tickLayer 0 identityEd25519 keys, signed documents, groupsCode Fleeta key per peer and a certified key per agent (24 h)
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.
What you needJDK 21 and Maven. The AgentSpaces 0.6.0 libraries resolve from Maven Central. The app calls no model and needs no key, so the demo and the test run offline on loopback.
aspace://guide/code-fleet/cast · chapter 2

The cast: three coders, two reviewers, one coordinator

The group has six peers and five agents. Each agent is a plain Java object annotated for the binder: the Coder and the Reviewer are the only two agent classes. The coordinator is a peer with no agent on it. The demo's main and the test play that role by writing issues and reading CI results directly on its replicas.

Agent Class and annotations Peers in the demo Reads and writes
coordinator (no agent)the demo's main and the test call issues().write(...) and changes().readAll(...)coordinator :7571, the seedwrites Issue to issues (10 min lease, peer-signed); reads CiResult and the CodeChange copies in changes, and the CodeChange results in issues
coder (three)CodeFleet.Coder; @AgentSpec(name = "coder", goals = {"code"}), @BidFunction(space = issues), @SpaceTake(space = issues, lease = "5s"), @SpaceRef(changes)coder-frontend :7572
coder-backend :7573
coder-sweeper :7574
takes Issue from issues; writes CodeChange to issues as the completion result, and a copy to changes
reviewer (two)CodeFleet.Reviewer; @AgentSpec(name = "reviewer", goals = {"review"}), @SpaceTake(space = changes, lease = "5s"), @SpaceRef(changes)review-a :7575
review-b :7576
takes CodeChange from changes; writes Review as the completion result, and a CiResult on approval
ONE GROUP, code-fleet: 6 PEERS, 5 AGENTS, A REPLICA OF BOTH SPACES ON EVERY PEERcoordinator:7571 the seedno agent boundwrites 9 Issue entries, reads CiResultissues space (AUCTION, settle 250 ms): Issue in, the lowest bidder takes itcoder-frontend:7572agent coder, own certified keybids 3 per unit, x3 off "frontend"@SpaceTake issues, lease 5 scoder-backend:7573agent coder, own certified keybids 3 per unit, x3 off "backend"@SpaceTake issues, lease 5 scoder-sweeper:7574agent coder, own certified keybids 2 per unit, x3 on every issue@SpaceTake issues, lease 5 sdies on its take after 2 changeschanges space (LEASE_RACE, settle 150 ms): a CodeChange copy in, whichever reviewer is free takes itreview-a:7575agent reviewer, own certified key@SpaceTake changes, lease 5 sapproves a change that costs at most 100review-b:7576agent reviewer, own certified key@SpaceTake changes, lease 5 sapproves a change that costs at most 100Every peer runs both replicas. The agents sit on five of the peers; the coordinator carries none.
The cast. Six peers in one JVM in the demo and the test, each with its own key and its own replica of both spaces. The coordinator writes the issues and reads the CI results. A coder prices and takes from the issues space and hands a copy of its change to the changes space. A reviewer takes that copy. No agent talks to another agent: every arrow is an entry in a space.

The three coders differ only in the numbers handed to costModel. The frontend and backend coders carry an expertise string and a price of 3 per unit. The sweeper carries the expertise "any", a price of 2 per unit, and a limit of 2 completed changes, after which its next take fails on purpose (chapter 10). Both reviewers carry a skill of 10, which sets the largest cost they approve. Every take annotation also names a poll timeout of 2 s and a result lease of 1 h: a take loop polls for 2 s and polls again, and a completion's result entry lives for 1 h.

CodeFleet.java: binding the agents
/**
 * Binds a coder on its peer.
 *
 * @param peer      the coder's peer
 * @param costModel its bid
 * @param dieAfter  changes to complete before dying mid-take, or -1 to live
 * @return the bound coder; close it to stop it, or ask it whether it died
 */
public static Coder runCoder(Peer peer, ToDoubleFunction<Object> costModel,
                             int dieAfter) {
    Coder coder = new Coder(peer.name(), costModel, dieAfter);
    coder.binding = peer.group().bind(coder);
    return coder;
}
✓ one agent per peer · the sweeper is told to die after two changes · two reviewers of skill 10
One bid function per space per peerA replicated space asks one cost function. The binder refuses a second @BidFunction on the same space of one peer, by name, so each coder sits on its own peer. The reviewers bind no bid function at all, because only an AUCTION space consults one and they take from a LEASE_RACE space.
aspace://guide/code-fleet/forming · chapter 3

How the fleet forms and how work finds a coder

Every peer builds the same group advertisement from the same literal founding, listens on a TCP port, and dials one seed. The first peer to start, the coordinator, is the seed and dials nobody. The other five dial it, learn the other members through it, and open their replicas of the two spaces before the first tick.

HOW A PEER JOINS: group code-fleet, founding the text "code-fleet-v1"coder-sweeper:7574coordinator:7571, the seedfrontend, backendalready members1 dial the seedconfigured seed 127.0.0.1:7571 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 rumorsStep 4 carries peer ads only: the app registers its group without a DiscoveryService, so no agent card and no space ad goes out.Step 5 finds each replica by space name: every peer builds issues and changes before it starts ticking.
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. Code Fleet publishes no cards, so there are none to hear. Its founding is a literal text: the code fixes the group id, every peer dials the seed, and nothing asks for the group by id.
Setting Value in the app Where it comes from
group namecode-fleetGroupAdvertisement in CodeFleet.group()
foundingthe literal text code-fleet-v1; the group id is the base58 SHA-256 of those bytesGroupId.fromFounding(...)
membership policyOPEN, anyone who reaches a seed joinsthe same advertisement
advertised default strategyAUCTION; each space still declares its own (chapter 4)the same advertisement
seedthe coordinator at 127.0.0.1:7571 in the demo; the test takes a free port per peer and passes the first as the seedstartPeer(name, port, seedPort)
transportTCP only, one TcpTransport per peer, listening on 127.0.0.1node.listen(...)
securitya fresh Ed25519 identity per peer, every frame signed (the node's default channel authentication), plain TCP without TLSPeerIdentity.generate(), PeerNode.builder(identity).build()
membership tuningmember ttl 30 s, ping timeout 2 s, 2 indirect probes, one probe per secondGroupMembership.Config
gossipfanout 3, period 1 s, the advertisement's defaultsGossipParameters.defaults()
tick250 msnode.startTicking(...)

A literal founding is the simple way to fix a group in code, and it has one consequence worth knowing: nothing can ask for the group by its id, because no signed founding document exists to serve. Every peer dials the seed, which is why startPeer takes the seed port. A fleet that wants join-by-id signs a founding document instead, as the developer guide's section on finding the group describes.

CodeFleet.java: group and startPeer
/**
 * Assembles one peer. The issue space runs AUCTION and the change space runs
 * LEASE_RACE. The peer carries no bid function until a coder binds: the coder's
 * {@code @BidFunction} installs its cost model on the issue space.
 *
 * @param name     the peer's name, also the writer name of its replicas
 * @param port     the TCP port
 * @param seedPort an existing member's port, or 0 for the first
 * @return the running peer
 * @throws Exception if the port cannot be bound
 */
public static Peer startPeer(String name, int port, int seedPort) throws Exception {
    PeerIdentity identity = PeerIdentity.generate();
    PeerNode node = PeerNode.builder(identity).build();
    node.listen(new TcpTransport(), HOST + ":" + port);
    List<PeerAdvertisement.Endpoint> seeds = seedPort == 0 ? List.of()
            : List.of(new PeerAdvertisement.Endpoint("tcp", HOST + ":" + seedPort, 0));
    GroupRuntime runtime = node.joinGroup(group(),
            new GroupMembership.Config(Duration.ofSeconds(30), Duration.ofSeconds(2), 2),
            seeds);
    // No bid on the builder: a coder's @BidFunction prices the AUCTION space at
    // bind time, and a coordinator or reviewer, which never takes an issue,
    // carries none. A space accepts one bid function per peer, so a placeholder
    // on a non-bidder would block the coder that needs the slot.
    ReplicatedSpace issues = ReplicatedSpace.builder(runtime, ISSUES, identity, name)
            .settleWindow(Duration.ofMillis(250))
            .strategy(ConflictStrategyType.AUCTION)
            .build();
    ReplicatedSpace changes = ReplicatedSpace.builder(runtime, CHANGES, identity, name)
            .settleWindow(Duration.ofMillis(150))
            .build();
    // The agents are annotated POJOs bound through the facade. With the renewing
    // subordinate identity factory (a certificate that renews at half of 24 h),
    // each one signs its changes with a certified key of its own, and its
    // @SpaceRef is a per-agent view of the replica, so "who won each issue" is
    // the authenticated, attested issuer of the change.
    AgentSpaces spaces = new AgentSpaces(identity, InstantSource.system(),
            agentName -> identity.renewingSubordinate(agentName, java.time.Duration.ofHours(24), java.time.InstantSource.system()));
    AgentSpaces.GroupContext group = spaces.register("code-fleet", runtime.id(), runtime, null);
    group.space(ISSUES, issues);
    group.space(CHANGES, changes);
    node.startTicking(Duration.ofMillis(250));
    return new Peer(name, node, runtime, issues, changes, group);
}
✓ one group advertisement · a seed dial · both spaces registered before startTicking

Finding work without cards

Code Fleet uses discovery only for membership. spaces.register("code-fleet", runtime.id(), runtime, null) hands the facade no DiscoveryService, so the binder builds each agent's card and keeps it in Bound.card() without publishing it. The spaces advertise nothing either, because neither builder calls advertise(...). A coder finds an issue by type: the binder turns the parameter of code(Issue) into a template on the issues space, and the take loop polls it.

The routing rule that follows is the one the developer guide recommends: send work by entry type through a space, and treat a card as a hint for a reader such as a console or a planner. Passing a DiscoveryService as the fourth argument would publish five cards, each carrying the agent's goal, what it consumes and produces, and its own key and certificate.

HOW A CODER FINDS AN ISSUE: BY ENTRY TYPE IN A SPACE, WITH NO CARD LOOKUPcoordinatorwrites Issueissues space, a replica on every peerTemplate.of(Issue.class)the binder builds it from the parameter typecoder @ frontendcoder @ backendcoder @ sweepertake loops,poll 2 sWHAT THE BINDER BUILDS AND THIS APP NEVER PUBLISHESAgentCard aspace://<group>/agent/<peer>/coder, goals [code], ttl 15 min, own key and certificateconsumes ...CodeFleet$Issue#v1, produces ...CodeFleet$CodeChange#v1, space binding issuesregister(..., null) passes no DiscoveryService, so each card stays in Bound.card() and no peer reads it.
Finding work without cards. A coder reaches an issue because both sit in the same space under the same entry type. Nothing in the app reads a card, and the space delivers the work whether or not a card arrived. The dashed cards are what the binder builds for each bound agent; passing a DiscoveryService to register would publish them for a console or a planner.
aspace://guide/code-fleet/spaces · chapter 4

The spaces: an auction ledger and a review race

Two replicated spaces carry the work, each with a strategy that matches the job. The issues space runs AUCTION with a 250 ms settle window. The changes space takes the builder default, LEASE_RACE, with a 150 ms window. Each peer builds both and holds a full replica of each.

issues AUCTION settle 250 mschanges LEASE_RACE settle 150 msIssueissuesissueId, area, difficultywritten by the coordinator, peer-signedwrite lease 10 mintake: lowest bid, lease 5 sthe winner completes it with its resultCodeChangeissuesissueId, area, byAgent, costthe completion's result, in the winning coder's namelease 1 hthe allocation ledger: who won each issue, at what costcoders read and take here; the coordinator writesCodeChangechangesissueId, area, byAgent, costwritten by the coder after its renew check passeswrite lease 1 htake: first claim after 150 msthe reviewer completes with a ReviewReviewchangesissueId, byReviewer, approved, notethe completion's result, in the reviewer's namelease 1 hCiResultchangesissueId, passedwritten by the reviewer on an approvalwrite lease 1 hcopyreviewers take here; the coordinator reads CiResult
Two spaces, two strategies. The issues space decides by bid and doubles as the ledger, because each winner's CodeChange lands beside the work it finished. The changes space decides by arrival, which suits a job any reviewer can do. Each space fixes one strategy, so a fleet that needs both runs two spaces, as a system with two queues would.
Space Strategy Records Leases Who writes
issuesAUCTION, settle 250 msIssue in, CodeChange out as the completion resultissue 10 min, take 5 s, result 1 hthe coordinator writes the issue; the winning coder writes the result under its own key
changesLEASE_RACE, settle 150 msCodeChange copy in, Review out as the completion result, CiResult beside itcopy 1 h, take 5 s, review 1 h, CI 1 hthe coder writes the copy, the reviewer writes the review and the CI result
CodeFleet.java: the two spaces
ReplicatedSpace issues = ReplicatedSpace.builder(runtime, ISSUES, identity, name)
        .settleWindow(Duration.ofMillis(250))
        .strategy(ConflictStrategyType.AUCTION)
        .build();
ReplicatedSpace changes = ReplicatedSpace.builder(runtime, CHANGES, identity, name)
        .settleWindow(Duration.ofMillis(150))
        .build();
✓ no bidFunction on the builder: the binder installs it when a coder binds

The records are small on purpose. A CodeChange names the issue, the area, the agent that produced it, and its cost, which is the winning bid. Because the winner's result lands in the issues space beside the work it finished, a reader of that one space sees every allocation and its price.

ONE ENTRY IN THE SPACE issues (completion result)CodeChangeString issueIdString areaString byAgentdouble costspace strategyAUCTIONlease1 hsigned bythe winning coder's own certified 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.
Two settle windowsOn a LEASE_RACE space the window decides who holds a take: the first claim after the window keeps it. On an AUCTION space the same window has a second job, covered in chapter 7: it is the time during which another coder may still counter-claim with a lower bid. The builder's own Javadoc describes only the first use.
aspace://guide/code-fleet/run · chapter 5

One run, end to end

The flow below is one issue travelling through the fleet. The coordinator writes it, the coders bid, one coder codes it, a reviewer takes the copy, and the coordinator reads the CI result. The code under each step is the whole of it: there is no hidden orchestrator.

ONE ISSUE, FROM WRITE TO GREEN CIcoordinatorcodersissueschangesreviewers123456789write an Issuethe coordinator, 10 min lease, 9 of themprice it and claim the cheapesteach free coder runs its @BidFunction on what it seesthe settle window decides250 ms, lowest bid keeps the claim, take lease 5 scode()the winner works for 300 msrenew, then write a CodeChange copya displaced coder's renew throws, so no copycomplete the takethe returned CodeChange lands in issues as the resulttake the copyLEASE_RACE, 150 ms settle, then 150 ms of reviewwrite CiResult, complete with Reviewan approval, so passed = trueread the CiResultwaits for 9 issues with one: the cycle closes
One run, end to end. Steps 1 to 3 are the auction, step 4 the work, steps 5 and 6 the hand-off: a renew check, then a copy for review and the ledger entry behind, and steps 7 to 9 the review and the CI feedback. The arrows are reads and writes of spaces; no step calls another agent.

Steps 1 to 3: write, price, settle

The coordinator writes 9 issues in a loop. The area comes from i % 3 and the difficulty from 1 + (i % 5), so the demo has three frontend issues, three backend issues and three infra issues with difficulties 1 to 5. Each write is an entry with a 10 minute lease. A coder's take loop sees it as soon as gossip delivers it, prices it, and claims the issue it can do most cheaply (chapter 7).

CodeFleet.java: the coordinator writes the issues
String[] areas = {"frontend", "backend", "infra"};
int issueCount = 9;
for (int i = 1; i <= issueCount; i++) {
    coordinator.issues().write(new Issue("ISSUE-" + i, areas[i % 3],
            1 + (i % 5)), Lease.of(Duration.ofMinutes(10)));
}

Steps 4 to 6: code, copy, complete

The winner's code method runs once the settle window has confirmed its claim. It sleeps 300 ms for the coding work, renews its take lease, writes a copy of its change to the review space, and returns the change. The renew is a check as well as an extension: it throws when a lower bid has displaced the claim, and the coder then writes nothing (chapter 7). The binder completes the take with the returned value as the result entry, which is how the issues space becomes the ledger. The copy goes before the completion because the binder completes the take only when the method returns, so a reviewer can already hold the change by the time the issue completes.

CodeFleet.java: the Coder
@SpaceTake(space = ISSUES, lease = "5s", pollTimeout = "2s", resultLease = "1h")
public CodeChange code(Issue issue) {
    if (dieAfter >= 0 && done >= dieAfter) {
        // Crash mid-take: stop this agent and abandon the held issue. The
        // binder never completes a take whose action threw, so the 5 s lease
        // lapses and the issue reappears for another coder.
        abandoned = issue;
        close();
        throw new IllegalStateException(label + " died mid-take");
    }
    double cost = costModel.applyAsDouble(issue);
    sleep(300); // the coding work
    // Still the holder? A lower bid can reach this replica after our settle
    // window and displace the claim. renew throws LeaseExpiredException then,
    // so a displaced coder writes no review copy and no result, and the
    // binder logs the failed action and returns the coder to its take loop.
    TakeContext.current().ifPresent(TakeContext::renew);
    CodeChange change = new CodeChange(issue.issueId(), issue.area(), label, cost);
    changes.write(change, Lease.of(Duration.ofHours(1))); // for review
    done++;
    return change; // completes the take with the change as its result
}
✓ the returned CodeChange completes the take and lands as the result · the copy for review goes through the @SpaceRef after the renew check

Steps 7 to 9: review and CI

A reviewer takes the copy from the changes space under LEASE_RACE, spends 150 ms reviewing, approves it when its cost is at most 100, and then writes a passing CiResult and returns the Review. The coordinator polls the changes space for CiResult entries and stops when 9 different issues have a passing one. Chapter 8 follows that loop in detail.

CodeFleet.java: the coordinator watches for CI
for (int tick = 0; tick < 30; tick++) {
    // Count issues, not entries: a duplicate CiResult must not end the wait early.
    long ciPassed = coordinator.changes().readAll(Template.of(CiResult.class), 100)
            .stream().filter(CiResult::passed).map(CiResult::issueId)
            .distinct().count();
    long allocated = coordinator.issues()
            .readAll(Template.of(CodeChange.class), 100).stream()
            .map(CodeChange::issueId).distinct().count();
    System.out.printf("  allocated=%d in-review=%d ci-passed=%d%n",
            allocated,
            coordinator.changes().readAll(Template.of(CodeChange.class), 100).size(),
            ciPassed);
    if (ciPassed >= issueCount) {
        break;
    }
    sleep(1000);
}

A recorded run

This is the demo's output from 2026-11-04, verbatim. The three progress columns come from the coordinator's replicas: allocated counts the distinct issues that have a completion in the issues space, in-review counts copies in the changes space that no reviewer holds yet, and ci-passed counts the distinct issues that have a passing CiResult. in-review stays at 0 because a free reviewer claims a copy within a poll or two and a held entry drops out of readAll.

code-fleet: cost-aware coding swarm, no dispatcher

9 issues published across frontend/backend/infra; agents bid by expertise and cost:

  allocated=0 in-review=0 ci-passed=0
  allocated=3 in-review=0 ci-passed=1
  allocated=8 in-review=0 ci-passed=7
  allocated=8 in-review=0 ci-passed=8
  allocated=8 in-review=0 ci-passed=8
  allocated=8 in-review=0 ci-passed=8
  allocated=8 in-review=0 ci-passed=8
  allocated=9 in-review=0 ci-passed=8
  allocated=9 in-review=0 ci-passed=9

== allocation (who won each issue, and at what cost) ==
  ISSUE-1   backend   -> coder-backend    cost 6  (peer:zHB64ubkqo…, AGENT_ATTESTED)
  ISSUE-2   infra     -> coder-sweeper    cost 18  (peer:zDjVktTQbx…, AGENT_ATTESTED)
  ISSUE-3   frontend  -> coder-frontend   cost 12  (peer:z79kNcttZf…, AGENT_ATTESTED)
  ISSUE-4   backend   -> coder-backend    cost 15  (peer:zHB64ubkqo…, AGENT_ATTESTED)
  ISSUE-5   infra     -> coder-sweeper    cost 6  (peer:zDjVktTQbx…, AGENT_ATTESTED)
  ISSUE-6   frontend  -> coder-frontend   cost 6  (peer:z79kNcttZf…, AGENT_ATTESTED)
  ISSUE-7   backend   -> coder-backend    cost 9  (peer:zHB64ubkqo…, AGENT_ATTESTED)
  ISSUE-8   infra     -> coder-frontend   cost 36  (peer:z79kNcttZf…, AGENT_ATTESTED)
  ISSUE-9   frontend  -> coder-frontend   cost 15  (peer:z79kNcttZf…, AGENT_ATTESTED)

changes per agent: {coder-backend=3, coder-frontend=4, coder-sweeper=2}

The sweeper died on ISSUE-8 (its bid was 24) after 2 changes.
Its lease lapsed and coder-frontend finished ISSUE-8 at cost 36.
9 of 9 issues allocated, with no central dispatcher.

The allocation table is the ledger. Each row is the issuer-attributed result the winning coder wrote, with the issuer's peer and its attestation printed beside the byAgent label the change declares. A displaced coder writes no result, so each issue shows one row. The view still keeps the cheaper change per issue, in case a duplicate lands in the few milliseconds between a winner's renew and its completion (chapter 7). The last lines report what happened to the sweeper. The demo asks the sweeper's Coder whether it died and on which issue, prices that issue with the sweeper's own cost model, and names the coder that finished it. When the sweeper never reaches a third take, the text says that nobody died.

CodeFleet.java: the allocation view and the closing report
Map<String, ai.badmonkey.agentspaces.api.space.Space.Issued<CodeChange>> winners =
        new java.util.TreeMap<>();
coordinator.issues().readAllIssued(Template.of(CodeChange.class), 100).forEach(c ->
        winners.merge(c.entry().issueId(), c,
                (a, b) -> a.entry().cost() <= b.entry().cost() ? a : b));
// Every coder is bound as "coder", so the issuer names the peer; the
// change's byAgent label is the readable name. CodeFleetTest checks
// that the two agree.
winners.values().forEach(c -> System.out.printf(
        "  %-9s %-9s -> %-16s cost %.0f  (%s, %s)%n",
        c.entry().issueId(), c.entry().area(), c.entry().byAgent(), c.entry().cost(),
        c.issuer().peer().display(), c.attestation()));
Map<String, Long> perAgent = new java.util.TreeMap<>();
winners.values().forEach(c -> perAgent.merge(c.entry().byAgent(), 1L, Long::sum));
✓ readAllIssued returns each change with its authenticated issuer · the closing lines come from Coder.abandoned()
aspace://guide/code-fleet/bids · chapter 6

The price of work: the bid functions

The whole policy of the fleet is one small method. costModel(expertise, costPerUnit) returns a function from an issue to a price: the price per unit times the issue's difficulty, multiplied by 3 when the issue's area is not the coder's expertise. The coder's @BidFunction calls it, and the binder hands the method to the issues replica as its cost function when the coder binds.

CodeFleet.java: the price
/**
 * A coder's cost model: {@code costPerUnit} times the issue's difficulty, tripled
 * when the issue's area is not {@code expertise}. The comparison is
 * {@code equals}, so an expertise that names no area, such as {@code "any"},
 * never matches and the price is tripled on every issue.
 *
 * @param expertise   the area this coder prices at its own rate
 * @param costPerUnit its price per unit of difficulty
 * @return the bid function over {@link Issue}s
 */
public static ToDoubleFunction<Object> costModel(String expertise, double costPerUnit) {
    return entry -> {
        Issue issue = (Issue) entry;
        double base = costPerUnit * issue.difficulty();
        return issue.area().equals(expertise) ? base : base * 3.0;
    };
}
✓ a plain method over the entry · one @BidFunction per space per peer · every bidder on a space uses the same unit
WHAT EACH CODER BIDS FOR THE NINE DEMO ISSUES (PER UNIT: 3.0, 3.0, 2.0; x3 OFF AREA)coder-frontend3.0 per unitcoder-backend3.0 per unitcoder-sweeper2.0 per unit, anyrecorded runwinner and costISSUE-1 backend d218612coder-backend 6ISSUE-2 infra d3272718coder-sweeper 18ISSUE-3 frontend d4123624coder-frontend 12ISSUE-4 backend d5451530coder-backend 15ISSUE-5 infra d1996coder-sweeper 6ISSUE-6 frontend d261812coder-frontend 6ISSUE-7 backend d327918coder-backend 9ISSUE-8 infra d4363624coder-frontend 36ISSUE-9 frontend d5154530coder-frontend 15A shaded chip is the lowest bid for that issue. The dashed result is ISSUE-8: the sweeper's 24 was lowest, but the sweeper had died on it,so the two specialists were left at 36 each and the auction paid the mismatch price.
The bids. These numbers are the app's cost model run over the demo's nine issues: price per unit times difficulty, tripled outside the coder's expertise. The sweeper's expertise is the word "any", which no issue carries, so it pays the triple on every issue and lands between the specialists.

Read the matrix by rows. On ISSUE-1, a backend issue of difficulty 2, the backend coder bids 6, the sweeper 12 and the frontend coder 18. On ISSUE-2, an infra issue of difficulty 3, nobody has the expertise, so the sweeper's 18 undercuts the specialists' 27. On ISSUE-8, an infra issue of difficulty 4, the sweeper bids 24 and the specialists 36, which is the row the kill story in chapter 10 turns on.

The sweeper's price deserves a close look. Its expertise is the string "any", and costModel compares it to the issue's area with equals, so it never matches and the sweeper pays the factor of 3 on every issue. The result is a ladder of three rungs, shown below. A reading of "any" as a wildcard would price the sweeper at 2 per unit, under both specialists on their own areas, and it would take every issue. The ladder is what makes the demo's division of labor work, and it comes from that one comparison.

THE PRICE LADDER PER UNIT OF DIFFICULTY, AND WHO HOLDS EACH RUNGa frontend issuecoder-frontend3coder-sweeper6coder-backend9a backend issuecoder-backend3coder-sweeper6coder-frontend9an infra issuecoder-sweeper6coder-frontend9coder-backend9a tie: the lower stamp holdsWith the sweeper gone, an infra issue has no rung below 9, and the two specialists tie. That is the price of the death in the kill story:the fleet pays three times a specialist's own rate rather than leave the issue unclaimed.
The ladder. The prices form three rungs, so the winner of each area follows from the rungs alone: the matching specialist on its own area, the sweeper on infra, and nobody cheaper than 9 once the sweeper is gone.

What to watch for in a bid function

  • Use one unit. The space compares bids directly, so every coder prices in the same unit. Here it is an abstract cost; a real fleet might denominate dollars or tokens.
  • Keep it fast and pure. The space calls the function for every live issue of the type on every poll, about every 20 ms per idle coder. This one is plain arithmetic, while a bid that called a model or a database would slow every claim.
  • Price the same way twice. The claim carries the bid computed at claim time, and code() computes the cost again for the change. The two agree because the model is deterministic, and the recorded costs equal the winning bids.
  • Check the strategy first. A @BidFunction on a LEASE_RACE space is never called. When an auction behaves like a race, look at the space's strategy before the function.
aspace://guide/code-fleet/auction · chapter 7

One auction round

An auction here has no auctioneer and no bidding phase. Each coder with a free take loop looks at the issues its replica holds, runs its bid function over them, sorts by its own price, and claims the cheapest one it can. A claim is a signed record: the entry it is for, an epoch, the holder, the bid, an HLC stamp and an expiry. Claims travel by gossip like any other state, and every replica merges them with the same rule, so replicas that have seen the same claims agree on the holder with no coordination.

Replicas apply one merge rule to the claims they hold, and that rule decides the auction. A higher epoch supersedes. Within an epoch the lowest bid holds. Equal bids go to the lower stamp, then to the lower holder id. After it claims, a coder sleeps for the settle window, 250 ms here, and then checks whether its claim is still the one in force. If it is, the take succeeds. If another replica's lower bid reached it during the window, the take fails quietly and the coder moves on to its next candidate. A challenger has a limit of its own: a coder may counter-claim an issue another coder holds only with a strictly lower bid, and only while the holder's settle window is open.

ONE AUCTION ROUND ON ISSUE-7 (backend, difficulty 3): MS FROM THE FIRST CLAIM, ONE TRACED RUNsettle window 250 mscoder-sweeperprices ISSUE-7 at 18coder-backendprices ISSUE-7 at 9claim, every replicathe lowest bid in an epoch holdsreviewersreview-a took the copy18claim lostclaims ISSUE-29code() 300 ms+541 copy to changes, +547 completion, +551 result in issues189holds: epoch 1, take lease 5 stake +564CiResult +877Review +8880 ms250 ms500 ms750 msthe 5 s take lease runs on from the claim, past the right edge of the picture
One auction round. Two coders claimed ISSUE-7 within a few milliseconds of each other. Every replica keeps the lower bid for the same claim epoch, so 9 replaced 18 and the sweeper's claim lost when its window closed, after which it claimed ISSUE-2. The winner coded for 300 ms, left a copy for review, and completed the take. The offsets come from one traced run; another run shifts them by tens of milliseconds and may pick a different pair of claimants.

The picture comes from a traced run. Two coders claimed ISSUE-7 within a few milliseconds of each other, the sweeper at 18 and the backend coder at 9. The lattice kept 9, the sweeper's window closed with its claim lost, and it moved on to ISSUE-2 about 259 ms after its first claim. The listing below is the observer's output for that issue, verbatim. The observer is a scratch program that lives outside the app: it subscribed Space.notify on the coordinator's replicas and logged the first price each cost model computed per issue.

   38 ms  issues  WRITTEN ISSUE-7 by coordinator/coordinator
   44 ms     bid  backend prices ISSUE-7 (backend, d3) at 9.0
  617 ms     bid  sweeper prices ISSUE-7 (backend, d3) at 18.0
  621 ms     bid  frontend prices ISSUE-7 (backend, d3) at 27.0
  642 ms  issues  TAKEN ISSUE-7 by coder-sweeper/coder
  901 ms  issues  TAKEN ISSUE-2 by coder-sweeper/coder
 1183 ms  changes WRITTEN CodeChange ISSUE-7 by coder-backend/coder
 1189 ms  issues  COMPLETED ISSUE-7 by coder-backend/coder
 1193 ms  issues  WRITTEN CodeChange ISSUE-7 cost 9.0 byAgent coder-backend
 1206 ms  changes TAKEN CodeChange ISSUE-7 by review-a/reviewer
 1519 ms  changes WRITTEN CiResult ISSUE-7 passed=true
 1525 ms  changes COMPLETED CodeChange ISSUE-7 by review-a/reviewer
 1530 ms  changes WRITTEN Review ISSUE-7 review-a LGTM

One detail in that listing is easy to misread. TAKEN ISSUE-7 by coder-sweeper is the first claim the coordinator's replica merged. A replica fires TAKEN once per claim epoch, so a watcher that is not the claimant hears the first claim it merges and not the final holder. The COMPLETED event names the holder that finished, which was the backend coder. A reader who needs the final holder should wait for the completion or read the result entry.

THE LIFE OF ONE ISSUE: THE SPACE EVENT KINDS A WATCHER SEESWRITTENIssue, lease 10 minTAKENepoch n, a bid, lease 5 sCOMPLETEDresult CodeChange writtenREAPPEAREDthe take lease lapsedEXPIRED10 min, nobody took ita coder claimsthe holder returnsno completion in 5 sepoch n + 1:a new auctionuntakena lower bid inside the 250 ms window takes the claimThese five are SpaceEvent kinds. REAPPEARED comes from the lease sweep, so a re-claim that lands first leaves no event, as in the traced run.
The life of an issue. An issue sits written until a coder claims it. A claim is a bid with an expiry: a lower bid in the settle window replaces the holder, completion ends the issue, and a lapsed lease sends it back to be claimed again at the next epoch. The kill story is the path through REAPPEARED.

What the rounds teach

  • An issue waits for a free coder. The coordinator wrote ISSUE-7 at 38 ms, and its first claim reached the coordinator at 642 ms, after the three coders finished their first changes. Each coder runs one take at a time, so 9 issues on three coders run in about three waves.
  • The window limits when a counter-claim can be made, and every replica merges it whenever it arrives. A claim travels by gossip like any other state, so a lower bid made inside the window can reach a holder after the window has closed. The merge rule still gives the issue to the lower bid, and the holder, which believed it had won, finds out when it next asks its replica. In the trace the claims of the first wave reached the coordinator within about ten milliseconds, far inside the window. On a slow or loaded link the delay can be longer.
  • A holder can learn late that it lost. A checking run on 2026-11-04, made before the coder guarded its copy, showed it. One coder's completion failed with LeaseExpiredException: take lease lapsed or lost about half a second after its claim, far inside its 5 s lease, so another claim had displaced it after its own settle window passed. Its copy was already in the changes space, because the copy goes first, and the reviewers saw a second change for that issue. The coder now checks before it writes the copy, as the next section shows.
  • A claim carries a lease. The holder has 5 s from the claim. Chapters 8 and 10 use that: a reviewer's take would lapse the same way, and a coder that dies leaves its claim to run out.

A displaced coder checks before it writes

The coder's code method asks its replica once more after the work and before the copy. TakeContext.current() returns the take the binder is running, and renew() extends its lease by the binding's lease, 5 s here. The replica also checks the claim when it renews: it throws LeaseExpiredException when the claim in force names another holder or epoch, or has expired. A displaced coder therefore stops at the renew. It writes no review copy and returns no result, so the binder has no completion to attempt. It logs the failed action at WARNING and the coder polls for its next issue. The reviewers see one copy per issue, the winner's, and write one CiResult.

CodeFleet.java: the check before the copy
// Still the holder? A lower bid can reach this replica after our settle
// window and displace the claim. renew throws LeaseExpiredException then,
// so a displaced coder writes no review copy and no result, and the
// binder logs the failed action and returns the coder to its take loop.
TakeContext.current().ifPresent(TakeContext::renew);
CodeChange change = new CodeChange(issue.issueId(), issue.area(), label, cost);
changes.write(change, Lease.of(Duration.ofHours(1))); // for review
done++;
✓ renew throws when the claim in force is no longer this coder's · the copy is written only after it passes
A DISPLACED CODER: THE RENEW CHECK BETWEEN THE WORK AND THE REVIEW COPYclaim at its bida signed claim, take lease 5 ssettle window, 250 msno better bid has arrived yet: the take succeedscode(): 300 ms of worka lower bid made inside the window can still arriveTakeContext renew()is the claim in force still this coder's?yesthe claim is still its ownrenew extends the take leasewrite the CodeChange copy to changesreturn the change: the take completes and theresult lands in issuesnoa lower bid displaced itrenew throws LeaseExpiredExceptionno copy is written, and the take is never completedthe binder logs the failed action at WARNINGand the coder polls for its next issuerenew narrows the window and leaves the few milliseconds before the completion open. A lower bid merged in that gap still leaves a duplicate,which the demo's loop and the test absorb by counting distinct issue ids.
A displaced coder. After its settle window a coder believes it holds the issue, and a lower bid made inside the window can still reach its replica later. The coder asks the replica once more, after the work and before the copy, and a displaced coder stops there with nothing written.

A displacement after the holder's own window is rare under the app's windows, 250 ms on every peer, so a scratch program outside the app forces it. It runs two coders on two peers. Coder-a sits on a peer whose issues window is 5 ms and prices the issue at 18. Coder-b sits on a peer whose window is 3000 ms and prices it at 3, and the program binds it 120 ms after it writes the issue. Coder-a claims the issue and starts its 300 ms of work. Coder-b then counter-claims with the lower bid, which its long window allows, and the claim reaches coder-a's replica during the work. The listing is that program's output on 2026-11-04, followed by the first lines of the WARNING the binder logged for coder-a. Both coders bind under the local name coder, which is why the events read by coder. Only coder-b writes a copy, and the throw in the stack comes from renew, called by Coder.code. Against the earlier Coder, which had no renew, the same program showed coder-a's copy written at 372 ms and a completion that failed in completeInternal.

   14 ms  issues  WRITTEN ISSUE-X by coordinator
   35 ms  issues  TAKEN ISSUE-X by coder
  141 ms  binding coder-b (price 3) while coder-a (price 18) works
 3468 ms  changes WRITTEN CodeChange ISSUE-X byAgent coder-b
 3474 ms  issues  COMPLETED ISSUE-X by coder
 3478 ms  issues  WRITTEN CodeChange ISSUE-X byAgent coder-b

WARNING: coder.code: action failed; lease will lapse
ai.badmonkey.agentspaces.api.error.LeaseExpiredException: take lease lapsed for entry e1208299-0afa-4c61-8055-27d8b0a916ed
	at ai.badmonkey.agentspaces.space.replicated.ReplicatedSpace$Taken.renew(ReplicatedSpace.java:3246)
	at ai.badmonkey.agentspaces.agent.TakeContext.renew(TakeContext.java:88)
	at ai.badmonkey.agentspaces.flagship.code.CodeFleet$Coder.code(CodeFleet.java:236)

The check narrows the window and leaves a few milliseconds open. The binder completes the take only when code returns, so the app cannot write the copy after the completion, and a lower bid merged between the renew and the completion would still leave a duplicate copy. Two places absorb that case. The demo's progress loop counts distinct issue ids with a passing CiResult, so a duplicate cannot end the wait early, and the flow test checks distinct ids in both spaces, so a duplicate cannot stand in for a missing issue.

aspace://guide/code-fleet/review · chapter 8

Review and CI close the loop

The changes space runs LEASE_RACE with a 150 ms window, which suits a job any reviewer can do. A reviewer carries no bid function. It takes a CodeChange, spends 150 ms on the review, and approves when change.cost() <= skill * 10. With a skill of 10 the threshold is 100, and no price in the demo exceeds 45, so the reviewers approve every change.

REVIEW AND CI: THE LOOP, AS BUILT AND AS LEFT OPENcodercode() returnsCodeChangechangescopy in changeslease 1 hreviewertake, 150 ms reviewapproved = cost <= 100(skill 10 x 10)no price in the demo exceeds 45,so every change is approvedCiResultchangespassed = truelease 1 happroved: also writesReviewchangesapproved, notecompletes the takealwayscoordinatorreadAll(CiResult)stops at 9 issues with a CiResulta rejection writes only a Review(approved = false): no CiResult,and nothing reopens the issue
The review loop. The cycle closes when the coordinator has read one CiResult per issue. The reviewer writes that CiResult itself, so it stands in for a CI runner. A rejection writes a Review and stops: no agent consumes it, so a real propose-review-revise loop is still to be built, as the README says.
CodeFleet.java: the Reviewer
@SpaceTake(space = CHANGES, lease = "5s", pollTimeout = "2s", resultLease = "1h")
public Review review(CodeChange change) {
    sleep(150); // the review work
    boolean approved = change.cost() <= skill * 10.0;
    if (approved) {
        changes.write(new CiResult(change.issueId(), true), Lease.of(Duration.ofHours(1)));
    }
    return new Review(change.issueId(), label, approved, approved ? "LGTM" : "needs work");
}
✓ the Review is the completion result · the CiResult is an extra write on approval

The loop closes in the coordinator. It polls the changes space for CiResult entries and counts the distinct issues among them until it reaches 9. The reviewer writes that CiResult itself, so it stands in for a CI runner: in a real fleet a build agent would take approved changes and write the result. The take uses the same shape. A reviewer that died mid-review would let its 5 s lease lapse, and the copy would reappear for the other reviewer.

Count issue idsThe coordinator stops when 9 different issue ids have a passing CiResult. An earlier version of the loop counted entries. In a checking run on 2026-11-04 a displaced coder's copy had been reviewed too, so the entry count reached 9 while the issues space held 8 results and the sweeper's issue had not been re-run yet, and the loop would have stopped early. The coder's renew check now keeps that copy from existing, and counting ids covers a duplicate that slips through the gap before the completion. A fleet that stops on a count should count the set of ids.
What the loop leaves openA rejected change writes a Review with approved = false and no CiResult. Nothing consumes that review, so nothing reopens the issue and the coordinator would wait for a CI result that never arrives. The README names the missing piece, a rejection path that reopens the issue for a propose, review and revise loop. The Review.approved flag is already there for it.
aspace://guide/code-fleet/identity · chapter 9

Every agent signs as itself

The app builds the facade with an identity factory, and that one argument changes what the rest of the fleet can prove. Without it, every agent on a peer signs with the peer's key and a reader can name only the peer. With identity.renewingSubordinate(agentName, 24 h, clock), each bound agent gets an Ed25519 key of its own, certified by its peer, and the binder hands it a per-agent view of each replica.

CodeFleet.java: the identity factory
// The agents are annotated POJOs bound through the facade. With the renewing
// subordinate identity factory (a certificate that renews at half of 24 h),
// each one signs its changes with a certified key of its own, and its
// @SpaceRef is a per-agent view of the replica, so "who won each issue" is
// the authenticated, attested issuer of the change.
AgentSpaces spaces = new AgentSpaces(identity, InstantSource.system(),
        agentName -> identity.renewingSubordinate(agentName, java.time.Duration.ofHours(24), java.time.InstantSource.system()));
AgentSpaces.GroupContext group = spaces.register("code-fleet", runtime.id(), runtime, null);
group.space(ISSUES, issues);
group.space(CHANGES, changes);
✓ a key of its own per agent · certificates last 24 h and renew at half-life
ONE PEER, TWO KINDS OF WRITER: THE PEER'S KEY AND AN AGENT'S OWN KEYpeer keyPeerIdentity.generate()certifiescoder's own keyrenewingSubordinate, 24 h, renews at halfthe peer signs a certificate;the agent signs what it writesTHE issues REPLICA ON THIS PEER: ONE REPLICA, ONE CLOCKthe replica's own handlepeer-signed writerreplica.as(coder identity)a per-agent viewthe coordinator writes Issue here@SpaceRef and the take loop get this viewa write through a view is issued and signed by that agent;a claim or completion through it names that agent as the holder;reads and event subscriptions are the replica's ownreadAllIssuedIssued(entry, issuer, attestation)Issue PEER_ASSERTEDCodeChange AGENT_ATTESTEDthe test asserts, for every CodeChange:issuer local name "coder"issuer peer = peer named by byAgentattestation AGENT_ATTESTED
Per-agent identity. Each bound agent gets a key of its own, certified by its peer, and every handle it holds is a view of the peer's replica under that key. A reader can therefore name the agent that wrote a change as well as its peer. The coordinator, which binds no agent, writes under the peer's key and its entries read as asserted.

A view is the same replica under another identity: one gossip registration and one clock per node, with the writer swapped. The agent issues and signs every write through it, and a claim or completion through it names the agent as the holder. The coder's take loop takes and completes through that view, and its @SpaceRef field holds a view of the changes space, so even the copy it writes for review carries its key.

The reader's side is readAllIssued, which returns each entry with its issuer and an attestation: AGENT_ATTESTED when the entry carries an agent certificate, PEER_ASSERTED when only the peer vouches for it. The coordinator writes issues under its peer's key and binds no agent, so its entries read as asserted. The coders' results read as attested.

The byAgent field is a different matter: it is a label the writer chose. The test checks the label against the evidence, and the demo prints both so a reader can compare them.

CodeFleetTest.java: attribution as evidence
// Attribution is evidence: every change's declared author is
// its authenticated issuer, and every change is signed by that agent's own
// certified key.
java.util.Map<String, ai.badmonkey.agentspaces.common.id.PeerId> peerOf = new java.util.HashMap<>();
for (Peer peer : fleet) {
    peerOf.put(peer.name(), peer.node().peerId());
}
assertThat(coordinator.issues().readAllIssued(Template.of(CodeChange.class), 100))
        .isNotEmpty()
        .allSatisfy(issued -> {
            assertThat(issued.issuer().localName()).isEqualTo("coder");
            assertThat(issued.issuer().peer()).isEqualTo(peerOf.get(issued.entry().byAgent()));
            assertThat(issued.attestation())
                    .isEqualTo(ai.badmonkey.agentspaces.api.space.Space.Attestation.AGENT_ATTESTED);
        });
✓ the declared author is the authenticated issuer · an agent key attests every change
Which factoryThe facade's own documentation names identity::subordinate for a fixed certificate of one hour. Code Fleet uses renewingSubordinate, which keeps one key and re-issues its certificate at half-life, so a coder that runs for days never outlives it. Receivers judge each certificate at the moment of signing, so old results stay verifiable.
aspace://guide/code-fleet/death · chapter 10

When a worker dies

The demo kills the sweeper by configuration. runCoder takes a dieAfter count, and the sweeper's is 2. When its third take starts, code() closes the coder's own binding and throws. The binder catches the exception, logs a warning, and never completes the take. The peer, its replica and its gossip keep running: what dies is the agent, and the agent is what held the lease. Before it closes, the coder records the issue it holds in abandoned, which is how the demo's closing lines and the test name the orphan.

CodeFleet.java: the crash
@SpaceTake(space = ISSUES, lease = "5s", pollTimeout = "2s", resultLease = "1h")
public CodeChange code(Issue issue) {
    if (dieAfter >= 0 && done >= dieAfter) {
        // Crash mid-take: stop this agent and abandon the held issue. The
        // binder never completes a take whose action threw, so the 5 s lease
        // lapses and the issue reappears for another coder.
        abandoned = issue;
        close();
        throw new IllegalStateException(label + " died mid-take");
    }
    double cost = costModel.applyAsDouble(issue);
    sleep(300); // the coding work
    // Still the holder? A lower bid can reach this replica after our settle
    // window and displace the claim. renew throws LeaseExpiredException then,
    // so a displaced coder writes no review copy and no result, and the
    // binder logs the failed action and returns the coder to its take loop.
    TakeContext.current().ifPresent(TakeContext::renew);
    CodeChange change = new CodeChange(issue.issueId(), issue.area(), label, cost);
    changes.write(change, Lease.of(Duration.ofHours(1))); // for review
    done++;
    return change; // completes the take with the change as its result
}
✓ close the binding, then throw · the take is never completed · the lease runs out

Nothing in the app detects the failure or hands the work on. The claim carries a 5 s expiry from the moment the coder made it. When the expiry passes, the issue is claimable again at the next epoch, and the coders that are still alive run the auction again. The only bidders left for an infra issue are the specialists, who both price it at 9 per unit. The 24 that the sweeper would have charged became 36.

WHEN THE SWEEPER DIES ON ISSUE-8: MS FROM THE FIRST ISSUE WRITE, ONE TRACED RUNcoder-sweeperissues replicathe other codersreviewersoffset1470 ms1482 ms1482 ms~6482 ms6488 ms7061 ms7387 mscompletes ISSUE-2, its second changeclaims ISSUE-8 at its bid of 24done 2 >= dieAfter 2:close, then throwthe binder logs a warning and never completesheld for 5 s, nobody working(the second claim shows up 5006 ms after the first)claim expiresfrontend and backend claim at 36equal bids: the lower stamp holdsthe winner completes, result cost 36CiResult for ISSUE-8, then the review completes
When a worker dies. The sweeper held ISSUE-8 for a full take lease without doing anything, because a throw leaves the take open. When the lease ran out the issue could be claimed again, and the specialists, the only bidders left, paid 36 for work the sweeper would have done at 24. The winner of the tie differs between runs: backend here, frontend in the recorded demo.

These are the lines of the trace behind the picture, verbatim from the same run. The sweeper completed ISSUE-2 at 1470 ms, claimed ISSUE-8 at 1482 ms, and said nothing more. The second claim reached the coordinator 5006 ms later, from a specialist, at the 36 both specialists priced. The backend coder completed it, and the CI result for ISSUE-8, the last of the nine, landed at 7387 ms.

  616 ms     bid  backend prices ISSUE-8 (infra, d4) at 36.0
  617 ms     bid  sweeper prices ISSUE-8 (infra, d4) at 24.0
  621 ms     bid  frontend prices ISSUE-8 (infra, d4) at 36.0
 1470 ms  issues  COMPLETED ISSUE-2 by coder-sweeper/coder
 1477 ms  issues  WRITTEN CodeChange ISSUE-2 cost 18.0 byAgent coder-sweeper
 1482 ms  issues  TAKEN ISSUE-8 by coder-sweeper/coder
 6488 ms  issues  TAKEN ISSUE-8 by coder-frontend/coder
 7049 ms  changes WRITTEN CodeChange ISSUE-8 by coder-backend/coder
 7061 ms  issues  COMPLETED ISSUE-8 by coder-backend/coder
 7068 ms  issues  WRITTEN CodeChange ISSUE-8 cost 36.0 byAgent coder-backend
 7075 ms  changes TAKEN CodeChange ISSUE-8 by review-a/reviewer
 7387 ms  changes WRITTEN CiResult ISSUE-8 passed=true
 7396 ms  changes COMPLETED CodeChange ISSUE-8 by review-b/reviewer
 7401 ms  changes WRITTEN Review ISSUE-8 review-b LGTM

In the recorded demo the same shape produced a different winner: ISSUE-8 went to the frontend coder at 36. The two specialists bid the same, so the tie goes to the lower stamp, and which coder's stamp is lower depends on timing. Both outcomes are correct, and a test that asserted one of them would be a flaky test. The warning the binder logs is the visible mark of the death:

WARNING: coder.code: action failed; lease will lapse
java.lang.IllegalStateException: coder-sweeper died mid-take

What to watch for

  • The lease is the recovery time. The fleet waited 5 s for an issue that was never in progress. A shorter lease recovers faster. The price is that a job longer than the lease starts to look dead while it still works.
  • A displaced worker stops at its renew. If another claim replaced the holder's, the holder's renew throws a lease error, so it writes no copy for review and the binder has no completion to attempt. Before the check existed, the copy stayed in the changes space. The few milliseconds between the renew and the completion stay open, and counting distinct issue ids covers them.
  • Long jobs renew. The 300 ms job here fits its lease with room to spare, and the app calls TakeContext.current().ifPresent(TakeContext::renew) once, as the displacement check. A coder that works for minutes can call it as it goes, which extends the take lease by the binding's lease each time.
  • Recovery has a price. The fleet paid 36 for work priced at 24 and took about 5 extra seconds to finish. It chose to pay, which is the trade the README describes: a higher price keeps the migration moving.
aspace://guide/code-fleet/running · chapter 11

Running and testing it

The project is a standalone Maven build. It needs JDK 21 and the AgentSpaces 0.6.0 libraries, which resolve from Maven Central, and it needs no API key.

cd agentspaces-code-fleet
mvn test            # the flow test over real TCP: 1 test, about 9 seconds
./run-demo.sh       # the demo: nine issues, one worker dying, all CI green

The demo listens on the fixed ports 7571 to 7576, so two copies at once collide. The test asks the operating system for a free port per peer and runs beside anything else. The script is one line, mvn -q compile exec:java. The pom declares 6 AgentSpaces modules, all at the one version property below, and two test libraries (junit-jupiter, assertj-core).

pom.xml: the version and the modules
<properties>
  <maven.compiler.release>21</maven.compiler.release>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <agentspaces.version>0.6.0</agentspaces.version>
  <junit.version>5.13.4</junit.version>
  <assertj.version>3.27.7</assertj.version>
</properties>
✓ api, common, identity, peering, space and agent, all at ${agentspaces.version}

What the flow test asserts

There is one test, everyIssueIsAllocatedReviewedAndPassesCiDespiteAWorkerDying. It starts the six peers over real TCP, binds the agents, waits 1.5 seconds for the group to settle, writes the 9 issues, and then asserts in order. The picture lists the assertions and, on the right, what they leave unproven. The CI wait and the allocation check both count distinct issue ids, and the sweeper assertions read the Coder that runCoder returns.

THE FLOW TEST: ONE SCENARIO, OVER REAL TCPWHAT IT DOES NOT ASSERT16 peers on free ports, the first is the seed2bind 3 coders (the sweeper dies after 2) and 2 reviewers,wait 1.5 s3write 9 issues4within 120 s: CI results for 9 distinct issue ids, every onepassed5within 30 s: 9 distinct issue ids as CodeChange in issues6the sweeper authored at most 2 of them7at least 2 distinct authors8the sweeper died, and the issue it held was completed byanother coder9each CodeChange: issuer "coder", issuer peer = peer named bybyAgent, AGENT_ATTESTEDthe price of the orphan's re-run, or how longit waited: only the 120 s ceiling appliesthat each winner was the lowest bidderhow the reviewers split the work, or anyrejectionthat no duplicate was ever written: bothdistinct-id checks tolerate a duplicateCodeChange or CiResult
What the test proves. It proves that nine issues all reach a passing CI with a worker configured to die, that no more than two changes came from that worker, that the worker died and another coder completed the issue it held, that the work was shared, and that the agent key that signed each change is the author the change names. The right column lists what a reader may be tempted to read into it.
CodeFleetTest.java: the assertions
// Every issue eventually produces an approved change that passes CI,
// even though the sweeper dies after two changes. The check is on
// distinct issue ids, so a duplicate CiResult cannot stand in for a
// missing issue.
Set<String> expected = new TreeSet<>();
for (int i = 1; i <= issueCount; i++) {
    expected.add("ISSUE-" + i);
}
List<CiResult> ci = awaitCi(coordinator, issueCount, Duration.ofSeconds(120));
assertThat(ci.stream().map(CiResult::issueId).collect(Collectors.toSet())).isEqualTo(expected);
assertThat(ci).allSatisfy(r -> assertThat(r.passed()).isTrue());

// Every issue was allocated: the AUCTION completions land in the issues
// space as CodeChange result entries (the changes space copies are taken
// and consumed by review, becoming Review entries). Await them settling.
List<CodeChange> changes = awaitAllocations(coordinator, issueCount,
        Duration.ofSeconds(30));
Set<String> changedIssues = changes.stream().map(CodeChange::issueId)
        .collect(Collectors.toSet());
assertThat(changedIssues).isEqualTo(expected);
✓ 1 test · 9.1 to 9.5 s on 2026-11-04 · no key and no model

On 2026-11-04 at AgentSpaces 0.5.0 the test passed three times, in 9.11, 9.45 and 9.25 seconds of test time and about 10.0 to 10.2 seconds for the whole Maven build. The stack trace in the output is the sweeper's deliberate crash. The test proves what its assertions say: CI passed for nine distinct issues with a worker configured to die, nine distinct issues have a completed change, no more than two changes came from that worker, the work was shared between at least two coders, the sweeper died and the issue it held was completed by another coder that passed CI, and the agent key that signed each change is the author the change names. It does not assert the price or the delay of the re-run, that each winner was the lowest bidder, or that no duplicate was ever written, because both distinct-id checks tolerate one. The sweeper assertion needs the sweeper to reach a third take. It does so in practice, because nine issues keep three coders busy for about three waves, and a run in which it never did would fail on the assertion that the sweeper reached its third take and died.

aspace://guide/code-fleet/next · chapter 12

Where to go next

The developer guide covers the parts this app uses: @BidFunction and @SpaceTake for the annotations, conflict strategies for LEASE_RACE and AUCTION, leases, agent certificates for the per-agent keys, and the example apps for the other example apps. The workflow guide has a short chapter on routing by cost and one on the two failure models. The Party Bus guide puts an auction beside a quorum vote and an ordered log, and the Superfriends guide runs three model frameworks in one fleet.

Where to take it

  • Real models behind the same contract. Replace the sleep in code() with a model call that returns a CodeChange. The bid function is the seam for a real cost, latency and quality model per agent.
  • A rejection path. Let a rejected Review write the issue back, so the cycle becomes propose, review, revise.
  • Cards for a console. Pass a DiscoveryService to register, and the five agent cards become visible to the fleet console and to planners.
  • Patches as artifacts. A CodeChange carries no diff today. With the content swarm that came in 0.5.0 (agentspaces-content), a coder can publish its patch as an artifact and put the root in the entry, and a reviewer fetches the bytes from every member that holds them.
  • A lapse counter. The traced run shows no REAPPEARED event for ISSUE-8, because the re-claim landed before the lease sweep. A watcher that counts TAKEN events per issue is the dependable meter: a second TAKEN for one issue marks one lapse, and the kill story becomes a number on a dashboard.