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(labor): stop re-pitching the same workers every minute and give an unbid bounty a retry lane

nirholasc42868986a8b
diff --git a/api/_lib/agent-labor.js b/api/_lib/agent-labor.js
index 0c148db10..f765ef968 100644
--- a/api/_lib/agent-labor.js
+++ b/api/_lib/agent-labor.js
@@ -444,8 +444,20 @@ export async function upsertLaborPolicy(agentId, userId, patch) {
return shapePolicy(row);
}
-/** Worker agents whose autonomous policy matches a bounty's skill + reward floor. */
-export async function findAutoBidders({ requiredSkill, rewardAtomics, excludeAgentId }) {
+/**
+ * Worker agents whose autonomous policy matches a bounty's skill + reward floor
+ * and who have not bid on it yet.
+ *
+ * `bountyId` excludes agents holding any bid row on that bounty, which is what
+ * makes the sweep safe to repeat. The cron drives an open bounty once a minute
+ * for as long as it stays open, and every one of those passes used to re-price
+ * and re-pitch the SAME workers: an LLM call each, once a minute, forever, on a
+ * bounty that is merely waiting for its poster's min_bids. It also flipped a bid
+ * the worker had moved out of 'pending' back to pending through upsertBid's ON
+ * CONFLICT, and reported each rewrite to the economy heartbeat as a fresh bid.
+ * A worker bids on a bounty once; changing that bid is the worker's call.
+ */
+export async function findAutoBidders({ requiredSkill, rewardAtomics, excludeAgentId, bountyId = null }) {
await ensureLaborTables();
const reward = String(toBig(rewardAtomics));
const rows = await sql`
@@ -457,6 +469,9 @@ export async function findAutoBidders({ requiredSkill, rewardAtomics, excludeAge
AND p.agent_id != ${excludeAgentId}
AND (p.min_reward_atomics IS NULL OR p.min_reward_atomics <= ${reward})
AND (${requiredSkill}::text IS NULL OR ${requiredSkill} = ANY(p.skills))
+ AND (${bountyId}::uuid IS NULL OR NOT EXISTS (
+ SELECT 1 FROM agent_bids bd
+ WHERE bd.bounty_id = ${bountyId} AND bd.worker_agent_id = p.agent_id))
LIMIT 25`;
return rows;
}
diff --git a/api/_lib/labor-match.js b/api/_lib/labor-match.js
index 5b2ac83d9..2a0b4cf85 100644
--- a/api/_lib/labor-match.js
+++ b/api/_lib/labor-match.js
@@ -82,8 +82,9 @@ async function generateAwardRationale({ bounty, bids, winner }) {
/**
* Place autonomous bids on an open bounty from every opted-in worker whose policy
- * matches its skill + reward floor. Idempotent per worker (upsert). Returns the
- * number of bids placed/updated.
+ * matches its skill + reward floor and that has not bid on it yet. Safe to repeat:
+ * a second sweep over the same bounty places no bid and spends no LLM call, so the
+ * returned count is always bids that are new this sweep.
*/
export async function autoBidForBounty(bounty) {
if (!bounty || bounty.status !== 'open') return 0;
@@ -92,6 +93,7 @@ export async function autoBidForBounty(bounty) {
requiredSkill: bounty.required_skill || null,
rewardAtomics,
excludeAgentId: bounty.poster_agent_id,
+ bountyId: bounty.id,
});
let placed = 0;
for (const w of bidders) {
diff --git a/api/labor/award.js b/api/labor/award.js
index 9a0789b67..cffe32084 100644
--- a/api/labor/award.js
+++ b/api/labor/award.js
@@ -1,10 +1,10 @@
-// POST /api/labor/award — the poster (owner of the posting agent) awards a bid.
+// POST /api/labor/award: the poster (owner of the posting agent) awards a bid.
// Moves no money on its own (the reward is already escrowed): it transitions the
// bounty to 'working', creates the job, and rejects the other bids. If the worker
// is autonomous, the autopilot then performs + settles the job through to payout.
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
-import { authWrite, loadOwnedAgent } from '../_lib/labor-auth.js';
+import { authWrite, loadOwnedAgent, ownershipError, requireUuid } from '../_lib/labor-auth.js';
import { getBounty, getBid, listBidsForBounty, getJobByBounty } from '../_lib/agent-labor.js';
import { applyAward } from '../_lib/labor-match.js';
import { runAutopilot } from '../_lib/labor-settle.js';
@@ -20,6 +20,8 @@ export default wrap(async (req, res) => {
const body = (await readJson(req)) || {};
const { bountyId, bidId } = body;
if (!bountyId || !bidId) return error(res, 400, 'validation_error', 'bountyId and bidId are required');
+ if (!requireUuid(res, bountyId, 'bountyId')) return;
+ if (!requireUuid(res, bidId, 'bidId')) return;
const bounty = await getBounty(bountyId);
if (!bounty) return error(res, 404, 'not_found', 'bounty not found');
@@ -27,7 +29,7 @@ export default wrap(async (req, res) => {
try {
await loadOwnedAgent(bounty.poster_agent_id, userId); // caller must own the poster
} catch (e) {
- return error(res, e.status || 400, e.code || 'bad_request', e.message);
+ return ownershipError(res, e);
}
if (bounty.status !== 'open') return error(res, 409, 'bounty_closed', `this bounty is ${bounty.status}, cannot be awarded`);
@@ -38,7 +40,7 @@ export default wrap(async (req, res) => {
const shaped = (await listBidsForBounty(bountyId)).find((b) => b.id === bidId);
const winner = { ...shaped, worker_user_id: rawBid.worker_user_id, price_atomics: String(rawBid.price_atomics) };
- const rationale = `Awarded by owner to ${winner.worker_name} — ${winner.price_three} $THREE, score ${winner.score ?? 'n/a'}.`;
+ const rationale = `Awarded by owner to ${winner.worker_name}: ${winner.price_three} $THREE, score ${winner.score ?? 'n/a'}.`;
const awarded = await applyAward({ bounty, winner, rationale, auto: false });
diff --git a/api/labor/deliver.js b/api/labor/deliver.js
index ae9574fb6..28466c4c9 100644
--- a/api/labor/deliver.js
+++ b/api/labor/deliver.js
@@ -1,11 +1,11 @@
-// POST /api/labor/deliver — a worker agent (owned by the caller) submits the
+// POST /api/labor/deliver: a worker agent (owned by the caller) submits the
// deliverable for its awarded job. Delivery immediately triggers verification +
// settlement: a neutral verifier scores the work against the spec and, ONLY on a
// pass, escrow is released on-chain to the worker with the skill royalty routed to
-// the author. No human approves — the verdict gates the money.
+// the author. No human approves; the verdict gates the money.
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
-import { authWrite, loadOwnedAgent } from '../_lib/labor-auth.js';
+import { authWrite, loadOwnedAgent, ownershipError, requireUuid } from '../_lib/labor-auth.js';
import { getJob, getBounty, markJobDelivered } from '../_lib/agent-labor.js';
import { runSettlement } from '../_lib/labor-settle.js';
@@ -20,6 +20,7 @@ export default wrap(async (req, res) => {
const body = (await readJson(req)) || {};
const { jobId } = body;
if (!jobId) return error(res, 400, 'validation_error', 'jobId is required');
+ if (!requireUuid(res, jobId, 'jobId')) return;
const job = await getJob(jobId);
if (!job) return error(res, 404, 'not_found', 'job not found');
@@ -27,18 +28,22 @@ export default wrap(async (req, res) => {
try {
await loadOwnedAgent(job.worker_agent_id, userId); // caller must own the worker
} catch (e) {
- return error(res, e.status || 400, e.code || 'bad_request', e.message);
+ return ownershipError(res, e);
}
if (job.status !== 'working') return error(res, 409, 'not_deliverable', `job is ${job.status}, not awaiting delivery`);
const raw = body.deliverable;
- const deliverable =
- typeof raw === 'string'
- ? { output: raw.slice(0, 8000), produced_at: new Date().toISOString() }
- : raw && typeof raw === 'object'
- ? { output: String(raw.output ?? '').slice(0, 8000), ...raw, produced_at: new Date().toISOString() }
+ const submitted =
+ typeof raw === 'string' ? { output: raw }
+ : raw && typeof raw === 'object' && !Array.isArray(raw) ? raw
: null;
- if (!deliverable || !deliverable.output) return error(res, 400, 'validation_error', 'deliverable (string or { output }) is required');
+ // The caller's own keys are spread FIRST: written the other way round, an
+ // object deliverable's untruncated `output` overwrote the clamped copy and the
+ // 8000-char cap did nothing, so any payload size reached the verifier prompt.
+ const deliverable = submitted
+ ? { ...submitted, output: String(submitted.output ?? '').slice(0, 8000), produced_at: new Date().toISOString() }
+ : null;
+ if (!deliverable?.output) return error(res, 400, 'validation_error', 'deliverable (string or { output }) is required');
const delivered = await markJobDelivered(jobId, deliverable);
if (!delivered) return error(res, 409, 'not_deliverable', 'job could not be marked delivered (already delivered?)');
diff --git a/api/labor/post.js b/api/labor/post.js
index 5b76e7d3c..7f74ed422 100644
--- a/api/labor/post.js
+++ b/api/labor/post.js
@@ -1,4 +1,4 @@
-// POST /api/labor/post — an agent (owned by the caller) posts a bounty and
+// POST /api/labor/post: an agent (owned by the caller) posts a bounty and
// escrows the reward in $THREE from its own custodial wallet into real on-chain
// escrow. Every guard is server-side: ownership, spend policy (per-tx + daily
// ceiling + kill switch), and a fail-closed price feed so the spend is valued in
@@ -10,7 +10,7 @@
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
-import { authWrite, loadOwnedAgent, requireSolanaWallet } from '../_lib/labor-auth.js';
+import { authWrite, loadOwnedAgent, ownershipError, requireSolanaWallet, requireUuid } from '../_lib/labor-auth.js';
import { TOKEN_MINT } from '../_lib/token/config.js';
import { getTokenPriceUsd } from '../_lib/token/price.js';
import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
@@ -18,7 +18,7 @@ import {
SpendLimitError, reserveSpendUsd, releaseSpendReservation, updateCustodyEvent,
} from '../_lib/agent-trade-guards.js';
import { escrowConfigured, escrowAddressOrNull, fundEscrow } from '../_lib/labor-escrow.js';
-import { createBounty, setBountyEscrow, setBountyStatus, threeToAtomics, atomicsToThree, _toBig as toBig } from '../_lib/agent-labor.js';
+import { createBounty, setBountyEscrow, setBountyStatus, parseAtomics, parseThree, atomicsToThree, _toBig as toBig } from '../_lib/agent-labor.js';
import { runAutopilot } from '../_lib/labor-settle.js';
export default wrap(async (req, res) => {
@@ -36,12 +36,30 @@ export default wrap(async (req, res) => {
const { posterAgentId, title, spec, requiredSkill = null, rewardThree, rewardAtomics, deadline = null } = body;
if (!posterAgentId || typeof posterAgentId !== 'string') return error(res, 400, 'validation_error', 'posterAgentId is required');
- if (!title || typeof title !== 'string' || title.length > 140) return error(res, 400, 'validation_error', 'title is required (≤140 chars)');
- if (!spec || typeof spec !== 'string' || spec.length > 4000) return error(res, 400, 'validation_error', 'spec is required (≤4000 chars)');
-
- const reward = rewardAtomics != null ? toBig(rewardAtomics) : threeToAtomics(rewardThree);
+ if (!requireUuid(res, posterAgentId, 'posterAgentId')) return;
+ if (!title || typeof title !== 'string' || title.length > 140) return error(res, 400, 'validation_error', 'title is required (max 140 chars)');
+ if (!spec || typeof spec !== 'string' || spec.length > 4000) return error(res, 400, 'validation_error', 'spec is required (max 4000 chars)');
+
+ // Parse the reward strictly. toBig() throws a SyntaxError on junk (an opaque
+ // 500 for what is plainly bad input) and threeToAtomics() silently returns
+ // zero, which reported "reward must be greater than zero" for a typo that was
+ // never a number at all. Both now answer a 400 that names the real problem.
+ if (rewardAtomics == null && rewardThree == null) {
+ return error(res, 400, 'validation_error', 'rewardThree or rewardAtomics is required');
+ }
+ const reward = rewardAtomics != null ? parseAtomics(rewardAtomics) : parseThree(rewardThree);
+ if (reward == null) return error(res, 400, 'validation_error', 'reward must be a non-negative amount of $THREE');
if (reward <= 0n) return error(res, 400, 'validation_error', 'reward must be greater than zero');
+ // A deadline lands in a timestamptz column, so an unparseable one used to
+ // blow up inside the INSERT as a 500 after the bounty row was already shaped.
+ let deadlineIso = null;
+ if (deadline != null && deadline !== '') {
+ const at = new Date(deadline);
+ if (Number.isNaN(at.getTime())) return error(res, 400, 'validation_error', 'deadline must be an ISO 8601 timestamp');
+ deadlineIso = at.toISOString();
+ }
+
if (!escrowConfigured()) {
return error(res, 503, 'escrow_unavailable', 'the labor-market escrow wallet is not configured on this server');
}
@@ -50,24 +68,24 @@ export default wrap(async (req, res) => {
try {
poster = requireSolanaWallet(await loadOwnedAgent(posterAgentId, userId));
} catch (e) {
- return error(res, e.status || 400, e.code || 'bad_request', e.message);
+ return ownershipError(res, e);
}
// Value the reward in real USD for the spend policy. Fail closed if no price
- // feed is live — a paid action must never proceed on a guessed price.
+ // feed is live: a paid action must never proceed on a guessed price.
let usd;
try {
const { priceUsd } = await getTokenPriceUsd();
usd = atomicsToThree(reward) * priceUsd;
} catch {
- return error(res, 503, 'price_unavailable', 'live $THREE price is unavailable — cannot value the escrow; try again shortly');
+ return error(res, 503, 'price_unavailable', 'live $THREE price is unavailable, so the escrow cannot be valued; try again shortly');
}
// Create the bounty row first so the reservation + escrow can reference it.
const bounty = await createBounty({
posterAgentId, posterUserId: userId, title: title.trim(), spec: spec.trim(),
requiredSkill: requiredSkill ? String(requiredSkill).slice(0, 80) : null,
- rewardAtomics: reward, deadline, auto: false,
+ rewardAtomics: reward, deadline: deadlineIso, auto: false,
meta: { reward_usd_at_post: usd },
});
@@ -87,8 +105,8 @@ export default wrap(async (req, res) => {
return error(res, 500, 'reserve_failed', 'could not reserve the escrow spend');
}
- // Fund escrow on-chain: poster wallet → escrow wallet. A throw here means the
- // transfer did not land, so release the hold and cancel — no money moved.
+ // Fund escrow on-chain: poster wallet to escrow wallet. A throw here means the
+ // transfer did not land, so release the hold and cancel; no money moved.
let fundSig;
try {
const posterKeypair = await recoverSolanaAgentKeypair(poster.meta.encrypted_solana_secret, {
@@ -99,7 +117,7 @@ export default wrap(async (req, res) => {
await releaseSpendReservation(reservationId, 'labor_escrow_fund_failed');
await setBountyStatus(bounty.id, 'cancelled');
console.error('[labor/post] escrow funding failed', e?.message);
- return error(res, 502, 'escrow_fund_failed', `the bounty was not posted — no $THREE moved: ${e?.message || 'transfer failed'}`);
+ return error(res, 502, 'escrow_fund_failed', `the bounty was not posted, no $THREE moved: ${e?.message || 'transfer failed'}`);
}
await updateCustodyEvent(reservationId, { status: 'confirmed', signature: fundSig, meta: { settled: true } })
diff --git a/api/labor/release.js b/api/labor/release.js
index 2dadd82e7..a9bde9b8e 100644
--- a/api/labor/release.js
+++ b/api/labor/release.js
@@ -1,9 +1,9 @@
-// POST /api/labor/release — a platform moderator force-resolves a bounty's
+// POST /api/labor/release: a platform moderator force-resolves a bounty's
// on-chain escrow WITHOUT ever holding or seeing the escrow private key.
//
// The escrow secret lives only on the server (LABOR_ESCROW_SECRET_BASE58). A
// moderator never owns it, never sees it, and never signs an escrow transaction
-// themselves — they authorize the move through their authenticated admin session
+// themselves: they authorize the move through their authenticated admin session
// and the server signs. This is the human-override lane on top of the autonomous
// verifier-gated settlement: use it to resolve a stuck or disputed bounty.
//
@@ -18,6 +18,7 @@
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireAdmin, isAdminRequest } from '../_lib/admin.js';
+import { requireUuid } from '../_lib/labor-auth.js';
import {
getBounty, getJobByBounty, getJob, markJobDelivered, setBountyStatus,
atomicsToThree, _toBig as toBig,
@@ -56,6 +57,7 @@ export default wrap(async (req, res) => {
const bountyId = body.bountyId;
const action = body.action === 'refund' ? 'refund' : body.action === 'release' ? 'release' : null;
if (!bountyId) return error(res, 400, 'validation_error', 'bountyId is required');
+ if (!requireUuid(res, bountyId, 'bountyId')) return;
if (!action) return error(res, 400, 'validation_error', "action must be 'release' or 'refund'");
const bounty = await getBounty(bountyId);
@@ -68,7 +70,7 @@ export default wrap(async (req, res) => {
// Open bounty (escrow funded, no worker awarded): only a refund makes sense.
if (!job) {
- if (action === 'release') return error(res, 409, 'no_worker', 'no worker has been awarded — only refund is available');
+ if (action === 'release') return error(res, 409, 'no_worker', 'no worker has been awarded, so only refund is available');
await ensureEscrowGas().catch(() => {});
const to = await posterSolanaAddress(bounty);
if (!to) return error(res, 409, 'no_poster_wallet', 'poster has no Solana wallet to refund to');
@@ -76,12 +78,12 @@ export default wrap(async (req, res) => {
try {
refundSig = await payFromEscrow({ toAddress: to, amountAtomics: toBig(bounty.reward_atomics) });
} catch (e) {
- return error(res, 502, 'refund_failed', `escrow refund did not land — no $THREE moved: ${e?.message || 'transfer failed'}`);
+ return error(res, 502, 'refund_failed', `escrow refund did not land, no $THREE moved: ${e?.message || 'transfer failed'}`);
}
await setBountyStatus(bounty.id, 'refunded', { refundSig });
emitReasoning({
agentId: bounty.poster_agent_id, kind: 'labor.moderator_refund',
- summary: `Moderator refunded "${bounty.title}" — no worker awarded`,
+ summary: `Moderator refunded "${bounty.title}" (no worker awarded)`,
detail: { bounty_id: bounty.id, moderator, refund_sig: refundSig },
});
return json(res, 200, {
@@ -101,7 +103,7 @@ export default wrap(async (req, res) => {
const verdict = {
pass: action === 'release',
score: action === 'release' ? 1 : 0,
- reason: `moderator ${action} by ${moderator.wallet || moderator.admin_id}${moderator.reason ? ` — ${moderator.reason}` : ''}`,
+ reason: `moderator ${action} by ${moderator.wallet || moderator.admin_id}${moderator.reason ? `: ${moderator.reason}` : ''}`,
moderator,
};
diff --git a/api/labor/settle.js b/api/labor/settle.js
index 6367b37dc..fe2c700e4 100644
--- a/api/labor/settle.js
+++ b/api/labor/settle.js
@@ -1,11 +1,11 @@
-// POST /api/labor/settle — verify a delivered job and release escrow on-chain.
+// POST /api/labor/settle: verify a delivered job and release escrow on-chain.
// Idempotent (job settle_key): a retry never double-pays. Callable by either
// participant (poster or worker owner) so a stuck-but-delivered job can always be
-// resolved; the neutral verifier — not the caller — decides whether funds release.
+// resolved; the neutral verifier, not the caller, decides whether funds release.
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
-import { authWrite } from '../_lib/labor-auth.js';
+import { authWrite, requireUuid } from '../_lib/labor-auth.js';
import { getJob, getJobByBounty, getBounty } from '../_lib/agent-labor.js';
import { runSettlement } from '../_lib/labor-settle.js';
@@ -26,7 +26,13 @@ export default wrap(async (req, res) => {
const body = (await readJson(req)) || {};
const { jobId, bountyId } = body;
- const job = jobId ? await getJob(jobId) : bountyId ? await getJobByBounty(bountyId) : null;
+ // Say "you sent nothing" rather than "the job does not exist": a caller that
+ // omitted both ids used to get a 404 and go hunting for a missing job.
+ if (!jobId && !bountyId) return error(res, 400, 'validation_error', 'jobId or bountyId is required');
+ if (jobId && !requireUuid(res, jobId, 'jobId')) return;
+ if (!jobId && !requireUuid(res, bountyId, 'bountyId')) return;
+
+ const job = jobId ? await getJob(jobId) : await getJobByBounty(bountyId);
if (!job) return error(res, 404, 'not_found', 'job not found');
if (!(await ownsEither(userId, job.poster_agent_id, job.worker_agent_id))) {
diff --git a/api/labor/tick.js b/api/labor/tick.js
index 4ec84ea65..3a44fd734 100644
--- a/api/labor/tick.js
+++ b/api/labor/tick.js
@@ -1,15 +1,16 @@
-// POST /api/labor/tick — cron driver for the Agent Labor Market.
+// POST /api/labor/tick: cron driver for the Agent Labor Market.
// Advances autonomous bounties that haven't reached a terminal state inline:
-// • open bounties (collect auto-bids, auto-award if the poster opted in)
-// • working jobs with an autonomous worker (perform → verify → settle)
+// • open bounties that already drew bids (auto-award if the poster opted in)
+// • recently posted bounties nobody has bid on yet (retry the auto-bid sweep)
+// • working jobs with an autonomous worker (perform, verify, settle)
// • delivered/verifying jobs (settle now)
// Authenticated with the Vercel cron Bearer secret. No-op (503) if unset.
//
-// Both scans below are capped at BATCH so a tick stays inside its budget, and
-// both deliberately select ONLY rows this tick can actually advance. That is not
-// an optimization, it is the correctness property that keeps the cap from
-// starving the market: the scans are ordered oldest-first, so any row the driver
-// can never move occupies a slot on every tick forever. Two such rows existed:
+// Every scan below is capped at BATCH so a tick stays inside its budget, and each
+// deliberately selects ONLY rows this tick can actually advance. That is not an
+// optimization, it is the correctness property that keeps the cap from starving
+// the market: the scans are ordered oldest-first, so any row the driver can never
+// move occupies a slot on every tick forever. Two such rows existed:
// • a 'working' job whose worker never opted into autonomy. runAutopilot
// returns immediately for it, so it can only ever leave 'working' through
// the manual /deliver endpoint. Ten of them (a human sitting on ten jobs)
@@ -23,6 +24,17 @@
// Same reasoning drives the job ordering: delivered/verifying jobs are one step
// from releasing escrow, so they settle before working jobs spend the tick on an
// LLM perform call.
+//
+// The zero-bid lane is the market's only bootstrap retry. Auto-bidding is gated
+// on the WORKER's policy (findAutoBidders reads worker_enabled), never on the
+// poster's, which is why /post calls runAutopilot for every bounty regardless of
+// the poster's settings. The award scan above cannot stand in for that: it needs
+// a pending bid AND a poster auto-award policy, so a bounty whose post-time sweep
+// matched nobody (no autonomous worker held the skill yet, or the pitch router
+// was down that second) had no path back to a bid, ever. It gets one here for a
+// bounded window: a row ages out of BID_RETRY_WINDOW on its own, so an unbiddable
+// bounty cannot squat a slot forever the way the two rows above used to. An
+// attempt with no matching worker costs one indexed SELECT and no LLM call.
import { json, method, wrap } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
@@ -32,6 +44,10 @@ import { requireCron } from '../_lib/cron-auth.js';
const BATCH = 10;
const MAX_REPORTED_ERRORS = 5;
+// How long after posting a bounty keeps getting auto-bid sweeps. Long enough to
+// outlast a router outage or a worker enabling autonomy right after the post,
+// short enough that a bounty nobody can serve leaves the scan on its own.
+const BID_RETRY_WINDOW = '1 hour';
export default wrap(async (req, res) => {
if (!method(req, res, ['POST', 'GET'])) return;
@@ -54,6 +70,16 @@ export default wrap(async (req, res) => {
ORDER BY (pending_bids >= min_bids) DESC, created_at ASC
LIMIT ${BATCH}`;
+ const unbidBounties = await sql`
+ SELECT b.id FROM agent_bounties b
+ WHERE b.status = 'open'
+ AND b.created_at > now() - ${BID_RETRY_WINDOW}::interval
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_bids bd
+ WHERE bd.bounty_id = b.id AND bd.status = 'pending')
+ ORDER BY b.created_at ASC
+ LIMIT ${BATCH}`;
+
const stuckJobs = await sql`
SELECT j.id, j.bounty_id, j.status FROM agent_jobs j
WHERE j.created_at < now() - interval '15 seconds'
@@ -66,8 +92,12 @@ export default wrap(async (req, res) => {
ORDER BY (j.status <> 'working') DESC, j.created_at ASC
LIMIT ${BATCH}`;
+ // The two bounty scans are disjoint by construction (one requires a pending
+ // bid, the other requires none), so no bounty is driven twice in a tick.
+ const bounties = [...openBounties, ...unbidBounties];
+
const results = {
- scanned: openBounties.length + stuckJobs.length,
+ scanned: bounties.length + stuckJobs.length,
bids: 0, awarded: 0, settled: 0, failed: 0,
};
const errors = [];
@@ -82,7 +112,7 @@ export default wrap(async (req, res) => {
if (errors.length < MAX_REPORTED_ERRORS) errors.push(`${scope}: ${message.slice(0, 160)}`);
};
- for (const b of openBounties) {
+ for (const b of bounties) {
try {
const r = await runAutopilot(b.id);
results.bids += r?.bids || 0;
diff --git a/tests/labor-autobid-sweep.test.js b/tests/labor-autobid-sweep.test.js
new file mode 100644
index 000000000..0aac26792
--- /dev/null
+++ b/tests/labor-autobid-sweep.test.js
@@ -0,0 +1,119 @@
+// The auto-bid sweep runs on every labor tick for as long as a bounty stays
+// open, so it has to be safe to repeat. Before the 2026-08-13 audit it was not:
+// findAutoBidders returned every matching worker whether or not it had already
+// bid, and upsertBid rewrote that worker's existing row. On a bounty waiting for
+// its poster's min_bids that meant one LLM pitch per matching worker per minute,
+// forever; each rewrite was reported to the economy heartbeat as a fresh bid; and
+// a bid the worker had moved out of 'pending' was flipped back through the ON
+// CONFLICT clause. These tests pin the fix: a worker is asked to bid once.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const calls = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ const text = Array.isArray(strings) ? strings.join(' ? ') : String(strings);
+ calls.push({ text, values });
+ return Promise.resolve([]);
+ },
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const { findAutoBidders } = await import('../api/_lib/agent-labor.js');
+
+const lastMatching = (re) => [...calls].reverse().find((c) => re.test(c.text));
+
+beforeEach(() => { calls.length = 0; });
+
+describe('findAutoBidders', () => {
+ it('excludes workers that already hold a bid on the bounty', async () => {
+ await findAutoBidders({
+ requiredSkill: 'render', rewardAtomics: 1_000_000n,
+ excludeAgentId: 'poster-agent', bountyId: 'bounty-1',
+ });
+
+ const q = lastMatching(/FROM agent_labor_policies/);
+ expect(q).toBeTruthy();
+ expect(q.text).toMatch(/NOT EXISTS/i);
+ expect(q.text).toMatch(/FROM agent_bids/);
+ expect(q.text).toMatch(/worker_agent_id = p\.agent_id/);
+ expect(q.values).toContain('bounty-1');
+ });
+
+ it('still filters on the worker policy, not the poster policy', async () => {
+ await findAutoBidders({
+ requiredSkill: null, rewardAtomics: 5n, excludeAgentId: 'poster-agent', bountyId: 'bounty-1',
+ });
+
+ const q = lastMatching(/FROM agent_labor_policies/);
+ expect(q.text).toMatch(/p\.worker_enabled = true/);
+ expect(q.text).not.toMatch(/auto_award/);
+ // The reward floor is compared as an exact integer string, never a float.
+ expect(q.values).toContain('5');
+ });
+
+ it('keeps the call usable without a bounty id (the guard is null-tolerant)', async () => {
+ await findAutoBidders({ requiredSkill: 'render', rewardAtomics: 1n, excludeAgentId: 'a' });
+
+ const q = lastMatching(/FROM agent_labor_policies/);
+ expect(q.values).toContain(null);
+ expect(q.text).toMatch(/IS NULL OR NOT EXISTS/i);
+ });
+});
+
+describe('autoBidForBounty', () => {
+ const bounty = {
+ id: 'bounty-1', status: 'open', required_skill: 'render',
+ reward_atomics: '1000000', poster_agent_id: 'poster-agent', title: 'Render a scene',
+ spec: 'Make a 3D scene',
+ };
+
+ async function loadWithBidders(bidders) {
+ vi.resetModules();
+ const findAutoBiddersMock = vi.fn(async () => bidders);
+ const upsertBid = vi.fn(async () => ({ id: 'bid-1' }));
+ vi.doMock('../api/_lib/agent-labor.js', () => ({
+ scoreBid: () => 0.5,
+ workerReputation: async () => ({ reputation: 0.5 }),
+ findAutoBidders: findAutoBiddersMock,
+ upsertBid,
+ getBounty: vi.fn(), getLaborPolicy: vi.fn(), listBidsForBounty: vi.fn(),
+ createJob: vi.fn(), markBidAwarded: vi.fn(), rejectOtherBids: vi.fn(),
+ setBountyStatus: vi.fn(), getJobByBounty: vi.fn(), markJobDelivered: vi.fn(),
+ }));
+ const llmComplete = vi.fn(async () => ({ text: 'pitch' }));
+ vi.doMock('../api/_lib/llm.js', () => ({ llmComplete, llmConfigured: () => true }));
+ const mod = await import('../api/_lib/labor-match.js');
+ return { autoBidForBounty: mod.autoBidForBounty, findAutoBiddersMock, upsertBid, llmComplete };
+ }
+
+ it('asks only for workers that have not bid on this bounty', async () => {
+ const { autoBidForBounty, findAutoBiddersMock } = await loadWithBidders([]);
+ await autoBidForBounty(bounty);
+ expect(findAutoBiddersMock).toHaveBeenCalledWith(expect.objectContaining({ bountyId: 'bounty-1' }));
+ });
+
+ it('spends nothing on a repeat sweep where every worker already bid', async () => {
+ const { autoBidForBounty, upsertBid, llmComplete } = await loadWithBidders([]);
+ expect(await autoBidForBounty(bounty)).toBe(0);
+ expect(upsertBid).not.toHaveBeenCalled();
+ expect(llmComplete).not.toHaveBeenCalled();
+ });
+
+ it('bids once for a worker that has not been asked yet', async () => {
+ const { autoBidForBounty, upsertBid } = await loadWithBidders([
+ { agent_id: 'w1', agent_name: 'Worker', owner_user_id: 'u1', max_bid_atomics: '900000' },
+ ]);
+ expect(await autoBidForBounty(bounty)).toBe(1);
+ expect(upsertBid).toHaveBeenCalledWith(expect.objectContaining({
+ bountyId: 'bounty-1', workerAgentId: 'w1', auto: true,
+ }));
+ });
+
+ it('never bids on a bounty that is no longer open', async () => {
+ const { autoBidForBounty, findAutoBiddersMock } = await loadWithBidders([{ agent_id: 'w1' }]);
+ expect(await autoBidForBounty({ ...bounty, status: 'working' })).toBe(0);
+ expect(findAutoBiddersMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/labor-tick-batch.test.js b/tests/labor-tick-batch.test.js
index 4bafec6f8..635b62698 100644
--- a/tests/labor-tick-batch.test.js
+++ b/tests/labor-tick-batch.test.js
@@ -21,9 +21,19 @@
// failure was swallowed by `.catch(() => null)`, a fully stalled lane
// reported `{ ok: true, settled: 0 }`, indistinguishable from a quiet minute.
//
+// A fourth, found by the 2026-08-13 re-audit of the same file:
+//
+// 4. NO BOOTSTRAP RETRY. The only bounty scan required a pending bid AND a
+// poster policy with auto_award, but auto-bidding is gated on the WORKER's
+// policy, never the poster's. A bounty whose post-time sweep matched nobody
+// (no autonomous worker held the skill yet, or the pitch router was down that
+// second) therefore had no path back to a bid, ever. The zero-bid lane gives
+// it one inside a bounded window, so an unbiddable bounty still ages out
+// instead of squatting a slot.
+//
// The sql double models only what those bugs turn on: which rows each scan asks
// for. A handler that drops the worker_enabled requirement, the min_bids
-// priority, or the per-row guards fails here.
+// priority, the zero-bid lane, or the per-row guards fails here.
import { describe, it, expect, beforeEach, vi } from 'vitest';
@@ -80,16 +90,23 @@ const req = (over = {}) => ({
// The rows each scan would return, and the query text the handler asked with.
let bountyRows;
+let unbidRows;
let jobRows;
let queries;
function installSql() {
- queries = { bounties: null, jobs: null };
+ queries = { bounties: null, unbid: null, jobs: null };
h.sql.mockImplementation((strings) => {
const q = Array.isArray(strings) ? strings.join(' ? ') : String(strings);
if (/FROM agent_bounties/i.test(q)) {
- queries.bounties = q;
- return Promise.resolve(bountyRows);
+ // The award lane joins the poster policy for min_bids; the bootstrap lane
+ // asks for the bounties that have no pending bid at all.
+ if (/min_bids/i.test(q)) {
+ queries.bounties = q;
+ return Promise.resolve(bountyRows);
+ }
+ queries.unbid = q;
+ return Promise.resolve(unbidRows);
}
if (/FROM agent_jobs/i.test(q)) {
queries.jobs = q;
@@ -108,6 +125,7 @@ async function tick(over) {
beforeEach(() => {
vi.clearAllMocks();
bountyRows = [];
+ unbidRows = [];
jobRows = [];
installSql();
h.runAutopilot.mockResolvedValue({ bids: 0, awarded: false, settled: null, settledNow: false });
@@ -147,11 +165,38 @@ describe('labor tick: scans only rows it can advance', () => {
expect(queries.bounties).toMatch(/pending_bids >= min_bids\) DESC/);
});
- it('bounds both scans inside the statement', async () => {
+ it('bounds every scan inside the statement', async () => {
await tick();
expect(queries.bounties).toMatch(/LIMIT/i);
+ expect(queries.unbid).toMatch(/LIMIT/i);
expect(queries.jobs).toMatch(/LIMIT/i);
});
+
+ it('retries the auto-bid sweep on open bounties nobody has bid on', async () => {
+ await tick();
+ // No pending bid, and no poster-policy join: auto-bidding is the worker's
+ // opt-in, so requiring the poster's auto_award here would strand the bounty.
+ expect(queries.unbid).toMatch(/NOT EXISTS/i);
+ expect(queries.unbid).toMatch(/agent_bids/);
+ expect(queries.unbid).not.toMatch(/agent_labor_policies/);
+ });
+
+ it('ages a bounty out of the bootstrap lane instead of retrying it forever', async () => {
+ await tick();
+ // A window is what stops an unbiddable bounty from holding a slot on every
+ // tick, the same head-of-line failure the other two scans were fixed for.
+ expect(queries.unbid).toMatch(/created_at > now\(\)/);
+ expect(queries.unbid).toMatch(/interval/);
+ });
+
+ it('drives a zero-bid bounty and counts the bids it wins', async () => {
+ unbidRows = [{ id: 'fresh' }];
+ h.runAutopilot.mockResolvedValue({ bids: 2, awarded: false, settled: null, settledNow: false });
+
+ const res = await tick();
+ expect(h.runAutopilot).toHaveBeenCalledWith('fresh');
+ expect(res.body).toMatchObject({ ok: true, scanned: 1, bids: 2, failed: 0 });
+ });
});
describe('labor tick: counting', () => {
@@ -186,6 +231,19 @@ describe('labor tick: counting', () => {
expect(res.body).toMatchObject({ scanned: 1, settled: 0 });
});
+ it('counts both bounty lanes and isolates a failure in either', async () => {
+ bountyRows = [{ id: 'awardable' }];
+ unbidRows = [{ id: 'fresh' }];
+ h.runAutopilot
+ .mockResolvedValueOnce({ bids: 0, awarded: true, settled: null, settledNow: false })
+ .mockRejectedValueOnce(new Error('router down'));
+
+ const res = await tick();
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toMatchObject({ ok: true, scanned: 2, awarded: 1, failed: 1 });
+ expect(res.body.errors[0]).toContain('fresh');
+ });
+
it('drives a working job without re-fetching its bounty', async () => {
jobRows = [{ id: 'j1', bounty_id: 'b1', status: 'working' }];
await tick();