caisson-cli 0.0.0-stage → 0.2.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.
Files changed (215) hide show
  1. package/README.math-mvp.md +28 -0
  2. package/README.md +56 -3
  3. package/dist/admin/adminRoutes.d.ts +10 -0
  4. package/dist/admin/adminRoutes.js +194 -0
  5. package/dist/admin/adminRoutes.js.map +1 -0
  6. package/dist/admin/index.d.ts +2 -0
  7. package/dist/admin/index.js +4 -0
  8. package/dist/admin/index.js.map +1 -0
  9. package/dist/admin/workspaceAdmin.d.ts +417 -0
  10. package/dist/admin/workspaceAdmin.js +569 -0
  11. package/dist/admin/workspaceAdmin.js.map +1 -0
  12. package/dist/analytics/index.d.ts +1 -0
  13. package/dist/analytics/index.js +3 -0
  14. package/dist/analytics/index.js.map +1 -0
  15. package/dist/analytics/metrics.d.ts +105 -0
  16. package/dist/analytics/metrics.js +837 -0
  17. package/dist/analytics/metrics.js.map +1 -0
  18. package/dist/audit/index.d.ts +4 -0
  19. package/dist/audit/index.js +6 -0
  20. package/dist/audit/index.js.map +1 -0
  21. package/dist/audit/pipeline.d.ts +90 -0
  22. package/dist/audit/pipeline.js +424 -0
  23. package/dist/audit/pipeline.js.map +1 -0
  24. package/dist/audit/receiptSchema.d.ts +441 -0
  25. package/dist/audit/receiptSchema.js +208 -0
  26. package/dist/audit/receiptSchema.js.map +1 -0
  27. package/dist/audit/stageA.d.ts +50 -0
  28. package/dist/audit/stageA.js +218 -0
  29. package/dist/audit/stageA.js.map +1 -0
  30. package/dist/audit/stageB.d.ts +48 -0
  31. package/dist/audit/stageB.js +113 -0
  32. package/dist/audit/stageB.js.map +1 -0
  33. package/dist/auth/agentAuth.d.ts +28 -0
  34. package/dist/auth/agentAuth.js +88 -0
  35. package/dist/auth/agentAuth.js.map +1 -0
  36. package/dist/auth/agentCardSigner.d.ts +55 -0
  37. package/dist/auth/agentCardSigner.js +188 -0
  38. package/dist/auth/agentCardSigner.js.map +1 -0
  39. package/dist/billing/billingRoutes.d.ts +11 -0
  40. package/dist/billing/billingRoutes.js +303 -0
  41. package/dist/billing/billingRoutes.js.map +1 -0
  42. package/dist/billing/bountyRoutes.d.ts +9 -0
  43. package/dist/billing/bountyRoutes.js +332 -0
  44. package/dist/billing/bountyRoutes.js.map +1 -0
  45. package/dist/billing/index.d.ts +3 -0
  46. package/dist/billing/index.js +4 -0
  47. package/dist/billing/index.js.map +1 -0
  48. package/dist/billing/subscriptions.d.ts +226 -0
  49. package/dist/billing/subscriptions.js +673 -0
  50. package/dist/billing/subscriptions.js.map +1 -0
  51. package/dist/cli/caissonCli.d.ts +15 -0
  52. package/dist/cli/caissonCli.js +528 -0
  53. package/dist/cli/caissonCli.js.map +1 -0
  54. package/dist/cli/doctor.d.ts +31 -0
  55. package/dist/cli/doctor.js +321 -0
  56. package/dist/cli/doctor.js.map +1 -0
  57. package/dist/cli/inviteCard.d.ts +25 -0
  58. package/dist/cli/inviteCard.js +111 -0
  59. package/dist/cli/inviteCard.js.map +1 -0
  60. package/dist/cli/mcpProxy.d.ts +36 -0
  61. package/dist/cli/mcpProxy.js +292 -0
  62. package/dist/cli/mcpProxy.js.map +1 -0
  63. package/dist/config.d.ts +19 -0
  64. package/dist/config.js +28 -0
  65. package/dist/config.js.map +1 -0
  66. package/dist/db/adapter.d.ts +210 -0
  67. package/dist/db/adapter.js +769 -0
  68. package/dist/db/adapter.js.map +1 -0
  69. package/dist/db/sqlite.d.ts +7 -0
  70. package/dist/db/sqlite.js +60 -0
  71. package/dist/db/sqlite.js.map +1 -0
  72. package/dist/db/telemetry.d.ts +11 -0
  73. package/dist/db/telemetry.js +9 -0
  74. package/dist/db/telemetry.js.map +1 -0
  75. package/dist/economy/bountyEngine.d.ts +248 -0
  76. package/dist/economy/bountyEngine.js +836 -0
  77. package/dist/economy/bountyEngine.js.map +1 -0
  78. package/dist/economy/index.d.ts +5 -0
  79. package/dist/economy/index.js +6 -0
  80. package/dist/economy/index.js.map +1 -0
  81. package/dist/economy/scLedger.d.ts +183 -0
  82. package/dist/economy/scLedger.js +528 -0
  83. package/dist/economy/scLedger.js.map +1 -0
  84. package/dist/economy/scMinting.d.ts +177 -0
  85. package/dist/economy/scMinting.js +659 -0
  86. package/dist/economy/scMinting.js.map +1 -0
  87. package/dist/economy/scSinks.d.ts +135 -0
  88. package/dist/economy/scSinks.js +314 -0
  89. package/dist/economy/scSinks.js.map +1 -0
  90. package/dist/economy/usdLedger.d.ts +211 -0
  91. package/dist/economy/usdLedger.js +604 -0
  92. package/dist/economy/usdLedger.js.map +1 -0
  93. package/dist/mcp/handlers.d.ts +136 -0
  94. package/dist/mcp/handlers.js +809 -0
  95. package/dist/mcp/handlers.js.map +1 -0
  96. package/dist/mcp/httpServer.d.ts +29 -0
  97. package/dist/mcp/httpServer.js +384 -0
  98. package/dist/mcp/httpServer.js.map +1 -0
  99. package/dist/mcp/serverFactory.d.ts +4 -0
  100. package/dist/mcp/serverFactory.js +53 -0
  101. package/dist/mcp/serverFactory.js.map +1 -0
  102. package/dist/mcp/stdioServer.d.ts +2 -0
  103. package/dist/mcp/stdioServer.js +24 -0
  104. package/dist/mcp/stdioServer.js.map +1 -0
  105. package/dist/mcp/toolMetadata.d.ts +15 -0
  106. package/dist/mcp/toolMetadata.js +73 -0
  107. package/dist/mcp/toolMetadata.js.map +1 -0
  108. package/dist/memo/artifactIndex.d.ts +51 -0
  109. package/dist/memo/artifactIndex.js +162 -0
  110. package/dist/memo/artifactIndex.js.map +1 -0
  111. package/dist/memo/dependencyBundle.d.ts +33 -0
  112. package/dist/memo/dependencyBundle.js +86 -0
  113. package/dist/memo/dependencyBundle.js.map +1 -0
  114. package/dist/memo/embeddings.d.ts +110 -0
  115. package/dist/memo/embeddings.js +672 -0
  116. package/dist/memo/embeddings.js.map +1 -0
  117. package/dist/packs/foundryEvm.d.ts +21 -0
  118. package/dist/packs/foundryEvm.js +274 -0
  119. package/dist/packs/foundryEvm.js.map +1 -0
  120. package/dist/packs/index.d.ts +8 -0
  121. package/dist/packs/index.js +19 -0
  122. package/dist/packs/index.js.map +1 -0
  123. package/dist/packs/mathLean4.d.ts +7 -0
  124. package/dist/packs/mathLean4.js +145 -0
  125. package/dist/packs/mathLean4.js.map +1 -0
  126. package/dist/packs/rustKani.d.ts +17 -0
  127. package/dist/packs/rustKani.js +257 -0
  128. package/dist/packs/rustKani.js.map +1 -0
  129. package/dist/packs/sdk.d.ts +314 -0
  130. package/dist/packs/sdk.js +271 -0
  131. package/dist/packs/sdk.js.map +1 -0
  132. package/dist/preflight/leanTripwire.d.ts +19 -0
  133. package/dist/preflight/leanTripwire.js +105 -0
  134. package/dist/preflight/leanTripwire.js.map +1 -0
  135. package/dist/storage/blobStore.d.ts +11 -0
  136. package/dist/storage/blobStore.js +39 -0
  137. package/dist/storage/blobStore.js.map +1 -0
  138. package/dist/storage/gitStore.d.ts +68 -0
  139. package/dist/storage/gitStore.js +228 -0
  140. package/dist/storage/gitStore.js.map +1 -0
  141. package/dist/types/errors.d.ts +16 -0
  142. package/dist/types/errors.js +23 -0
  143. package/dist/types/errors.js.map +1 -0
  144. package/dist/types/schemas.d.ts +453 -0
  145. package/dist/types/schemas.js +197 -0
  146. package/dist/types/schemas.js.map +1 -0
  147. package/dist/web/discoveryRoutes.d.ts +24 -0
  148. package/dist/web/discoveryRoutes.js +532 -0
  149. package/dist/web/discoveryRoutes.js.map +1 -0
  150. package/dist/web/docsRoutes.d.ts +14 -0
  151. package/dist/web/docsRoutes.js +451 -0
  152. package/dist/web/docsRoutes.js.map +1 -0
  153. package/dist/web/explorer/dagLayout.d.ts +41 -0
  154. package/dist/web/explorer/dagLayout.js +183 -0
  155. package/dist/web/explorer/dagLayout.js.map +1 -0
  156. package/dist/web/explorer/index.d.ts +45 -0
  157. package/dist/web/explorer/index.js +512 -0
  158. package/dist/web/explorer/index.js.map +1 -0
  159. package/dist/web/explorer/renderers.d.ts +35 -0
  160. package/dist/web/explorer/renderers.js +399 -0
  161. package/dist/web/explorer/renderers.js.map +1 -0
  162. package/dist/web/landing.d.ts +36 -0
  163. package/dist/web/landing.js +532 -0
  164. package/dist/web/landing.js.map +1 -0
  165. package/dist/web/onboardingRoutes.d.ts +96 -0
  166. package/dist/web/onboardingRoutes.js +629 -0
  167. package/dist/web/onboardingRoutes.js.map +1 -0
  168. package/dist/web/repoBrowser.d.ts +19 -0
  169. package/dist/web/repoBrowser.js +128 -0
  170. package/dist/web/repoBrowser.js.map +1 -0
  171. package/dist/worker/executionAdapter.d.ts +14 -0
  172. package/dist/worker/executionAdapter.js +162 -0
  173. package/dist/worker/executionAdapter.js.map +1 -0
  174. package/dist/worker/finalize.d.ts +21 -0
  175. package/dist/worker/finalize.js +146 -0
  176. package/dist/worker/finalize.js.map +1 -0
  177. package/dist/worker/firecrackerAdapter.d.ts +180 -0
  178. package/dist/worker/firecrackerAdapter.js +421 -0
  179. package/dist/worker/firecrackerAdapter.js.map +1 -0
  180. package/dist/worker/loop.d.ts +56 -0
  181. package/dist/worker/loop.js +239 -0
  182. package/dist/worker/loop.js.map +1 -0
  183. package/dist/worker/postMergeSync.d.ts +17 -0
  184. package/dist/worker/postMergeSync.js +52 -0
  185. package/dist/worker/postMergeSync.js.map +1 -0
  186. package/dist/worker/prepareInput.d.ts +41 -0
  187. package/dist/worker/prepareInput.js +130 -0
  188. package/dist/worker/prepareInput.js.map +1 -0
  189. package/dist/worker/queue.d.ts +83 -0
  190. package/dist/worker/queue.js +278 -0
  191. package/dist/worker/queue.js.map +1 -0
  192. package/dist/worker/sandbox.d.ts +2 -0
  193. package/dist/worker/sandbox.js +3 -0
  194. package/dist/worker/sandbox.js.map +1 -0
  195. package/dist/worker/webhook.d.ts +14 -0
  196. package/dist/worker/webhook.js +110 -0
  197. package/dist/worker/webhook.js.map +1 -0
  198. package/migrations/001_init.sql +193 -0
  199. package/migrations/002_epic3_scale.sql +34 -0
  200. package/migrations/003_swarm_credits.sql +153 -0
  201. package/migrations/004_usd_bounties.sql +216 -0
  202. package/migrations_pg/001_init.sql +229 -0
  203. package/migrations_pg/002_multitenant_rls.sql +63 -0
  204. package/migrations_pg/003_swarm_credits.sql +135 -0
  205. package/migrations_pg/004_usd_bounties.sql +201 -0
  206. package/package.json +58 -6
  207. package/packs/foundry-evm/pack.json +60 -0
  208. package/packs/foundry-evm/verifier/Dockerfile +9 -0
  209. package/packs/foundry-evm/verifier/run.py +160 -0
  210. package/packs/math-lean4/pack.json +68 -0
  211. package/packs/rust-kani/pack.json +53 -0
  212. package/packs/rust-kani/verifier/Dockerfile +7 -0
  213. package/packs/rust-kani/verifier/run.py +159 -0
  214. package/public/.well-known/agent-card.json +162 -0
  215. package/public/llms.txt +40 -0
@@ -0,0 +1,659 @@
1
+ // src/economy/scMinting.ts
2
+ // Downstream-Utility Swarm Credit Issuance & Dual Sybil Gate (Epic 4 / E4-2)
3
+ // Reference: docs/08-business-model-unit-economics-branding-spec.md §2
4
+ //
5
+ // Formula:
6
+ // SC_mint(o) = max(0,
7
+ // sum_{a in V_o} [ M_base(a) + min(4 * M_base(a), 15 * sum_{k=1..n_a} w_eff(o_k, o) / sqrt(k)) ]
8
+ // + sum_{d in D_o} min(20, 4 * sum_{o' != o} w_eff(o', o))
9
+ // + sum_{f in F_o} 20
10
+ // - P_slop(o)
11
+ // )
12
+ //
13
+ // Base Mint M_base:
14
+ // Leaf = 5 SC, Mid-DAG = 10 SC, Root Closure = 25 SC, Verified Counterexample / Audit Defect = 20 SC.
15
+ //
16
+ // Dual Sybil Gate:
17
+ // w_eff(o', o) = tau(o') * (1 - clamp(2 * (e_{o'->o} - 0.5), 0, 1))
18
+ // - tau(o') = 0.1 for new/unbonded accounts until identity_bonded = true AND >= 3 public verified merges, then 1.0
19
+ // - e_{o'->o} = fraction of o''s outgoing external citations targeting o; > 50% linearly decays weight to 0.
20
+ import { nowIso } from '../db/sqlite.js';
21
+ import { checkWorkspaceMintEligibility, ensureOperatorAccount, mintSwarmCredits, scToUnits, unitsToSc, } from './scLedger.js';
22
+ export const BASE_MINT_SC = {
23
+ leaf: 5,
24
+ mid_dag: 10,
25
+ root_closure: 25,
26
+ counterexample: 20,
27
+ audit_defect: 20,
28
+ };
29
+ export const REUSE_COEFF_SC = 15;
30
+ export const REUSE_CAP_MULTIPLIER = 4;
31
+ export const DEAD_END_COEFF_SC = 4;
32
+ export const DEAD_END_CAP_SC = 20;
33
+ export const NEW_ACCOUNT_TAU = 0.1;
34
+ export const TRUSTED_ACCOUNT_TAU = 1.0;
35
+ export const TRUST_MIN_PUBLIC_MERGES = 3;
36
+ export const DEFAULT_SLOP_PENALTY_CONFIG = {
37
+ precheckBypassSc: 10,
38
+ abandonedLeaseSc: 5,
39
+ unprecheckedFailSc: 5,
40
+ };
41
+ function clamp(v, min, max) {
42
+ return Math.max(min, Math.min(max, v));
43
+ }
44
+ function round2(n) {
45
+ return Math.round(n * 100) / 100;
46
+ }
47
+ function round4(n) {
48
+ return Math.round(n * 10_000) / 10_000;
49
+ }
50
+ function safeJsonParse(raw, fallback) {
51
+ if (!raw)
52
+ return fallback;
53
+ try {
54
+ return JSON.parse(raw);
55
+ }
56
+ catch {
57
+ return fallback;
58
+ }
59
+ }
60
+ /**
61
+ * Pure Dual Sybil Gate weight function from Doc 08 §2:
62
+ * `w_eff(o', o) = tau(o') * (1 - clamp(2 * (e_{o'->o} - 0.5), 0, 1))`
63
+ */
64
+ export function computeExclusivityMultiplier(exclusivity) {
65
+ const e = clamp(exclusivity, 0, 1);
66
+ return 1 - clamp(2 * (e - 0.5), 0, 1);
67
+ }
68
+ /**
69
+ * Computes `w_eff(o', o)` from citer trust `tau` and citation exclusivity `e_{o' -> o}`.
70
+ */
71
+ export function computeEffectiveCitationWeight(tau, exclusivity) {
72
+ return clamp(tau, 0, 1) * computeExclusivityMultiplier(exclusivity);
73
+ }
74
+ /**
75
+ * Computes `tau(o')` for an operator:
76
+ * `0.1` for new/unbonded accounts until BOTH `identity_bonded === true` AND `public_verified_merges >= 3`,
77
+ * at which point `tau` graduates to `1.0`.
78
+ */
79
+ export function computeTrustTau(identityBonded, publicVerifiedMerges) {
80
+ return identityBonded && publicVerifiedMerges >= TRUST_MIN_PUBLIC_MERGES
81
+ ? TRUSTED_ACCOUNT_TAU
82
+ : NEW_ACCOUNT_TAU;
83
+ }
84
+ /**
85
+ * Computes concave reuse bonus for a single verified artifact given effective weights of distinct external citers:
86
+ * `min(4 * M_base, 15 * sum_{k=1..n} w_eff(o_k, o) / sqrt(k))`
87
+ * Weights are sorted descending so honest high-trust citers are never diluted by low-trust sybils arriving earlier.
88
+ */
89
+ export function computeConcaveReuseBonus(baseSc, externalWeights) {
90
+ const capSc = REUSE_CAP_MULTIPLIER * baseSc;
91
+ const sorted = [...externalWeights].filter((w) => w > 0).sort((a, b) => b - a);
92
+ let sum = 0;
93
+ for (let i = 0; i < sorted.length; i++) {
94
+ sum += sorted[i] / Math.sqrt(i + 1);
95
+ }
96
+ const rawSc = REUSE_COEFF_SC * sum;
97
+ const cappedSc = Math.min(capSc, rawSc);
98
+ return { rawSc, cappedSc, capSc };
99
+ }
100
+ /**
101
+ * Computes dead-end consultation bonus:
102
+ * `min(20, 4 * sum_{o' != o} w_eff(o', o))`
103
+ */
104
+ export function computeDeadEndBonus(externalWeights) {
105
+ const sum = externalWeights.filter((w) => w > 0).reduce((acc, w) => acc + w, 0);
106
+ const rawSc = DEAD_END_COEFF_SC * sum;
107
+ const cappedSc = Math.min(DEAD_END_CAP_SC, rawSc);
108
+ return { rawSc, cappedSc, capSc: DEAD_END_CAP_SC };
109
+ }
110
+ /**
111
+ * Classifies a verified artifact into its Doc 08 §2 base-mint tier:
112
+ * - Explicit override via `node.bounty_config.sc_tier` (if valid)
113
+ * - `Counterexample` node -> `'counterexample'` (20 SC)
114
+ * - `Goal` / `Conjecture` / `RootClosure` / terminal node with `depends_on` parents & no `depends_on` children -> `'root_closure'` (25 SC)
115
+ * - Node with no `depends_on` parents & no `depends_on` children -> `'leaf'` (5 SC) unless `mid_dag`
116
+ * - Intermediate node with `depends_on` parents or children -> `'mid_dag'` (10 SC)
117
+ * - Foundational leaf (0 `depends_on` parents, has `depends_on` children) -> `'leaf'` (5 SC)
118
+ */
119
+ export function classifyArtifactMintTier(node, artifact, dependsParentsCount, dependsChildrenCount) {
120
+ const bountyCfg = safeJsonParse(node?.bounty_config, {});
121
+ const explicit = bountyCfg.sc_tier;
122
+ if (explicit === 'leaf' ||
123
+ explicit === 'mid_dag' ||
124
+ explicit === 'root_closure' ||
125
+ explicit === 'counterexample' ||
126
+ explicit === 'audit_defect') {
127
+ return explicit;
128
+ }
129
+ const nodeType = String(node?.type ?? '');
130
+ if (nodeType === 'Counterexample') {
131
+ return 'counterexample';
132
+ }
133
+ if (nodeType === 'FormalizationAudit') {
134
+ return 'audit_defect';
135
+ }
136
+ if (nodeType === 'Goal' ||
137
+ nodeType === 'RootClosure' ||
138
+ nodeType === 'Conjecture' ||
139
+ (dependsParentsCount > 0 && dependsChildrenCount === 0)) {
140
+ return 'root_closure';
141
+ }
142
+ if (artifact?.artifact_type === 'literature_check') {
143
+ return 'leaf';
144
+ }
145
+ if (dependsParentsCount > 0 && dependsChildrenCount > 0) {
146
+ return 'mid_dag';
147
+ }
148
+ return 'leaf';
149
+ }
150
+ /**
151
+ * Computes global `tau(o)` trust status for an operator across all eligible audited/sponsored public workspaces.
152
+ */
153
+ export function getOperatorTrustStatus(db, operatorId) {
154
+ const acct = db
155
+ .prepare('SELECT identity_bonded FROM sc_accounts WHERE operator_id = ?')
156
+ .get(operatorId);
157
+ const bonded = Number(acct?.identity_bonded ?? 0) === 1;
158
+ const mergeRow = db
159
+ .prepare(`
160
+ SELECT COUNT(*) AS cnt
161
+ FROM artifacts a
162
+ JOIN agent_identities ag ON ag.id = a.author_agent_id
163
+ JOIN workspaces w ON w.id = a.workspace_id
164
+ WHERE ag.operator_id = ?
165
+ AND a.artifact_type <> 'dead_end'
166
+ AND w.visibility = 'public'
167
+ AND w.sc_minting_policy IN ('audited_public', 'sponsored_public')
168
+ `)
169
+ .get(operatorId);
170
+ const merges = Number(mergeRow?.cnt ?? 0);
171
+ return {
172
+ operator_id: operatorId,
173
+ identity_bonded: bonded,
174
+ public_verified_merges: merges,
175
+ tau: computeTrustTau(bonded, merges),
176
+ };
177
+ }
178
+ /**
179
+ * Evaluates the Doc 08 §2 concave `SC_mint(o)` formula across eligible audited/sponsored public workspaces
180
+ * (or a specific workspace), enforcing:
181
+ * - Strict exclusion of private workspaces (`0.00 SC` global minting)
182
+ * - Strict exclusion of unaudited Lemma/Conjecture nodes blocked by an unverified FormalizationAudit
183
+ * - Strict exclusion of same-operator self-citations (even across multiple agents of the same operator)
184
+ * - Dual Sybil Gate: `tau(o')` trust ramp + `e_{o'->o}` citation exclusivity linear decay
185
+ * - Slop penalties (`PRECHECK_FAILED`, expired/abandoned leases, unprechecked fails) floored at 0 SC
186
+ */
187
+ export function computeSwarmCreditIssuance(db, opts = {}) {
188
+ const generatedAt = opts.now ?? nowIso();
189
+ const slopCfg = {
190
+ ...DEFAULT_SLOP_PENALTY_CONFIG,
191
+ ...(opts.slopConfig ?? {}),
192
+ };
193
+ const requireAudited = opts.requireAuditedWorkspace ?? true;
194
+ // 1. Identify eligible vs excluded workspaces
195
+ const allWorkspaces = opts.workspaceId
196
+ ? db.prepare('SELECT * FROM workspaces WHERE id = ? OR slug = ?').all(opts.workspaceId, opts.workspaceId)
197
+ : db.prepare('SELECT * FROM workspaces').all();
198
+ const scopeWsId = opts.workspaceId ? (allWorkspaces[0]?.id ?? opts.workspaceId) : null;
199
+ const eligibleWsIds = new Set();
200
+ const excludedWorkspaces = [];
201
+ for (const ws of allWorkspaces) {
202
+ const check = checkWorkspaceMintEligibility(db, ws.id, { requireAudited });
203
+ if (check.eligible) {
204
+ eligibleWsIds.add(ws.id);
205
+ }
206
+ else {
207
+ excludedWorkspaces.push({
208
+ workspace_id: ws.id,
209
+ reason: check.reason ?? 'Not eligible for global SC minting',
210
+ });
211
+ }
212
+ }
213
+ // Load agent -> operator map
214
+ const agents = db.prepare('SELECT id, operator_id FROM agent_identities').all();
215
+ const agentToOp = new Map(agents.map((a) => [a.id, a.operator_id]));
216
+ // Load bonded flags from sc_accounts
217
+ const scAccounts = db.prepare('SELECT operator_id, identity_bonded FROM sc_accounts WHERE operator_id IS NOT NULL').all();
218
+ const bondedByOp = new Map(scAccounts.map((a) => [a.operator_id, Number(a.identity_bonded) === 1]));
219
+ // Compute global public verified merge count per operator (for tau trust ramp across all eligible public workspaces)
220
+ const globalMergeRows = db
221
+ .prepare(`
222
+ SELECT ag.operator_id, COUNT(*) AS cnt
223
+ FROM artifacts a
224
+ JOIN agent_identities ag ON ag.id = a.author_agent_id
225
+ JOIN workspaces w ON w.id = a.workspace_id
226
+ WHERE a.artifact_type <> 'dead_end'
227
+ AND w.visibility = 'public'
228
+ AND w.sc_minting_policy IN ('audited_public', 'sponsored_public')
229
+ GROUP BY ag.operator_id
230
+ `)
231
+ .all();
232
+ const globalMergesByOp = new Map(globalMergeRows.map((r) => [r.operator_id, Number(r.cnt)]));
233
+ const getTrust = (opId) => {
234
+ const bonded = bondedByOp.get(opId) ?? false;
235
+ const merges = globalMergesByOp.get(opId) ?? 0;
236
+ return {
237
+ operator_id: opId,
238
+ identity_bonded: bonded,
239
+ public_verified_merges: merges,
240
+ tau: computeTrustTau(bonded, merges),
241
+ };
242
+ };
243
+ if (eligibleWsIds.size === 0) {
244
+ return {
245
+ generated_at: generatedAt,
246
+ scope_workspace_id: scopeWsId,
247
+ eligible_workspaces: [],
248
+ excluded_workspaces: excludedWorkspaces,
249
+ operators: [],
250
+ total_net_mint_sc: 0,
251
+ total_net_mint_units: 0,
252
+ };
253
+ }
254
+ const wsIdList = Array.from(eligibleWsIds);
255
+ const wsPlaceholders = wsIdList.map(() => '?').join(',');
256
+ // Load nodes and edges for eligible workspaces
257
+ const nodes = db
258
+ .prepare(`SELECT * FROM nodes WHERE workspace_id IN (${wsPlaceholders})`)
259
+ .all(...wsIdList);
260
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
261
+ const edges = db
262
+ .prepare(`SELECT * FROM node_edges WHERE workspace_id IN (${wsPlaceholders})`)
263
+ .all(...wsIdList);
264
+ const dependsParentsCount = new Map();
265
+ const dependsChildrenCount = new Map();
266
+ const unauditedNodeIds = new Set();
267
+ for (const e of edges) {
268
+ if (e.edge_type === 'depends_on') {
269
+ dependsParentsCount.set(e.child_node_id, (dependsParentsCount.get(e.child_node_id) ?? 0) + 1);
270
+ dependsChildrenCount.set(e.parent_node_id, (dependsChildrenCount.get(e.parent_node_id) ?? 0) + 1);
271
+ }
272
+ else if (e.edge_type === 'audits') {
273
+ const auditNode = nodeById.get(e.parent_node_id);
274
+ if (requireAudited && auditNode && auditNode.status !== 'verified') {
275
+ unauditedNodeIds.add(e.child_node_id);
276
+ }
277
+ }
278
+ }
279
+ // Load artifacts in eligible workspaces (excluding those attached to unaudited gated nodes)
280
+ const rawArtifacts = db
281
+ .prepare(`SELECT * FROM artifacts WHERE workspace_id IN (${wsPlaceholders})`)
282
+ .all(...wsIdList);
283
+ const eligibleArtifacts = rawArtifacts.filter((a) => !unauditedNodeIds.has(a.source_node_id));
284
+ const artifactById = new Map(eligibleArtifacts.map((a) => [a.id, a]));
285
+ const verifiedArtifacts = eligibleArtifacts.filter((a) => a.artifact_type !== 'dead_end');
286
+ const deadEndArtifacts = eligibleArtifacts.filter((a) => a.artifact_type === 'dead_end');
287
+ const deadEndById = new Map(deadEndArtifacts.map((d) => [d.id, d]));
288
+ // Load artifact lineage edges whose parent & child are both in eligible verified artifacts
289
+ const lineageRows = db
290
+ .prepare('SELECT artifact_id, parent_artifact_id FROM artifact_lineage')
291
+ .all();
292
+ // Track distinct external citers per verified parent artifact AND outgoing citation counts per citer -> target
293
+ const externalCitersByArtifact = new Map();
294
+ const selfCitationsByArtifact = new Map();
295
+ const outgoingCitesByCiter = new Map();
296
+ const totalOutgoingByCiter = new Map();
297
+ const recordOutgoingCitation = (citerOp, targetOp) => {
298
+ const byTarget = outgoingCitesByCiter.get(citerOp) ?? new Map();
299
+ byTarget.set(targetOp, (byTarget.get(targetOp) ?? 0) + 1);
300
+ outgoingCitesByCiter.set(citerOp, byTarget);
301
+ totalOutgoingByCiter.set(citerOp, (totalOutgoingByCiter.get(citerOp) ?? 0) + 1);
302
+ };
303
+ for (const row of lineageRows) {
304
+ const parent = artifactById.get(row.parent_artifact_id);
305
+ const child = artifactById.get(row.artifact_id);
306
+ if (!parent || !child)
307
+ continue;
308
+ if (parent.artifact_type === 'dead_end' || child.artifact_type === 'dead_end')
309
+ continue;
310
+ const parentOp = agentToOp.get(parent.author_agent_id);
311
+ const childOp = agentToOp.get(child.author_agent_id);
312
+ if (!parentOp || !childOp)
313
+ continue;
314
+ if (parentOp === childOp) {
315
+ selfCitationsByArtifact.set(parent.id, (selfCitationsByArtifact.get(parent.id) ?? 0) + 1);
316
+ continue;
317
+ }
318
+ const citers = externalCitersByArtifact.get(parent.id) ?? new Set();
319
+ const isNewForArtifact = !citers.has(childOp);
320
+ citers.add(childOp);
321
+ externalCitersByArtifact.set(parent.id, citers);
322
+ // Count each distinct (child_artifact -> parent_artifact) external citation toward exclusivity
323
+ if (isNewForArtifact) {
324
+ recordOutgoingCitation(childOp, parentOp);
325
+ }
326
+ }
327
+ // Load events & runs in eligible workspaces for dead-end consumption & slop penalties
328
+ const events = db
329
+ .prepare(`SELECT * FROM mcp_tool_events WHERE workspace_id IN (${wsPlaceholders})`)
330
+ .all(...wsIdList);
331
+ const runs = db
332
+ .prepare(`SELECT * FROM verification_runs WHERE workspace_id IN (${wsPlaceholders})`)
333
+ .all(...wsIdList);
334
+ const externalConsumersByDeadEnd = new Map();
335
+ const selfExposuresByDeadEnd = new Map();
336
+ const recordDeadEndExposure = (deadEndId, consumerOp) => {
337
+ const de = deadEndById.get(deadEndId);
338
+ if (!de)
339
+ return;
340
+ const authorOp = agentToOp.get(de.author_agent_id);
341
+ if (!authorOp)
342
+ return;
343
+ if (authorOp === consumerOp) {
344
+ selfExposuresByDeadEnd.set(deadEndId, (selfExposuresByDeadEnd.get(deadEndId) ?? 0) + 1);
345
+ return;
346
+ }
347
+ const consumers = externalConsumersByDeadEnd.get(deadEndId) ?? new Set();
348
+ if (!consumers.has(consumerOp)) {
349
+ consumers.add(consumerOp);
350
+ externalConsumersByDeadEnd.set(deadEndId, consumers);
351
+ recordOutgoingCitation(consumerOp, authorOp);
352
+ }
353
+ };
354
+ for (const ev of events) {
355
+ if (ev.tool_name !== 'query_cache' && ev.tool_name !== 'read_graph')
356
+ continue;
357
+ const consumerOp = agentToOp.get(ev.agent_id);
358
+ if (!consumerOp)
359
+ continue;
360
+ const returned = safeJsonParse(ev.returned_ids, []);
361
+ for (const id of returned) {
362
+ if (deadEndById.has(id)) {
363
+ recordDeadEndExposure(id, consumerOp);
364
+ }
365
+ }
366
+ }
367
+ for (const r of runs) {
368
+ const consumerOp = agentToOp.get(r.agent_id);
369
+ if (!consumerOp)
370
+ continue;
371
+ const precheck = safeJsonParse(r.precheck_proof, {});
372
+ const consulted = Array.isArray(precheck?.client_telemetry?.dead_ends_consulted)
373
+ ? precheck.client_telemetry.dead_ends_consulted
374
+ : [];
375
+ for (const id of consulted) {
376
+ if (deadEndById.has(id)) {
377
+ recordDeadEndExposure(id, consumerOp);
378
+ }
379
+ }
380
+ }
381
+ // Helper to evaluate Dual Sybil Gate weight trace w_eff(citerOp, targetOp)
382
+ const getCitationWeightTrace = (citerOp, targetOp) => {
383
+ const trust = getTrust(citerOp);
384
+ const totalOut = totalOutgoingByCiter.get(citerOp) ?? 0;
385
+ const toTarget = outgoingCitesByCiter.get(citerOp)?.get(targetOp) ?? 0;
386
+ const exclusivity = totalOut > 0 ? toTarget / totalOut : 0;
387
+ const mult = computeExclusivityMultiplier(exclusivity);
388
+ const wEff = trust.tau * mult;
389
+ return {
390
+ citer_operator_id: citerOp,
391
+ target_operator_id: targetOp,
392
+ tau: trust.tau,
393
+ exclusivity: round4(exclusivity),
394
+ exclusivity_multiplier: round4(mult),
395
+ w_eff: round4(wEff),
396
+ };
397
+ };
398
+ // Audit defect catches (20 SC each)
399
+ const auditDefectsByOp = new Map();
400
+ for (const node of nodes) {
401
+ if (node.type !== 'FormalizationAudit')
402
+ continue;
403
+ const vr = safeJsonParse(node.verifier_result, {});
404
+ const metrics = vr?.metrics ?? {};
405
+ const hasDefect = node.status === 'disputed' || vr?.status === 'fail' || Number(metrics.defects_caught ?? 0) > 0;
406
+ if (!hasDefect)
407
+ continue;
408
+ const reporters = new Set();
409
+ if (Array.isArray(metrics.defect_reporter_operators)) {
410
+ for (const op of metrics.defect_reporter_operators)
411
+ reporters.add(String(op));
412
+ }
413
+ if (Array.isArray(metrics.defect_reporter_agents)) {
414
+ for (const agId of metrics.defect_reporter_agents) {
415
+ const op = agentToOp.get(String(agId));
416
+ if (op)
417
+ reporters.add(op);
418
+ }
419
+ }
420
+ for (const op of reporters) {
421
+ auditDefectsByOp.set(op, (auditDefectsByOp.get(op) ?? 0) + 1);
422
+ }
423
+ }
424
+ // Slop signals per operator
425
+ const precheckBypassesByOp = new Map();
426
+ const abandonedLeasesByOp = new Map();
427
+ const unprecheckedFailsByOp = new Map();
428
+ for (const ev of events) {
429
+ const op = agentToOp.get(ev.agent_id);
430
+ if (!op)
431
+ continue;
432
+ if (ev.tool_name === 'submit_artifact' && ev.outcome_code === 'PRECHECK_FAILED') {
433
+ precheckBypassesByOp.set(op, (precheckBypassesByOp.get(op) ?? 0) + 1);
434
+ }
435
+ if (ev.tool_name === 'claim_node' && ev.outcome_code === 'LEASE_EXPIRED') {
436
+ abandonedLeasesByOp.set(op, (abandonedLeasesByOp.get(op) ?? 0) + 1);
437
+ }
438
+ }
439
+ for (const n of nodes) {
440
+ if (n.status === 'claimed' && n.claim_agent_id && n.claim_expires_at && n.claim_expires_at < generatedAt) {
441
+ const op = agentToOp.get(n.claim_agent_id);
442
+ if (op) {
443
+ abandonedLeasesByOp.set(op, (abandonedLeasesByOp.get(op) ?? 0) + 1);
444
+ }
445
+ }
446
+ }
447
+ for (const r of runs) {
448
+ if (r.status === 'fail' && !r.precheck_proof) {
449
+ const op = agentToOp.get(r.agent_id);
450
+ if (op) {
451
+ unprecheckedFailsByOp.set(op, (unprecheckedFailsByOp.get(op) ?? 0) + 1);
452
+ }
453
+ }
454
+ }
455
+ // Collect all operators active in eligible workspaces
456
+ const activeOps = new Set();
457
+ for (const a of eligibleArtifacts) {
458
+ const op = agentToOp.get(a.author_agent_id);
459
+ if (op)
460
+ activeOps.add(op);
461
+ }
462
+ for (const op of auditDefectsByOp.keys())
463
+ activeOps.add(op);
464
+ for (const op of precheckBypassesByOp.keys())
465
+ activeOps.add(op);
466
+ for (const op of abandonedLeasesByOp.keys())
467
+ activeOps.add(op);
468
+ for (const op of unprecheckedFailsByOp.keys())
469
+ activeOps.add(op);
470
+ // Assemble per-operator breakdown
471
+ const breakdowns = [];
472
+ for (const opId of Array.from(activeOps).sort()) {
473
+ const opVerified = verifiedArtifacts.filter((a) => agentToOp.get(a.author_agent_id) === opId);
474
+ const opDeadEnds = deadEndArtifacts.filter((d) => agentToOp.get(d.author_agent_id) === opId);
475
+ let baseSc = 0;
476
+ let downstreamReuseSc = 0;
477
+ let deadEndSc = 0;
478
+ let selfCitationsExcluded = 0;
479
+ const artifactDetails = [];
480
+ for (const art of opVerified) {
481
+ const node = nodeById.get(art.source_node_id);
482
+ const tier = classifyArtifactMintTier(node, art, dependsParentsCount.get(art.source_node_id) ?? 0, dependsChildrenCount.get(art.source_node_id) ?? 0);
483
+ const artBase = BASE_MINT_SC[tier];
484
+ const citerSet = externalCitersByArtifact.get(art.id) ?? new Set();
485
+ const traces = Array.from(citerSet)
486
+ .map((citerOp) => getCitationWeightTrace(citerOp, opId))
487
+ .sort((a, b) => b.w_eff - a.w_eff || a.citer_operator_id.localeCompare(b.citer_operator_id));
488
+ const bonus = computeConcaveReuseBonus(artBase, traces.map((t) => t.w_eff));
489
+ const selfExcl = selfCitationsByArtifact.get(art.id) ?? 0;
490
+ baseSc += artBase;
491
+ downstreamReuseSc += bonus.cappedSc;
492
+ selfCitationsExcluded += selfExcl;
493
+ artifactDetails.push({
494
+ artifact_id: art.id,
495
+ workspace_id: art.workspace_id,
496
+ node_id: art.source_node_id,
497
+ tier,
498
+ base_sc: round2(artBase),
499
+ reuse_cap_sc: round2(bonus.capSc),
500
+ raw_reuse_sc: round2(bonus.rawSc),
501
+ capped_reuse_sc: round2(bonus.cappedSc),
502
+ total_sc: round2(artBase + bonus.cappedSc),
503
+ external_citers: traces,
504
+ self_citations_excluded: selfExcl,
505
+ });
506
+ }
507
+ const deadEndDetails = [];
508
+ for (const de of opDeadEnds) {
509
+ const consumers = externalConsumersByDeadEnd.get(de.id) ?? new Set();
510
+ const traces = Array.from(consumers)
511
+ .map((cOp) => getCitationWeightTrace(cOp, opId))
512
+ .sort((a, b) => b.w_eff - a.w_eff || a.citer_operator_id.localeCompare(b.citer_operator_id));
513
+ const bonus = computeDeadEndBonus(traces.map((t) => t.w_eff));
514
+ const selfExcl = selfExposuresByDeadEnd.get(de.id) ?? 0;
515
+ deadEndSc += bonus.cappedSc;
516
+ selfCitationsExcluded += selfExcl;
517
+ deadEndDetails.push({
518
+ artifact_id: de.id,
519
+ workspace_id: de.workspace_id,
520
+ node_id: de.source_node_id,
521
+ raw_sc: round2(bonus.rawSc),
522
+ capped_sc: round2(bonus.cappedSc),
523
+ external_consumers: traces,
524
+ self_exposures_excluded: selfExcl,
525
+ });
526
+ }
527
+ const auditDefectsCaught = auditDefectsByOp.get(opId) ?? 0;
528
+ const auditDefectSc = auditDefectsCaught * BASE_MINT_SC.audit_defect;
529
+ const precheckBypasses = precheckBypassesByOp.get(opId) ?? 0;
530
+ const abandonedLeases = abandonedLeasesByOp.get(opId) ?? 0;
531
+ const unprecheckedFails = unprecheckedFailsByOp.get(opId) ?? 0;
532
+ const slopPenaltySc = precheckBypasses * slopCfg.precheckBypassSc +
533
+ abandonedLeases * slopCfg.abandonedLeaseSc +
534
+ unprecheckedFails * slopCfg.unprecheckedFailSc;
535
+ const grossSc = baseSc + downstreamReuseSc + deadEndSc + auditDefectSc;
536
+ const netScExact = Math.max(0, grossSc - slopPenaltySc);
537
+ const netUnits = scToUnits(round2(netScExact));
538
+ breakdowns.push({
539
+ operator_id: opId,
540
+ trust: getTrust(opId),
541
+ base_sc: round2(baseSc),
542
+ downstream_reuse_sc: round2(downstreamReuseSc),
543
+ dead_end_sc: round2(deadEndSc),
544
+ audit_defect_sc: round2(auditDefectSc),
545
+ gross_sc: round2(grossSc),
546
+ slop_penalty_sc: round2(slopPenaltySc),
547
+ slop_details: {
548
+ precheck_bypasses: precheckBypasses,
549
+ abandoned_leases: abandonedLeases,
550
+ unprechecked_fails: unprecheckedFails,
551
+ },
552
+ net_mint_sc: unitsToSc(netUnits),
553
+ net_mint_units: netUnits,
554
+ self_citations_excluded: selfCitationsExcluded,
555
+ artifacts: artifactDetails,
556
+ dead_ends: deadEndDetails,
557
+ audit_defects_caught: auditDefectsCaught,
558
+ });
559
+ }
560
+ breakdowns.sort((a, b) => b.net_mint_units - a.net_mint_units || a.operator_id.localeCompare(b.operator_id));
561
+ const totalUnits = breakdowns.reduce((s, b) => s + b.net_mint_units, 0);
562
+ return {
563
+ generated_at: generatedAt,
564
+ scope_workspace_id: scopeWsId,
565
+ eligible_workspaces: wsIdList.sort(),
566
+ excluded_workspaces: excludedWorkspaces,
567
+ operators: breakdowns,
568
+ total_net_mint_sc: unitsToSc(totalUnits),
569
+ total_net_mint_units: totalUnits,
570
+ };
571
+ }
572
+ /**
573
+ * Incrementally settles calculated Swarm Credit issuance for a workspace into the immutable double-entry ledger.
574
+ * Uses `sc_mint_claims` so re-running settlement only mints newly accrued delta (idempotent; never double-mints).
575
+ * Private or zero-sum workspaces settle 0 SC cleanly.
576
+ */
577
+ export function settleWorkspaceSwarmCredits(db, workspaceId, opts = {}) {
578
+ const ts = opts.now ?? nowIso();
579
+ const report = computeSwarmCreditIssuance(db, { ...opts, workspaceId, now: ts });
580
+ const resolvedWsId = report.scope_workspace_id ?? workspaceId;
581
+ if (!report.eligible_workspaces.includes(resolvedWsId)) {
582
+ return {
583
+ settled_at: ts,
584
+ workspace_id: resolvedWsId,
585
+ total_newly_minted_units: 0,
586
+ total_newly_minted_sc: 0,
587
+ items: [],
588
+ };
589
+ }
590
+ const scopeKey = `ws:${resolvedWsId}`;
591
+ const items = [];
592
+ let totalNewUnits = 0;
593
+ for (const op of report.operators) {
594
+ ensureOperatorAccount(db, op.operator_id, { now: ts });
595
+ const claimRow = db
596
+ .prepare('SELECT minted_units_total FROM sc_mint_claims WHERE operator_id = ? AND scope_key = ?')
597
+ .get(op.operator_id, scopeKey);
598
+ const previouslyMinted = Number(claimRow?.minted_units_total ?? 0);
599
+ const deltaUnits = Math.max(0, op.net_mint_units - previouslyMinted);
600
+ if (deltaUnits <= 0) {
601
+ items.push({
602
+ operator_id: op.operator_id,
603
+ workspace_id: resolvedWsId,
604
+ target_units: op.net_mint_units,
605
+ previously_minted_units: previouslyMinted,
606
+ newly_minted_units: 0,
607
+ newly_minted_sc: 0,
608
+ entry_id: null,
609
+ });
610
+ continue;
611
+ }
612
+ const entry = mintSwarmCredits(db, {
613
+ operatorId: op.operator_id,
614
+ amountUnits: deltaUnits,
615
+ workspaceId: resolvedWsId,
616
+ referenceType: 'sc_issuance_settlement',
617
+ referenceId: opts.epochId ?? ts,
618
+ memo: `Downstream-utility SC settlement in ${resolvedWsId} (+${unitsToSc(deltaUnits)} SC)`,
619
+ metadata: {
620
+ base_sc: op.base_sc,
621
+ downstream_reuse_sc: op.downstream_reuse_sc,
622
+ dead_end_sc: op.dead_end_sc,
623
+ audit_defect_sc: op.audit_defect_sc,
624
+ slop_penalty_sc: op.slop_penalty_sc,
625
+ tau: op.trust.tau,
626
+ },
627
+ idempotencyKey: `settle:${resolvedWsId}:${op.operator_id}:${op.net_mint_units}`,
628
+ now: ts,
629
+ requireAuditedWorkspace: opts.requireAuditedWorkspace,
630
+ });
631
+ const nextTotal = previouslyMinted + deltaUnits;
632
+ db.prepare(`
633
+ INSERT INTO sc_mint_claims (operator_id, scope_key, minted_units_total, last_entry_id, updated_at)
634
+ VALUES (?, ?, ?, ?, ?)
635
+ ON CONFLICT(operator_id, scope_key) DO UPDATE SET
636
+ minted_units_total = excluded.minted_units_total,
637
+ last_entry_id = excluded.last_entry_id,
638
+ updated_at = excluded.updated_at
639
+ `).run(op.operator_id, scopeKey, nextTotal, entry.id, ts);
640
+ totalNewUnits += deltaUnits;
641
+ items.push({
642
+ operator_id: op.operator_id,
643
+ workspace_id: resolvedWsId,
644
+ target_units: op.net_mint_units,
645
+ previously_minted_units: previouslyMinted,
646
+ newly_minted_units: deltaUnits,
647
+ newly_minted_sc: unitsToSc(deltaUnits),
648
+ entry_id: entry.id,
649
+ });
650
+ }
651
+ return {
652
+ settled_at: ts,
653
+ workspace_id: resolvedWsId,
654
+ total_newly_minted_units: totalNewUnits,
655
+ total_newly_minted_sc: unitsToSc(totalNewUnits),
656
+ items,
657
+ };
658
+ }
659
+ //# sourceMappingURL=scMinting.js.map