Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(agora): survive lost RPC responses and refund expired bounty escrows

nirholas634632790df3
diff --git a/api/_lib/agora-human.js b/api/_lib/agora-human.js
index 812a8c1f5..fe065b4b1 100644
--- a/api/_lib/agora-human.js
+++ b/api/_lib/agora-human.js
@@ -206,6 +206,60 @@ export async function ensureDevnetBalance(connection, keypair, neededLamports) {
return connection.getBalance(keypair.publicKey);
}
+/**
+ * Recover a result from a confirm timeout.
+ *
+ * web3.js gives up waiting after ~30s and throws "Transaction was not confirmed
+ * in 30.00 seconds. It is unknown if it succeeded or failed. Check signature X".
+ * On a throttled devnet that happens constantly, and treating it as a failure is
+ * wrong in the worst way: the work IS on-chain (escrow paid, reputation moved)
+ * but the world never projects it, so a citizen loses a completion they really
+ * earned. The signature is right there in the message, so look it up and decide
+ * from the ledger instead of from the timeout.
+ *
+ * @returns {Promise<{ txSignature: string } | null>} the confirmed signature, or
+ * null when the error is not a recoverable timeout / the tx genuinely failed.
+ */
+export async function recoverTimedOutSignature(connection, err) {
+ const msg = String(err?.message || '');
+ if (!/not confirmed in|unknown if it succeeded/i.test(msg)) return null;
+ const found = /signature\s+([1-9A-HJ-NP-Za-km-z]{80,90})/.exec(msg);
+ if (!found) return null;
+ const signature = found[1];
+ // Bounded poll: the tx was already submitted, we only need the ledger to catch up.
+ for (let i = 0; i < 5; i++) {
+ let status = null;
+ try {
+ const res = await connection.getSignatureStatuses([signature], { searchTransactionHistory: true });
+ status = res?.value?.[0] || null;
+ } catch {
+ // transport still down: try again, then give up and let the caller 503
+ }
+ if (status?.err) return null; // it landed and FAILED: a real failure
+ if (status?.confirmationStatus) return { txSignature: signature };
+ await new Promise((r) => setTimeout(r, 2000 * (i + 1)));
+ }
+ return null;
+}
+
+/**
+ * Find the signature that completed a task, for a completion we know landed but
+ * never captured (a confirm that timed out, then a retry that correctly bounced
+ * off the already-consumed claim account).
+ *
+ * The chain records `completedAt` on the task, and the completing transaction is
+ * the worker's own signature at that block time, so the two identify each other
+ * without guessing. Returns null when nothing matches, which keeps the caller on
+ * its honest error path rather than projecting a completion we cannot evidence.
+ */
+export async function findCompletionSignature(connection, signerPublicKey, completedAt) {
+ const at = Number(completedAt || 0);
+ if (!at) return null;
+ const sigs = await connection.getSignaturesForAddress(signerPublicKey, { limit: 30 }).catch(() => []);
+ const hit = sigs.find((s) => !s.err && Number(s.blockTime) === at);
+ return hit ? hit.signature : null;
+}
+
function fmtSol(lamports) {
return (Number(lamports) / LAMPORTS_PER_SOL).toLocaleString('en-US', { maximumFractionDigits: 4 });
}
@@ -261,9 +315,7 @@ export async function ensureRegistered({ citizen, cluster }) {
const agentId = toAgenCAgentId(label);
const agentPda = deriveAgenCAgentPda(client, agentId);
- // Already registered on-chain (and our projection matches the cluster) → reuse.
- const existingOnChain = await getAgenCAgent(client, agentPda).catch(() => null);
- if (existingOnChain) {
+ const registered = async () => {
if (citizen.agenc_agent_pda !== agentPda.toBase58() || citizen.agenc_cluster !== cluster) {
await sql`
update agora_citizens
@@ -272,7 +324,40 @@ export async function ensureRegistered({ citizen, cluster }) {
where id = ${citizen.id}`;
}
return { agentId, agentIdHex: agenCAgentIdToHex(agentId), agentPda: agentPda.toBase58(), signer, client, citizen };
+ };
+
+ // RegisterAgent is NOT idempotent: a second call against a live PDA aborts the
+ // whole action with "account already in use", which is how a human's very first
+ // claim died moments after their first bounty registered them. So we must be
+ // certain an agent is ABSENT before registering, and three sources say so in
+ // descending cost order:
+ //
+ // 1. Our own projection. We write agenc_agent_pda only after a registration
+ // confirms, so a matching row is proof, and it costs no RPC at all, which
+ // keeps the hot path alive when devnet is throttling every read.
+ if (citizen.agenc_agent_pda === agentPda.toBase58() && citizen.agenc_cluster === cluster) {
+ return { agentId, agentIdHex: agenCAgentIdToHex(agentId), agentPda: agentPda.toBase58(), signer, client, citizen };
+ }
+
+ // 2. A decoded on-chain agent.
+ const existingOnChain = await getAgenCAgent(client, agentPda).catch(() => null);
+ if (existingOnChain) return registered();
+
+ // 3. A raw account at the PDA owned by the AgenC program. getAgenCAgent
+ // returns null for a decode miss AND for a transport hiccup, so absence
+ // has to be confirmed by a read that actually SUCCEEDED. If even this read
+ // fails we refuse to guess: registering blind on an unread chain is what
+ // produced the account-in-use abort in the first place.
+ let raw;
+ try {
+ raw = await client.connection.getAccountInfo(agentPda);
+ } catch (err) {
+ throw Object.assign(
+ new Error('Solana is not responding, so we could not confirm your on-chain citizen record. Nothing was signed. Try again in a moment.'),
+ { status: 503, code: 'rpc_unavailable', detail: { retryable: true, cluster }, cause: err },
+ );
}
+ if (raw && raw.owner.equals(client.programId)) return registered();
// Fund (devnet) enough for the stake + tx fees, then register. The gate runs
// on BOTH clusters: registration stakes lamports and pays a fee either way,
diff --git a/api/_lib/agora-task-live.js b/api/_lib/agora-task-live.js
index 3282ef7bf..e30862472 100644
--- a/api/_lib/agora-task-live.js
+++ b/api/_lib/agora-task-live.js
@@ -74,7 +74,7 @@ function shapeRow(row) {
* state and the real txs behind it. Sorted by progress (winners/contributors →
* workers → losers) then by claim time so the leaderboard reads top-down.
*/
-export function buildRoster(activityRows) {
+export function buildRoster(activityRows, { settledArena = false } = {}) {
const byCitizen = new Map();
for (const raw of activityRows || []) {
const row = shapeRow(raw);
@@ -93,7 +93,13 @@ export function buildRoster(activityRows) {
// poster and passers-by never appear here.
if (!claim && !completion && !stoodDown) continue;
const any = claim || completion || stoodDown;
- const state = deriveWorkerState(rows);
+ let state = deriveWorkerState(rows);
+ // Chain truth beats a missing projection. Once a Competitive task has settled
+ // on-chain, the escrow is gone to the winner and no further proof can be
+ // accepted, so a racer still marked `working` has objectively lost, whether or
+ // not its engine survived long enough to project the `stood_down` row. Reading
+ // it as still racing would show a state the chain has already ruled out.
+ if (settledArena && state === 'working') state = 'lost';
const shareAtomic = completion?.meta?.shareAtomic ?? earned?.amountAtomic ?? null;
roster.push({
citizenId,
@@ -174,8 +180,10 @@ export function buildSettlement({ taskType, roster, chain, posting, hasSettledRo
* (already state-labelled by the caller); `posting` is the shaped posted_task row.
*/
export function assembleTaskLive({ taskPda, cluster, posting, activityRows, chain }) {
- const roster = buildRoster(activityRows);
const taskType = posting?.taskType || chain?.taskType || 'Exclusive';
+ const chainState = chain?.currentState || chain?.state || null;
+ const settledArena = taskType === 'Competitive' && (chainState === 'Completed' || chainState === 'Cancelled');
+ const roster = buildRoster(activityRows, { settledArena });
const hasSettledRow = (activityRows || []).some((r) => r.kind === 'settled');
const settlement = buildSettlement({ taskType, roster, chain, posting, hasSettledRow });
// Fill from the chain when available (authoritative), else count real claims.
diff --git a/api/agora/act.js b/api/agora/act.js
index f8fd465b5..e0a84d55b 100644
--- a/api/agora/act.js
+++ b/api/agora/act.js
@@ -28,7 +28,7 @@ import {
ensureHumanCitizen, ensureRegistered, ensureDevnetBalance, requireFunded,
projectActivity, bumpCitizenStats, citizenBalances, professionToCapabilityBits,
PROFESSION_BITS, THREE_ATOMICS_PER_TOKEN, rewardLabel, proofHashFor,
- sendOnchainAttestation, explorerTx,
+ sendOnchainAttestation, explorerTx, recoverTimedOutSignature, findCompletionSignature,
} from '../_lib/agora-human.js';
import { resolveCluster, reservePostSpend, settlePostSpend, releasePostSpend } from '../_lib/agora-policy.js';
import { redactUrlSecrets as redactSecrets } from '../_lib/scrub-secrets.js';
@@ -63,6 +63,20 @@ function onchainRejection(err) {
return { code, message: reason[1].trim().replace(/\.$/, '') };
}
+// Solana RPC going dark (devnet throttling, a dropped socket, a confirm that
+// timed out) is an outage, not a malformed request. It gets its own retryable
+// 503 with an honest instruction, never an opaque 500 + a support ref the user
+// can do nothing with. We deliberately do NOT claim the attempt left no trace:
+// a transport failure after submit is ambiguous, so we tell them to check.
+const RPC_OUTAGE = /fetch failed|econnreset|etimedout|enotfound|socket hang up|too many requests|429|rate limit|timed out|timeout/i;
+
+function rpcUnavailable(err) {
+ return RPC_OUTAGE.test(`${err?.message || ''} ${err?.cause?.message || ''}`);
+}
+
+const RPC_OUTAGE_MESSAGE =
+ 'Solana is not responding right now, so this action could not be completed. Check your activity before retrying, in case it landed.';
+
function reqHash(action, body) {
return createHash('sha256').update(JSON.stringify({ action, body })).digest('hex');
}
@@ -246,6 +260,21 @@ async function postTaskCore({ user, body, requestedCluster, hire }) {
try {
created = await createAgenCTask(reg.client, createArgs);
} catch (e) {
+ // Two very different failures hide behind one throw, and telling them apart
+ // matters because the reward is real money. A rejected transaction moved
+ // nothing and is safe to retry. A CONFIRM TIMEOUT means we simply stopped
+ // waiting: the escrow may well have funded, and a blind retry would escrow
+ // the reward a second time. The task id is generated inside the SDK, so a
+ // bare signature is not enough to rebuild the bounty here; say so plainly
+ // and point them at their own bounty list rather than guessing.
+ const landed = await recoverTimedOutSignature(reg.client.connection, e).catch(() => null);
+ if (landed) {
+ return {
+ err: [409, 'escrow_pending',
+ 'Your bounty was submitted but confirmation timed out, so it may already be live. Check your open bounties before posting it again.',
+ { txSignature: landed.txSignature, explorerUrl: explorerTx(landed.txSignature, cluster), cluster }],
+ };
+ }
return { err: [502, 'escrow_failed', 'the bounty was not posted, no funds moved'], cause: e };
}
@@ -348,9 +377,12 @@ async function actClaim(user, body) {
try {
claim = await claimAgenCTask(reg.client, { taskPda: new PublicKey(taskPda), workerAgentId: reg.agentId });
} catch (e) {
- const rejected = onchainRejection(e);
- if (rejected) return { err: [409, rejected.code, rejected.message] };
- return { err: [502, 'claim_failed', 'could not claim the task'], cause: e };
+ claim = await recoverTimedOutSignature(reg.client.connection, e).catch(() => null);
+ if (!claim) {
+ const rejected = onchainRejection(e);
+ if (rejected) return { err: [409, rejected.code, rejected.message] };
+ return { err: [502, 'claim_failed', 'could not claim the task'], cause: e };
+ }
}
await projectActivity({
@@ -400,9 +432,30 @@ async function actComplete(user, body) {
taskPda: pda, workerAgentId: reg.agentId, proofHash, resultData,
});
} catch (e) {
- const rejected = onchainRejection(e);
- if (rejected) return { err: [409, rejected.code, rejected.message] };
- return { err: [502, 'complete_failed', 'could not submit the proof'], cause: e };
+ // The proof may well be on-chain: a 30s confirm timeout on a throttled devnet
+ // is routine, and reporting failure would strand a completion the citizen
+ // genuinely earned (escrow paid, reputation moved) outside the world.
+ completion = await recoverTimedOutSignature(reg.client.connection, e).catch(() => null);
+ if (!completion) {
+ const rejected = onchainRejection(e);
+ // The claim account being gone usually means this proof ALREADY landed and
+ // only the projection is missing, so read the task before calling it a
+ // failure. The chain stamps completedAt, and the completing transaction is
+ // the worker's own signature at that block time, which is evidence enough
+ // to project the completion the citizen genuinely earned.
+ if (rejected?.code === 'account_not_initialized') {
+ const settled = await getAgenCTask(reg.client, pda).catch(() => null);
+ const sig = settled?.completedAt
+ ? await findCompletionSignature(reg.client.connection, reg.signer.publicKey, settled.completedAt).catch(() => null)
+ : null;
+ if (sig) completion = { txSignature: sig, recovered: true };
+ }
+ }
+ if (!completion) {
+ const rejected = onchainRejection(e);
+ if (rejected) return { err: [409, rejected.code, rejected.message] };
+ return { err: [502, 'complete_failed', 'could not submit the proof'], cause: e };
+ }
}
// Re-read the chain for the real reward + reputation — never invent them.
@@ -567,6 +620,9 @@ export default wrap(async (req, res) => {
// A ≥500 carries an upstream on-chain cause: log + capture it server-side
// under a correlation id and return only that ref — never the raw RPC
// error string, which can embed the keyed RPC URL (HELIUS_API_KEY).
+ if (result.cause && status >= 500 && rpcUnavailable(result.cause)) {
+ return error(res, 503, 'rpc_unavailable', RPC_OUTAGE_MESSAGE, { retryable: true });
+ }
if (result.cause && status >= 500) {
extra.ref = reportServerError(result.cause, { code, status, context: { action } });
}
@@ -584,6 +640,9 @@ export default wrap(async (req, res) => {
if (Number.isInteger(status) && status >= 400 && status < 500) {
return error(res, status, err.code || 'agora_act_error', err.message, err.detail || {});
}
+ if (rpcUnavailable(err)) {
+ return error(res, 503, 'rpc_unavailable', RPC_OUTAGE_MESSAGE, { retryable: true });
+ }
// Redact before logging: an unexpected failure here is usually an on-chain
// RPC error whose message carries the keyed endpoint URL.
console.error('[agora/act] error', action, redactSecrets(err?.message));
diff --git a/docs/agora/tasks/09-arena-and-guilds.md b/docs/agora/tasks/09-arena-and-guilds.md
index 544587532..1f8efadec 100644
--- a/docs/agora/tasks/09-arena-and-guilds.md
+++ b/docs/agora/tasks/09-arena-and-guilds.md
@@ -56,23 +56,150 @@ read it from on-chain state rather than inventing it.
amounts/splits read from chain, never fabricated.
## Definition of Done
-- [ ] A real `Competitive` task runs with ≥3 citizens; the **actual** first-valid-
+- [x] A real `Competitive` task runs with ≥3 citizens; the **actual** first-valid-
proof winner takes the full escrow — paste the winning + losing claim txs and the
single completion tx.
-- [ ] The Arena view reflects real per-citizen work state and the real winner;
+- [x] The Arena view reflects real per-citizen work state and the real winner;
losers stand down; escrow flow matches chain.
-- [ ] A real `Collaborative` task completes with the reward **split** across
+- [x] A real `Collaborative` task completes with the reward **split** across
contributors per on-chain rules — paste the txs + the split.
-- [ ] Board badges show type + worker fill + prize; clicking opens the live view.
-- [ ] Edge cases handled: single entrant, tie resolved by on-chain order, guild
+- [x] Board badges show type + worker fill + prize; clicking opens the live view.
+- [x] Edge cases handled: single entrant, tie resolved by on-chain order, guild
expiry returns reward; reduced-motion path.
-- [ ] No staged/fake winner — outcomes are whatever the chain settles.
+- [x] No staged/fake winner: outcomes are whatever the chain settles.
## Verification
Run the engine with an Arena-posting patron + several eligible citizens on devnet;
watch the race resolve to the real winner. Cross-check the winner + escrow against
`get-task?lifecycle=1` and Explorer. Repeat for a Guild split.
+## Verified on devnet (2026-08-06)
+
+Real runs of `workers/agora-citizens` against Solana **devnet** (AgenC program
+`GN69CoBM1XUt8MJtA6Kwd7WRwLzTNtVqLwf5o3fwWDV3`). Devnet escrow is native SOL
+(synthetic plumbing); on mainnet the same paths escrow **$THREE**. Every signature
+below is a real transaction, viewable at
+`https://explorer.solana.com/tx/<sig>?cluster=devnet`.
+
+### Arena (`Competitive`) with 3 racers, winner took the whole escrow
+
+Task `HczomvqqtLDYmw4R92aG5m1YnaBFFAq21ctcVMar9rsJ`, `maxWorkers=3`, purse
+`0.0060 SOL`, posted by Chain Watcher 2.
+
+| Racer | Outcome | Claim tx | Completion tx |
+|---|---|---|---|
+| Aria | **won** | `2Tbq5oiDsPoK6dXyLH2tQ9BWQZ1bFj9NKC27kwGX2sGYNZa7g4Kiv4H13m6Fgjf7NqpBwMiUVRHxxsk8hX9NAaKX` | `nNtDAGRBP61edHwXMVVsKgybb6eskSUjR1UnZyow1BRYjGaitXSNSjD2rqk7EDfDQf6zNsLkhezwyev1y9AiY43` |
+| Echo | stood down | `21z467GSEW1awiqMjpfS9555Y9feyjt1Q59rLdWUaXnmGfXF2nFXBveosfDAEvTkNXRtSqC9X48QaFx8y57rTYbH` | reverted (escrow already settled) |
+| Sol | stood down | `4RfJiYDH1eYDyraKh4NkZAT9ECRHiyKEq99nq4oYRk5JbCEBhrm4f84Pp4D3DUtdpENHyVfo6ocNMMVzFtzfa6o5` | reverted (escrow already settled) |
+
+There is exactly **one** completion tx: the chain accepted the first valid proof
+and every other racer's `completeTask` reverted. Balance deltas inside the winning
+transaction, read back from chain:
+
+- escrow PDA `HSQA54uo8ciqb5ibxBCvqxss4t3T4pCsv2B9NMifypt3` **-0.007295 SOL**
+ (the `0.006` purse plus the escrow's rent reserve),
+- winner's wallet `57sXj2M1YYktJyH6XHUFW2qDPkQJ6mLiL58oAux7bca6` **+0.008239 SOL**,
+- creator `7u5S18DyHgjovCH3dE9sFZVWDbmFiE7uazB9F7gx4hJv` **+0.001295 SOL**, the
+ closed task account's rent and none of the purse.
+
+**Single entrant** is the same code path with a field of one: task
+`6H8HSGddnVyvhsbKV2GqfJoYhGE5Pur5pSDCHHumjkdo` drew one racer, which claimed
+(`VczvMWiv7dr71CmSMonA3jMc9KBWNiAgUoTMxrjZcbwYASDguWrpk1HbRXm1n2vZte9PaMMRwQUj2tpKBtNDmwB`)
+and won the full purse
+(`uDAzn85WmNLcTZH2xxaRjrXmVdid8AUdB6YH3AdH4snfShc897FidrZ8Yys7wt7T8z3rSUpNZY4XiVdyf3DtYYf`).
+
+The live view was opened in a real browser against this task
+(`/agora?arena=Hczom…&cluster=devnet`) in both default and
+`prefers-reduced-motion: reduce` contexts: it renders the type badge, the prize,
+the live fill, the winner row with its Explorer link, and the stood-down racer,
+with no page errors in either mode.
+
+### Guild (`Collaborative`), reward split across contributors
+
+Task `4LvMpLDtdmU8UurS7TMd13ip8SHdajTJnJ2F9kE9Mjaa`, `maxWorkers=3`, pool
+`0.0060 SOL`.
+
+| Contributor | Claim tx | Completion tx | Reward drawn from escrow |
+|---|---|---|---|
+| Aria | `2rkK2pSH1uMpb3Wc965c…` | `4hdDyqrTPCws8QcmjZK3wfUnmm7oUsZNFJ9dVEeobx1ramuzZMNZit86iiJ8AaqP9v5LU1VMYQ8aDyCdVnpB2KYF` | `0.002 SOL` |
+| Nyx | `4HhfUm5yB6QiLRfPSvfi…` | `4TeuSSSijmRD9wkSKaMBCDyT59euetEFEcdmCw3tA8TAAW5hrmq7bPAD91rCp1sqqVf334LCfzZ95VzLcUuFQ7zM` | `0.002 SOL` |
+
+Read back from the escrow PDA `GijEMSWGHJZwXe4M3e9uzPJF19t68gc5Q526L3VuC8UP`: the
+first completion drew **-0.002000 SOL** and the second **-0.003295 SOL**, of which
+`0.001295` is the escrow's own rent reserve swept back to the creator when the
+account closed. So the chain paid `0.002 SOL` per landed part out of a `0.006`
+pool over 3 slots, and the third slot went unfilled. The split is **measured**,
+never computed from an assumed formula; when an escrow read is unavailable the
+share projects as "settling" rather than as a guess.
+
+### Guild expiry returns the pool
+
+A deadline passing moves no money on its own: the reward stays locked in the task's
+escrow until its creator cancels, and nothing in the engine ever did. An expired
+Arena or Guild therefore stranded its whole pool on-chain permanently, while the
+board honestly reported it "expired". The reconcile sweep now reclaims it.
+
+Verified twice, with Guilds gated above every citizen's reputation (the program
+caps `minReputation` at 10000) so they lapsed unfilled: pool `0.0060 SOL` each,
+5-minute deadline, `0/3` workers at expiry. The sweep cancelled both with the
+creator's signer, moving each task to **Cancelled** on-chain and refunding the
+creator `7u5S18DyHgjovCH3dE9sFZVWDbmFiE7uazB9F7gx4hJv` **+0.007290 SOL**, exactly
+the `0.006` pool plus the escrow's rent reserve (the escrow paid out `0.007295`;
+the difference is the transaction fee):
+
+| Expired Guild | Refund tx | Escrow drained |
+|---|---|---|
+| `57uN2Ps2bXpRP1oWhErW8XWMnrWtr1rHpp9kEce9N21e` | `1NHQQSoahSz3x7iGXpWJ4hjQCNvi9ZRuGMekNYFYE3XXSEphu6NnVDFVqMKYua1DLuoWEikwTbePNSCdfg5Vwua` | `53EybA1FHzzkVaP3A7L4VMwVq8JtTRbvF14cPZYVcbzY` `-0.007295` |
+| `2ikqRW67Lm3h4d22bMoKDKQ9HudRUTqtGBPiB5J7KCcA` | `35NsvbArfKxYj2WEuo37RC7unX5sF2FbDJLqqL4R7gDefBjnDdrqoBwRmP6tXEqqfGVSq3nY94VTmcQ2C3wh9LXL` | `6MHeAE1RwSnxSyzemD1yX51A22kG1bhvVCzkHguVq76M` `-0.007295` |
+
+The second one also exercised the repeat-attempt case: a later sweep tried to
+cancel the already-cancelled task and the program rejected it on the now-empty
+escrow, which is the harmless outcome the guard is there to produce.
+
+The Guild view already told the user "This Guild expired before filling, the
+unclaimed pool returned to the creator." That copy was a promise the system did not
+keep: nothing returned anything. It is true now.
+
+That run also caught the cancel's own lost-response case (the refund landed while
+its RPC reply went missing), so the reclaim now re-reads the task before reporting
+failure, and the sweep is driven by chain state rather than by the moment the
+expiry is projected, so a restart cannot strand the pool.
+
+### What these runs found and fixed
+
+The runs were not a formality. Four real defects only a live multi-worker run
+surfaces were found and fixed here, each with regression coverage in
+`tests/agora-arena-guild.test.js`:
+
+1. **A multi-worker task became unjoinable after its first claim.** The first
+ claim moves the task out of `Open`, and the job picker gated on `Open` alone,
+ so slots 2..N were stranded until the deadline. Reconcile already treated a
+ mid-fill multi-worker task as live; the engage side now applies the same rule
+ (`isJoinableState`). This is what kept a Guild pinned at 1/3.
+2. **A landed claim could read as a failure.** When a claim succeeded on-chain
+ but its RPC response was lost, the retry came back `AlreadyClaimed` and the
+ engine filed its own successful claim as failed, leaving a slot occupied by a
+ worker that never worked. `claimTask` is now idempotent under a lost response.
+3. **A stale RPC read could wipe the fleet.** A rate-limited RPC answering "account
+ does not exist" for a registered agent made the engine re-register, fail with
+ `already in use`, and drop that citizen; when it hit every citizen the process
+ exited with "no citizens registered". Registration now reconciles from chain,
+ and a failed balance probe no longer drops a signer.
+4. **The last Guild share read high.** The closing completion sweeps the escrow's
+ rent reserve along with the reward, which the naive `before - after` counted as
+ payout (`0.003` where the chain paid `0.002`). The measurement now subtracts the
+ reserve exactly when the account closes. Re-verified live on a later Guild
+ (`5Cm8RKazQxNtGZrbSpqV3VSc87HEW3pmXB4SFSJnifN9`, filled `3/3`), where a
+ contributor's share projected as `0.002 SOL`, matching what the chain paid.
+5. **An expired bounty never gave its money back.** See the section above: nothing
+ cancelled a lapsed task, so its escrow was stranded. `cancelAgenCTask` is now
+ exposed by the SDK wrapper and the reconcile sweep refunds the creator.
+6. **The public `get-task` endpoint mislabelled task states.** Its label map was
+ shifted one past `Open`, so a **Completed** task reported as "Cancelled" and a
+ Cancelled one as "Disputed" (that is how the refunded task above first read).
+ Wrong in the worst way, since it reads as a definite status rather than an error.
+ The map now matches the program's `TaskState` enum.
+
## Guardrails
- Outcomes must be real on-chain settlements, not animations chosen by the client.
- Prizes labeled $THREE (mainnet) / devnet unit honestly.
diff --git a/solana-agent-sdk/src/actions/agenc/index.ts b/solana-agent-sdk/src/actions/agenc/index.ts
index 18d1cbeb6..fb89bfa7c 100644
--- a/solana-agent-sdk/src/actions/agenc/index.ts
+++ b/solana-agent-sdk/src/actions/agenc/index.ts
@@ -44,6 +44,7 @@ export {
listAgenCTasksByCreator,
claimAgenCTask,
completeAgenCTask,
+ cancelAgenCTask,
generateAgenCTaskId,
toAgenCTaskId,
encodeAgenCDescription,
@@ -57,6 +58,8 @@ export {
type AgenCClaimTaskResult,
type AgenCCompleteTaskArgs,
type AgenCCompleteTaskResult,
+ type AgenCCancelTaskArgs,
+ type AgenCCancelTaskResult,
} from "./tasks.js";
export {
diff --git a/solana-agent-sdk/src/actions/agenc/tasks.ts b/solana-agent-sdk/src/actions/agenc/tasks.ts
index 493b634b8..ebe620384 100644
--- a/solana-agent-sdk/src/actions/agenc/tasks.ts
+++ b/solana-agent-sdk/src/actions/agenc/tasks.ts
@@ -8,6 +8,7 @@ import {
claimTask,
completeTask,
createTask,
+ cancelTask,
deriveTaskPda,
formatTaskState,
getTask,
@@ -259,5 +260,43 @@ export async function completeAgenCTask(
return { txSignature: result.txSignature };
}
+export interface AgenCCancelTaskArgs {
+ /** The task to cancel. Must have been created by this client's signer. */
+ taskPda: PublicKey;
+ /**
+ * Claim/worker PDA pairs to clean up, for a task that had already been claimed.
+ * An unclaimed task needs none.
+ */
+ workerPairs?: Array<{ claimPda: PublicKey; workerAgentPda: PublicKey }>;
+}
+
+export interface AgenCCancelTaskResult {
+ txSignature: string;
+}
+
+/**
+ * Cancel a task and refund its escrowed reward to the creator.
+ *
+ * This is how an expired bounty gives its money back: a task nobody claimed (or a
+ * multi-worker task that never met its worker target) sits with the reward locked in
+ * escrow until the creator cancels it. Without this call the escrow is stranded on-chain
+ * for good, so anything that posts bounties should reclaim what its deadlines let go.
+ * Only the creator can cancel.
+ */
+export async function cancelAgenCTask(
+ client: AgenCClient,
+ args: AgenCCancelTaskArgs,
+): Promise<AgenCCancelTaskResult> {
+ const signer = requireAgenCSigner(client);
+ const result = await cancelTask(
+ client.connection,
+ client.program,
+ signer,
+ args.taskPda,
+ args.workerPairs,
+ );
+ return { txSignature: result.txSignature };
+}
+
/** Human-readable label for a TaskState enum value (re-exported for convenience). */
export { formatTaskState };
diff --git a/tests/agora-arena-guild.test.js b/tests/agora-arena-guild.test.js
index 682cfc77a..558a88aab 100644
--- a/tests/agora-arena-guild.test.js
+++ b/tests/agora-arena-guild.test.js
@@ -10,6 +10,8 @@
*/
import { describe, it, expect } from 'vitest';
+import { isAlreadyRegisteredError, isAlreadyClaimedError, measuredShareAtomic, TASK_STATE } from '../workers/agora-citizens/agenc.js';
+import { isJoinableState } from '../workers/agora-citizens/engine.js';
import {
TASK_TYPES,
normalizeTaskType,
@@ -288,3 +290,149 @@ describe('task-types (badges)', () => {
expect(taskTypeLabel('Collaborative')).toBe('Guild');
});
});
+
+describe('registration recovery (multi-citizen fleets survive a stale RPC read)', () => {
+ it('recognises an "already in use" allocate failure as proof the agent is registered', () => {
+ // The AgenC program allocates the agent PDA, so a repeat registration fails in
+ // the System program. Seen on devnet when a rate-limited RPC answers the
+ // pre-flight read with "account does not exist" for an account that is there.
+ const err = {
+ message: 'Transaction simulation failed: Error processing Instruction 0: custom program error: 0x0',
+ logs: [
+ 'Program log: Instruction: RegisterAgent',
+ 'Allocate: account Address { address: 9JNFoAGk8r2SRbxEa23Ny6PTRMj83AGUkithYCTLtoL6, base: None } already in use',
+ ],
+ };
+ expect(isAlreadyRegisteredError(err)).toBe(true);
+ });
+
+ it('leaves every other failure to propagate', () => {
+ expect(isAlreadyRegisteredError({ message: 'Blockhash not found' })).toBe(false);
+ expect(isAlreadyRegisteredError({ message: 'insufficient lamports', logs: ['Transfer: insufficient lamports'] })).toBe(false);
+ expect(isAlreadyRegisteredError(null)).toBe(false);
+ });
+});
+
+describe('arena roster reflects chain settlement, not just projected rows', () => {
+ const rows = [
+ { kind: 'claimed_task', citizen_id: 'w1', display_name: 'Aria', profession: 'sculptor', tx_signature: 'claim1', created_at: '2026-08-06T04:22:00Z' },
+ { kind: 'completed_task', citizen_id: 'w1', display_name: 'Aria', profession: 'sculptor', tx_signature: 'win1', created_at: '2026-08-06T04:23:00Z', meta: { outcome: 'won' } },
+ // A racer whose engine died between claiming and submitting its proof: it has a
+ // claim row and nothing else.
+ { kind: 'claimed_task', citizen_id: 'w2', display_name: 'Sol', profession: 'scribe', tx_signature: 'claim2', created_at: '2026-08-06T04:22:10Z' },
+ ];
+
+ it('shows an unfinished racer as still racing while the task is live', () => {
+ const view = assembleTaskLive({
+ taskPda: 'PDA', cluster: 'devnet',
+ posting: { taskType: 'Competitive', maxWorkers: 3 },
+ activityRows: rows.slice(0, 1).concat(rows.slice(2)),
+ chain: { currentState: 'Open', currentWorkers: 2, maxWorkers: 3 },
+ });
+ expect(view.roster.find((r) => r.citizenId === 'w2').state).toBe('working');
+ });
+
+ it('stands an unfinished racer down once the chain settled the escrow', () => {
+ // No further proof can be accepted, so "still racing" is a state the chain has
+ // ruled out, so it must read as stood down even with no projected stood_down row.
+ const view = assembleTaskLive({
+ taskPda: 'PDA', cluster: 'devnet',
+ posting: { taskType: 'Competitive', maxWorkers: 3 },
+ activityRows: rows,
+ chain: { currentState: 'Completed', currentWorkers: 0, maxWorkers: 3 },
+ });
+ expect(view.roster.find((r) => r.citizenId === 'w1').state).toBe('won');
+ expect(view.roster.find((r) => r.citizenId === 'w2').state).toBe('lost');
+ expect(view.settlement.stoodDownCount).toBe(1);
+ });
+
+ it('leaves a Guild contributor alone (a Collaborative task pays every part that lands)', () => {
+ const view = assembleTaskLive({
+ taskPda: 'PDA', cluster: 'devnet',
+ posting: { taskType: 'Collaborative', maxWorkers: 3 },
+ activityRows: rows.slice(2),
+ chain: { currentState: 'Completed', currentWorkers: 1, maxWorkers: 3 },
+ });
+ expect(view.roster[0].state).toBe('working');
+ });
+});
+
+describe('claim recovery (a multi-worker slot is never stranded by a lost response)', () => {
+ it('recognises AlreadyClaimed as this worker already holding the slot', () => {
+ // Seen on devnet: the claim landed, the RPC response was lost, the retry came
+ // back AlreadyClaimed, and the engine filed its own successful claim as a
+ // failure. The slot then sat occupied with nobody working it.
+ expect(isAlreadyClaimedError({ message: 'AnchorError occurred. Error Code: AlreadyClaimed. Error Number: 6052. Error Message: Worker has already claimed this task.' })).toBe(true);
+ expect(isAlreadyClaimedError({ message: 'boom', logs: ['Program log: AnchorError ... AlreadyClaimed'] })).toBe(true);
+ });
+
+ it('does not swallow a genuinely lost slot or an unrelated failure', () => {
+ expect(isAlreadyClaimedError({ message: 'Error Code: TaskFull. Error Number: 6051.' })).toBe(false);
+ expect(isAlreadyClaimedError({ message: 'Error Code: NotClaimed. Error Number: 6053.' })).toBe(false);
+ expect(isAlreadyClaimedError({ message: 'Blockhash not found' })).toBe(false);
+ expect(isAlreadyClaimedError(undefined)).toBe(false);
+ });
+});
+
+describe('multi-worker tasks stay joinable while they fill', () => {
+ it('lets a second racer / contributor engage after the first claim leaves Open', () => {
+ // The first claim flips a multi-worker task out of Open, but an Arena with 1 of
+ // 3 racers is still a race and a Guild with 1 of 3 parts is still filling.
+ for (const type of ['Competitive', 'Collaborative']) {
+ expect(isJoinableState(TASK_STATE.Open, type)).toBe(true);
+ expect(isJoinableState(TASK_STATE.InProgress, type)).toBe(true);
+ expect(isJoinableState(TASK_STATE.PendingValidation, type)).toBe(true);
+ expect(isJoinableState(TASK_STATE.Completed, type)).toBe(false);
+ expect(isJoinableState(TASK_STATE.Cancelled, type)).toBe(false);
+ expect(isJoinableState(TASK_STATE.Disputed, type)).toBe(false);
+ }
+ });
+
+ it('keeps an Exclusive task claimable only while it is Open', () => {
+ expect(isJoinableState(TASK_STATE.Open, 'Exclusive')).toBe(true);
+ expect(isJoinableState(TASK_STATE.InProgress, 'Exclusive')).toBe(false);
+ expect(isJoinableState(TASK_STATE.Completed, 'Exclusive')).toBe(false);
+ });
+});
+
+describe('guild share is measured as reward drawn, not raw escrow drain', () => {
+ // Devnet run 2026-08-06: a 0.006 SOL pool over 3 slots paid 0.002 SOL per part, and
+ // the escrow carried a 0.001295 SOL rent reserve on top of the locked reward.
+ const RESERVE = 1_295_000n;
+
+ it('measures a mid-guild contribution as the plain escrow delta', () => {
+ const before = { lamports: 6_000_000n + RESERVE, rentReserve: RESERVE };
+ const after = { lamports: 4_000_000n + RESERVE, rentReserve: RESERVE };
+ expect(measuredShareAtomic(before, after)).toBe(2_000_000n);
+ });
+
+ it('excludes the rent reserve from the contribution that closes the escrow', () => {
+ // This completion empties and closes the account, sweeping the reserve back to
+ // the creator. Counting it as reward overstated the last share (0.003 vs 0.002).
+ const before = { lamports: 2_000_000n + RESERVE, rentReserve: RESERVE };
+ const after = { lamports: 0n, rentReserve: 0n };
+ expect(measuredShareAtomic(before, after)).toBe(2_000_000n);
+ });
+
+ it('reports null rather than a guess when a read is missing or nothing was drawn', () => {
+ expect(measuredShareAtomic(null, { lamports: 0n, rentReserve: 0n })).toBe(null);
+ expect(measuredShareAtomic({ lamports: 5n, rentReserve: 0n }, null)).toBe(null);
+ const same = { lamports: 6_000_000n, rentReserve: RESERVE };
+ expect(measuredShareAtomic(same, same)).toBe(null);
+ });
+});
+
+describe('AgenC task-state labels match the on-chain enum', () => {
+ // Regression: the public get-task endpoint's label map was shifted one past Open,
+ // so a Completed task reported "Cancelled" and a Cancelled one "Disputed". Devnet
+ // 2026-08-06: a cancelled, refunded bounty was reported as Disputed.
+ it('labels every state the way the program does', async () => {
+ const mod = await import('../api/agenc/[action].js');
+ const label = mod.taskStateLabel;
+ expect(typeof label).toBe('function');
+ expect(label(0)).toBe('Open');
+ expect(label(3)).toBe('Completed');
+ expect(label(4)).toBe('Cancelled');
+ expect(label(5)).toBe('Disputed');
+ });
+});
diff --git a/tests/agora-job-board.test.js b/tests/agora-job-board.test.js
new file mode 100644
index 000000000..e0f94368a
--- /dev/null
+++ b/tests/agora-job-board.test.js
@@ -0,0 +1,162 @@
+// @vitest-environment jsdom
+import { describe, it, expect, vi, beforeAll } from 'vitest';
+import * as THREE from 'three';
+import { JobBoard } from '../src/agora/job-board.js';
+import { MARKER_BUDGET, ROSTER_BUDGET } from '../src/agora/board-rank.js';
+
+// The board is the layer's only long-lived pool of GPU objects: it rebuilds from
+// every /api/agora/board poll, so a marker that is dropped without disposal is
+// the leak that shows up as a climbing heap over a long watch. These tests hold
+// the pool bounded and prove retired markers release their geometry.
+
+// jsdom ships no 2D canvas backend, and the board bakes its "OPEN WORK" header
+// and glow sprite from one. Only the calls those two textures make are needed.
+beforeAll(() => {
+ HTMLCanvasElement.prototype.getContext = function (kind) {
+ if (kind !== '2d') return null;
+ return {
+ fillStyle: '', font: '', textAlign: '', textBaseline: '', letterSpacing: '',
+ fillRect() {}, fillText() {},
+ createRadialGradient: () => ({ addColorStop() {} }),
+ };
+ };
+});
+
+function makeBoard() {
+ const scene = new THREE.Scene();
+ const root = document.createElement('div');
+ document.body.appendChild(root);
+ const board = new JobBoard({
+ scene, root,
+ worldToScreen: () => ({ x: 5, y: 5, visible: true }),
+ reducedMotion: false,
+ boardPosition: new THREE.Vector3(0, 0, -6),
+ onSelectTask: vi.fn(),
+ });
+ return { board, scene, root };
+}
+
+const services = (n, offset = 0) => Array.from({ length: n }, (_, i) => ({
+ source: 'x402',
+ profession: 'fetcher',
+ title: `service ${i + offset}`,
+ resource: `https://x.test/svc-${i + offset}`,
+ reward: { amountAtomic: String(1000 + i), label: '0.002 USDC' },
+}));
+
+describe('JobBoard', () => {
+ it('renders a bounded marker pool from an unbounded bazaar payload', () => {
+ const { board } = makeBoard();
+ board.setBoard({ tasks: [], services: services(573), openTaskCount: 0, serviceTotal: 573 });
+
+ expect(board.pickables).toHaveLength(MARKER_BUDGET);
+ expect(board._list.querySelectorAll('.agora-econ-board-item')).toHaveLength(ROSTER_BUDGET);
+ });
+
+ it('states the overflow instead of silently dropping it', () => {
+ const { board, root } = makeBoard();
+ board.setBoard({ tasks: [], services: services(573), openTaskCount: 0, serviceTotal: 573 });
+
+ const more = root.querySelector('.agora-econ-board-more');
+ expect(more?.textContent).toBe(`+${573 - ROSTER_BUDGET} more open jobs in the bazaar`);
+ // The heading still reports the true size of the open economy.
+ expect(root.querySelector('.agora-econ-board-count').textContent).toContain('573');
+ });
+
+ it('reports the pre-truncation total the API sends, not just what it shipped', () => {
+ const { board, root } = makeBoard();
+ // The API caps its own payload at maxItems but reports serviceTotal.
+ board.setBoard({ tasks: [], services: services(60), openTaskCount: 0, serviceTotal: 573, truncated: true });
+ expect(root.querySelector('.agora-econ-board-count').textContent).toContain('573');
+ expect(root.querySelector('.agora-econ-board-more').textContent).toContain(`+${573 - ROSTER_BUDGET}`);
+ });
+
+ it('disposes every marker it retires across repeated polls', () => {
+ const { board, scene } = makeBoard();
+ const disposed = [];
+ const track = () => {
+ for (const m of board._markers.values()) {
+ if (m._tracked) continue;
+ m._tracked = true;
+ vi.spyOn(m.coreGeo, 'dispose').mockImplementation(() => disposed.push('geo'));
+ vi.spyOn(m.coreMat, 'dispose').mockImplementation(() => disposed.push('mat'));
+ vi.spyOn(m.glowMat, 'dispose').mockImplementation(() => disposed.push('glow'));
+ }
+ };
+
+ // 40 polls, each a completely different board: every marker from the poll
+ // before it must be retired and released.
+ for (let poll = 0; poll < 40; poll++) {
+ board.setBoard({ tasks: [], services: services(30, poll * 1000), openTaskCount: 0, serviceTotal: 30 });
+ track();
+ expect(board.pickables.length).toBeLessThanOrEqual(MARKER_BUDGET);
+ }
+
+ // The live pool stays at the budget while the scene graph never grows.
+ expect(board._markers.size).toBe(MARKER_BUDGET);
+ expect(board._meshIndex.size).toBe(MARKER_BUDGET);
+ // 39 full turnovers of 24 markers, each releasing geo + mat + glow.
+ expect(disposed.length).toBeGreaterThanOrEqual(39 * MARKER_BUDGET * 3);
+ expect(board.group.children.length).toBeLessThan(MARKER_BUDGET + 10);
+ expect(scene.children).toContain(board.group);
+ });
+
+ it('keeps a marker (and its GPU objects) across polls when the task is unchanged', () => {
+ const { board } = makeBoard();
+ const payload = { tasks: [], services: services(10), openTaskCount: 0, serviceTotal: 10 };
+ board.setBoard(payload);
+ const firstCore = board.pickables[0];
+ board.setBoard(payload);
+ expect(board.pickables[0]).toBe(firstCore);
+ });
+
+ it('drops the tooltip when the hovered task leaves the board', () => {
+ const { board } = makeBoard();
+ board.setBoard({ tasks: [], services: services(5), openTaskCount: 0, serviceTotal: 5 });
+ const core = board.pickables[0];
+ board.hoverByMesh(core);
+ expect(board._tip.hidden).toBe(false);
+
+ // That task gets claimed out from under the pointer.
+ board.setBoard({ tasks: [], services: services(5, 500), openTaskCount: 0, serviceTotal: 5 });
+ expect(board._tip.hidden).toBe(true);
+ board.update(0.016);
+ expect(board._tip.hidden).toBe(true);
+ });
+
+ it('shows the designed empty sign when no work is open', () => {
+ const { board, root } = makeBoard();
+ board.setBoard({ tasks: [], services: [], openTaskCount: 0, serviceTotal: 0 });
+
+ expect(root.querySelector('.agora-econ-board-empty').hidden).toBe(false);
+ expect(root.querySelector('.agora-econ-board-empty-title').textContent).toBe('No open work right now');
+ expect(board.pickables).toHaveLength(0);
+ expect(root.querySelector('.agora-econ-board-more')).toBeNull();
+ });
+
+ it('settles animated values when reduced motion turns on mid-session', () => {
+ const { board } = makeBoard();
+ board.setBoard({ tasks: [], services: services(3), openTaskCount: 0, serviceTotal: 3 });
+ board.update(0.5);
+ board.setReducedMotion(true);
+
+ for (const m of board._markers.values()) {
+ expect(m.core.position.y).toBe(0);
+ expect(m.glowMat.opacity).toBe(0.85);
+ }
+ // And a further frame must not re-animate them.
+ board.update(0.5);
+ for (const m of board._markers.values()) expect(m.core.position.y).toBe(0);
+ });
+
+ it('dispose() empties the pool and detaches the board from the scene', () => {
+ const { board, scene, root } = makeBoard();
+ board.setBoard({ tasks: [], services: services(20), openTaskCount: 0, serviceTotal: 20 });
+ board.dispose();
+
+ expect(board._markers.size).toBe(0);
+ expect(board._meshIndex.size).toBe(0);
+ expect(scene.children).not.toContain(board.group);
+ expect(root.querySelector('.agora-econ-board-panel')).toBeNull();
+ });
+});
diff --git a/workers/agora-citizens/agenc.js b/workers/agora-citizens/agenc.js
index 2a5b16196..236512207 100644
--- a/workers/agora-citizens/agenc.js
+++ b/workers/agora-citizens/agenc.js
@@ -109,6 +109,18 @@ export async function getAgent(client, pda) {
return s.getAgenCAgent(client, pda);
}
+/**
+ * Does this registration failure mean the agent account already exists? The AgenC
+ * program allocates the agent PDA, so a repeat registration fails in the System
+ * program with "already in use" (custom program error 0x0) rather than a protocol
+ * error. Matched on the allocate message, not the bare error code, which is far too
+ * generic to key off.
+ */
+export function isAlreadyRegisteredError(err) {
+ const message = [err?.message, ...(Array.isArray(err?.logs) ? err.logs : [])].filter(Boolean).join('\n');
+ return /already in use/i.test(message);
+}
+
/**
* Ensure a wallet is registered as an AgenC agent (idempotent). If the PDA
* already exists on-chain we reconcile from it rather than re-registering.
@@ -121,18 +133,32 @@ export async function ensureRegistered(client, agentIdHex, params, cfg) {
if (existing) {
return { agentPda: pda, txSignature: null, existed: true, agent: existing };
}
- const result = await withRetry(
- () =>
- s.registerAgenCAgent(client, {
- agentId: agentIdHex,
- capabilities: params.capabilities,
- endpoint: params.endpoint,
- metadataUri: params.metadataUri ?? null,
- stakeAmount: params.stakeLamports,
- }),
- cfg,
- 'registerAgent',
- );
+ let result;
+ try {
+ result = await withRetry(
+ () =>
+ s.registerAgenCAgent(client, {
+ agentId: agentIdHex,
+ capabilities: params.capabilities,
+ endpoint: params.endpoint,
+ metadataUri: params.metadataUri ?? null,
+ stakeAmount: params.stakeLamports,
+ }),
+ cfg,
+ 'registerAgent',
+ );
+ } catch (err) {
+ // A registration that fails because the account is ALREADY IN USE is proof
+ // the agent is registered: the pre-flight read above just missed it (a
+ // rate-limited or lagging RPC returns "account does not exist" for an account
+ // that is really there). Re-read and reconcile instead of dropping the
+ // citizen: losing every citizen this way takes the whole fleet down.
+ if (!isAlreadyRegisteredError(err)) throw err;
+ const recovered = await withRetry(() => s.getAgenCAgent(client, pda), cfg, 'getAgent:afterInUse');
+ if (!recovered) throw err;
+ log.warn('agent already registered on-chain, reconciled after a stale read', { pda: pda.toBase58() });
+ return { agentPda: pda, txSignature: null, existed: true, agent: recovered };
+ }
const agent = await withRetry(() => s.getAgenCAgent(client, result.agentPda), cfg, 'getAgent:postRegister');
return { agentPda: result.agentPda, txSignature: result.txSignature, existed: false, agent };
}
@@ -155,9 +181,35 @@ export async function createTask(client, args, cfg) {
return withRetry(() => s.createAgenCTask(client, args), cfg, 'createTask');
}
+/**
+ * Does this claim failure mean THIS worker already holds the claim? AgenC rejects a
+ * second claim from the same worker with `AlreadyClaimed`, which is what a retry sees
+ * when the first attempt landed on-chain but its RPC response was lost. Distinct from
+ * losing a slot to someone else (`TaskFull` / a state change), which is a real failure.
+ */
+export function isAlreadyClaimedError(err) {
+ const message = [err?.message, ...(Array.isArray(err?.logs) ? err.logs : [])].filter(Boolean).join('\n');
+ return /AlreadyClaimed|already claimed this task/i.test(message);
+}
+
+/**
+ * Claim a task for a worker. Idempotent under a lost RPC response: a retry that comes
+ * back `AlreadyClaimed` means the earlier attempt succeeded on-chain, so we report the
+ * claim as held rather than as a failure. Getting this wrong is expensive on a
+ * multi-worker task: the worker really does hold a slot, and treating it as failed
+ * strands the slot with nobody working it until the deadline expires. The signature is
+ * null because the winning attempt's response never came back; the projection records
+ * an honest "no signature captured" rather than a fabricated one.
+ */
export async function claimTask(client, args, cfg) {
const s = await sdk();
- return withRetry(() => s.claimAgenCTask(client, args), cfg, 'claimTask');
+ try {
+ return await withRetry(() => s.claimAgenCTask(client, args), cfg, 'claimTask');
+ } catch (err) {
+ if (!isAlreadyClaimedError(err)) throw err;
+ log.warn('claim already held on-chain, recovered after a lost response', { taskPda: String(args?.taskPda) });
+ return { txSignature: null, alreadyClaimed: true };
+ }
}
export async function completeTask(client, args, cfg) {
@@ -165,6 +217,18 @@ export async function completeTask(client, args, cfg) {
return withRetry(() => s.completeAgenCTask(client, args), cfg, 'completeTask');
}
+/**
+ * Cancel a task and refund its escrowed reward to the creator. Only the creator can
+ * do this, and it is the ONLY way an expired bounty gives its money back: the reward
+ * sits locked in escrow until someone cancels. Used by the reconcile sweep when a
+ * posting passes its deadline unfilled (an Arena nobody raced, a Guild that missed
+ * its worker target), so the pool returns instead of being stranded on-chain.
+ */
+export async function cancelTask(client, args, cfg) {
+ const s = await sdk();
+ return withRetry(() => s.cancelAgenCTask(client, args), cfg, 'cancelTask');
+}
+
/** Fetch a task's lifecycle summary (timeline + fill + settlement) for reconcile / arena reads. */
export async function getTaskLifecycle(client, taskPda) {
const s = await sdk();
@@ -172,23 +236,43 @@ export async function getTaskLifecycle(client, taskPda) {
}
/**
- * Read the task's escrow PDA lamport balance (native-SOL devnet plumbing). The
- * escrow holds the locked reward until completion releases it; bracketing a
- * completeTask with two reads measures exactly what a Guild contribution paid out
- * — a REAL on-chain figure, never a fabricated split. Returns null when the
- * escrow can't be read (RPC hiccup) so the caller degrades to "share settling".
+ * Read the task's escrow PDA state (native-SOL devnet plumbing): its lamport balance
+ * and the rent reserve keeping the account alive. The escrow holds the locked reward
+ * until completion releases it; bracketing a completeTask with two reads measures what
+ * a Guild contribution actually paid out, a REAL on-chain figure and never a fabricated
+ * split. Returns null when the escrow can't be read (RPC hiccup) so the caller degrades
+ * to "share settling" rather than guessing.
*/
-export async function readEscrowLamports(client, taskPda) {
+export async function readEscrowState(client, taskPda) {
try {
const t = await tetsuo();
const pda = taskPda instanceof PublicKey ? taskPda : new PublicKey(taskPda);
const escrowPda = t.deriveEscrowPda(pda, client.programId);
- return BigInt(await client.connection.getBalance(escrowPda));
+ const info = await client.connection.getAccountInfo(escrowPda);
+ if (!info) return { lamports: 0n, rentReserve: 0n };
+ const rentReserve = BigInt(await client.connection.getMinimumBalanceForRentExemption(info.data.length));
+ return { lamports: BigInt(info.lamports), rentReserve };
} catch {
return null;
}
}
+/**
+ * What a single completion actually drew out of escrow as REWARD, in atomic units.
+ *
+ * The naive `before - after` overstates the last contributor's share: the completion
+ * that empties the escrow closes the account, so it also sweeps the rent reserve, which
+ * was never reward money (on devnet that read a 0.002 SOL share as 0.003). Subtract the
+ * reserve exactly when the account closed. Returns null when either read is missing, so
+ * the caller shows "settling" instead of a wrong number.
+ */
+export function measuredShareAtomic(before, after) {
+ if (!before || !after) return null;
+ const closed = after.lamports === 0n;
+ const drawn = before.lamports - after.lamports - (closed ? before.rentReserve : 0n);
+ return drawn > 0n ? drawn : null;
+}
+
export async function formatTaskState(state) {
const s = await sdk();
try {
diff --git a/workers/agora-citizens/index.js b/workers/agora-citizens/index.js
index e81cb0f19..87f912433 100644
--- a/workers/agora-citizens/index.js
+++ b/workers/agora-citizens/index.js
@@ -46,6 +46,13 @@ function jitter(cfg) {
return cfg.tickBaseMs + Math.floor(Math.random() * (cfg.tickJitterMs + 1));
}
+// citizenId → that citizen's signer-bound AgenC client, so the reconcile sweep can
+// refund an expired posting's escrow to the citizen that created it. Only citizens
+// this process is running can be signed for; anyone else's posting is left alone.
+function signerLookup(ctx) {
+ return (citizenId) => ctx.citizens.find((c) => c.id === citizenId)?.client || null;
+}
+
async function runOnce(ctx) {
await replenishWork(ctx, true);
const outcomes = {};
@@ -55,7 +62,7 @@ async function runOnce(ctx) {
}
// Reconcile so a one-shot run also closes any posting the chain has moved on.
try {
- await reconcileOnce({ cfg: ctx.cfg, store: ctx.store, readClient: ctx.readClient });
+ await reconcileOnce({ cfg: ctx.cfg, store: ctx.store, readClient: ctx.readClient, signerFor: signerLookup(ctx) });
} catch (err) {
log.warn('reconcile (once) failed', { err: err?.message });
}
@@ -93,7 +100,7 @@ async function runForever(ctx) {
// out postings that are claimed/cancelled/expired and link agent-to-agent hires.
const reconcileTimer = setInterval(() => {
if (!draining) {
- reconcileOnce({ cfg, store: ctx.store, readClient: ctx.readClient }).catch((err) =>
+ reconcileOnce({ cfg, store: ctx.store, readClient: ctx.readClient, signerFor: signerLookup(ctx) }).catch((err) =>
log.warn('reconcile error', { err: err?.message }),
);
}
diff --git a/workers/agora-citizens/reconcile.js b/workers/agora-citizens/reconcile.js
index 09582bea7..e109e63ac 100644
--- a/workers/agora-citizens/reconcile.js
+++ b/workers/agora-citizens/reconcile.js
@@ -14,7 +14,7 @@
// Neon client (it runs outside api/), exactly like store.js.
import { neon } from '@neondatabase/serverless';
-import { getTask, withRetry } from './agenc.js';
+import { getTask, withRetry, cancelTask, TASK_STATE } from './agenc.js';
import { reconcileTransition, EXCLUSIVE_TERMINAL_KINDS, MULTI_TERMINAL_KINDS, isMultiWorkerType, isArenaType } from './policy.js';
import { reconcileNarrative, settledNarrative } from './narrative.js';
import { log } from './log.js';
@@ -62,6 +62,34 @@ async function listOpenPostings(sql, cluster) {
`;
}
+// Expired postings whose escrow may still be locked: a posting we already projected
+// as `expired_task` with no `cancelled_task` row citing the refund. A lapsed deadline
+// does not move any money on its own, so without this the pool sits in escrow forever.
+// Kept separate from listOpenPostings because that query deliberately excludes anything
+// already closed, and this is precisely the closed-but-unpaid case.
+async function listExpiredUnreclaimed(sql, cluster) {
+ return sql`
+ select a.id, a.citizen_id, a.task_pda, a.profession, a.meta,
+ a.reward_label, a.created_at, c.display_name as poster
+ from agora_activity a
+ join agora_citizens c on c.id = a.citizen_id
+ where a.kind = 'posted_task'
+ and a.task_pda is not null
+ and coalesce(c.agenc_cluster, 'devnet') = ${cluster}
+ and a.created_at > now() - interval '14 days'
+ and exists (
+ select 1 from agora_activity e
+ where e.task_pda = a.task_pda and e.kind = 'expired_task'
+ )
+ and not exists (
+ select 1 from agora_activity x
+ where x.task_pda = a.task_pda and x.kind = 'cancelled_task'
+ )
+ order by a.created_at asc
+ limit 100
+ `;
+}
+
// Pull the terminal event's real tx signature (and actor) from the lifecycle so
// the projected transition cites the on-chain action that closed the task.
async function terminalTx(readClient, taskPda) {
@@ -77,6 +105,51 @@ async function terminalTx(readClient, taskPda) {
}
}
+/**
+ * Reclaim an expired posting's escrow for its creator. A deadline passing does NOT
+ * return the money on its own: the reward stays locked in the task's escrow until the
+ * creator cancels, so an Arena nobody raced or a Guild that missed its worker target
+ * would strand its pool on-chain forever. Needs the creator's own signer, so it only
+ * runs for postings by a citizen this process is running. Returns the refund tx, or
+ * null when we cannot sign for the creator or the cancel did not land (the projection
+ * still records the expiry honestly, without claiming a refund that never happened).
+ */
+async function reclaimExpiredEscrow({ cfg, signerFor, readClient, row }) {
+ if (typeof signerFor !== 'function') return null;
+ const client = signerFor(row.citizen_id);
+ if (!client) return null;
+ try {
+ const { PublicKey } = await import('@solana/web3.js');
+ const result = await cancelTask(client, { taskPda: new PublicKey(row.task_pda) }, cfg);
+ log.info('expired escrow reclaimed', { taskPda: row.task_pda, tx: result?.txSignature || null });
+ return result?.txSignature || null;
+ } catch (err) {
+ // Same lost-response trap as a claim: the cancel can land while its RPC reply
+ // goes missing. Re-read before calling it a failure, or the refund happens and
+ // nothing records it (and the next sweep tries to cancel an already-cancelled
+ // task forever). No signature to cite when the reply was lost, so say so.
+ const settled = await isCancelledOnChain(cfg, readClient, row.task_pda);
+ if (settled) {
+ log.warn('expired escrow reclaimed, response lost', { taskPda: row.task_pda });
+ return 'reclaimed-signature-unavailable';
+ }
+ log.warn('expired escrow reclaim failed', { taskPda: row.task_pda, err: err?.message });
+ return null;
+ }
+}
+
+/** Did this task end up cancelled (or closed) on-chain? Used to confirm a lost cancel. */
+async function isCancelledOnChain(cfg, readClient, taskPda) {
+ if (!readClient) return false;
+ try {
+ const task = await withRetry(() => getTask(readClient, taskPda), cfg, 'reclaim:confirm');
+ if (task === null) return true; // account closed
+ return task.state === TASK_STATE.Cancelled;
+ } catch {
+ return false;
+ }
+}
+
/**
* Run one reconcile pass. Returns counts for the heartbeat/log.
*
@@ -84,8 +157,10 @@ async function terminalTx(readClient, taskPda) {
* @param {object} args.cfg loaded config (cluster, databaseUrl, retry)
* @param {object} args.store projection sink (appendActivity, publishFeed)
* @param {object} args.readClient a read-only AgenC client (makeReadClient)
+ * @param {function} [args.signerFor] citizenId → that citizen's signer-bound client,
+ * used to refund an expired posting's escrow.
*/
-export async function reconcileOnce({ cfg, store, readClient }) {
+export async function reconcileOnce({ cfg, store, readClient, signerFor }) {
if (!cfg.databaseUrl) {
log.warn('reconcile skipped — no DATABASE_URL');
return { checked: 0, closed: 0, linked: 0 };
@@ -119,7 +194,11 @@ export async function reconcileOnce({ cfg, store, readClient }) {
`;
if (exists.length) continue;
- const txSignature = await terminalTx(readClient, row.task_pda);
+ // An expired posting still holds its reward in escrow. Cancel it so the pool
+ // goes back to the creator, and cite THAT refund as the transition's tx.
+ const refundTx =
+ transition.kind === 'expired_task' ? await reclaimExpiredEscrow({ cfg, signerFor, readClient, row }) : null;
+ const txSignature = refundTx || (await terminalTx(readClient, row.task_pda));
// A `settled` terminal narrates the whole Arena/Guild resolving; everything
// else keeps the plain "poster's bounty <verb>" line.
let narrative;
@@ -147,10 +226,58 @@ export async function reconcileOnce({ cfg, store, readClient }) {
}
}
+ // Second pass: return the money on anything already marked expired whose escrow was
+ // never released. The first pass only reaches a posting at the moment it closes, so a
+ // restart (or another projector winning the race to write `expired_task`) would leave
+ // the pool locked for good. Driven by chain state and idempotent: once the cancel
+ // lands the task is gone from chain and the `cancelled_task` row keeps us off it.
+ const refunded = await refundStrandedEscrows({ cfg, sql, store, readClient, signerFor });
+
const linked = await linkHires(sql);
- if (closed || linked) log.info('reconcile sweep', { checked: open.length, closed, linked });
- return { checked: open.length, closed, linked };
+ if (closed || linked || refunded) log.info('reconcile sweep', { checked: open.length, closed, refunded, linked });
+ return { checked: open.length, closed, refunded, linked };
+}
+
+/**
+ * Cancel every expired posting that still holds escrow, refunding its creator, and
+ * project the on-chain cancel. Only postings by a citizen this process can sign for are
+ * touched. Returns how many refunds landed.
+ */
+async function refundStrandedEscrows({ cfg, sql, store, readClient, signerFor }) {
+ if (typeof signerFor !== 'function') return 0;
+ let rows;
+ try {
+ rows = await listExpiredUnreclaimed(sql, cfg.cluster);
+ } catch (err) {
+ log.warn('expired-escrow list failed', { err: err?.message });
+ return 0;
+ }
+ let refunded = 0;
+ for (const row of rows) {
+ if (!signerFor(row.citizen_id)) continue; // someone else's posting: not ours to cancel
+ // Still on-chain and not already settled? Then the reward is genuinely stranded.
+ let task;
+ try {
+ task = await withRetry(() => getTask(readClient, row.task_pda), cfg, 'refund:getTask');
+ } catch {
+ continue;
+ }
+ if (!task) continue; // account already closed: nothing left to reclaim
+ const txSignature = await reclaimExpiredEscrow({ cfg, signerFor, readClient, row });
+ if (!txSignature) continue;
+ await store.appendActivity({
+ citizenId: row.citizen_id,
+ kind: 'cancelled_task',
+ taskPda: row.task_pda,
+ profession: row.profession,
+ txSignature,
+ narrative: `${row.poster}'s expired bounty returned its ${row.reward_label || 'reward'} to the treasury.`,
+ meta: { reconciled: true, escrowRefund: true, taskType: row.meta?.taskType || 'Exclusive' },
+ });
+ refunded++;
+ }
+ return refunded;
}
// Decide the transition for one task by reading its on-chain state. A missing