caisson-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.math-mvp.md +28 -0
- package/README.md +37 -2
- package/dist/admin/adminRoutes.d.ts +10 -0
- package/dist/admin/adminRoutes.js +194 -0
- package/dist/admin/adminRoutes.js.map +1 -0
- package/dist/admin/index.d.ts +2 -0
- package/dist/admin/index.js +4 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/admin/workspaceAdmin.d.ts +417 -0
- package/dist/admin/workspaceAdmin.js +569 -0
- package/dist/admin/workspaceAdmin.js.map +1 -0
- package/dist/analytics/index.d.ts +1 -0
- package/dist/analytics/index.js +3 -0
- package/dist/analytics/index.js.map +1 -0
- package/dist/analytics/metrics.d.ts +105 -0
- package/dist/analytics/metrics.js +837 -0
- package/dist/analytics/metrics.js.map +1 -0
- package/dist/audit/index.d.ts +4 -0
- package/dist/audit/index.js +6 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/pipeline.d.ts +90 -0
- package/dist/audit/pipeline.js +424 -0
- package/dist/audit/pipeline.js.map +1 -0
- package/dist/audit/receiptSchema.d.ts +441 -0
- package/dist/audit/receiptSchema.js +208 -0
- package/dist/audit/receiptSchema.js.map +1 -0
- package/dist/audit/stageA.d.ts +50 -0
- package/dist/audit/stageA.js +218 -0
- package/dist/audit/stageA.js.map +1 -0
- package/dist/audit/stageB.d.ts +48 -0
- package/dist/audit/stageB.js +113 -0
- package/dist/audit/stageB.js.map +1 -0
- package/dist/auth/agentAuth.d.ts +18 -0
- package/dist/auth/agentAuth.js +59 -0
- package/dist/auth/agentAuth.js.map +1 -0
- package/dist/auth/agentCardSigner.d.ts +55 -0
- package/dist/auth/agentCardSigner.js +188 -0
- package/dist/auth/agentCardSigner.js.map +1 -0
- package/dist/billing/billingRoutes.d.ts +11 -0
- package/dist/billing/billingRoutes.js +303 -0
- package/dist/billing/billingRoutes.js.map +1 -0
- package/dist/billing/bountyRoutes.d.ts +9 -0
- package/dist/billing/bountyRoutes.js +332 -0
- package/dist/billing/bountyRoutes.js.map +1 -0
- package/dist/billing/index.d.ts +3 -0
- package/dist/billing/index.js +4 -0
- package/dist/billing/index.js.map +1 -0
- package/dist/billing/subscriptions.d.ts +226 -0
- package/dist/billing/subscriptions.js +673 -0
- package/dist/billing/subscriptions.js.map +1 -0
- package/dist/cli/caissonCli.d.ts +10 -0
- package/dist/cli/caissonCli.js +471 -0
- package/dist/cli/caissonCli.js.map +1 -0
- package/dist/cli/inviteCard.d.ts +12 -0
- package/dist/cli/inviteCard.js +49 -0
- package/dist/cli/inviteCard.js.map +1 -0
- package/dist/cli/mcpProxy.d.ts +36 -0
- package/dist/cli/mcpProxy.js +292 -0
- package/dist/cli/mcpProxy.js.map +1 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.js +28 -0
- package/dist/config.js.map +1 -0
- package/dist/db/adapter.d.ts +210 -0
- package/dist/db/adapter.js +769 -0
- package/dist/db/adapter.js.map +1 -0
- package/dist/db/sqlite.d.ts +7 -0
- package/dist/db/sqlite.js +60 -0
- package/dist/db/sqlite.js.map +1 -0
- package/dist/db/telemetry.d.ts +11 -0
- package/dist/db/telemetry.js +9 -0
- package/dist/db/telemetry.js.map +1 -0
- package/dist/economy/bountyEngine.d.ts +248 -0
- package/dist/economy/bountyEngine.js +836 -0
- package/dist/economy/bountyEngine.js.map +1 -0
- package/dist/economy/index.d.ts +5 -0
- package/dist/economy/index.js +6 -0
- package/dist/economy/index.js.map +1 -0
- package/dist/economy/scLedger.d.ts +183 -0
- package/dist/economy/scLedger.js +528 -0
- package/dist/economy/scLedger.js.map +1 -0
- package/dist/economy/scMinting.d.ts +177 -0
- package/dist/economy/scMinting.js +659 -0
- package/dist/economy/scMinting.js.map +1 -0
- package/dist/economy/scSinks.d.ts +135 -0
- package/dist/economy/scSinks.js +314 -0
- package/dist/economy/scSinks.js.map +1 -0
- package/dist/economy/usdLedger.d.ts +211 -0
- package/dist/economy/usdLedger.js +604 -0
- package/dist/economy/usdLedger.js.map +1 -0
- package/dist/mcp/handlers.d.ts +134 -0
- package/dist/mcp/handlers.js +781 -0
- package/dist/mcp/handlers.js.map +1 -0
- package/dist/mcp/httpServer.d.ts +25 -0
- package/dist/mcp/httpServer.js +368 -0
- package/dist/mcp/httpServer.js.map +1 -0
- package/dist/mcp/serverFactory.d.ts +4 -0
- package/dist/mcp/serverFactory.js +53 -0
- package/dist/mcp/serverFactory.js.map +1 -0
- package/dist/mcp/stdioServer.d.ts +2 -0
- package/dist/mcp/stdioServer.js +24 -0
- package/dist/mcp/stdioServer.js.map +1 -0
- package/dist/mcp/toolMetadata.d.ts +15 -0
- package/dist/mcp/toolMetadata.js +73 -0
- package/dist/mcp/toolMetadata.js.map +1 -0
- package/dist/memo/artifactIndex.d.ts +51 -0
- package/dist/memo/artifactIndex.js +162 -0
- package/dist/memo/artifactIndex.js.map +1 -0
- package/dist/memo/dependencyBundle.d.ts +33 -0
- package/dist/memo/dependencyBundle.js +86 -0
- package/dist/memo/dependencyBundle.js.map +1 -0
- package/dist/memo/embeddings.d.ts +110 -0
- package/dist/memo/embeddings.js +672 -0
- package/dist/memo/embeddings.js.map +1 -0
- package/dist/packs/foundryEvm.d.ts +21 -0
- package/dist/packs/foundryEvm.js +274 -0
- package/dist/packs/foundryEvm.js.map +1 -0
- package/dist/packs/index.d.ts +8 -0
- package/dist/packs/index.js +19 -0
- package/dist/packs/index.js.map +1 -0
- package/dist/packs/mathLean4.d.ts +7 -0
- package/dist/packs/mathLean4.js +145 -0
- package/dist/packs/mathLean4.js.map +1 -0
- package/dist/packs/rustKani.d.ts +17 -0
- package/dist/packs/rustKani.js +257 -0
- package/dist/packs/rustKani.js.map +1 -0
- package/dist/packs/sdk.d.ts +314 -0
- package/dist/packs/sdk.js +271 -0
- package/dist/packs/sdk.js.map +1 -0
- package/dist/preflight/leanTripwire.d.ts +19 -0
- package/dist/preflight/leanTripwire.js +105 -0
- package/dist/preflight/leanTripwire.js.map +1 -0
- package/dist/storage/blobStore.d.ts +11 -0
- package/dist/storage/blobStore.js +39 -0
- package/dist/storage/blobStore.js.map +1 -0
- package/dist/storage/gitStore.d.ts +68 -0
- package/dist/storage/gitStore.js +228 -0
- package/dist/storage/gitStore.js.map +1 -0
- package/dist/types/errors.d.ts +16 -0
- package/dist/types/errors.js +23 -0
- package/dist/types/errors.js.map +1 -0
- package/dist/types/schemas.d.ts +453 -0
- package/dist/types/schemas.js +197 -0
- package/dist/types/schemas.js.map +1 -0
- package/dist/web/discoveryRoutes.d.ts +20 -0
- package/dist/web/discoveryRoutes.js +456 -0
- package/dist/web/discoveryRoutes.js.map +1 -0
- package/dist/web/explorer/dagLayout.d.ts +41 -0
- package/dist/web/explorer/dagLayout.js +183 -0
- package/dist/web/explorer/dagLayout.js.map +1 -0
- package/dist/web/explorer/index.d.ts +45 -0
- package/dist/web/explorer/index.js +512 -0
- package/dist/web/explorer/index.js.map +1 -0
- package/dist/web/explorer/renderers.d.ts +35 -0
- package/dist/web/explorer/renderers.js +397 -0
- package/dist/web/explorer/renderers.js.map +1 -0
- package/dist/web/repoBrowser.d.ts +19 -0
- package/dist/web/repoBrowser.js +128 -0
- package/dist/web/repoBrowser.js.map +1 -0
- package/dist/worker/executionAdapter.d.ts +14 -0
- package/dist/worker/executionAdapter.js +162 -0
- package/dist/worker/executionAdapter.js.map +1 -0
- package/dist/worker/finalize.d.ts +21 -0
- package/dist/worker/finalize.js +146 -0
- package/dist/worker/finalize.js.map +1 -0
- package/dist/worker/firecrackerAdapter.d.ts +180 -0
- package/dist/worker/firecrackerAdapter.js +421 -0
- package/dist/worker/firecrackerAdapter.js.map +1 -0
- package/dist/worker/loop.d.ts +56 -0
- package/dist/worker/loop.js +239 -0
- package/dist/worker/loop.js.map +1 -0
- package/dist/worker/postMergeSync.d.ts +17 -0
- package/dist/worker/postMergeSync.js +52 -0
- package/dist/worker/postMergeSync.js.map +1 -0
- package/dist/worker/prepareInput.d.ts +41 -0
- package/dist/worker/prepareInput.js +130 -0
- package/dist/worker/prepareInput.js.map +1 -0
- package/dist/worker/queue.d.ts +83 -0
- package/dist/worker/queue.js +278 -0
- package/dist/worker/queue.js.map +1 -0
- package/dist/worker/sandbox.d.ts +2 -0
- package/dist/worker/sandbox.js +3 -0
- package/dist/worker/sandbox.js.map +1 -0
- package/dist/worker/webhook.d.ts +14 -0
- package/dist/worker/webhook.js +110 -0
- package/dist/worker/webhook.js.map +1 -0
- package/migrations/001_init.sql +193 -0
- package/migrations/002_epic3_scale.sql +34 -0
- package/migrations/003_swarm_credits.sql +153 -0
- package/migrations/004_usd_bounties.sql +216 -0
- package/migrations_pg/001_init.sql +229 -0
- package/migrations_pg/002_multitenant_rls.sql +63 -0
- package/migrations_pg/003_swarm_credits.sql +135 -0
- package/migrations_pg/004_usd_bounties.sql +201 -0
- package/package.json +55 -4
- package/packs/foundry-evm/pack.json +60 -0
- package/packs/foundry-evm/verifier/Dockerfile +9 -0
- package/packs/foundry-evm/verifier/run.py +160 -0
- package/packs/math-lean4/pack.json +68 -0
- package/packs/rust-kani/pack.json +53 -0
- package/packs/rust-kani/verifier/Dockerfile +7 -0
- package/packs/rust-kani/verifier/run.py +159 -0
- package/public/.well-known/agent-card.json +153 -0
- package/public/llms.txt +35 -0
|
@@ -0,0 +1,836 @@
|
|
|
1
|
+
// src/economy/bountyEngine.ts
|
|
2
|
+
// Automated Bounty Escrow, Anti-Slop Staking & Recursive Dependency Royalties (Epic 5 / E5-2)
|
|
3
|
+
// Reference: docs/01 §6, docs/02 §5, docs/08 §3
|
|
4
|
+
//
|
|
5
|
+
// Core Guarantees:
|
|
6
|
+
// 1. Deterministic-Verifier-Only Settlement: USD bounties may ONLY be funded on workspaces
|
|
7
|
+
// using deterministic verifiers (never `peer_review` or `owner_signoff`), and settlement
|
|
8
|
+
// strictly requires `verifierResult.status === 'pass' && verifierResult.deterministic === true`.
|
|
9
|
+
// 2. Anti-Slop Staking & Slashing: Submitters lock a USD stake (respecting `per_task_spend_cap`);
|
|
10
|
+
// reward-hacked or deterministically failing submissions are slashed, while passing
|
|
11
|
+
// submissions, `STALE_BASE` races, and transient infra errors are refunded 100%.
|
|
12
|
+
// 3. Automatic Recursive `derived_from` Royalty Splits: 10%–20% (`1000–2000 bps`) of the
|
|
13
|
+
// post-fee distributable reward automatically splits recursively up the verified
|
|
14
|
+
// `artifact_lineage` DAG using exact Largest-Remainder cent apportionment.
|
|
15
|
+
// 4. Platform Take Rate: 10%–15% (`1000–1500 bps`, default 12%) routed to `usd_sys:platform_revenue`
|
|
16
|
+
// in the exact same atomic double-entry USD journal transaction.
|
|
17
|
+
import { newId, nowIso } from '../db/sqlite.js';
|
|
18
|
+
import { SwarmError } from '../types/errors.js';
|
|
19
|
+
import { assertAndRecordAgentTaskSpend, centsToUsd, postUsdJournalEntry, releaseAgentTaskSpend, USD_SYSTEM_REVENUE_ACCOUNT, USD_SYSTEM_SLASH_POOL_ACCOUNT, usdBountyEscrowAccountId, usdOperatorAccountId, usdStakeEscrowAccountId, } from './usdLedger.js';
|
|
20
|
+
export const MIN_PLATFORM_FEE_BPS = 1000; // 10%
|
|
21
|
+
export const MAX_PLATFORM_FEE_BPS = 1500; // 15%
|
|
22
|
+
export const DEFAULT_PLATFORM_FEE_BPS = 1200; // 12%
|
|
23
|
+
export const MIN_ROYALTY_POOL_BPS = 1000; // 10%
|
|
24
|
+
export const MAX_ROYALTY_POOL_BPS = 2000; // 20%
|
|
25
|
+
export const DEFAULT_ROYALTY_POOL_BPS = 1500; // 15%
|
|
26
|
+
export const DEFAULT_RECURSIVE_DECAY_BPS = 5000; // 50% flows upstream at each recursive hop
|
|
27
|
+
export const MAX_ROYALTY_LINEAGE_DEPTH = 10;
|
|
28
|
+
function hydrateBounty(row) {
|
|
29
|
+
return {
|
|
30
|
+
id: String(row.id),
|
|
31
|
+
workspace_id: String(row.workspace_id),
|
|
32
|
+
node_id: String(row.node_id),
|
|
33
|
+
sponsor_operator_id: String(row.sponsor_operator_id),
|
|
34
|
+
funded_by_agent_id: row.funded_by_agent_id ? String(row.funded_by_agent_id) : null,
|
|
35
|
+
currency: 'USD',
|
|
36
|
+
reward_cents: Number(row.reward_cents),
|
|
37
|
+
reward_usd: centsToUsd(Number(row.reward_cents)),
|
|
38
|
+
platform_fee_bps: Number(row.platform_fee_bps),
|
|
39
|
+
royalty_pool_bps: Number(row.royalty_pool_bps),
|
|
40
|
+
recursive_decay_bps: Number(row.recursive_decay_bps),
|
|
41
|
+
anti_slop_stake_cents: Number(row.anti_slop_stake_cents),
|
|
42
|
+
anti_slop_stake_usd: centsToUsd(Number(row.anti_slop_stake_cents)),
|
|
43
|
+
slash_recipient: row.slash_recipient,
|
|
44
|
+
escrow_account_id: String(row.escrow_account_id),
|
|
45
|
+
status: row.status,
|
|
46
|
+
lock_entry_id: row.lock_entry_id ? String(row.lock_entry_id) : null,
|
|
47
|
+
settlement_entry_id: row.settlement_entry_id ? String(row.settlement_entry_id) : null,
|
|
48
|
+
winning_run_id: row.winning_run_id ? String(row.winning_run_id) : null,
|
|
49
|
+
winning_artifact_id: row.winning_artifact_id ? String(row.winning_artifact_id) : null,
|
|
50
|
+
winning_operator_id: row.winning_operator_id ? String(row.winning_operator_id) : null,
|
|
51
|
+
platform_fee_cents: Number(row.platform_fee_cents ?? 0),
|
|
52
|
+
total_royalties_cents: Number(row.total_royalties_cents ?? 0),
|
|
53
|
+
winner_net_cents: Number(row.winner_net_cents ?? 0),
|
|
54
|
+
expires_at: row.expires_at ? String(row.expires_at) : null,
|
|
55
|
+
created_at: String(row.created_at),
|
|
56
|
+
settled_at: row.settled_at ? String(row.settled_at) : null,
|
|
57
|
+
updated_at: String(row.updated_at),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function hydrateStake(row) {
|
|
61
|
+
return {
|
|
62
|
+
id: String(row.id),
|
|
63
|
+
bounty_id: String(row.bounty_id),
|
|
64
|
+
run_id: row.run_id ? String(row.run_id) : null,
|
|
65
|
+
node_id: String(row.node_id),
|
|
66
|
+
agent_id: String(row.agent_id),
|
|
67
|
+
operator_id: String(row.operator_id),
|
|
68
|
+
stake_account_id: String(row.stake_account_id),
|
|
69
|
+
stake_cents: Number(row.stake_cents),
|
|
70
|
+
stake_usd: centsToUsd(Number(row.stake_cents)),
|
|
71
|
+
status: row.status,
|
|
72
|
+
slash_reason: row.slash_reason ? String(row.slash_reason) : null,
|
|
73
|
+
lock_entry_id: row.lock_entry_id ? String(row.lock_entry_id) : null,
|
|
74
|
+
resolution_entry_id: row.resolution_entry_id ? String(row.resolution_entry_id) : null,
|
|
75
|
+
created_at: String(row.created_at),
|
|
76
|
+
resolved_at: row.resolved_at ? String(row.resolved_at) : null,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function hydratePayout(row) {
|
|
80
|
+
return {
|
|
81
|
+
id: String(row.id),
|
|
82
|
+
bounty_id: String(row.bounty_id),
|
|
83
|
+
journal_entry_id: String(row.journal_entry_id),
|
|
84
|
+
recipient_account_id: String(row.recipient_account_id),
|
|
85
|
+
recipient_operator_id: row.recipient_operator_id ? String(row.recipient_operator_id) : null,
|
|
86
|
+
payout_role: row.payout_role,
|
|
87
|
+
source_artifact_id: row.source_artifact_id ? String(row.source_artifact_id) : null,
|
|
88
|
+
lineage_depth: Number(row.lineage_depth ?? 0),
|
|
89
|
+
share_bps: Number(row.share_bps ?? 0),
|
|
90
|
+
amount_cents: Number(row.amount_cents),
|
|
91
|
+
amount_usd: centsToUsd(Number(row.amount_cents)),
|
|
92
|
+
created_at: String(row.created_at),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Policy check (Doc 02 §5): Autonomous USD bounties are strictly restricted to deterministic verifiers.
|
|
97
|
+
* Non-deterministic gates (`peer_review`, `owner_signoff`, or `deterministic: false`) are rejected.
|
|
98
|
+
*/
|
|
99
|
+
export function assertDeterministicVerifierConfig(verifierCfg, workspaceId) {
|
|
100
|
+
const vType = String(verifierCfg?.type ?? '');
|
|
101
|
+
if (vType === 'peer_review' || vType === 'owner_signoff') {
|
|
102
|
+
throw new SwarmError('UNAUTHORIZED', `NON_DETERMINISTIC_VERIFIER: Automated USD bounties cannot be attached to workspace '${workspaceId}' with verifier type '${vType}'. Only deterministic verifiers (oci_container or deterministic webhook) are eligible.`, false, { workspace_id: workspaceId, verifier_type: vType });
|
|
103
|
+
}
|
|
104
|
+
if (verifierCfg?.deterministic === false) {
|
|
105
|
+
throw new SwarmError('UNAUTHORIZED', `NON_DETERMINISTIC_VERIFIER: Workspace '${workspaceId}' verifier_config explicitly marks deterministic=false.`, false, { workspace_id: workspaceId, verifier_type: vType });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function syncNodeBountyConfig(db, bounty, ts) {
|
|
109
|
+
const summary = {
|
|
110
|
+
bounty_id: bounty.id,
|
|
111
|
+
currency: 'USD',
|
|
112
|
+
reward_cents: bounty.reward_cents,
|
|
113
|
+
reward_usd: bounty.reward_usd,
|
|
114
|
+
anti_slop_stake_cents: bounty.anti_slop_stake_cents,
|
|
115
|
+
anti_slop_stake_usd: bounty.anti_slop_stake_usd,
|
|
116
|
+
platform_fee_bps: bounty.platform_fee_bps,
|
|
117
|
+
royalty_pool_bps: bounty.royalty_pool_bps,
|
|
118
|
+
status: bounty.status,
|
|
119
|
+
sponsor_operator_id: bounty.sponsor_operator_id,
|
|
120
|
+
winning_operator_id: bounty.winning_operator_id,
|
|
121
|
+
winning_artifact_id: bounty.winning_artifact_id,
|
|
122
|
+
settled_at: bounty.settled_at,
|
|
123
|
+
};
|
|
124
|
+
db.prepare('UPDATE nodes SET bounty_config = ?, updated_at = ? WHERE id = ?').run(JSON.stringify(summary), ts, bounty.node_id);
|
|
125
|
+
}
|
|
126
|
+
/** Retrieves a USD bounty by ID. */
|
|
127
|
+
export function getBountyById(db, bountyId) {
|
|
128
|
+
const row = db.prepare('SELECT * FROM usd_bounties WHERE id = ?').get(bountyId);
|
|
129
|
+
return row ? hydrateBounty(row) : null;
|
|
130
|
+
}
|
|
131
|
+
/** Retrieves the currently active (`status = 'funded'`) USD bounty on a node, if any. */
|
|
132
|
+
export function getActiveBountyForNode(db, nodeId) {
|
|
133
|
+
const row = db
|
|
134
|
+
.prepare(`SELECT * FROM usd_bounties WHERE node_id = ? AND status = 'funded' ORDER BY created_at DESC LIMIT 1`)
|
|
135
|
+
.get(nodeId);
|
|
136
|
+
return row ? hydrateBounty(row) : null;
|
|
137
|
+
}
|
|
138
|
+
/** Lists payouts recorded for a settled bounty. */
|
|
139
|
+
export function listBountyPayouts(db, bountyId) {
|
|
140
|
+
const rows = db
|
|
141
|
+
.prepare('SELECT * FROM bounty_payouts WHERE bounty_id = ? ORDER BY payout_role ASC, amount_cents DESC, id ASC')
|
|
142
|
+
.all(bountyId);
|
|
143
|
+
return rows.map(hydratePayout);
|
|
144
|
+
}
|
|
145
|
+
/** Lists anti-slop stakes associated with a bounty. */
|
|
146
|
+
export function listBountyStakes(db, bountyId) {
|
|
147
|
+
const rows = db
|
|
148
|
+
.prepare('SELECT * FROM bounty_stakes WHERE bounty_id = ? ORDER BY created_at DESC')
|
|
149
|
+
.all(bountyId);
|
|
150
|
+
return rows.map(hydrateStake);
|
|
151
|
+
}
|
|
152
|
+
/** Lists bounties for the public Bounty Board (enforcing privacy airlock for non-member callers). */
|
|
153
|
+
export function listBounties(db, opts = {}) {
|
|
154
|
+
const where = [];
|
|
155
|
+
const params = [];
|
|
156
|
+
if (opts.workspaceId) {
|
|
157
|
+
where.push('(b.workspace_id = ? OR w.slug = ?)');
|
|
158
|
+
params.push(opts.workspaceId, opts.workspaceId);
|
|
159
|
+
}
|
|
160
|
+
if (opts.status) {
|
|
161
|
+
where.push('b.status = ?');
|
|
162
|
+
params.push(opts.status);
|
|
163
|
+
}
|
|
164
|
+
if (!opts.includeAllForAdmin) {
|
|
165
|
+
if (opts.viewerAgentId) {
|
|
166
|
+
where.push(`(w.visibility = 'public' OR EXISTS (
|
|
167
|
+
SELECT 1 FROM workspace_members m WHERE m.workspace_id = w.id AND m.agent_id = ?
|
|
168
|
+
))`);
|
|
169
|
+
params.push(opts.viewerAgentId);
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
where.push(`w.visibility = 'public'`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const limit = Math.max(1, Math.min(200, opts.limit ?? 50));
|
|
176
|
+
const whereSql = where.length ? `WHERE ${where.join(' AND ')}` : '';
|
|
177
|
+
const rows = db
|
|
178
|
+
.prepare(`
|
|
179
|
+
SELECT b.*, w.slug AS workspace_slug, w.title AS workspace_title, w.domain_pack_ref,
|
|
180
|
+
n.title AS node_title, n.type AS node_type
|
|
181
|
+
FROM usd_bounties b
|
|
182
|
+
JOIN workspaces w ON w.id = b.workspace_id
|
|
183
|
+
JOIN nodes n ON n.id = b.node_id
|
|
184
|
+
${whereSql}
|
|
185
|
+
ORDER BY CASE b.status WHEN 'funded' THEN 0 WHEN 'disputed' THEN 1 ELSE 2 END,
|
|
186
|
+
b.reward_cents DESC, b.created_at DESC
|
|
187
|
+
LIMIT ?
|
|
188
|
+
`)
|
|
189
|
+
.all(...params, limit);
|
|
190
|
+
return rows.map((r) => ({
|
|
191
|
+
...hydrateBounty(r),
|
|
192
|
+
workspace_slug: String(r.workspace_slug),
|
|
193
|
+
workspace_title: String(r.workspace_title),
|
|
194
|
+
node_title: String(r.node_title),
|
|
195
|
+
node_type: String(r.node_type),
|
|
196
|
+
domain_pack_ref: r.domain_pack_ref ? String(r.domain_pack_ref) : null,
|
|
197
|
+
}));
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Funds and escrows a new USD bounty on an open/claimed DAG node.
|
|
201
|
+
* Enforces:
|
|
202
|
+
* - Deterministic verifier policy on the workspace
|
|
203
|
+
* - Platform take rate in [10%, 15%] and royalty pool in [10%, 20%]
|
|
204
|
+
* - `per_task_spend_cap` when funded by a scoped agent
|
|
205
|
+
* - Atomic USD escrow lock (`usd_op:<sponsor>` -> `usd_escrow:<bountyId>`)
|
|
206
|
+
*/
|
|
207
|
+
export function createAndFundBounty(db, params) {
|
|
208
|
+
if (!Number.isInteger(params.rewardCents) || params.rewardCents <= 0) {
|
|
209
|
+
throw new SwarmError('INVALID_INPUT', 'rewardCents must be a positive integer (USD cents)');
|
|
210
|
+
}
|
|
211
|
+
const platformFeeBps = params.platformFeeBps ?? DEFAULT_PLATFORM_FEE_BPS;
|
|
212
|
+
if (!Number.isInteger(platformFeeBps) || platformFeeBps < MIN_PLATFORM_FEE_BPS || platformFeeBps > MAX_PLATFORM_FEE_BPS) {
|
|
213
|
+
throw new SwarmError('INVALID_INPUT', `platformFeeBps must be between ${MIN_PLATFORM_FEE_BPS} (10%) and ${MAX_PLATFORM_FEE_BPS} (15%)`);
|
|
214
|
+
}
|
|
215
|
+
const royaltyPoolBps = params.royaltyPoolBps ?? DEFAULT_ROYALTY_POOL_BPS;
|
|
216
|
+
if (!Number.isInteger(royaltyPoolBps) || royaltyPoolBps < MIN_ROYALTY_POOL_BPS || royaltyPoolBps > MAX_ROYALTY_POOL_BPS) {
|
|
217
|
+
throw new SwarmError('INVALID_INPUT', `royaltyPoolBps must be between ${MIN_ROYALTY_POOL_BPS} (10%) and ${MAX_ROYALTY_POOL_BPS} (20%)`);
|
|
218
|
+
}
|
|
219
|
+
const recursiveDecayBps = params.recursiveDecayBps ?? DEFAULT_RECURSIVE_DECAY_BPS;
|
|
220
|
+
if (!Number.isInteger(recursiveDecayBps) || recursiveDecayBps < 0 || recursiveDecayBps > 10_000) {
|
|
221
|
+
throw new SwarmError('INVALID_INPUT', 'recursiveDecayBps must be between 0 and 10000');
|
|
222
|
+
}
|
|
223
|
+
const antiSlopStakeCents = params.antiSlopStakeCents !== undefined
|
|
224
|
+
? params.antiSlopStakeCents
|
|
225
|
+
: Math.min(Math.max(100, Math.round(params.rewardCents * 0.02)), 5000);
|
|
226
|
+
if (!Number.isInteger(antiSlopStakeCents) || antiSlopStakeCents < 0) {
|
|
227
|
+
throw new SwarmError('INVALID_INPUT', 'antiSlopStakeCents must be a non-negative integer');
|
|
228
|
+
}
|
|
229
|
+
const slashRecipient = params.slashRecipient ?? 'slash_pool';
|
|
230
|
+
const ts = params.now ?? nowIso();
|
|
231
|
+
const tx = db.transaction(() => {
|
|
232
|
+
const node = db.prepare('SELECT * FROM nodes WHERE id = ?').get(params.nodeId);
|
|
233
|
+
if (!node) {
|
|
234
|
+
throw new SwarmError('NOT_FOUND', `Node '${params.nodeId}' not found`);
|
|
235
|
+
}
|
|
236
|
+
if (node.status === 'verified' || node.status === 'dead_end') {
|
|
237
|
+
throw new SwarmError('INVALID_INPUT', `Cannot attach bounty to node '${node.id}' with status '${node.status}'`);
|
|
238
|
+
}
|
|
239
|
+
const ws = db.prepare('SELECT * FROM workspaces WHERE id = ?').get(node.workspace_id);
|
|
240
|
+
if (!ws) {
|
|
241
|
+
throw new SwarmError('NOT_FOUND', `Workspace '${node.workspace_id}' not found`);
|
|
242
|
+
}
|
|
243
|
+
const verifierCfg = JSON.parse(ws.verifier_config || '{}');
|
|
244
|
+
assertDeterministicVerifierConfig(verifierCfg, ws.id);
|
|
245
|
+
const existingFunded = getActiveBountyForNode(db, node.id);
|
|
246
|
+
if (existingFunded) {
|
|
247
|
+
throw new SwarmError('LEASE_CONFLICT', `Node '${node.id}' already has an active funded bounty (${existingFunded.id})`);
|
|
248
|
+
}
|
|
249
|
+
// If funded by a scoped agent, verify operator binding and enforce per_task_spend_cap
|
|
250
|
+
if (params.fundedByAgentId) {
|
|
251
|
+
const ag = db
|
|
252
|
+
.prepare('SELECT id, operator_id FROM agent_identities WHERE id = ?')
|
|
253
|
+
.get(params.fundedByAgentId);
|
|
254
|
+
if (!ag || ag.operator_id !== params.sponsorOperatorId) {
|
|
255
|
+
throw new SwarmError('UNAUTHORIZED', 'Funding agent does not belong to sponsor operator');
|
|
256
|
+
}
|
|
257
|
+
assertAndRecordAgentTaskSpend(db, {
|
|
258
|
+
agentId: params.fundedByAgentId,
|
|
259
|
+
taskKey: `node:${node.id}`,
|
|
260
|
+
amountCents: params.rewardCents,
|
|
261
|
+
now: ts,
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
const bountyId = newId('bty');
|
|
265
|
+
const escrowAccountId = usdBountyEscrowAccountId(bountyId);
|
|
266
|
+
const lockEntry = postUsdJournalEntry(db, {
|
|
267
|
+
entryType: 'bounty_escrow_lock',
|
|
268
|
+
currency: 'USD',
|
|
269
|
+
workspaceId: ws.id,
|
|
270
|
+
bountyId,
|
|
271
|
+
referenceType: 'bounty_create',
|
|
272
|
+
referenceId: node.id,
|
|
273
|
+
memo: `Escrow USD bounty ${bountyId} ($${centsToUsd(params.rewardCents).toFixed(2)}) on ${node.id}`,
|
|
274
|
+
metadata: {
|
|
275
|
+
node_id: node.id,
|
|
276
|
+
sponsor_operator_id: params.sponsorOperatorId,
|
|
277
|
+
platform_fee_bps: platformFeeBps,
|
|
278
|
+
royalty_pool_bps: royaltyPoolBps,
|
|
279
|
+
anti_slop_stake_cents: antiSlopStakeCents,
|
|
280
|
+
},
|
|
281
|
+
idempotencyKey: params.idempotencyKey ?? `bounty_lock:${bountyId}`,
|
|
282
|
+
now: ts,
|
|
283
|
+
legs: [
|
|
284
|
+
{ accountId: usdOperatorAccountId(params.sponsorOperatorId), deltaCents: -params.rewardCents },
|
|
285
|
+
{ accountId: escrowAccountId, deltaCents: params.rewardCents },
|
|
286
|
+
],
|
|
287
|
+
});
|
|
288
|
+
db.prepare(`
|
|
289
|
+
INSERT INTO usd_bounties (
|
|
290
|
+
id, workspace_id, node_id, sponsor_operator_id, funded_by_agent_id,
|
|
291
|
+
currency, reward_cents, platform_fee_bps, royalty_pool_bps, recursive_decay_bps,
|
|
292
|
+
anti_slop_stake_cents, slash_recipient, escrow_account_id, status,
|
|
293
|
+
lock_entry_id, expires_at, created_at, updated_at
|
|
294
|
+
) VALUES (?, ?, ?, ?, ?, 'USD', ?, ?, ?, ?, ?, ?, ?, 'funded', ?, ?, ?, ?)
|
|
295
|
+
`).run(bountyId, ws.id, node.id, params.sponsorOperatorId, params.fundedByAgentId ?? null, params.rewardCents, platformFeeBps, royaltyPoolBps, recursiveDecayBps, antiSlopStakeCents, slashRecipient, escrowAccountId, lockEntry.id, params.expiresAt ?? null, ts, ts);
|
|
296
|
+
const bounty = getBountyById(db, bountyId);
|
|
297
|
+
syncNodeBountyConfig(db, bounty, ts);
|
|
298
|
+
return { bounty, lock_entry: lockEntry };
|
|
299
|
+
});
|
|
300
|
+
return tx.immediate();
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Cancels an unsettled USD bounty and refunds the full escrow back to the sponsor.
|
|
304
|
+
* Refuses cancellation while a verification run is actively verifying or already settled.
|
|
305
|
+
*/
|
|
306
|
+
export function cancelBounty(db, params) {
|
|
307
|
+
const ts = params.now ?? nowIso();
|
|
308
|
+
const tx = db.transaction(() => {
|
|
309
|
+
const bounty = getBountyById(db, params.bountyId);
|
|
310
|
+
if (!bounty) {
|
|
311
|
+
throw new SwarmError('NOT_FOUND', `Bounty '${params.bountyId}' not found`);
|
|
312
|
+
}
|
|
313
|
+
if (!params.isAdmin && bounty.sponsor_operator_id !== params.actorOperatorId) {
|
|
314
|
+
throw new SwarmError('UNAUTHORIZED', 'Only the bounty sponsor or platform admin may cancel a bounty');
|
|
315
|
+
}
|
|
316
|
+
if (bounty.status !== 'funded' && bounty.status !== 'disputed') {
|
|
317
|
+
throw new SwarmError('INVALID_INPUT', `Bounty '${bounty.id}' cannot be canceled from status '${bounty.status}'`);
|
|
318
|
+
}
|
|
319
|
+
const node = db.prepare('SELECT status FROM nodes WHERE id = ?').get(bounty.node_id);
|
|
320
|
+
if (node?.status === 'verifying') {
|
|
321
|
+
throw new SwarmError('LEASE_CONFLICT', 'Cannot cancel bounty while a submission is actively verifying');
|
|
322
|
+
}
|
|
323
|
+
const refundEntry = postUsdJournalEntry(db, {
|
|
324
|
+
entryType: 'bounty_escrow_refund',
|
|
325
|
+
currency: 'USD',
|
|
326
|
+
workspaceId: bounty.workspace_id,
|
|
327
|
+
bountyId: bounty.id,
|
|
328
|
+
referenceType: 'bounty_cancel',
|
|
329
|
+
referenceId: bounty.id,
|
|
330
|
+
memo: `Refund canceled bounty ${bounty.id} to ${bounty.sponsor_operator_id}`,
|
|
331
|
+
idempotencyKey: `bounty_cancel:${bounty.id}`,
|
|
332
|
+
now: ts,
|
|
333
|
+
legs: [
|
|
334
|
+
{ accountId: bounty.escrow_account_id, deltaCents: -bounty.reward_cents },
|
|
335
|
+
{ accountId: usdOperatorAccountId(bounty.sponsor_operator_id), deltaCents: bounty.reward_cents },
|
|
336
|
+
],
|
|
337
|
+
});
|
|
338
|
+
if (bounty.funded_by_agent_id) {
|
|
339
|
+
releaseAgentTaskSpend(db, {
|
|
340
|
+
agentId: bounty.funded_by_agent_id,
|
|
341
|
+
taskKey: `node:${bounty.node_id}`,
|
|
342
|
+
amountCents: bounty.reward_cents,
|
|
343
|
+
now: ts,
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
db.prepare(`UPDATE usd_bounties SET status = 'canceled', updated_at = ? WHERE id = ?`).run(ts, bounty.id);
|
|
347
|
+
const updated = getBountyById(db, bounty.id);
|
|
348
|
+
syncNodeBountyConfig(db, updated, ts);
|
|
349
|
+
return { bounty: updated, refund_entry: refundEntry };
|
|
350
|
+
});
|
|
351
|
+
return tx.immediate();
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Locks a submitter's anti-slop USD stake before verification begins.
|
|
355
|
+
* Strictly enforces the submitting agent's `per_task_spend_cap`.
|
|
356
|
+
*/
|
|
357
|
+
export function lockAntiSlopStake(db, params) {
|
|
358
|
+
if (!Number.isInteger(params.stakeCents) || params.stakeCents <= 0) {
|
|
359
|
+
throw new SwarmError('INVALID_INPUT', 'stakeCents must be a positive integer');
|
|
360
|
+
}
|
|
361
|
+
const ts = params.now ?? nowIso();
|
|
362
|
+
const tx = db.transaction(() => {
|
|
363
|
+
const bounty = getBountyById(db, params.bountyId);
|
|
364
|
+
if (!bounty || bounty.status !== 'funded') {
|
|
365
|
+
throw new SwarmError('INVALID_INPUT', `Active funded bounty '${params.bountyId}' not found`);
|
|
366
|
+
}
|
|
367
|
+
// Enforce per-task spend cap on submitting agent
|
|
368
|
+
assertAndRecordAgentTaskSpend(db, {
|
|
369
|
+
agentId: params.agentId,
|
|
370
|
+
taskKey: `bounty:${bounty.id}`,
|
|
371
|
+
amountCents: params.stakeCents,
|
|
372
|
+
now: ts,
|
|
373
|
+
});
|
|
374
|
+
const stakeId = newId('stk');
|
|
375
|
+
const stakeAccountId = usdStakeEscrowAccountId(stakeId);
|
|
376
|
+
const lockEntry = postUsdJournalEntry(db, {
|
|
377
|
+
entryType: 'stake_lock',
|
|
378
|
+
currency: 'USD',
|
|
379
|
+
workspaceId: bounty.workspace_id,
|
|
380
|
+
bountyId: bounty.id,
|
|
381
|
+
referenceType: 'anti_slop_stake',
|
|
382
|
+
referenceId: params.runId ?? stakeId,
|
|
383
|
+
memo: `Lock anti-slop stake ($${centsToUsd(params.stakeCents).toFixed(2)}) for ${params.agentId} on ${params.nodeId}`,
|
|
384
|
+
idempotencyKey: `stake_lock:${stakeId}`,
|
|
385
|
+
now: ts,
|
|
386
|
+
legs: [
|
|
387
|
+
{ accountId: usdOperatorAccountId(params.operatorId), deltaCents: -params.stakeCents },
|
|
388
|
+
{ accountId: stakeAccountId, deltaCents: params.stakeCents },
|
|
389
|
+
],
|
|
390
|
+
});
|
|
391
|
+
db.prepare(`
|
|
392
|
+
INSERT INTO bounty_stakes (
|
|
393
|
+
id, bounty_id, run_id, node_id, agent_id, operator_id,
|
|
394
|
+
stake_account_id, stake_cents, status, lock_entry_id, created_at
|
|
395
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'locked', ?, ?)
|
|
396
|
+
`).run(stakeId, bounty.id, params.runId ?? null, params.nodeId, params.agentId, params.operatorId, stakeAccountId, params.stakeCents, lockEntry.id, ts);
|
|
397
|
+
const row = db.prepare('SELECT * FROM bounty_stakes WHERE id = ?').get(stakeId);
|
|
398
|
+
return { stake: hydrateStake(row), lock_entry: lockEntry };
|
|
399
|
+
});
|
|
400
|
+
return tx.immediate();
|
|
401
|
+
}
|
|
402
|
+
/** Binds a newly created `verification_runs.id` to a pre-locked anti-slop stake. */
|
|
403
|
+
export function attachRunToAntiSlopStake(db, stakeId, runId) {
|
|
404
|
+
db.prepare('UPDATE bounty_stakes SET run_id = ? WHERE id = ? AND run_id IS NULL').run(runId, stakeId);
|
|
405
|
+
}
|
|
406
|
+
/** Finds a stake locked for a given verification run ID. */
|
|
407
|
+
export function getStakeForRun(db, runId) {
|
|
408
|
+
const row = db.prepare('SELECT * FROM bounty_stakes WHERE run_id = ?').get(runId);
|
|
409
|
+
return row ? hydrateStake(row) : null;
|
|
410
|
+
}
|
|
411
|
+
/** Refunds a locked anti-slop stake back to the submitter (e.g., on pass, STALE_BASE, or transient infra error). */
|
|
412
|
+
export function refundAntiSlopStake(db, params) {
|
|
413
|
+
const ts = params.now ?? nowIso();
|
|
414
|
+
const tx = db.transaction(() => {
|
|
415
|
+
const raw = db.prepare('SELECT * FROM bounty_stakes WHERE id = ?').get(params.stakeId);
|
|
416
|
+
if (!raw)
|
|
417
|
+
throw new SwarmError('NOT_FOUND', `Stake '${params.stakeId}' not found`);
|
|
418
|
+
const stake = hydrateStake(raw);
|
|
419
|
+
if (stake.status !== 'locked') {
|
|
420
|
+
return { stake, entry: null };
|
|
421
|
+
}
|
|
422
|
+
const bounty = getBountyById(db, stake.bounty_id);
|
|
423
|
+
const entry = postUsdJournalEntry(db, {
|
|
424
|
+
entryType: 'stake_refund',
|
|
425
|
+
currency: 'USD',
|
|
426
|
+
workspaceId: bounty.workspace_id,
|
|
427
|
+
bountyId: bounty.id,
|
|
428
|
+
referenceType: 'anti_slop_stake_refund',
|
|
429
|
+
referenceId: stake.run_id ?? stake.id,
|
|
430
|
+
memo: `Refund anti-slop stake ${stake.id} (${params.reason ?? 'verified'})`,
|
|
431
|
+
idempotencyKey: `stake_refund:${stake.id}`,
|
|
432
|
+
now: ts,
|
|
433
|
+
legs: [
|
|
434
|
+
{ accountId: stake.stake_account_id, deltaCents: -stake.stake_cents },
|
|
435
|
+
{ accountId: usdOperatorAccountId(stake.operator_id), deltaCents: stake.stake_cents },
|
|
436
|
+
],
|
|
437
|
+
});
|
|
438
|
+
releaseAgentTaskSpend(db, {
|
|
439
|
+
agentId: stake.agent_id,
|
|
440
|
+
taskKey: `bounty:${bounty.id}`,
|
|
441
|
+
amountCents: stake.stake_cents,
|
|
442
|
+
now: ts,
|
|
443
|
+
});
|
|
444
|
+
db.prepare(`
|
|
445
|
+
UPDATE bounty_stakes
|
|
446
|
+
SET status = 'refunded', slash_reason = ?, resolution_entry_id = ?, resolved_at = ?
|
|
447
|
+
WHERE id = ?
|
|
448
|
+
`).run(params.reason ?? null, entry.id, ts, stake.id);
|
|
449
|
+
return {
|
|
450
|
+
stake: hydrateStake(db.prepare('SELECT * FROM bounty_stakes WHERE id = ?').get(stake.id)),
|
|
451
|
+
entry,
|
|
452
|
+
};
|
|
453
|
+
});
|
|
454
|
+
return tx.immediate();
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Slashes a locked anti-slop stake on deterministic verification failure or reward-hacking bypass
|
|
458
|
+
* (e.g., Stage 0 AST tripwire `sorry`/`axiom`/`native_decide`, failing proof, tampered spec).
|
|
459
|
+
*/
|
|
460
|
+
export function slashAntiSlopStake(db, params) {
|
|
461
|
+
const ts = params.now ?? nowIso();
|
|
462
|
+
const tx = db.transaction(() => {
|
|
463
|
+
const raw = db.prepare('SELECT * FROM bounty_stakes WHERE id = ?').get(params.stakeId);
|
|
464
|
+
if (!raw)
|
|
465
|
+
throw new SwarmError('NOT_FOUND', `Stake '${params.stakeId}' not found`);
|
|
466
|
+
const stake = hydrateStake(raw);
|
|
467
|
+
if (stake.status !== 'locked') {
|
|
468
|
+
return { stake, entry: null };
|
|
469
|
+
}
|
|
470
|
+
const bounty = getBountyById(db, stake.bounty_id);
|
|
471
|
+
const recipientAccountId = bounty.slash_recipient === 'sponsor'
|
|
472
|
+
? usdOperatorAccountId(bounty.sponsor_operator_id)
|
|
473
|
+
: USD_SYSTEM_SLASH_POOL_ACCOUNT;
|
|
474
|
+
const entry = postUsdJournalEntry(db, {
|
|
475
|
+
entryType: 'stake_slash',
|
|
476
|
+
currency: 'USD',
|
|
477
|
+
workspaceId: bounty.workspace_id,
|
|
478
|
+
bountyId: bounty.id,
|
|
479
|
+
referenceType: 'anti_slop_stake_slash',
|
|
480
|
+
referenceId: stake.run_id ?? stake.id,
|
|
481
|
+
memo: `Slash anti-slop stake ${stake.id} (${params.reason.slice(0, 200)})`,
|
|
482
|
+
metadata: {
|
|
483
|
+
slashed_operator_id: stake.operator_id,
|
|
484
|
+
slashed_agent_id: stake.agent_id,
|
|
485
|
+
slash_reason: params.reason,
|
|
486
|
+
recipient_account_id: recipientAccountId,
|
|
487
|
+
},
|
|
488
|
+
idempotencyKey: `stake_slash:${stake.id}`,
|
|
489
|
+
now: ts,
|
|
490
|
+
legs: [
|
|
491
|
+
{ accountId: stake.stake_account_id, deltaCents: -stake.stake_cents },
|
|
492
|
+
{ accountId: recipientAccountId, deltaCents: stake.stake_cents },
|
|
493
|
+
],
|
|
494
|
+
});
|
|
495
|
+
db.prepare(`
|
|
496
|
+
UPDATE bounty_stakes
|
|
497
|
+
SET status = 'slashed', slash_reason = ?, resolution_entry_id = ?, resolved_at = ?
|
|
498
|
+
WHERE id = ?
|
|
499
|
+
`).run(params.reason.slice(0, 500), entry.id, ts, stake.id);
|
|
500
|
+
return {
|
|
501
|
+
stake: hydrateStake(db.prepare('SELECT * FROM bounty_stakes WHERE id = ?').get(stake.id)),
|
|
502
|
+
entry,
|
|
503
|
+
};
|
|
504
|
+
});
|
|
505
|
+
return tx.immediate();
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Computes exact recursive `derived_from` dependency royalty splits across the verified
|
|
509
|
+
* upstream `artifact_lineage` DAG using:
|
|
510
|
+
* - Cycle-safe recursive traversal up to `maxDepth` (default 10)
|
|
511
|
+
* - Configurable `recursiveDecayBps` (default 5000 = 50% retained by node author, 50% passed upstream)
|
|
512
|
+
* - Leaf foundational artifacts retain 100% of their allocated weight
|
|
513
|
+
* - Exact integer cent allocation via Hamilton / Largest-Remainder apportionment (0-cent drift)
|
|
514
|
+
*/
|
|
515
|
+
export function computeRecursiveRoyaltySplits(db, params) {
|
|
516
|
+
if (params.royaltyPoolCents <= 0)
|
|
517
|
+
return [];
|
|
518
|
+
const decayFraction = Math.max(0, Math.min(1, (params.recursiveDecayBps ?? DEFAULT_RECURSIVE_DECAY_BPS) / 10_000));
|
|
519
|
+
const maxDepth = Math.max(1, params.maxDepth ?? MAX_ROYALTY_LINEAGE_DEPTH);
|
|
520
|
+
const artStmt = db.prepare(`
|
|
521
|
+
SELECT a.id, a.artifact_type, a.author_agent_id, ag.operator_id
|
|
522
|
+
FROM artifacts a
|
|
523
|
+
JOIN agent_identities ag ON ag.id = a.author_agent_id
|
|
524
|
+
WHERE a.id = ?
|
|
525
|
+
`);
|
|
526
|
+
const parentsStmt = db.prepare(`
|
|
527
|
+
SELECT l.parent_artifact_id
|
|
528
|
+
FROM artifact_lineage l
|
|
529
|
+
JOIN artifacts p ON p.id = l.parent_artifact_id
|
|
530
|
+
WHERE l.artifact_id = ? AND p.artifact_type <> 'dead_end'
|
|
531
|
+
ORDER BY l.parent_artifact_id ASC
|
|
532
|
+
`);
|
|
533
|
+
const artCache = new Map();
|
|
534
|
+
const parentsCache = new Map();
|
|
535
|
+
const loadArt = (id) => {
|
|
536
|
+
if (!artCache.has(id)) {
|
|
537
|
+
const r = artStmt.get(id);
|
|
538
|
+
artCache.set(id, r && r.artifact_type !== 'dead_end'
|
|
539
|
+
? { id: String(r.id), author_agent_id: String(r.author_agent_id), operator_id: String(r.operator_id) }
|
|
540
|
+
: null);
|
|
541
|
+
}
|
|
542
|
+
return artCache.get(id);
|
|
543
|
+
};
|
|
544
|
+
const loadParents = (id) => {
|
|
545
|
+
if (!parentsCache.has(id)) {
|
|
546
|
+
const rows = parentsStmt.all(id);
|
|
547
|
+
parentsCache.set(id, rows.map((r) => r.parent_artifact_id));
|
|
548
|
+
}
|
|
549
|
+
return parentsCache.get(id);
|
|
550
|
+
};
|
|
551
|
+
const weights = new Map();
|
|
552
|
+
const distribute = (artifactId, weight, depth, pathSet) => {
|
|
553
|
+
if (weight <= 0)
|
|
554
|
+
return;
|
|
555
|
+
const rawParents = loadParents(artifactId).filter((pid) => !pathSet.has(pid) && loadArt(pid) !== null);
|
|
556
|
+
if (depth === 0) {
|
|
557
|
+
if (rawParents.length === 0)
|
|
558
|
+
return;
|
|
559
|
+
const perParent = weight / rawParents.length;
|
|
560
|
+
for (const pid of rawParents) {
|
|
561
|
+
const nextPath = new Set(pathSet);
|
|
562
|
+
nextPath.add(pid);
|
|
563
|
+
distribute(pid, perParent, 1, nextPath);
|
|
564
|
+
}
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
const meta = loadArt(artifactId);
|
|
568
|
+
if (!meta)
|
|
569
|
+
return;
|
|
570
|
+
const passUp = rawParents.length > 0 && depth < maxDepth ? weight * decayFraction : 0;
|
|
571
|
+
const retain = weight - passUp;
|
|
572
|
+
if (retain > 0) {
|
|
573
|
+
const cur = weights.get(artifactId);
|
|
574
|
+
if (cur) {
|
|
575
|
+
cur.weight += retain;
|
|
576
|
+
cur.minDepth = Math.min(cur.minDepth, depth);
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
weights.set(artifactId, {
|
|
580
|
+
weight: retain,
|
|
581
|
+
minDepth: depth,
|
|
582
|
+
authorAgentId: meta.author_agent_id,
|
|
583
|
+
operatorId: meta.operator_id,
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
if (passUp > 0 && rawParents.length > 0) {
|
|
588
|
+
const perParent = passUp / rawParents.length;
|
|
589
|
+
for (const pid of rawParents) {
|
|
590
|
+
const nextPath = new Set(pathSet);
|
|
591
|
+
nextPath.add(pid);
|
|
592
|
+
distribute(pid, perParent, depth + 1, nextPath);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
distribute(params.winningArtifactId, 1.0, 0, new Set([params.winningArtifactId]));
|
|
597
|
+
if (weights.size === 0)
|
|
598
|
+
return [];
|
|
599
|
+
// Normalize weights to 1.0 (protects against floating-point epsilon)
|
|
600
|
+
let totalWeight = 0;
|
|
601
|
+
for (const v of weights.values())
|
|
602
|
+
totalWeight += v.weight;
|
|
603
|
+
if (totalWeight <= 0)
|
|
604
|
+
return [];
|
|
605
|
+
// Hamilton / Largest-Remainder Method for exact integer cent allocation
|
|
606
|
+
const rawAllocations = Array.from(weights.entries()).map(([artifactId, info]) => {
|
|
607
|
+
const norm = info.weight / totalWeight;
|
|
608
|
+
const exactCents = norm * params.royaltyPoolCents;
|
|
609
|
+
const floorCents = Math.floor(exactCents);
|
|
610
|
+
return {
|
|
611
|
+
artifactId,
|
|
612
|
+
info,
|
|
613
|
+
norm,
|
|
614
|
+
floorCents,
|
|
615
|
+
remainder: exactCents - floorCents,
|
|
616
|
+
};
|
|
617
|
+
});
|
|
618
|
+
let allocated = rawAllocations.reduce((s, x) => s + x.floorCents, 0);
|
|
619
|
+
let leftover = params.royaltyPoolCents - allocated;
|
|
620
|
+
// Deterministic tie-break: largest remainder first, then shallower depth, then artifact_id ASC
|
|
621
|
+
const byRemainder = [...rawAllocations].sort((a, b) => {
|
|
622
|
+
if (Math.abs(b.remainder - a.remainder) > 1e-12)
|
|
623
|
+
return b.remainder - a.remainder;
|
|
624
|
+
if (a.info.minDepth !== b.info.minDepth)
|
|
625
|
+
return a.info.minDepth - b.info.minDepth;
|
|
626
|
+
return a.artifactId.localeCompare(b.artifactId);
|
|
627
|
+
});
|
|
628
|
+
for (let i = 0; i < leftover && i < byRemainder.length; i++) {
|
|
629
|
+
byRemainder[i].floorCents += 1;
|
|
630
|
+
allocated += 1;
|
|
631
|
+
}
|
|
632
|
+
return rawAllocations
|
|
633
|
+
.filter((x) => x.floorCents > 0)
|
|
634
|
+
.sort((a, b) => b.floorCents - a.floorCents || a.artifactId.localeCompare(b.artifactId))
|
|
635
|
+
.map((x) => ({
|
|
636
|
+
artifact_id: x.artifactId,
|
|
637
|
+
operator_id: x.info.operatorId,
|
|
638
|
+
author_agent_id: x.info.authorAgentId,
|
|
639
|
+
lineage_depth: x.info.minDepth,
|
|
640
|
+
weight: Number(x.norm.toFixed(6)),
|
|
641
|
+
share_bps: Math.round(x.norm * 10_000),
|
|
642
|
+
amount_cents: x.floorCents,
|
|
643
|
+
amount_usd: centsToUsd(x.floorCents),
|
|
644
|
+
}));
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Atomically settles a funded USD bounty upon a deterministic verification pass:
|
|
648
|
+
* 1. Verifies `verifierResult.status === 'pass'` AND `verifierResult.deterministic === true`
|
|
649
|
+
* (if `deterministic === false`, transitions bounty to `'disputed'` and holds escrow!).
|
|
650
|
+
* 2. Refunds the winner's locked anti-slop stake (if any).
|
|
651
|
+
* 3. Computes platform take rate (10–15% of gross reward), recursive `derived_from`
|
|
652
|
+
* royalty pool (10–20% of post-fee distributable when upstream dependencies exist),
|
|
653
|
+
* and winner net payout (`distributable - royalties`).
|
|
654
|
+
* 4. Executes ONE atomic double-entry USD journal entry draining `usd_escrow:<bountyId>`
|
|
655
|
+
* to exact `$0.00` and crediting `usd_sys:platform_revenue`, upstream royalty authors,
|
|
656
|
+
* and the winning operator.
|
|
657
|
+
*/
|
|
658
|
+
export function settleBountyOnVerificationPass(db, params) {
|
|
659
|
+
const bounty = getActiveBountyForNode(db, params.nodeId);
|
|
660
|
+
if (!bounty)
|
|
661
|
+
return null;
|
|
662
|
+
const ts = params.now ?? nowIso();
|
|
663
|
+
// Check workspace & result determinism (Policy: autonomous bounties require deterministic verifier)
|
|
664
|
+
const ws = db.prepare('SELECT verifier_config FROM workspaces WHERE id = ?').get(bounty.workspace_id);
|
|
665
|
+
const verifierCfg = ws ? JSON.parse(ws.verifier_config || '{}') : {};
|
|
666
|
+
const isNonDetType = verifierCfg.type === 'peer_review' || verifierCfg.type === 'owner_signoff';
|
|
667
|
+
if (params.verifierResult.status !== 'pass' || params.verifierResult.deterministic !== true || isNonDetType) {
|
|
668
|
+
db.prepare(`UPDATE usd_bounties SET status = 'disputed', updated_at = ? WHERE id = ?`).run(ts, bounty.id);
|
|
669
|
+
const disputed = getBountyById(db, bounty.id);
|
|
670
|
+
syncNodeBountyConfig(db, disputed, ts);
|
|
671
|
+
return {
|
|
672
|
+
settled: false,
|
|
673
|
+
reason: 'NON_DETERMINISTIC_VERIFIER: Autonomous bounty settlement requires status="pass" and deterministic=true',
|
|
674
|
+
bounty: disputed,
|
|
675
|
+
journal_entry: null,
|
|
676
|
+
payouts: [],
|
|
677
|
+
refunded_stake: null,
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
const tx = db.transaction(() => {
|
|
681
|
+
const fresh = getBountyById(db, bounty.id);
|
|
682
|
+
if (fresh.status === 'settled') {
|
|
683
|
+
return {
|
|
684
|
+
settled: true,
|
|
685
|
+
bounty: fresh,
|
|
686
|
+
journal_entry: null,
|
|
687
|
+
payouts: listBountyPayouts(db, fresh.id),
|
|
688
|
+
refunded_stake: getStakeForRun(db, params.runId),
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
const winAgent = db
|
|
692
|
+
.prepare('SELECT operator_id FROM agent_identities WHERE id = ?')
|
|
693
|
+
.get(params.winningAgentId);
|
|
694
|
+
if (!winAgent) {
|
|
695
|
+
throw new SwarmError('NOT_FOUND', `Winning agent '${params.winningAgentId}' not found`);
|
|
696
|
+
}
|
|
697
|
+
const winnerOperatorId = winAgent.operator_id;
|
|
698
|
+
// 1. Refund winning submitter's locked anti-slop stake (if any)
|
|
699
|
+
let refundedStake = null;
|
|
700
|
+
const runStake = getStakeForRun(db, params.runId);
|
|
701
|
+
if (runStake && runStake.status === 'locked') {
|
|
702
|
+
refundedStake = refundAntiSlopStake(db, {
|
|
703
|
+
stakeId: runStake.id,
|
|
704
|
+
reason: 'verification_pass',
|
|
705
|
+
now: ts,
|
|
706
|
+
}).stake;
|
|
707
|
+
}
|
|
708
|
+
// 2. Compute exact cent splits (Platform fee + Recursive derived_from royalties + Winner net)
|
|
709
|
+
const platformFeeCents = Math.floor((fresh.reward_cents * fresh.platform_fee_bps) / 10_000);
|
|
710
|
+
const distributableCents = fresh.reward_cents - platformFeeCents;
|
|
711
|
+
const candidateRoyaltyPoolCents = Math.floor((distributableCents * fresh.royalty_pool_bps) / 10_000);
|
|
712
|
+
const royaltySplits = computeRecursiveRoyaltySplits(db, {
|
|
713
|
+
winningArtifactId: params.artifactId,
|
|
714
|
+
royaltyPoolCents: candidateRoyaltyPoolCents,
|
|
715
|
+
recursiveDecayBps: fresh.recursive_decay_bps,
|
|
716
|
+
});
|
|
717
|
+
const totalRoyaltiesCents = royaltySplits.reduce((sum, r) => sum + r.amount_cents, 0);
|
|
718
|
+
const winnerNetCents = distributableCents - totalRoyaltiesCents;
|
|
719
|
+
// Aggregate credits per account so journal legs are concise while bounty_payouts preserves full per-artifact attribution
|
|
720
|
+
const creditByAccount = new Map();
|
|
721
|
+
const addCredit = (accountId, cents, earned) => {
|
|
722
|
+
if (cents <= 0)
|
|
723
|
+
return;
|
|
724
|
+
const cur = creditByAccount.get(accountId);
|
|
725
|
+
if (cur) {
|
|
726
|
+
cur.cents += cents;
|
|
727
|
+
cur.earned = cur.earned || earned;
|
|
728
|
+
}
|
|
729
|
+
else {
|
|
730
|
+
creditByAccount.set(accountId, { cents, earned });
|
|
731
|
+
}
|
|
732
|
+
};
|
|
733
|
+
addCredit(USD_SYSTEM_REVENUE_ACCOUNT, platformFeeCents, false);
|
|
734
|
+
addCredit(usdOperatorAccountId(winnerOperatorId), winnerNetCents, true);
|
|
735
|
+
for (const split of royaltySplits) {
|
|
736
|
+
addCredit(usdOperatorAccountId(split.operator_id), split.amount_cents, true);
|
|
737
|
+
}
|
|
738
|
+
const legs = [
|
|
739
|
+
{ accountId: fresh.escrow_account_id, deltaCents: -fresh.reward_cents },
|
|
740
|
+
...Array.from(creditByAccount.entries()).map(([accountId, v]) => ({
|
|
741
|
+
accountId,
|
|
742
|
+
deltaCents: v.cents,
|
|
743
|
+
countAsEarned: v.earned,
|
|
744
|
+
})),
|
|
745
|
+
];
|
|
746
|
+
const journalEntry = postUsdJournalEntry(db, {
|
|
747
|
+
entryType: 'bounty_settlement',
|
|
748
|
+
currency: 'USD',
|
|
749
|
+
workspaceId: fresh.workspace_id,
|
|
750
|
+
bountyId: fresh.id,
|
|
751
|
+
referenceType: 'verification_pass',
|
|
752
|
+
referenceId: params.runId,
|
|
753
|
+
memo: `Settle USD bounty ${fresh.id}: winner=${winnerOperatorId} ($${centsToUsd(winnerNetCents).toFixed(2)}), royalties=$${centsToUsd(totalRoyaltiesCents).toFixed(2)} (${royaltySplits.length} ancestors), platform_fee=$${centsToUsd(platformFeeCents).toFixed(2)}`,
|
|
754
|
+
metadata: {
|
|
755
|
+
winning_run_id: params.runId,
|
|
756
|
+
winning_artifact_id: params.artifactId,
|
|
757
|
+
winning_operator_id: winnerOperatorId,
|
|
758
|
+
platform_fee_cents: platformFeeCents,
|
|
759
|
+
total_royalties_cents: totalRoyaltiesCents,
|
|
760
|
+
winner_net_cents: winnerNetCents,
|
|
761
|
+
royalty_splits: royaltySplits,
|
|
762
|
+
},
|
|
763
|
+
idempotencyKey: `bounty_settle:${fresh.id}`,
|
|
764
|
+
now: ts,
|
|
765
|
+
legs,
|
|
766
|
+
});
|
|
767
|
+
const insertPayout = db.prepare(`
|
|
768
|
+
INSERT INTO bounty_payouts (
|
|
769
|
+
id, bounty_id, journal_entry_id, recipient_account_id, recipient_operator_id,
|
|
770
|
+
payout_role, source_artifact_id, lineage_depth, share_bps, amount_cents, created_at
|
|
771
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
772
|
+
`);
|
|
773
|
+
if (platformFeeCents > 0) {
|
|
774
|
+
insertPayout.run(newId('bpo'), fresh.id, journalEntry.id, USD_SYSTEM_REVENUE_ACCOUNT, null, 'platform_fee', null, 0, fresh.platform_fee_bps, platformFeeCents, ts);
|
|
775
|
+
}
|
|
776
|
+
if (winnerNetCents > 0) {
|
|
777
|
+
insertPayout.run(newId('bpo'), fresh.id, journalEntry.id, usdOperatorAccountId(winnerOperatorId), winnerOperatorId, 'winner', params.artifactId, 0, Math.round((winnerNetCents / fresh.reward_cents) * 10_000), winnerNetCents, ts);
|
|
778
|
+
}
|
|
779
|
+
for (const split of royaltySplits) {
|
|
780
|
+
insertPayout.run(newId('bpo'), fresh.id, journalEntry.id, usdOperatorAccountId(split.operator_id), split.operator_id, 'royalty', split.artifact_id, split.lineage_depth, split.share_bps, split.amount_cents, ts);
|
|
781
|
+
}
|
|
782
|
+
db.prepare(`
|
|
783
|
+
UPDATE usd_bounties
|
|
784
|
+
SET status = 'settled',
|
|
785
|
+
settlement_entry_id = ?,
|
|
786
|
+
winning_run_id = ?,
|
|
787
|
+
winning_artifact_id = ?,
|
|
788
|
+
winning_operator_id = ?,
|
|
789
|
+
platform_fee_cents = ?,
|
|
790
|
+
total_royalties_cents = ?,
|
|
791
|
+
winner_net_cents = ?,
|
|
792
|
+
settled_at = ?,
|
|
793
|
+
updated_at = ?
|
|
794
|
+
WHERE id = ?
|
|
795
|
+
`).run(journalEntry.id, params.runId, params.artifactId, winnerOperatorId, platformFeeCents, totalRoyaltiesCents, winnerNetCents, ts, ts, fresh.id);
|
|
796
|
+
const settledBounty = getBountyById(db, fresh.id);
|
|
797
|
+
syncNodeBountyConfig(db, settledBounty, ts);
|
|
798
|
+
return {
|
|
799
|
+
settled: true,
|
|
800
|
+
bounty: settledBounty,
|
|
801
|
+
journal_entry: journalEntry,
|
|
802
|
+
payouts: listBountyPayouts(db, fresh.id),
|
|
803
|
+
refunded_stake: refundedStake,
|
|
804
|
+
};
|
|
805
|
+
});
|
|
806
|
+
return tx.immediate();
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Resolves a run's anti-slop stake when verification finishes with a non-pass outcome:
|
|
810
|
+
* - `status === 'error'` (transient infra error) -> refund 100%
|
|
811
|
+
* - `status === 'fail'` with `stale_base: true` (git merge race, not slop) -> refund 100%
|
|
812
|
+
* - `status === 'fail'` (deterministic verification fail / reward hack / bad proof) -> SLASH
|
|
813
|
+
*/
|
|
814
|
+
export function resolveStakeOnNonPass(db, params) {
|
|
815
|
+
const stake = getStakeForRun(db, params.runId);
|
|
816
|
+
if (!stake || stake.status !== 'locked') {
|
|
817
|
+
return { action: 'none', stake };
|
|
818
|
+
}
|
|
819
|
+
const isStaleBase = Boolean(params.verifierResult.metrics?.stale_base);
|
|
820
|
+
if (params.finalStatus === 'error' || isStaleBase) {
|
|
821
|
+
const res = refundAntiSlopStake(db, {
|
|
822
|
+
stakeId: stake.id,
|
|
823
|
+
reason: isStaleBase ? 'stale_base_merge_conflict' : 'transient_verifier_error',
|
|
824
|
+
now: params.now,
|
|
825
|
+
});
|
|
826
|
+
return { action: 'refunded', stake: res.stake };
|
|
827
|
+
}
|
|
828
|
+
const reason = `verification_failed: ${String(params.verifierResult.logs || 'deterministic fail').slice(0, 300)}`;
|
|
829
|
+
const res = slashAntiSlopStake(db, {
|
|
830
|
+
stakeId: stake.id,
|
|
831
|
+
reason,
|
|
832
|
+
now: params.now,
|
|
833
|
+
});
|
|
834
|
+
return { action: 'slashed', stake: res.stake };
|
|
835
|
+
}
|
|
836
|
+
//# sourceMappingURL=bountyEngine.js.map
|