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.

feat(labor-market): evaluator and dispute-window controls, escrow trail panel, and tests for every transition and the no-locked-funds property

nirholas8eb931119dee
diff --git a/src/labor-market.css b/src/labor-market.css
index fc95f3061..6b5a8c1ef 100644
--- a/src/labor-market.css
+++ b/src/labor-market.css
@@ -583,3 +583,7 @@
.lm-deliv summary:hover { color: var(--ink); }
.lm-select-wrap select:hover { border-color: var(--stroke-strong); background: var(--surface-2); }
.lm-toast:hover { border-color: var(--accent); }
+
+.lm-trail { margin: 8px 0 0; padding-left: 18px; display: grid; gap: 6px; font-size: 12px; line-height: 1.4; }
+.lm-trail time { color: var(--lm-muted, #8a8f98); font-variant-numeric: tabular-nums; margin-right: 4px; }
+.lm-jobpanel form.lm-form { margin-top: 10px; }
diff --git a/src/labor-market.js b/src/labor-market.js
index b43245a32..8d6c7666d 100644
--- a/src/labor-market.js
+++ b/src/labor-market.js
@@ -412,7 +412,59 @@ async function openBounty(id, { push = true } = {}) {
}
}
-function drawerMarkup({ bounty: b, bids, job }) {
+const ESCROW_LABEL = {
+ funded: 'Funded', working: 'Working', submitted: 'Awaiting attestation', attested: 'Attested, dispute window open',
+ disputed: 'Disputed, funds frozen', released: 'Released to worker', refunded: 'Refunded to poster',
+};
+
+function fmtWhen(iso) {
+ return iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : '';
+}
+
+function escrowMarkup(e) {
+ if (!e) return '';
+ const v = e.viewer || {};
+ const who = e.evaluator.kind === 'platform' ? 'Platform checker' : e.evaluator.kind === 'poster' ? 'Hiring agent' : 'Registry agent';
+ const a = e.attestation;
+ const clock = e.state === 'attested' ? `Funds ${a?.verdict === 'pass' ? 'release' : 'refund'} ${fmtWhen(e.release_at)} unless disputed.`
+ : e.state === 'submitted' ? `Refunds the poster ${fmtWhen(e.attest_by)} if nobody attests.`
+ : e.state === 'disputed' ? `Arbiter rules by ${fmtWhen(e.arbiter_by)}, else the poster is refunded.`
+ : ['funded', 'working'].includes(e.state) ? `Job deadline ${fmtWhen(e.deadline_at)}.` : '';
+ const attBlock = a ? `<p class="lm-verdict ${a.verdict === 'pass' ? 'pass' : 'fail'}">Attestation: <strong>${esc(a.verdict)}</strong> · ${esc(a.reason_code)}${a.reason_detail ? ` · ${esc(a.reason_detail)}` : ''}${a.evidence_url ? ` · <a href="${esc(a.evidence_url)}" target="_blank" rel="noopener">evidence ↗</a>` : ''}<br><span class="lm-verifier">signed by ${esc(a.signer)}</span></p>` : '';
+ const disBlock = e.dispute ? `<p class="lm-verdict fail">Dispute by ${esc(e.dispute.by)}: ${esc(e.dispute.reason)}</p>` : '';
+ const resBlock = e.resolution ? `<p class="lm-verdict ${e.resolution.verdict === 'pass' ? 'pass' : 'fail'}">Ruling: <strong>${esc(e.resolution.verdict)}</strong>${e.resolution.reason_detail ? ` · ${esc(e.resolution.reason_detail)}` : ''}</p>` : '';
+ const trail = e.trail.length
+ ? `<details class="lm-deliv"><summary>Decision trail (${e.trail.length}) · ${e.chain?.ok ? 'chain intact' : 'CHAIN BROKEN'}</summary><ol class="lm-trail">${e.trail.map((t) => `<li><time datetime="${esc(t.at)}">${esc(fmtWhen(t.at))}</time> <strong>${esc(t.event)}</strong> ${esc(t.from || 'start')} to ${esc(t.to)} <span class="lm-verifier">by ${esc(t.actor)}${t.reason ? `: ${esc(t.reason)}` : ''}</span></li>`).join('')}</ol></details>`
+ : '';
+ const attestForm = v.can_attest ? `
+ <form class="lm-form" data-attest-form>
+ <label class="lm-field"><span>Verdict</span><select name="verdict"><option value="pass">Pass: release to worker</option><option value="fail">Fail: refund poster</option></select></label>
+ <label class="lm-field"><span>Reason code (fail only)</span><select name="reasonCode"><option value="">meets_spec</option><option>off_spec</option><option>incomplete</option><option>empty_deliverable</option><option>unverifiable</option><option>other</option></select></label>
+ <label class="lm-field"><span>Detail (optional)</span><input name="reasonDetail" maxlength="280" /></label>
+ <label class="lm-field"><span>Evidence URL (optional, https)</span><input name="evidenceUrl" type="url" maxlength="500" /></label>
+ <div class="lm-form-msg" data-attest-msg role="alert"></div>
+ <button type="submit" class="lm-btn lm-btn-primary">Sign &amp; submit attestation</button>
+ </form>` : '';
+ const disputeForm = v.can_dispute ? `
+ <form class="lm-form" data-dispute-form>
+ <label class="lm-field"><span>Why do you dispute this verdict? (10+ characters)</span><textarea name="reason" rows="3" minlength="10" maxlength="500" required></textarea></label>
+ <label class="lm-field"><span>Evidence URL (optional, https)</span><input name="evidenceUrl" type="url" maxlength="500" /></label>
+ <div class="lm-form-msg" data-dispute-msg role="alert"></div>
+ <button type="submit" class="lm-btn lm-btn-sm">Open dispute and freeze funds</button>
+ </form>` : '';
+ const cancelBtn = v.can_cancel ? `<button type="button" class="lm-btn lm-btn-sm" data-escrow-cancel>Cancel and refund escrow</button>` : '';
+ const paid = ['released', 'refunded'].includes(e.state)
+ ? `<p class="lm-settle-row">${e.paid_at ? `Paid out ${esc(fmtWhen(e.paid_at))}${e.settle_sig ? ` <a href="https://solscan.io/tx/${esc(e.settle_sig)}" target="_blank" rel="noopener">tx ↗</a>` : ''}` : 'Decision final. Payout is being sent and retries automatically.'}</p>` : '';
+ return `
+ <div class="lm-jobpanel" data-escrow-state="${esc(e.state)}">
+ <h4>Escrow · ${esc(ESCROW_LABEL[e.state] || e.state)}</h4>
+ <p class="lm-verifier">Evaluator: ${esc(who)} · dispute window ${e.dispute_window_seconds >= 3600 ? `${Math.round(e.dispute_window_seconds / 3600)}h` : e.dispute_window_seconds ? `${Math.round(e.dispute_window_seconds / 60)}m` : 'none'}</p>
+ ${clock ? `<p class="lm-mod-note">${esc(clock)}</p>` : ''}
+ ${attBlock}${disBlock}${resBlock}${paid}${attestForm}${disputeForm}${cancelBtn}${trail}
+ </div>`;
+}
+
+function drawerMarkup({ bounty: b, bids, job, escrow }) {
const iOwnPoster = ownsAgent(b.poster_agent_id);
const myWorker = state.myAgents.find((a) => a.id !== b.poster_agent_id);
const canBid = state.authed && b.status === 'open' && myWorker;
@@ -456,9 +508,9 @@ function drawerMarkup({ bounty: b, bids, job }) {
${verdict ? `<p class="lm-verdict ${verdict.pass ? 'pass' : 'fail'}">Verdict: <strong>${verdict.pass ? 'passed' : 'rejected'}</strong> · score ${Number(verdict.score).toFixed(2)} · ${esc(verdict.reason || '')} <span class="lm-verifier">(${esc(verdict.verifier || (verdict.moderator ? 'moderator' : ''))})</span></p>` : ''}
${job.settlement_explorer ? `<p class="lm-settle-row">Paid <strong>${fmtThree(job.worker_payout_three)} $THREE</strong>${Number(job.royalty_three) > 0 ? ` · royalty ${fmtThree(job.royalty_three)}` : ''} <a href="${esc(job.settlement_explorer)}" target="_blank" rel="noopener">settlement ↗</a>${job.invocation_explorer ? ` · <a href="${esc(job.invocation_explorer)}" target="_blank" rel="noopener">invocation ↗</a>` : ''}</p>` : ''}
${ownsAgent(job.worker_agent_id) && job.status === 'working' ? deliverForm(job.id) : ''}
- ${(iOwnPoster || ownsAgent(job.worker_agent_id)) && ['delivered', 'verifying'].includes(job.status) ? `<button type="button" class="lm-btn lm-btn-primary" data-settle="${esc(job.id)}">Verify &amp; settle now</button>` : ''}
</div>`;
}
+ jobHtml += escrowMarkup(escrow);
// Moderator override lane — only for admins, only while the escrow is live.
const canModerate = state.isModerator && b.escrow_fund_sig && !TERMINAL.has(b.status);
@@ -578,29 +630,66 @@ function wireDrawer(data) {
deliverForm.addEventListener('submit', async (e) => {
e.preventDefault();
const msg = $('[data-deliver-msg]', deliverForm);
- setMsg(msg, 'Delivering & settling on-chain…', '');
+ setMsg(msg, 'Submitting delivery…', '');
try {
const j = await postJson('/api/labor/deliver', { jobId: deliverForm.dataset.job, deliverable: { output: new FormData(deliverForm).get('output') } });
- const settled = j.settlement?.settled;
- setMsg(msg, settled ? 'Settled — payout released.' : `Verdict: ${j.settlement?.status || 'recorded'}.`, settled ? 'ok' : '');
- toast(settled ? 'Delivered & settled — payout released.' : `Delivered. Verdict: ${j.settlement?.status || 'recorded'}.`, settled ? 'ok' : 'warn',
- j.settlement?.explorer ? { href: j.settlement.explorer, linkText: 'tx ↗' } : {});
+ const st = j.escrow?.state;
+ const note = st === 'attested' ? 'Delivered. Verdict recorded, dispute window is open.' : 'Delivered. Awaiting the evaluator.';
+ setMsg(msg, note, 'ok');
+ toast(note, 'ok');
+ await refresh();
+ openBounty(bountyId, { push: false });
+ } catch (err) { setMsg(msg, err.message, 'err'); }
+ });
+ }
+
+ const attestForm = $('[data-attest-form]', body);
+ if (attestForm) {
+ attestForm.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const msg = $('[data-attest-msg]', attestForm);
+ const fd = new FormData(attestForm);
+ setMsg(msg, 'Signing attestation…', '');
+ try {
+ await postJson('/api/labor/escrow', {
+ action: 'attest', bountyId,
+ verdict: fd.get('verdict'), reasonCode: fd.get('reasonCode') || undefined,
+ reasonDetail: fd.get('reasonDetail') || undefined, evidenceUrl: fd.get('evidenceUrl') || undefined,
+ });
+ toast('Attestation recorded.', 'ok');
+ await refresh();
+ openBounty(bountyId, { push: false });
+ } catch (err) { setMsg(msg, err.message, 'err'); }
+ });
+ }
+
+ const disputeForm = $('[data-dispute-form]', body);
+ if (disputeForm) {
+ disputeForm.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const msg = $('[data-dispute-msg]', disputeForm);
+ const fd = new FormData(disputeForm);
+ setMsg(msg, 'Opening dispute…', '');
+ try {
+ await postJson('/api/labor/escrow', { action: 'dispute', bountyId, reason: fd.get('reason'), evidenceUrl: fd.get('evidenceUrl') || undefined });
+ toast('Dispute opened. Funds are frozen until it is ruled on.', 'ok');
await refresh();
openBounty(bountyId, { push: false });
} catch (err) { setMsg(msg, err.message, 'err'); }
});
}
- const settleBtn = $('[data-settle]', body);
- if (settleBtn) {
- settleBtn.addEventListener('click', async () => {
- settleBtn.disabled = true; settleBtn.textContent = 'Settling…';
+ const cancelBtn = $('[data-escrow-cancel]', body);
+ if (cancelBtn) {
+ cancelBtn.addEventListener('click', async () => {
+ if (!confirm('Cancel this bounty and refund the escrowed reward to the poster?')) return;
+ cancelBtn.disabled = true;
try {
- const j = await postJson('/api/labor/settle', { jobId: settleBtn.dataset.settle });
- toast(j.settled ? 'Settled — payout released.' : `Verdict: ${j.status || 'recorded'}.`, j.settled ? 'ok' : 'warn');
+ await postJson('/api/labor/escrow', { action: 'cancel', bountyId });
+ toast('Bounty cancelled. Escrow refunded.', 'ok');
await refresh();
openBounty(bountyId, { push: false });
- } catch (err) { settleBtn.disabled = false; settleBtn.textContent = 'Verify & settle now'; toast(err.message, 'err'); }
+ } catch (err) { cancelBtn.disabled = false; toast(err.message, 'err'); }
});
}
@@ -614,8 +703,8 @@ function wireDrawer(data) {
btn.textContent = action === 'release' ? 'Releasing…' : 'Refunding…';
try {
const j = await postJson('/api/labor/release', { bountyId, action });
- const sig = j.settlement_sig || j.refund_sig;
- toast(action === 'release' ? 'Released to worker.' : 'Refunded to poster.', 'ok',
+ const sig = j.settle_sig;
+ toast(action === 'release' ? 'Released to worker.' : 'Refunded to poster.', j.paid ? 'ok' : 'warn',
sig ? { href: `https://solscan.io/tx/${sig}`, linkText: 'tx ↗' } : {});
await refresh();
openBounty(bountyId, { push: false });
diff --git a/tests/api-labor-endpoints.test.js b/tests/api-labor-endpoints.test.js
index f833087d4..89b4fb73a 100644
--- a/tests/api-labor-endpoints.test.js
+++ b/tests/api-labor-endpoints.test.js
@@ -98,6 +98,17 @@ vi.mock('../api/_lib/labor-settle.js', () => ({
runAutopilot: vi.fn(async () => ({ bids: 0, awarded: true, settled: null, settledNow: false })),
runSettlement: vi.fn(async () => ({ settled: true, status: 'settled' })),
}));
+vi.mock('../api/_lib/labor-evaluation.js', () => ({
+ intakeDelivery: vi.fn(async () => ({ state: 'attested' })),
+ caseView: vi.fn(async () => null),
+ ensureCase: vi.fn(async () => null),
+ recordAward: vi.fn(async () => null),
+ moderatorOverride: vi.fn(async () => ({ paid_at: null })),
+}));
+vi.mock('../api/_lib/labor-escrow-ledger.js', () => ({
+ ensureEscrowTables: vi.fn(async () => true),
+ getCaseByBounty: vi.fn(async () => null),
+}));
vi.mock('../api/_lib/labor-escrow.js', () => ({
escrowConfigured: vi.fn(() => true),
escrowAddressOrNull: vi.fn(() => 'ESCROWADDR'),
diff --git a/tests/labor-escrow-machine.test.js b/tests/labor-escrow-machine.test.js
index 7a0a5cfa1..ce00742fd 100644
--- a/tests/labor-escrow-machine.test.js
+++ b/tests/labor-escrow-machine.test.js
@@ -32,6 +32,10 @@ describe('transition table', () => {
['disputed', 'resolve_pass', 'released'],
['disputed', 'resolve_fail', 'refunded'],
['disputed', 'arbiter_timeout', 'refunded'],
+ ...['funded', 'working', 'submitted', 'attested', 'disputed'].flatMap((st) => [
+ [st, 'override_pass', 'released'],
+ [st, 'override_fail', 'refunded'],
+ ]),
];
it.each(legal)('%s --%s--> %s', (from, event, to) => {
expect(applyEvent(from, event)).toBe(to);
@@ -51,6 +55,13 @@ describe('transition table', () => {
}
});
+ it('a moderator override cannot reopen a resolved case', () => {
+ for (const st of ['released', 'refunded']) {
+ expect(() => applyEvent(st, 'override_pass')).toThrow(/already/);
+ expect(() => applyEvent(st, 'override_fail')).toThrow(/already/);
+ }
+ });
+
it('a second attestation attempt is illegal once attested', () => {
expect(() => applyEvent('attested', 'attest')).toThrow(/cannot attest/);
});
diff --git a/tests/labor-evaluation.test.js b/tests/labor-evaluation.test.js
new file mode 100644
index 000000000..b7e83c530
--- /dev/null
+++ b/tests/labor-evaluation.test.js
@@ -0,0 +1,562 @@
+// Escrow lifecycle with an independent evaluator (api/_lib/labor-evaluation.js):
+// pass, fail, dispute (both rulings), timeouts, a double attestation, a late
+// dispute, payout retry, moderator override, and the property that no sequence of
+// actions leaves funds locked. The case ledger is an in-memory double with the
+// real compare-and-set and hash-chain semantics; money moves through spies.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import fc from 'fast-check';
+import { Keypair } from '@solana/web3.js';
+
+const h = vi.hoisted(() => ({
+ cases: new Map(),
+ events: [],
+ bounty: null,
+ job: null,
+ owners: new Set(),
+ wallets: {},
+ notes: [],
+ payFail: false,
+ paid: [],
+ verify: { pass: true, reason: 'ok', verifier: 'llm' },
+ attester: null,
+}));
+
+vi.mock('../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...v) => {
+ const q = strings.join('?');
+ if (/FROM agent_identities WHERE id = \? AND user_id/.test(q)) return h.owners.has(`${v[0]}:${v[1]}`) ? [{ ok: 1 }] : [];
+ if (/SELECT meta FROM agent_identities/.test(q)) return h.wallets[v[0]] ? [{ meta: { solana_address: h.wallets[v[0]] } }] : [];
+ if (/SELECT id FROM labor_escrow_cases/.test(q)) {
+ // Mirrors the WHERE clause of dueCaseIds so a bad pre-filter fails the lifecycle tests.
+ const now = Date.now();
+ const t = (x) => Date.parse(x);
+ return [...h.cases.values()].filter((c) =>
+ (['released', 'refunded'].includes(c.state) && !c.paid_at)
+ || (['funded', 'working'].includes(c.state) && t(c.deadline_at) <= now + 86_400_000)
+ || (c.state === 'submitted' && (c.evaluator_kind === 'platform' || t(c.attest_by) <= now + 86_400_000))
+ || (c.state === 'attested' && t(c.release_at) <= now)
+ || (c.state === 'disputed' && (c.evaluator_kind !== 'platform' || t(c.arbiter_by) <= now + 86_400_000)),
+ ).map((c) => ({ id: c.id }));
+ }
+ if (/UPDATE agent_bounties SET status = 'refunding'/.test(q)) {
+ if (!['open', 'working'].includes(h.bounty.status)) return [];
+ h.bounty.status = 'refunding';
+ return [{ status: 'refunding' }];
+ }
+ if (/UPDATE agent_bounties SET status = \?, updated_at/.test(q)) {
+ if (h.bounty.status === 'refunding') h.bounty.status = v[0];
+ return [];
+ }
+ return [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../api/_lib/agent-labor.js', () => ({
+ getBounty: vi.fn(async () => (h.bounty ? { ...h.bounty } : null)),
+ getJobByBounty: vi.fn(async () => (h.job ? { ...h.job } : null)),
+ markJobFailed: vi.fn(async (id, { status }) => { h.job.status = status; }),
+ markJobDelivered: vi.fn(async (id, d) => { h.job.status = 'delivered'; h.job.deliverable = d; return { ...h.job }; }),
+ setBountyStatus: vi.fn(async (id, status) => { h.bounty.status = status; }),
+ atomicsToThree: (a) => String(Number(a) / 1e6),
+ _toBig: (a) => BigInt(a),
+}));
+
+vi.mock('../api/_lib/labor-match.js', () => ({ verifyDeliverable: vi.fn(async () => ({ ...h.verify, score: h.verify.pass ? 1 : 0 })) }));
+
+vi.mock('../api/_lib/labor-escrow.js', () => ({
+ payFromEscrow: vi.fn(async ({ toAddress, amountAtomics }) => {
+ if (h.payFail) throw new Error('transaction was not confirmed');
+ h.paid.push({ to: toAddress, amount: amountAtomics });
+ return `SIG${h.paid.length}`;
+ }),
+ ensureEscrowGas: vi.fn(async () => ({})),
+}));
+
+vi.mock('../api/_lib/labor-settle.js', () => ({
+ runSettlement: vi.fn(async ({ job, bounty, verdict }) => {
+ if (h.payFail) throw new Error('transaction was not confirmed');
+ if (['settled', 'failed', 'refunded'].includes(h.job.status)) return { idempotent: true, status: h.job.status };
+ const sig = `SET${h.paid.length + 1}`;
+ h.paid.push({ to: verdict.pass ? 'worker' : 'poster', amount: BigInt(bounty.reward_atomics) });
+ h.job.status = verdict.pass ? 'settled' : verdict.neutral ? 'refunded' : 'failed';
+ return { settled: verdict.pass, status: h.job.status, settlement_sig: verdict.pass ? sig : null, refund_sig: verdict.pass ? null : sig };
+ }),
+}));
+
+vi.mock('../api/_lib/attest-event.js', () => ({ loadAttesterKeypair: () => { if (!h.attester) throw new Error('no key'); return h.attester; } }));
+vi.mock('../api/_lib/notify.js', () => ({ insertNotification: vi.fn(async (userId, type, p) => { h.notes.push({ userId, type, kind: p.kind }); }) }));
+
+vi.mock('../api/_lib/labor-escrow-ledger.js', async () => {
+ const m = await import('../api/_lib/labor-escrow-machine.js');
+ const snake = (k) => k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
+ const copy = (c) => (c ? structuredClone(c) : null);
+ let n = 0;
+ const append = (c, { from, to, event, actor, reason = null, data = {} }) => {
+ const seq = c.version;
+ const prev = [...h.events].reverse().find((e) => e.case_id === c.id);
+ const at = new Date().toISOString();
+ const hash = m.chainHash(prev?.hash || null, { seq, from, to, event, actor, reason, data, at });
+ h.events.push({ case_id: c.id, seq, from_state: from, to_state: to, event, actor, reason, data, at, prev_hash: prev?.hash || null, hash });
+ };
+ return {
+ ensureEscrowTables: async () => true,
+ getCase: async (id) => copy(h.cases.get(id)),
+ getCaseByBounty: async (b) => copy([...h.cases.values()].find((c) => c.bounty_id === b)),
+ openCase: async ({ bounty, evaluator, disputeWindowSeconds }) => {
+ const ex = [...h.cases.values()].find((c) => c.bounty_id === bounty.id);
+ if (ex) return copy(ex);
+ const ev = m.normalizeEvaluator(evaluator, { posterAgentId: bounty.poster_agent_id });
+ const c = {
+ id: `case${++n}`, bounty_id: bounty.id, job_id: null, state: 'funded', evaluator_kind: ev.kind,
+ evaluator_agent_id: ev.agentId, dispute_window_seconds: m.normalizeDisputeWindow(disputeWindowSeconds),
+ deadline_at: bounty.deadline ? new Date(bounty.deadline).toISOString() : new Date(Date.now() + m.DEFAULT_JOB_TTL_SECONDS * 1000).toISOString(),
+ version: 1, notified: {}, paid_at: null, outcome: null, attestation: null, dispute: null, resolution: null,
+ };
+ h.cases.set(c.id, c);
+ append(c, { from: null, to: 'funded', event: 'fund', actor: 'poster' });
+ return copy(c);
+ },
+ transition: async (caseRow, event, { actor, reason = null, data = {}, patch = {} } = {}) => {
+ const to = m.applyEvent(caseRow.state, event);
+ const cur = h.cases.get(caseRow.id);
+ if (cur.state !== caseRow.state) throw new m.EscrowError('state_changed', `escrow is already ${cur.state}; this action came too late`);
+ for (const [k, v] of Object.entries(patch)) if (v !== undefined && v !== null) cur[snake(k)] = v;
+ cur.state = to;
+ cur.version += 1;
+ append(cur, { from: caseRow.state, to, event, actor, reason, data });
+ return copy(cur);
+ },
+ markPaid: async (caseRow, { sig = null, data = {}, actor = 'platform' } = {}) => {
+ const cur = h.cases.get(caseRow.id);
+ if (cur.paid_at || !['released', 'refunded'].includes(cur.state)) return null;
+ cur.paid_at = new Date().toISOString();
+ cur.settle_sig = sig;
+ cur.version += 1;
+ append(cur, { from: cur.state, to: cur.state, event: 'payout', actor, data: { sig, ...data } });
+ return copy(cur);
+ },
+ markNotified: async (id, key) => {
+ const cur = h.cases.get(id);
+ if (cur.notified[key]) return false;
+ cur.notified[key] = true;
+ return true;
+ },
+ trailFor: async (id) => {
+ const events = h.events.filter((e) => e.case_id === id);
+ return { events, chain: m.verifyChain(events) };
+ },
+ };
+});
+
+const ev = await import('../api/_lib/labor-evaluation.js');
+const { EscrowError, verifyAttestation, verifyChain, isTerminal } = await import('../api/_lib/labor-escrow-machine.js');
+
+const T0 = new Date('2026-10-23T12:00:00.000Z');
+const HOUR = 3600_000;
+const DAY = 24 * HOUR;
+const advance = (ms) => vi.setSystemTime(new Date(Date.now() + ms));
+
+function setup({ evaluator = 'platform', disputeWindowSeconds = 86400 } = {}) {
+ h.cases.clear(); h.events.length = 0; h.notes.length = 0; h.paid.length = 0;
+ h.payFail = false;
+ h.verify = { pass: true, reason: 'meets the spec', verifier: 'llm' };
+ h.attester = Keypair.generate();
+ h.owners = new Set(['pa:up', 'wa:uw', 'ea:ue']);
+ h.wallets = { pa: 'POSTERADDR', wa: 'WORKERADDR', ea: 'EVALADDR' };
+ h.bounty = {
+ id: 'b1', title: 'Summarize', poster_agent_id: 'pa', poster_user_id: 'up', reward_atomics: '1000000',
+ escrow_fund_sig: 'FUND', status: 'open', deadline: null,
+ meta: { escrow: { evaluator, dispute_window_seconds: disputeWindowSeconds } },
+ };
+ h.job = { id: 'j1', bounty_id: 'b1', worker_agent_id: 'wa', worker_user_id: 'uw', status: 'working', price_atomics: '800000', deliverable: null };
+}
+
+async function award() {
+ h.bounty.status = 'working';
+ return ev.recordAward({ ...h.bounty }, { ...h.job });
+}
+async function deliver(output = 'a real deliverable') {
+ h.job.status = 'delivered';
+ h.job.deliverable = { output };
+ return ev.intakeDelivery({ bounty: { ...h.bounty }, job: { ...h.job } });
+}
+const state = async () => (await ev.caseView('b1')).state;
+const sweep = () => ev.sweepCases();
+
+/** The timestamped transition table for a case, as printed in docs/labor-market.md. */
+async function table(label) {
+ const v = await ev.caseView('b1');
+ const rows = v.trail.map((t) => `${t.seq.toString().padStart(2)} ${t.at} ${(t.from || 'start').padEnd(9)} -> ${t.to.padEnd(9)} ${t.event.padEnd(15)} ${t.actor}`);
+ console.log(`\n[${label}]\n${rows.join('\n')}`);
+ return v;
+}
+
+beforeEach(() => { vi.useFakeTimers({ now: T0 }); setup(); });
+afterEach(() => vi.useRealTimers());
+
+describe('pass: the platform checker approves, the window closes, funds release', () => {
+ it('walks funded to released and pays the worker once', async () => {
+ await award();
+ expect(await state()).toBe('working');
+ await deliver();
+ let v = await ev.caseView('b1');
+ expect(v.state).toBe('attested');
+ expect(v.attestation.verdict).toBe('pass');
+ expect(verifyAttestation({ payload: v.attestation.payload, signature: v.attestation.signature, signer: v.attestation.signer })).toBe(true);
+
+ await sweep(); // inside the window: nothing moves
+ expect(await state()).toBe('attested');
+ expect(h.paid).toHaveLength(0);
+
+ advance(DAY + 1000);
+ const r = await sweep();
+ expect(r).toMatchObject({ resolved: 1, paid: 1, failed: 0 });
+ v = await table('pass');
+ expect(v.state).toBe('released');
+ expect(v.outcome).toBe('pass');
+ expect(v.paid_at).toBeTruthy();
+ expect(h.paid).toEqual([{ to: 'worker', amount: 1_000_000n }]);
+ expect(v.chain.ok).toBe(true);
+ expect(h.job.status).toBe('settled');
+
+ await sweep(); // a second sweep pays nothing more
+ expect(h.paid).toHaveLength(1);
+ });
+
+ it('notifies both parties once per milestone', async () => {
+ await award(); await deliver();
+ advance(DAY + 1000); await sweep(); await sweep();
+ const delivered = h.notes.filter((n) => n.kind === 'delivered').map((n) => n.userId).sort();
+ expect(delivered).toEqual(['up', 'uw']);
+ expect(h.notes.filter((n) => n.kind === 'paid')).toHaveLength(2);
+ });
+});
+
+describe('fail: the checker rejects, the window closes, the buyer is refunded', () => {
+ it('refunds the poster and marks the job failed', async () => {
+ h.verify = { pass: false, reason: 'off spec', verifier: 'llm' };
+ await award(); await deliver('nonsense');
+ expect((await ev.caseView('b1')).attestation.verdict).toBe('fail');
+ advance(DAY + 1000); await sweep();
+ const v = await table('fail');
+ expect(v.state).toBe('refunded');
+ expect(v.outcome).toBe('fail');
+ expect(h.paid).toEqual([{ to: 'poster', amount: 1_000_000n }]);
+ expect(h.job.status).toBe('failed');
+ });
+});
+
+describe('dispute', () => {
+ it('freezes funds when the buyer disputes a pass, and the arbiter can overturn it', async () => {
+ await award(); await deliver();
+ await ev.openDispute({ bountyId: 'b1', userId: 'up', reason: 'The summary misses the second section entirely.' });
+ advance(10 * DAY); // far past the window: a dispute must freeze, not release
+ await sweep();
+ expect(await state()).toBe('refunded'); // arbiter_timeout after 7 days
+ expect((await ev.caseView('b1')).outcome).toBe('arbiter_timeout');
+ expect(h.paid).toEqual([{ to: 'poster', amount: 1_000_000n }]);
+ });
+
+ it('an arbiter ruling for the worker releases the funds', async () => {
+ await award(); await deliver();
+ await ev.openDispute({ bountyId: 'b1', userId: 'up', reason: 'I do not think this meets the spec at all.' });
+ expect(await state()).toBe('disputed');
+ await sweep();
+ expect(h.paid).toHaveLength(0); // frozen
+ await ev.arbitrate({ bountyId: 'b1', adminId: 'adm', input: { verdict: 'pass', reasonCode: 'meets_spec', reasonDetail: 'reviewed by hand' } });
+ const v = await table('dispute ruled for worker');
+ expect(v.state).toBe('released');
+ expect(v.resolution.verdict).toBe('pass');
+ expect(h.paid).toEqual([{ to: 'worker', amount: 1_000_000n }]);
+ });
+
+ it('an arbiter ruling for the buyer refunds', async () => {
+ await award(); await deliver();
+ await ev.openDispute({ bountyId: 'b1', userId: 'up', reason: 'I do not think this meets the spec at all.' });
+ await ev.arbitrate({ bountyId: 'b1', adminId: 'adm', input: { verdict: 'fail', reasonCode: 'off_spec' } });
+ expect(await state()).toBe('refunded');
+ expect(h.paid).toEqual([{ to: 'poster', amount: 1_000_000n }]);
+ });
+
+ it('only the losing side may dispute', async () => {
+ await award(); await deliver(); // verdict: pass, so the worker won
+ await expect(ev.openDispute({ bountyId: 'b1', userId: 'uw', reason: 'I want to dispute my own win here.' }))
+ .rejects.toMatchObject({ code: 'not_losing_side', status: 403 });
+ });
+
+ it('a stranger cannot dispute', async () => {
+ await award(); await deliver();
+ await expect(ev.openDispute({ bountyId: 'b1', userId: 'nobody', reason: 'I am not a party to this job.' }))
+ .rejects.toMatchObject({ code: 'forbidden' });
+ });
+
+ it('a dispute after the window closes is rejected, even before the cron has run', async () => {
+ await award(); await deliver();
+ advance(DAY + 1000);
+ await expect(ev.openDispute({ bountyId: 'b1', userId: 'up', reason: 'This arrived just a moment too late.' }))
+ .rejects.toMatchObject({ code: 'dispute_window_closed', status: 409 });
+ await sweep();
+ expect(await state()).toBe('released');
+ });
+
+ it('a dispute needs a reason', async () => {
+ await award(); await deliver();
+ await expect(ev.openDispute({ bountyId: 'b1', userId: 'up', reason: 'bad' })).rejects.toMatchObject({ code: 'reason_required' });
+ });
+
+ it('a dispute cannot be arbitrated twice', async () => {
+ await award(); await deliver();
+ await ev.openDispute({ bountyId: 'b1', userId: 'up', reason: 'The summary misses the second section entirely.' });
+ await ev.arbitrate({ bountyId: 'b1', adminId: 'adm', input: { verdict: 'pass', reasonCode: 'meets_spec' } });
+ await expect(ev.arbitrate({ bountyId: 'b1', adminId: 'adm', input: { verdict: 'fail', reasonCode: 'off_spec' } }))
+ .rejects.toMatchObject({ code: 'already_resolved' });
+ expect(h.paid).toHaveLength(1);
+ });
+});
+
+describe('hiring agent as evaluator', () => {
+ beforeEach(() => setup({ evaluator: 'poster', disputeWindowSeconds: 3600 }));
+
+ it('waits for the poster to attest, then counts the window from the attestation', async () => {
+ await award(); await deliver();
+ expect(await state()).toBe('submitted');
+ const view = await ev.caseView('b1', 'up');
+ expect(view.viewer.can_attest).toBe(true);
+ expect((await ev.caseView('b1', 'uw')).viewer.can_attest).toBe(false);
+
+ await ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: { verdict: 'pass' } });
+ expect(await state()).toBe('attested');
+ advance(HOUR + 1000); await sweep();
+ expect(await state()).toBe('released');
+ });
+
+ it('a second attestation is rejected with a typed 409 and changes nothing', async () => {
+ await award(); await deliver();
+ await ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: { verdict: 'pass' } });
+ const before = (await ev.caseView('b1')).attestation.signature;
+ await expect(ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: { verdict: 'fail', reasonCode: 'off_spec' } }))
+ .rejects.toMatchObject({ code: 'already_attested', status: 409 });
+ const after = await ev.caseView('b1');
+ expect(after.attestation.verdict).toBe('pass');
+ expect(after.attestation.signature).toBe(before);
+ });
+
+ it('a concurrent double attestation has exactly one winner', async () => {
+ await award(); await deliver();
+ const results = await Promise.allSettled([
+ ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: { verdict: 'pass' } }),
+ ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: { verdict: 'fail', reasonCode: 'other' } }),
+ ]);
+ expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1);
+ expect(h.events.filter((e) => e.event === 'attest')).toHaveLength(1);
+ });
+
+ it('only the evaluator can attest, and not once the case has moved on', async () => {
+ await award(); await deliver();
+ await expect(ev.submitAttestation({ bountyId: 'b1', userId: 'uw', input: { verdict: 'pass' } }))
+ .rejects.toMatchObject({ code: 'not_evaluator', status: 403 });
+ await ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: { verdict: 'pass' } });
+ advance(HOUR + 1000); await sweep();
+ await expect(ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: { verdict: 'fail', reasonCode: 'other' } }))
+ .rejects.toMatchObject({ code: 'already_resolved' });
+ });
+
+ it('no attestation by the deadline refunds the buyer', async () => {
+ await award(); await deliver();
+ advance(14 * DAY + 1000); await sweep(); // attest_by is the later of the job deadline and delivery + 3d
+ const v = await table('no attestation');
+ expect(v.state).toBe('refunded');
+ expect(v.outcome).toBe('attest_timeout');
+ expect(h.paid).toEqual([{ to: 'poster', amount: 1_000_000n }]);
+ expect(h.job.status).toBe('refunded'); // nobody's fault: not 'failed'
+ });
+
+ it('rejects a signature from the wrong signer', async () => {
+ await award(); await deliver();
+ await expect(ev.submitAttestation({
+ bountyId: 'b1', userId: 'up', input: { verdict: 'pass' },
+ signature: 'AAAA', signer: Keypair.generate().publicKey.toBase58(), issuedAt: new Date().toISOString(),
+ })).rejects.toMatchObject({ code: 'bad_signer' });
+ });
+
+ it('a disputed poster verdict is re-checked by the platform checker', async () => {
+ await award(); await deliver();
+ await ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: { verdict: 'fail', reasonCode: 'off_spec' } });
+ await ev.openDispute({ bountyId: 'b1', userId: 'uw', reason: 'The deliverable matches every line of the spec.' });
+ const v = await ev.caseView('b1');
+ expect(v.state).toBe('released'); // the checker passes it (verify.pass = true)
+ expect(v.resolution.verdict).toBe('pass');
+ expect(h.paid).toEqual([{ to: 'worker', amount: 1_000_000n }]);
+ });
+});
+
+describe('registry agent as evaluator', () => {
+ beforeEach(() => setup({ evaluator: { kind: 'agent', agentId: 'ea' }, disputeWindowSeconds: 0 }));
+
+ it('the registry agent attests and a zero window releases at the next sweep', async () => {
+ await award(); await deliver();
+ await ev.submitAttestation({ bountyId: 'b1', userId: 'ue', input: { verdict: 'pass' } });
+ await sweep();
+ expect(await state()).toBe('released');
+ });
+
+ it('refuses an evaluator who is also the worker', async () => {
+ h.owners.add('wa:ue');
+ h.cases.clear(); h.events.length = 0;
+ h.bounty.meta.escrow.evaluator = { kind: 'agent', agentId: 'wa' };
+ await award(); await deliver();
+ h.owners.add('wa:uw');
+ await expect(ev.submitAttestation({ bountyId: 'b1', userId: 'uw', input: { verdict: 'pass' } }))
+ .rejects.toMatchObject({ code: 'conflict_of_interest' });
+ });
+});
+
+describe('timeouts', () => {
+ it('an award that never delivers refunds at the deadline', async () => {
+ h.bounty.deadline = new Date(T0.getTime() + 2 * DAY).toISOString();
+ await award();
+ advance(2 * DAY + 1000); await sweep();
+ const v = await table('worker never delivers');
+ expect(v).toMatchObject({ state: 'refunded', outcome: 'deadline' });
+ expect(h.paid).toEqual([{ to: 'POSTERADDR', amount: 1_000_000n }]);
+ });
+
+ it('a bounty nobody takes refunds at the deadline', async () => {
+ h.bounty.deadline = new Date(T0.getTime() + DAY).toISOString();
+ h.job = null;
+ await ev.ensureCase({ ...h.bounty });
+ advance(DAY + 1000); await sweep();
+ expect(await state()).toBe('refunded');
+ expect(h.paid).toEqual([{ to: 'POSTERADDR', amount: 1_000_000n }]);
+ expect(h.bounty.status).toBe('refunded');
+ });
+
+ it('the poster can cancel before an award', async () => {
+ h.job = null;
+ await ev.ensureCase({ ...h.bounty });
+ await expect(ev.cancelBounty({ bountyId: 'b1', userId: 'uw' })).rejects.toMatchObject({ code: 'forbidden' });
+ await ev.cancelBounty({ bountyId: 'b1', userId: 'up' });
+ expect(await state()).toBe('refunded');
+ expect(h.paid).toHaveLength(1);
+ });
+
+ it('warns both parties once when a deadline is within a day', async () => {
+ h.bounty.deadline = new Date(T0.getTime() + 12 * HOUR).toISOString();
+ await award();
+ await sweep(); await sweep();
+ const soon = h.notes.filter((n) => n.kind === 'deadline_soon');
+ expect(soon.map((n) => n.userId).sort()).toEqual(['up', 'uw']);
+ });
+});
+
+describe('payout retry: the decision is durable even when the transfer fails', () => {
+ it('keeps the decision, tells the parties once, and pays exactly once on retry', async () => {
+ await award(); await deliver();
+ h.payFail = true;
+ advance(DAY + 1000);
+ await sweep();
+ let v = await ev.caseView('b1');
+ expect(v.state).toBe('released');
+ expect(v.paid_at).toBeNull();
+ await sweep();
+ expect(h.notes.filter((n) => n.kind === 'payout_delayed')).toHaveLength(2); // one per party, once
+ h.payFail = false;
+ await sweep();
+ v = await table('payout retried');
+ expect(v.paid_at).toBeTruthy();
+ expect(h.paid).toHaveLength(1);
+ expect(h.events.filter((e) => e.event === 'payout')).toHaveLength(1);
+ });
+});
+
+describe('moderator override', () => {
+ it('releases a disputed case to the worker', async () => {
+ await award(); await deliver();
+ await ev.openDispute({ bountyId: 'b1', userId: 'up', reason: 'The summary misses the second section entirely.' });
+ await ev.moderatorOverride({ bountyId: 'b1', adminId: 'm1', action: 'release', reason: 'reviewed' });
+ expect(await state()).toBe('released');
+ expect(h.paid).toEqual([{ to: 'worker', amount: 1_000_000n }]);
+ const last = (await ev.caseView('b1')).trail.find((t) => t.event === 'override_pass');
+ expect(last.actor).toBe('moderator:m1');
+ });
+
+ it('refunds an unawarded bounty and cannot reopen a resolved case', async () => {
+ h.job = null;
+ await ev.ensureCase({ ...h.bounty });
+ await ev.moderatorOverride({ bountyId: 'b1', adminId: 'm1', action: 'refund' });
+ expect(await state()).toBe('refunded');
+ await expect(ev.moderatorOverride({ bountyId: 'b1', adminId: 'm1', action: 'release' })).rejects.toBeInstanceOf(EscrowError);
+ expect(h.paid).toHaveLength(1);
+ });
+});
+
+describe('audit trail', () => {
+ it('every transition is on the trail with a timestamp, in an unbroken chain', async () => {
+ await award(); await deliver();
+ advance(DAY + 1000); await sweep();
+ const v = await ev.caseView('b1');
+ expect(v.trail.map((t) => t.event)).toEqual(['fund', 'award', 'deliver', 'attest', 'cooldown_pass', 'payout']);
+ expect(v.trail.every((t) => Number.isFinite(Date.parse(t.at)))).toBe(true);
+ expect(v.chain.ok).toBe(true);
+ });
+
+ it('detects a tampered trail', async () => {
+ await award(); await deliver();
+ h.events[1].actor = 'someone_else';
+ expect(verifyChain(h.events)).toMatchObject({ ok: false });
+ expect((await ev.caseView('b1')).chain.ok).toBe(false);
+ });
+});
+
+describe('property: no sequence of actions leaves funds locked forever', () => {
+ const action = fc.oneof(
+ fc.constant({ t: 'award' }),
+ fc.constant({ t: 'deliver' }),
+ fc.record({ t: fc.constant('attest'), pass: fc.boolean() }),
+ fc.constant({ t: 'dispute' }),
+ fc.constant({ t: 'cancel' }),
+ fc.record({ t: fc.constant('wait'), hours: fc.integer({ min: 0, max: 96 }) }),
+ fc.record({ t: fc.constant('payfail'), on: fc.boolean() }),
+ fc.constant({ t: 'sweep' }),
+ );
+
+ it('always ends released or refunded, and paid exactly once', async () => {
+ await fc.assert(fc.asyncProperty(
+ fc.constantFrom('platform', 'poster'),
+ fc.constantFrom(0, 3600, 86400),
+ fc.array(action, { maxLength: 14 }),
+ async (evaluator, windowS, actions) => {
+ vi.setSystemTime(T0);
+ setup({ evaluator, disputeWindowSeconds: windowS });
+ await ev.ensureCase({ ...h.bounty });
+ for (const a of actions) {
+ try {
+ if (a.t === 'award') await award();
+ else if (a.t === 'deliver' && h.bounty.status === 'working') await deliver();
+ else if (a.t === 'attest') await ev.submitAttestation({ bountyId: 'b1', userId: 'up', input: a.pass ? { verdict: 'pass' } : { verdict: 'fail', reasonCode: 'other' } });
+ else if (a.t === 'dispute') await ev.openDispute({ bountyId: 'b1', userId: 'up', reason: 'I dispute this verdict for good reasons.' });
+ else if (a.t === 'cancel') await ev.cancelBounty({ bountyId: 'b1', userId: 'up' });
+ else if (a.t === 'wait') advance(a.hours * HOUR);
+ else if (a.t === 'payfail') h.payFail = a.on;
+ else if (a.t === 'sweep') await sweep();
+ } catch (e) {
+ if (!(e instanceof EscrowError)) throw e;
+ }
+ }
+ // Leave the system alone for longer than every timer, with a healthy payout rail.
+ h.payFail = false;
+ for (let i = 0; i < 6; i++) { advance(20 * DAY); await sweep(); }
+ const c = [...h.cases.values()][0];
+ expect(isTerminal(c.state)).toBe(true);
+ expect(c.paid_at).toBeTruthy();
+ expect(h.paid).toHaveLength(1);
+ expect(verifyChain(h.events.filter((e) => e.case_id === c.id)).ok).toBe(true);
+ },
+ ), { numRuns: 120 });
+ });
+});
diff --git a/tests/labor-tick-batch.test.js b/tests/labor-tick-batch.test.js
index 635b62698..50bcc1dad 100644
--- a/tests/labor-tick-batch.test.js
+++ b/tests/labor-tick-batch.test.js
@@ -42,7 +42,7 @@ const h = vi.hoisted(() => {
return {
sql: vi.fn(),
runAutopilot: vi.fn(),
- runSettlement: vi.fn(),
+ intakeDelivery: vi.fn(),
getBounty: vi.fn(),
getJob: vi.fn(),
};
@@ -60,7 +60,12 @@ vi.mock('../api/_lib/agent-labor.js', () => ({
}));
vi.mock('../api/_lib/labor-settle.js', () => ({
runAutopilot: (...a) => h.runAutopilot(...a),
- runSettlement: (...a) => h.runSettlement(...a),
+}));
+vi.mock('../api/_lib/labor-evaluation.js', () => ({
+ intakeDelivery: (...a) => h.intakeDelivery(...a),
+}));
+vi.mock('../api/_lib/labor-escrow-ledger.js', () => ({
+ ensureEscrowTables: vi.fn(async () => true),
}));
const { default: handler } = await import('../api/labor/tick.js');
@@ -129,7 +134,7 @@ beforeEach(() => {
jobRows = [];
installSql();
h.runAutopilot.mockResolvedValue({ bids: 0, awarded: false, settled: null, settledNow: false });
- h.runSettlement.mockResolvedValue({ settled: true, status: 'settled' });
+ h.intakeDelivery.mockResolvedValue({ state: 'attested' });
h.getBounty.mockResolvedValue({ id: 'b1', title: 'T', poster_agent_id: 'p' });
h.getJob.mockImplementation(async (id) => ({ id, status: 'delivered', worker_agent_id: 'w' }));
});
@@ -210,14 +215,14 @@ describe('labor tick: counting', () => {
const res = await tick();
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
- ok: true, scanned: 3, bids: 3, awarded: 1, settled: 2, failed: 0,
+ ok: true, scanned: 3, bids: 3, awarded: 1, settled: 1, failed: 0,
});
expect(res.body.errors).toBeUndefined();
});
- it('does not count a settle another caller already claimed', async () => {
+ it('does not count a delivery that only opened evaluation', async () => {
jobRows = [{ id: 'j1', bounty_id: 'b1', status: 'verifying' }];
- h.runSettlement.mockResolvedValue({ idempotent: true, status: 'settled' });
+ h.intakeDelivery.mockResolvedValue(null);
const res = await tick();
expect(res.body).toMatchObject({ ok: true, scanned: 1, settled: 0, failed: 0 });
@@ -250,6 +255,12 @@ describe('labor tick: counting', () => {
expect(h.runAutopilot).toHaveBeenCalledWith('b1');
expect(h.getBounty).not.toHaveBeenCalled();
});
+
+ it('only lets the tick touch deliveries whose escrow case has not advanced', async () => {
+ await tick();
+ expect(queries.jobs).toMatch(/labor_escrow_cases/);
+ expect(queries.jobs).toMatch(/c\.state <> 'working'/);
+ });
});
describe('labor tick: failure isolation', () => {
@@ -262,18 +273,18 @@ describe('labor tick: failure isolation', () => {
const res = await tick();
expect(res.statusCode).toBe(200);
- expect(res.body).toMatchObject({ ok: true, scanned: 2, settled: 1, failed: 1 });
+ expect(res.body).toMatchObject({ ok: true, scanned: 2, settled: 0, failed: 1 });
expect(res.body.errors).toHaveLength(1);
expect(res.body.errors[0]).toContain('j1');
expect(res.body.errors[0]).toContain('connection reset');
expect(res.body.reason).toBe('1/2 items failed');
- // The second job still settled: the throw did not abort the loop.
- expect(h.runSettlement).toHaveBeenCalledTimes(1);
+ // The second job still entered evaluation: the throw did not abort the loop.
+ expect(h.intakeDelivery).toHaveBeenCalledTimes(1);
});
it('reports a lane where every row failed as an outage, not an idle tick', async () => {
jobRows = [{ id: 'j1', bounty_id: 'b1', status: 'delivered' }];
- h.runSettlement.mockRejectedValue(new Error('escrow unreachable'));
+ h.intakeDelivery.mockRejectedValue(new Error('escrow unreachable'));
const res = await tick();
expect(res.statusCode).toBe(502);
@@ -282,7 +293,7 @@ describe('labor tick: failure isolation', () => {
it('caps the reported errors so a batch-wide failure cannot bloat the response', async () => {
jobRows = Array.from({ length: 8 }, (_, i) => ({ id: `j${i}`, bounty_id: 'b1', status: 'delivered' }));
- h.runSettlement.mockRejectedValue(new Error('escrow unreachable'));
+ h.intakeDelivery.mockRejectedValue(new Error('escrow unreachable'));
const res = await tick();
expect(res.body.failed).toBe(8);