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.
Files changed (203) hide show
  1. package/README.math-mvp.md +28 -0
  2. package/README.md +37 -2
  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 +18 -0
  34. package/dist/auth/agentAuth.js +59 -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 +10 -0
  52. package/dist/cli/caissonCli.js +471 -0
  53. package/dist/cli/caissonCli.js.map +1 -0
  54. package/dist/cli/inviteCard.d.ts +12 -0
  55. package/dist/cli/inviteCard.js +49 -0
  56. package/dist/cli/inviteCard.js.map +1 -0
  57. package/dist/cli/mcpProxy.d.ts +36 -0
  58. package/dist/cli/mcpProxy.js +292 -0
  59. package/dist/cli/mcpProxy.js.map +1 -0
  60. package/dist/config.d.ts +19 -0
  61. package/dist/config.js +28 -0
  62. package/dist/config.js.map +1 -0
  63. package/dist/db/adapter.d.ts +210 -0
  64. package/dist/db/adapter.js +769 -0
  65. package/dist/db/adapter.js.map +1 -0
  66. package/dist/db/sqlite.d.ts +7 -0
  67. package/dist/db/sqlite.js +60 -0
  68. package/dist/db/sqlite.js.map +1 -0
  69. package/dist/db/telemetry.d.ts +11 -0
  70. package/dist/db/telemetry.js +9 -0
  71. package/dist/db/telemetry.js.map +1 -0
  72. package/dist/economy/bountyEngine.d.ts +248 -0
  73. package/dist/economy/bountyEngine.js +836 -0
  74. package/dist/economy/bountyEngine.js.map +1 -0
  75. package/dist/economy/index.d.ts +5 -0
  76. package/dist/economy/index.js +6 -0
  77. package/dist/economy/index.js.map +1 -0
  78. package/dist/economy/scLedger.d.ts +183 -0
  79. package/dist/economy/scLedger.js +528 -0
  80. package/dist/economy/scLedger.js.map +1 -0
  81. package/dist/economy/scMinting.d.ts +177 -0
  82. package/dist/economy/scMinting.js +659 -0
  83. package/dist/economy/scMinting.js.map +1 -0
  84. package/dist/economy/scSinks.d.ts +135 -0
  85. package/dist/economy/scSinks.js +314 -0
  86. package/dist/economy/scSinks.js.map +1 -0
  87. package/dist/economy/usdLedger.d.ts +211 -0
  88. package/dist/economy/usdLedger.js +604 -0
  89. package/dist/economy/usdLedger.js.map +1 -0
  90. package/dist/mcp/handlers.d.ts +134 -0
  91. package/dist/mcp/handlers.js +781 -0
  92. package/dist/mcp/handlers.js.map +1 -0
  93. package/dist/mcp/httpServer.d.ts +25 -0
  94. package/dist/mcp/httpServer.js +368 -0
  95. package/dist/mcp/httpServer.js.map +1 -0
  96. package/dist/mcp/serverFactory.d.ts +4 -0
  97. package/dist/mcp/serverFactory.js +53 -0
  98. package/dist/mcp/serverFactory.js.map +1 -0
  99. package/dist/mcp/stdioServer.d.ts +2 -0
  100. package/dist/mcp/stdioServer.js +24 -0
  101. package/dist/mcp/stdioServer.js.map +1 -0
  102. package/dist/mcp/toolMetadata.d.ts +15 -0
  103. package/dist/mcp/toolMetadata.js +73 -0
  104. package/dist/mcp/toolMetadata.js.map +1 -0
  105. package/dist/memo/artifactIndex.d.ts +51 -0
  106. package/dist/memo/artifactIndex.js +162 -0
  107. package/dist/memo/artifactIndex.js.map +1 -0
  108. package/dist/memo/dependencyBundle.d.ts +33 -0
  109. package/dist/memo/dependencyBundle.js +86 -0
  110. package/dist/memo/dependencyBundle.js.map +1 -0
  111. package/dist/memo/embeddings.d.ts +110 -0
  112. package/dist/memo/embeddings.js +672 -0
  113. package/dist/memo/embeddings.js.map +1 -0
  114. package/dist/packs/foundryEvm.d.ts +21 -0
  115. package/dist/packs/foundryEvm.js +274 -0
  116. package/dist/packs/foundryEvm.js.map +1 -0
  117. package/dist/packs/index.d.ts +8 -0
  118. package/dist/packs/index.js +19 -0
  119. package/dist/packs/index.js.map +1 -0
  120. package/dist/packs/mathLean4.d.ts +7 -0
  121. package/dist/packs/mathLean4.js +145 -0
  122. package/dist/packs/mathLean4.js.map +1 -0
  123. package/dist/packs/rustKani.d.ts +17 -0
  124. package/dist/packs/rustKani.js +257 -0
  125. package/dist/packs/rustKani.js.map +1 -0
  126. package/dist/packs/sdk.d.ts +314 -0
  127. package/dist/packs/sdk.js +271 -0
  128. package/dist/packs/sdk.js.map +1 -0
  129. package/dist/preflight/leanTripwire.d.ts +19 -0
  130. package/dist/preflight/leanTripwire.js +105 -0
  131. package/dist/preflight/leanTripwire.js.map +1 -0
  132. package/dist/storage/blobStore.d.ts +11 -0
  133. package/dist/storage/blobStore.js +39 -0
  134. package/dist/storage/blobStore.js.map +1 -0
  135. package/dist/storage/gitStore.d.ts +68 -0
  136. package/dist/storage/gitStore.js +228 -0
  137. package/dist/storage/gitStore.js.map +1 -0
  138. package/dist/types/errors.d.ts +16 -0
  139. package/dist/types/errors.js +23 -0
  140. package/dist/types/errors.js.map +1 -0
  141. package/dist/types/schemas.d.ts +453 -0
  142. package/dist/types/schemas.js +197 -0
  143. package/dist/types/schemas.js.map +1 -0
  144. package/dist/web/discoveryRoutes.d.ts +20 -0
  145. package/dist/web/discoveryRoutes.js +456 -0
  146. package/dist/web/discoveryRoutes.js.map +1 -0
  147. package/dist/web/explorer/dagLayout.d.ts +41 -0
  148. package/dist/web/explorer/dagLayout.js +183 -0
  149. package/dist/web/explorer/dagLayout.js.map +1 -0
  150. package/dist/web/explorer/index.d.ts +45 -0
  151. package/dist/web/explorer/index.js +512 -0
  152. package/dist/web/explorer/index.js.map +1 -0
  153. package/dist/web/explorer/renderers.d.ts +35 -0
  154. package/dist/web/explorer/renderers.js +397 -0
  155. package/dist/web/explorer/renderers.js.map +1 -0
  156. package/dist/web/repoBrowser.d.ts +19 -0
  157. package/dist/web/repoBrowser.js +128 -0
  158. package/dist/web/repoBrowser.js.map +1 -0
  159. package/dist/worker/executionAdapter.d.ts +14 -0
  160. package/dist/worker/executionAdapter.js +162 -0
  161. package/dist/worker/executionAdapter.js.map +1 -0
  162. package/dist/worker/finalize.d.ts +21 -0
  163. package/dist/worker/finalize.js +146 -0
  164. package/dist/worker/finalize.js.map +1 -0
  165. package/dist/worker/firecrackerAdapter.d.ts +180 -0
  166. package/dist/worker/firecrackerAdapter.js +421 -0
  167. package/dist/worker/firecrackerAdapter.js.map +1 -0
  168. package/dist/worker/loop.d.ts +56 -0
  169. package/dist/worker/loop.js +239 -0
  170. package/dist/worker/loop.js.map +1 -0
  171. package/dist/worker/postMergeSync.d.ts +17 -0
  172. package/dist/worker/postMergeSync.js +52 -0
  173. package/dist/worker/postMergeSync.js.map +1 -0
  174. package/dist/worker/prepareInput.d.ts +41 -0
  175. package/dist/worker/prepareInput.js +130 -0
  176. package/dist/worker/prepareInput.js.map +1 -0
  177. package/dist/worker/queue.d.ts +83 -0
  178. package/dist/worker/queue.js +278 -0
  179. package/dist/worker/queue.js.map +1 -0
  180. package/dist/worker/sandbox.d.ts +2 -0
  181. package/dist/worker/sandbox.js +3 -0
  182. package/dist/worker/sandbox.js.map +1 -0
  183. package/dist/worker/webhook.d.ts +14 -0
  184. package/dist/worker/webhook.js +110 -0
  185. package/dist/worker/webhook.js.map +1 -0
  186. package/migrations/001_init.sql +193 -0
  187. package/migrations/002_epic3_scale.sql +34 -0
  188. package/migrations/003_swarm_credits.sql +153 -0
  189. package/migrations/004_usd_bounties.sql +216 -0
  190. package/migrations_pg/001_init.sql +229 -0
  191. package/migrations_pg/002_multitenant_rls.sql +63 -0
  192. package/migrations_pg/003_swarm_credits.sql +135 -0
  193. package/migrations_pg/004_usd_bounties.sql +201 -0
  194. package/package.json +55 -4
  195. package/packs/foundry-evm/pack.json +60 -0
  196. package/packs/foundry-evm/verifier/Dockerfile +9 -0
  197. package/packs/foundry-evm/verifier/run.py +160 -0
  198. package/packs/math-lean4/pack.json +68 -0
  199. package/packs/rust-kani/pack.json +53 -0
  200. package/packs/rust-kani/verifier/Dockerfile +7 -0
  201. package/packs/rust-kani/verifier/run.py +159 -0
  202. package/public/.well-known/agent-card.json +153 -0
  203. package/public/llms.txt +35 -0
@@ -0,0 +1,837 @@
1
+ // src/analytics/metrics.ts
2
+ // Phase 0 Pilot Exit-Gate Scorecard, Full Metric Catalog, Swarm Sprint Leaderboard S(o),
3
+ // and Automated Token-Savings Report (Doc 05 §4 & Doc 07 §5.2, E2-3).
4
+ import { nowIso } from '../db/sqlite.js';
5
+ import { scanLeanStaticTripwire } from '../preflight/leanTripwire.js';
6
+ const ALLOWED_LEAN_AXIOMS = new Set(['propext', 'Classical.choice', 'Quot.sound']);
7
+ const OPEN_WEIGHT_MODEL_RX = /(qwen|deepseek|llama|mistral|mixtral|gemma|phi-|yi-|command-r|olmo|open[-_]?weight)/i;
8
+ function safeJsonParse(raw, fallback) {
9
+ if (!raw)
10
+ return fallback;
11
+ try {
12
+ return JSON.parse(raw);
13
+ }
14
+ catch {
15
+ return fallback;
16
+ }
17
+ }
18
+ function median(values) {
19
+ if (values.length === 0)
20
+ return null;
21
+ const sorted = [...values].sort((a, b) => a - b);
22
+ const mid = Math.floor(sorted.length / 2);
23
+ return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
24
+ }
25
+ function percentile(values, p) {
26
+ if (values.length === 0)
27
+ return null;
28
+ if (p === 0.5)
29
+ return median(values);
30
+ const sorted = [...values].sort((a, b) => a - b);
31
+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1));
32
+ return sorted[idx];
33
+ }
34
+ function round2(n) {
35
+ return Math.round(n * 100) / 100;
36
+ }
37
+ function round4(n) {
38
+ return Math.round(n * 10_000) / 10_000;
39
+ }
40
+ function resolveOptionalWorkspaceId(db, idOrSlug) {
41
+ if (!idOrSlug)
42
+ return null;
43
+ const row = db
44
+ .prepare('SELECT id FROM workspaces WHERE id = ? OR slug = ?')
45
+ .get(idOrSlug, idOrSlug);
46
+ return row?.id ?? idOrSlug;
47
+ }
48
+ /**
49
+ * Computes the complete Phase 0 Exit-Gate Scorecard, Metric Catalog, Token-Savings Report,
50
+ * and Swarm Sprint Leaderboard S(o) (strictly excluding self-citations).
51
+ */
52
+ export function computePilotReport(db, opts = {}) {
53
+ const generatedAt = opts.now ?? nowIso();
54
+ const scopeWsId = resolveOptionalWorkspaceId(db, opts.workspaceId);
55
+ const baselineWsId = resolveOptionalWorkspaceId(db, opts.baselineWorkspaceId);
56
+ const computeUsdPerSec = opts.computeUsdPerSecond ??
57
+ Number(process.env.CAISSON_COMPUTE_USD_PER_SEC ?? '0.00055');
58
+ const excludedOps = new Set(opts.excludeOperatorIds ?? []);
59
+ // Load agent -> operator directory
60
+ const agents = db.prepare('SELECT * FROM agent_identities').all();
61
+ const agentById = new Map();
62
+ const internalAgentIds = new Set();
63
+ const operatorDisplayNames = new Map();
64
+ const operatorOpenWeight = new Map();
65
+ for (const ag of agents) {
66
+ agentById.set(ag.id, ag);
67
+ if (ag.rate_limit_tier === 'internal') {
68
+ internalAgentIds.add(ag.id);
69
+ }
70
+ const names = operatorDisplayNames.get(ag.operator_id) ?? new Set();
71
+ names.add(ag.display_name);
72
+ operatorDisplayNames.set(ag.operator_id, names);
73
+ const meta = safeJsonParse(ag.model_metadata, {});
74
+ const metaStr = JSON.stringify(meta);
75
+ if (meta.open_weight === true || OPEN_WEIGHT_MODEL_RX.test(metaStr)) {
76
+ operatorOpenWeight.set(ag.operator_id, true);
77
+ }
78
+ }
79
+ const workspaces = db.prepare('SELECT * FROM workspaces').all();
80
+ const wsById = new Map(workspaces.map((w) => [w.id, w]));
81
+ // ---------------------------------------------------------------------------
82
+ // GATE 1: Voluntary Organic Reuse (>= 3 distinct teams in >= 2 workspaces)
83
+ // ---------------------------------------------------------------------------
84
+ const operatorWorkspaces = new Map();
85
+ for (const ws of workspaces) {
86
+ if (!excludedOps.has(ws.owner_operator_id)) {
87
+ const set = operatorWorkspaces.get(ws.owner_operator_id) ?? new Set();
88
+ set.add(ws.id);
89
+ operatorWorkspaces.set(ws.owner_operator_id, set);
90
+ }
91
+ }
92
+ const memberRows = db
93
+ .prepare(`
94
+ SELECT wm.workspace_id, a.operator_id, a.rate_limit_tier
95
+ FROM workspace_members wm
96
+ JOIN agent_identities a ON a.id = wm.agent_id
97
+ `)
98
+ .all();
99
+ for (const m of memberRows) {
100
+ if (m.rate_limit_tier === 'internal' || excludedOps.has(m.operator_id))
101
+ continue;
102
+ const set = operatorWorkspaces.get(m.operator_id) ?? new Set();
103
+ set.add(m.workspace_id);
104
+ operatorWorkspaces.set(m.operator_id, set);
105
+ }
106
+ const qualifyingReuseTeams = Array.from(operatorWorkspaces.entries())
107
+ .filter(([, wsSet]) => wsSet.size >= 2)
108
+ .map(([operator_id, wsSet]) => ({ operator_id, workspaces: Array.from(wsSet).sort() }))
109
+ .sort((a, b) => b.workspaces.length - a.workspaces.length || a.operator_id.localeCompare(b.operator_id));
110
+ const gate1 = {
111
+ id: 1,
112
+ name: 'Voluntary Organic Reuse',
113
+ status: qualifyingReuseTeams.length >= 3 ? 'pass' : 'fail',
114
+ threshold: '>= 3 distinct teams in >= 2 workspaces',
115
+ actual: `${qualifyingReuseTeams.length} distinct team(s)`,
116
+ details: {
117
+ qualifying_teams: qualifyingReuseTeams,
118
+ total_active_teams: operatorWorkspaces.size,
119
+ },
120
+ };
121
+ // Load scoped nodes, edges, artifacts, lineage, runs, events
122
+ const wsWhere = scopeWsId ? 'WHERE workspace_id = ?' : '';
123
+ const wsParams = scopeWsId ? [scopeWsId] : [];
124
+ const nodes = db.prepare(`SELECT * FROM nodes ${wsWhere}`).all(...wsParams);
125
+ const nodeById = new Map(nodes.map((n) => [n.id, n]));
126
+ const edges = db.prepare(`SELECT * FROM node_edges ${wsWhere}`).all(...wsParams);
127
+ const dependsParentsByNode = new Map();
128
+ const dependsChildrenByNode = new Map();
129
+ for (const e of edges) {
130
+ if (e.edge_type === 'depends_on') {
131
+ const pSet = dependsParentsByNode.get(e.child_node_id) ?? new Set();
132
+ pSet.add(e.parent_node_id);
133
+ dependsParentsByNode.set(e.child_node_id, pSet);
134
+ const cSet = dependsChildrenByNode.get(e.parent_node_id) ?? new Set();
135
+ cSet.add(e.child_node_id);
136
+ dependsChildrenByNode.set(e.parent_node_id, cSet);
137
+ }
138
+ }
139
+ const artifacts = db.prepare(`SELECT * FROM artifacts ${wsWhere}`).all(...wsParams);
140
+ const artifactById = new Map(artifacts.map((a) => [a.id, a]));
141
+ const verifiedArtifacts = artifacts.filter((a) => a.artifact_type !== 'dead_end');
142
+ const deadEndArtifacts = artifacts.filter((a) => a.artifact_type === 'dead_end');
143
+ const lineageRows = db.prepare('SELECT artifact_id, parent_artifact_id FROM artifact_lineage').all();
144
+ const parentsOfArt = new Map();
145
+ const childrenOfArt = new Map();
146
+ for (const l of lineageRows) {
147
+ if (!artifactById.has(l.artifact_id) || !artifactById.has(l.parent_artifact_id))
148
+ continue;
149
+ const pList = parentsOfArt.get(l.artifact_id) ?? [];
150
+ pList.push(l.parent_artifact_id);
151
+ parentsOfArt.set(l.artifact_id, pList);
152
+ const cList = childrenOfArt.get(l.parent_artifact_id) ?? [];
153
+ cList.push(l.artifact_id);
154
+ childrenOfArt.set(l.parent_artifact_id, cList);
155
+ }
156
+ // ---------------------------------------------------------------------------
157
+ // GATE 2: True Multi-Owner Closure (>= 3 sub-problems, >= 5 chained lemmas, >= 2 operators)
158
+ // ---------------------------------------------------------------------------
159
+ const verifiedArtIds = new Set(verifiedArtifacts.map((a) => a.id));
160
+ const terminalVerified = verifiedArtifacts.filter((a) => {
161
+ const kids = (childrenOfArt.get(a.id) ?? []).filter((cid) => verifiedArtIds.has(cid));
162
+ return kids.length === 0;
163
+ });
164
+ const qualifyingSubproblems = [];
165
+ for (const rootArt of terminalVerified) {
166
+ const visited = new Set([rootArt.id]);
167
+ const queue = [rootArt.id];
168
+ while (queue.length > 0) {
169
+ const curr = queue.shift();
170
+ for (const pId of parentsOfArt.get(curr) ?? []) {
171
+ if (verifiedArtIds.has(pId) && !visited.has(pId)) {
172
+ visited.add(pId);
173
+ queue.push(pId);
174
+ }
175
+ }
176
+ }
177
+ const ops = new Set();
178
+ for (const id of visited) {
179
+ const art = artifactById.get(id);
180
+ const ag = art ? agentById.get(art.author_agent_id) : null;
181
+ if (ag?.operator_id)
182
+ ops.add(ag.operator_id);
183
+ }
184
+ if (visited.size >= 5 && ops.size >= 2) {
185
+ qualifyingSubproblems.push({
186
+ root_artifact_id: rootArt.id,
187
+ workspace_id: rootArt.workspace_id,
188
+ chain_size: visited.size,
189
+ distinct_operators: Array.from(ops).sort(),
190
+ });
191
+ }
192
+ }
193
+ const gate2 = {
194
+ id: 2,
195
+ name: 'True Multi-Owner Closure',
196
+ status: qualifyingSubproblems.length >= 3 ? 'pass' : 'fail',
197
+ threshold: '>= 3 sub-problems (>= 5 chained lemmas, >= 2 distinct operators)',
198
+ actual: `${qualifyingSubproblems.length} qualifying sub-problem(s)`,
199
+ details: {
200
+ qualifying_subproblems: qualifyingSubproblems,
201
+ },
202
+ };
203
+ // Load verification runs & MCP tool events
204
+ const runsQuery = scopeWsId && baselineWsId && scopeWsId !== baselineWsId
205
+ ? 'SELECT * FROM verification_runs WHERE workspace_id IN (?, ?)'
206
+ : scopeWsId
207
+ ? 'SELECT * FROM verification_runs WHERE workspace_id = ?'
208
+ : 'SELECT * FROM verification_runs';
209
+ const runsParams = scopeWsId && baselineWsId && scopeWsId !== baselineWsId
210
+ ? [scopeWsId, baselineWsId]
211
+ : scopeWsId
212
+ ? [scopeWsId]
213
+ : [];
214
+ const allRuns = db.prepare(runsQuery).all(...runsParams);
215
+ const scopedRuns = scopeWsId ? allRuns.filter((r) => r.workspace_id === scopeWsId) : allRuns;
216
+ const passedScopedRuns = scopedRuns.filter((r) => r.status === 'pass');
217
+ const events = db.prepare(`SELECT * FROM mcp_tool_events ${wsWhere}`).all(...wsParams);
218
+ // ---------------------------------------------------------------------------
219
+ // GATE 3: Measurable Efficiency Gain (>= 20% reduction in tokens or attempts vs solo)
220
+ // ---------------------------------------------------------------------------
221
+ const soloTokens = [];
222
+ const swarmTokens = [];
223
+ const soloAttempts = [];
224
+ const swarmAttempts = [];
225
+ let totalCacheHitsReported = 0;
226
+ let totalDeadEndsConsultedReported = 0;
227
+ for (const r of allRuns) {
228
+ if (r.status !== 'pass')
229
+ continue;
230
+ const precheck = safeJsonParse(r.precheck_proof, {});
231
+ const tel = precheck?.client_telemetry ?? {};
232
+ const payloadMeta = safeJsonParse(r.payload_meta, {});
233
+ const derivedFrom = Array.isArray(payloadMeta.derived_from) ? payloadMeta.derived_from : [];
234
+ const cacheHits = Array.isArray(tel.cache_hits_used) ? tel.cache_hits_used : [];
235
+ const deadEndsConsulted = Array.isArray(tel.dead_ends_consulted) ? tel.dead_ends_consulted : [];
236
+ totalCacheHitsReported += cacheHits.length;
237
+ totalDeadEndsConsultedReported += deadEndsConsulted.length;
238
+ const hasTokenSample = typeof tel.estimated_input_tokens === 'number' || typeof tel.estimated_output_tokens === 'number';
239
+ const tokenTotal = (typeof tel.estimated_input_tokens === 'number' ? tel.estimated_input_tokens : 0) +
240
+ (typeof tel.estimated_output_tokens === 'number' ? tel.estimated_output_tokens : 0);
241
+ const hasAttemptSample = typeof tel.local_compile_attempts === 'number';
242
+ let cohort;
243
+ if (baselineWsId) {
244
+ cohort = r.workspace_id === baselineWsId ? 'solo' : 'swarm';
245
+ }
246
+ else if (tel.cohort === 'solo' || tel.cohort === 'baseline') {
247
+ cohort = 'solo';
248
+ }
249
+ else if (tel.cohort === 'swarm') {
250
+ cohort = 'swarm';
251
+ }
252
+ else {
253
+ cohort =
254
+ derivedFrom.length > 0 || cacheHits.length > 0 || deadEndsConsulted.length > 0
255
+ ? 'swarm'
256
+ : 'solo';
257
+ }
258
+ if (hasTokenSample) {
259
+ if (cohort === 'solo')
260
+ soloTokens.push(tokenTotal);
261
+ else
262
+ swarmTokens.push(tokenTotal);
263
+ }
264
+ if (hasAttemptSample) {
265
+ if (cohort === 'solo')
266
+ soloAttempts.push(tel.local_compile_attempts);
267
+ else
268
+ swarmAttempts.push(tel.local_compile_attempts);
269
+ }
270
+ }
271
+ const soloMedianTokens = median(soloTokens);
272
+ const swarmMedianTokens = median(swarmTokens);
273
+ const tokenReductionPct = soloMedianTokens !== null && soloMedianTokens > 0 && swarmMedianTokens !== null
274
+ ? round2(((soloMedianTokens - swarmMedianTokens) / soloMedianTokens) * 100)
275
+ : null;
276
+ const soloMedianAttempts = median(soloAttempts);
277
+ const swarmMedianAttempts = median(swarmAttempts);
278
+ const attemptReductionPct = soloMedianAttempts !== null && soloMedianAttempts > 0 && swarmMedianAttempts !== null
279
+ ? round2(((soloMedianAttempts - swarmMedianAttempts) / soloMedianAttempts) * 100)
280
+ : null;
281
+ const estimatedTotalTokensSaved = soloMedianTokens !== null && swarmMedianTokens !== null
282
+ ? Math.max(0, Math.round((soloMedianTokens - swarmMedianTokens) * swarmTokens.length))
283
+ : 0;
284
+ const tokenSavings = {
285
+ solo_runs_with_tokens: soloTokens.length,
286
+ swarm_runs_with_tokens: swarmTokens.length,
287
+ solo_median_tokens: soloMedianTokens !== null ? round2(soloMedianTokens) : null,
288
+ swarm_median_tokens: swarmMedianTokens !== null ? round2(swarmMedianTokens) : null,
289
+ token_reduction_pct: tokenReductionPct,
290
+ estimated_total_tokens_saved: estimatedTotalTokensSaved,
291
+ solo_runs_with_attempts: soloAttempts.length,
292
+ swarm_runs_with_attempts: swarmAttempts.length,
293
+ solo_median_attempts: soloMedianAttempts !== null ? round2(soloMedianAttempts) : null,
294
+ swarm_median_attempts: swarmMedianAttempts !== null ? round2(swarmMedianAttempts) : null,
295
+ attempt_reduction_pct: attemptReductionPct,
296
+ total_cache_hits_reported: totalCacheHitsReported,
297
+ total_dead_ends_consulted_reported: totalDeadEndsConsultedReported,
298
+ };
299
+ let gate3Status;
300
+ if (tokenReductionPct === null && attemptReductionPct === null) {
301
+ gate3Status = 'insufficient_data';
302
+ }
303
+ else if ((tokenReductionPct !== null && tokenReductionPct >= 20) ||
304
+ (attemptReductionPct !== null && attemptReductionPct >= 20)) {
305
+ gate3Status = 'pass';
306
+ }
307
+ else {
308
+ gate3Status = 'fail';
309
+ }
310
+ const gate3 = {
311
+ id: 3,
312
+ name: 'Measurable Efficiency Gain',
313
+ status: gate3Status,
314
+ threshold: '>= 20% reduction in tokens or compile attempts vs. solo baseline',
315
+ actual: tokenReductionPct !== null || attemptReductionPct !== null
316
+ ? `tokens: ${tokenReductionPct !== null ? `${tokenReductionPct}%` : 'n/a'}, attempts: ${attemptReductionPct !== null ? `${attemptReductionPct}%` : 'n/a'}`
317
+ : 'insufficient telemetry',
318
+ details: { ...tokenSavings },
319
+ };
320
+ // ---------------------------------------------------------------------------
321
+ // GATE 4: Zero-Slop Soundness (0 merges with sorry, disallowed axioms, or bypasses)
322
+ // ---------------------------------------------------------------------------
323
+ const soundnessViolations = [];
324
+ for (const art of verifiedArtifacts) {
325
+ const node = nodeById.get(art.source_node_id);
326
+ const ws = wsById.get(art.workspace_id);
327
+ const verifierCfg = safeJsonParse(ws?.verifier_config, {});
328
+ const envLockCfg = verifierCfg?.environment_lock ?? {};
329
+ if (node?.verifier_result) {
330
+ const vr = safeJsonParse(node.verifier_result, {});
331
+ if (vr.status && vr.status !== 'pass') {
332
+ soundnessViolations.push({
333
+ artifact_id: art.id,
334
+ node_id: art.source_node_id,
335
+ reason: `Verified artifact's node has non-pass verifier status '${vr.status}'`,
336
+ });
337
+ }
338
+ const metrics = vr.metrics ?? {};
339
+ if (metrics.statement_equivalent === false) {
340
+ soundnessViolations.push({
341
+ artifact_id: art.id,
342
+ node_id: art.source_node_id,
343
+ reason: 'Statement equivalence check failed',
344
+ });
345
+ }
346
+ const axioms = Array.isArray(metrics.axioms)
347
+ ? metrics.axioms
348
+ : Array.isArray(metrics.disallowed_axioms)
349
+ ? metrics.disallowed_axioms
350
+ : [];
351
+ const badAxioms = axioms
352
+ .map(String)
353
+ .filter((ax) => !ALLOWED_LEAN_AXIOMS.has(ax));
354
+ if (badAxioms.length > 0) {
355
+ soundnessViolations.push({
356
+ artifact_id: art.id,
357
+ node_id: art.source_node_id,
358
+ reason: `Disallowed kernel axioms: ${badAxioms.join(', ')}`,
359
+ });
360
+ }
361
+ }
362
+ // Static tripwire check on committed Lean payload (live Git if provided, else payload_preview)
363
+ const isLean = art.payload_uri.endsWith('.lean') ||
364
+ Boolean(ws?.domain_pack_ref?.startsWith('math-lean4') && art.artifact_type === 'lemma');
365
+ if (isLean) {
366
+ let leanSrc = null;
367
+ if (opts.git && ws && node?.payload_ref) {
368
+ leanSrc = opts.git.readFileAtCommit(ws.git_repo_uri, ws.git_head_sha, node.payload_ref);
369
+ }
370
+ if (leanSrc === null) {
371
+ leanSrc = String(art.payload_preview ?? '');
372
+ }
373
+ const scan = scanLeanStaticTripwire(leanSrc, {
374
+ allowNativeDecide: Boolean(envLockCfg.allow_native_decide),
375
+ allowBvDecide: Boolean(envLockCfg.allow_bv_decide),
376
+ });
377
+ if (!scan.ok) {
378
+ soundnessViolations.push({
379
+ artifact_id: art.id,
380
+ node_id: art.source_node_id,
381
+ reason: `Lean static tripwire violation: ${scan.rule} at line ${scan.line}`,
382
+ });
383
+ }
384
+ }
385
+ }
386
+ const gate4 = {
387
+ id: 4,
388
+ name: 'Zero-Slop Soundness',
389
+ status: soundnessViolations.length === 0 ? 'pass' : 'fail',
390
+ threshold: '0 merges with sorry, disallowed axioms, or statement-weakening bypasses',
391
+ actual: `${soundnessViolations.length} violation(s) across ${verifiedArtifacts.length} verified artifact(s)`,
392
+ details: {
393
+ verified_artifacts_checked: verifiedArtifacts.length,
394
+ violations: soundnessViolations,
395
+ },
396
+ };
397
+ // ---------------------------------------------------------------------------
398
+ // GATE 5: Sustainable Sandbox Economics (< $0.15 median compute cost per verified lemma)
399
+ // ---------------------------------------------------------------------------
400
+ const computeMsValues = passedScopedRuns
401
+ .map((r) => r.compute_ms)
402
+ .filter((ms) => typeof ms === 'number' && ms >= 0);
403
+ const costsUsd = computeMsValues.map((ms) => (ms / 1000) * computeUsdPerSec);
404
+ const medianCostUsd = median(costsUsd);
405
+ const totalCostUsd = costsUsd.reduce((sum, c) => sum + c, 0);
406
+ const gate5 = {
407
+ id: 5,
408
+ name: 'Sustainable Sandbox Economics',
409
+ status: medianCostUsd === null
410
+ ? 'insufficient_data'
411
+ : medianCostUsd < 0.15
412
+ ? 'pass'
413
+ : 'fail',
414
+ threshold: '< $0.15 median server verification cost per verified lemma',
415
+ actual: medianCostUsd !== null ? `$${round4(medianCostUsd)} median` : 'no completed verification runs',
416
+ details: {
417
+ passed_runs_measured: computeMsValues.length,
418
+ median_cost_usd: medianCostUsd !== null ? round4(medianCostUsd) : null,
419
+ mean_cost_usd: costsUsd.length > 0 ? round4(totalCostUsd / costsUsd.length) : null,
420
+ total_cost_usd: round4(totalCostUsd),
421
+ compute_usd_per_sec: computeUsdPerSec,
422
+ },
423
+ };
424
+ const exitGates = [gate1, gate2, gate3, gate4, gate5];
425
+ // ---------------------------------------------------------------------------
426
+ // FULL PHASE 0 METRIC CATALOG (Doc 05 §4.2)
427
+ // ---------------------------------------------------------------------------
428
+ const verifiedLemmas = verifiedArtifacts.filter((a) => a.artifact_type === 'lemma' || nodeById.get(a.source_node_id)?.type === 'Lemma');
429
+ let verifiedLemmasPerWeek = verifiedLemmas.length;
430
+ if (verifiedLemmas.length > 0) {
431
+ const timestamps = verifiedLemmas.map((a) => Date.parse(a.created_at)).filter((t) => Number.isFinite(t));
432
+ if (timestamps.length >= 2) {
433
+ const spanWeeks = Math.max(1, (Math.max(...timestamps) - Math.min(...timestamps)) / (7 * 86_400_000));
434
+ verifiedLemmasPerWeek = round2(verifiedLemmas.length / spanWeeks);
435
+ }
436
+ }
437
+ const leaseAcquires = events.filter((e) => e.tool_name === 'claim_node' && e.outcome_code === 'OK').length;
438
+ const leaseConflicts = events.filter((e) => e.tool_name === 'claim_node' && e.outcome_code === 'LEASE_CONFLICT').length;
439
+ const leaseExpiredEvents = events.filter((e) => e.tool_name === 'claim_node' && e.outcome_code === 'LEASE_EXPIRED').length;
440
+ const currentlyExpiredNodes = nodes.filter((n) => n.status === 'claimed' && n.claim_expires_at && n.claim_expires_at < generatedAt).length;
441
+ const totalLeaseTimeouts = leaseExpiredEvents + currentlyExpiredNodes;
442
+ // Dead-end peer exposure tracking (used for both Metric Catalog & Leaderboard C_ext(d))
443
+ const deadEndById = new Map(deadEndArtifacts.map((d) => [d.id, d]));
444
+ // Track earliest peer exposure per (deadEndId -> operator_id -> earliest_exposed_ts)
445
+ const deadEndExposureTime = new Map();
446
+ // Track latest claim/submit timestamp per (workspace_id, operator_id) to ensure exposure was PRIOR to claiming/closing
447
+ const operatorLatestActionByWs = new Map();
448
+ for (const ev of events) {
449
+ const ag = agentById.get(ev.agent_id);
450
+ if (!ag)
451
+ continue;
452
+ if ((ev.tool_name === 'claim_node' || ev.tool_name === 'submit_artifact') && ev.workspace_id) {
453
+ const key = `${ev.workspace_id}:${ag.operator_id}`;
454
+ const prev = operatorLatestActionByWs.get(key);
455
+ if (!prev || ev.created_at > prev) {
456
+ operatorLatestActionByWs.set(key, ev.created_at);
457
+ }
458
+ }
459
+ }
460
+ for (const ev of events) {
461
+ if (ev.tool_name !== 'query_cache' && ev.tool_name !== 'read_graph')
462
+ continue;
463
+ const ag = agentById.get(ev.agent_id);
464
+ if (!ag)
465
+ continue;
466
+ const returned = safeJsonParse(ev.returned_ids, []);
467
+ for (const id of returned) {
468
+ const de = deadEndById.get(id);
469
+ if (!de)
470
+ continue;
471
+ const authorOp = agentById.get(de.author_agent_id)?.operator_id;
472
+ if (authorOp === ag.operator_id)
473
+ continue; // strict self-exposure exclusion
474
+ const byOp = deadEndExposureTime.get(id) ?? new Map();
475
+ const prev = byOp.get(ag.operator_id);
476
+ if (!prev || ev.created_at < prev) {
477
+ byOp.set(ag.operator_id, ev.created_at);
478
+ }
479
+ deadEndExposureTime.set(id, byOp);
480
+ }
481
+ }
482
+ // Also include opt-in client_telemetry.dead_ends_consulted (explicitly reported prior consultation)
483
+ for (const r of scopedRuns) {
484
+ const ag = agentById.get(r.agent_id);
485
+ if (!ag)
486
+ continue;
487
+ const precheck = safeJsonParse(r.precheck_proof, {});
488
+ const consulted = Array.isArray(precheck?.client_telemetry?.dead_ends_consulted)
489
+ ? precheck.client_telemetry.dead_ends_consulted
490
+ : [];
491
+ for (const id of consulted) {
492
+ const de = deadEndById.get(id);
493
+ if (!de)
494
+ continue;
495
+ const authorOp = agentById.get(de.author_agent_id)?.operator_id;
496
+ if (authorOp === ag.operator_id)
497
+ continue;
498
+ const byOp = deadEndExposureTime.get(id) ?? new Map();
499
+ const prev = byOp.get(ag.operator_id);
500
+ if (!prev || r.created_at < prev) {
501
+ byOp.set(ag.operator_id, r.created_at);
502
+ }
503
+ deadEndExposureTime.set(id, byOp);
504
+ }
505
+ }
506
+ let deadEndsConsumedByPeers = 0;
507
+ for (const de of deadEndArtifacts) {
508
+ const exposedOps = deadEndExposureTime.get(de.id);
509
+ if (exposedOps && exposedOps.size > 0)
510
+ deadEndsConsumedByPeers++;
511
+ }
512
+ // Cross-operator artifact reuse rate
513
+ let crossOpReuseArtifacts = 0;
514
+ for (const art of verifiedArtifacts) {
515
+ const childOp = agentById.get(art.author_agent_id)?.operator_id;
516
+ const parents = parentsOfArt.get(art.id) ?? [];
517
+ const citesOtherOp = parents.some((pId) => {
518
+ const pArt = artifactById.get(pId);
519
+ const pOp = pArt ? agentById.get(pArt.author_agent_id)?.operator_id : undefined;
520
+ return Boolean(pOp && childOp && pOp !== childOp);
521
+ });
522
+ if (citesOtherOp)
523
+ crossOpReuseArtifacts++;
524
+ }
525
+ // FormalizationAudit defect catch rate
526
+ const auditNodes = nodes.filter((n) => n.type === 'FormalizationAudit');
527
+ let auditsWithDefects = 0;
528
+ const defectsByOperator = new Map();
529
+ for (const an of auditNodes) {
530
+ const vr = safeJsonParse(an.verifier_result, {});
531
+ const metrics = vr?.metrics ?? {};
532
+ const defectsCaught = Number(metrics.defects_caught ?? 0);
533
+ const hasDefect = an.status === 'disputed' || vr?.status === 'fail' || defectsCaught > 0;
534
+ if (hasDefect) {
535
+ auditsWithDefects++;
536
+ const reporterOps = new Set();
537
+ if (Array.isArray(metrics.defect_reporter_operators)) {
538
+ for (const op of metrics.defect_reporter_operators)
539
+ reporterOps.add(String(op));
540
+ }
541
+ if (Array.isArray(metrics.defect_reporter_agents)) {
542
+ for (const agId of metrics.defect_reporter_agents) {
543
+ const op = agentById.get(String(agId))?.operator_id;
544
+ if (op)
545
+ reporterOps.add(op);
546
+ }
547
+ }
548
+ for (const op of reporterOps) {
549
+ defectsByOperator.set(op, (defectsByOperator.get(op) ?? 0) + 1);
550
+ }
551
+ }
552
+ }
553
+ // Precheck pass rate
554
+ const precheckedRuns = scopedRuns.filter((r) => Boolean(r.precheck_proof));
555
+ const precheckedPassed = precheckedRuns.filter((r) => r.status === 'pass').length;
556
+ const catalog = {
557
+ verified_artifacts_total: verifiedArtifacts.length,
558
+ verified_lemmas_total: verifiedLemmas.length,
559
+ verified_lemmas_per_week: verifiedLemmasPerWeek,
560
+ lease_acquires: leaseAcquires,
561
+ lease_conflicts: leaseConflicts,
562
+ lease_expired_events: totalLeaseTimeouts,
563
+ lease_completion_rate_pct: leaseAcquires > 0 ? round2(Math.min(100, (verifiedArtifacts.length / leaseAcquires) * 100)) : null,
564
+ stale_timeout_rate_pct: leaseAcquires > 0 ? round2((totalLeaseTimeouts / leaseAcquires) * 100) : null,
565
+ dead_ends_logged_total: deadEndArtifacts.length,
566
+ dead_ends_consumed_by_peers: deadEndsConsumedByPeers,
567
+ dead_end_avoidance_rate_pct: deadEndArtifacts.length > 0 ? round2((deadEndsConsumedByPeers / deadEndArtifacts.length) * 100) : null,
568
+ cross_operator_reuse_artifacts: crossOpReuseArtifacts,
569
+ cross_operator_reuse_rate_pct: verifiedArtifacts.length > 0 ? round2((crossOpReuseArtifacts / verifiedArtifacts.length) * 100) : null,
570
+ formalization_audits_total: auditNodes.length,
571
+ formalization_audits_defects_caught: auditsWithDefects,
572
+ formalization_audit_defect_rate_pct: auditNodes.length > 0 ? round2((auditsWithDefects / auditNodes.length) * 100) : null,
573
+ prechecked_submissions: precheckedRuns.length,
574
+ prechecked_pass_rate_pct: precheckedRuns.length > 0 ? round2((precheckedPassed / precheckedRuns.length) * 100) : null,
575
+ verification_latency_p50_ms: percentile(computeMsValues, 0.5),
576
+ verification_latency_p95_ms: percentile(computeMsValues, 0.95),
577
+ };
578
+ const accByOp = new Map();
579
+ const getAcc = (opId) => {
580
+ let acc = accByOp.get(opId);
581
+ if (!acc) {
582
+ acc = {
583
+ operator_id: opId,
584
+ verified_artifacts: 0,
585
+ base_points: 0,
586
+ external_reuse_points: 0,
587
+ external_reuse_count: 0,
588
+ self_citations_excluded: 0,
589
+ dead_end_points: 0,
590
+ dead_end_exposures_external: 0,
591
+ audit_defect_points: 0,
592
+ audit_defects_caught: 0,
593
+ tripwire_bypasses: 0,
594
+ abandoned_leases: 0,
595
+ slop_penalty_points: 0,
596
+ max_single_artifact_u_ext: 0,
597
+ };
598
+ accByOp.set(opId, acc);
599
+ }
600
+ return acc;
601
+ };
602
+ const basePointsForArtifact = (art) => {
603
+ const node = nodeById.get(art.source_node_id);
604
+ const nType = node?.type ?? '';
605
+ if (nType === 'Counterexample')
606
+ return 40;
607
+ if (nType === 'Exposition' || nType === 'LiteratureCheck' || art.artifact_type === 'literature_check') {
608
+ return 15;
609
+ }
610
+ if (nType === 'Conjecture' || nType === 'Goal')
611
+ return 50;
612
+ const hasParents = (dependsParentsByNode.get(art.source_node_id)?.size ?? 0) > 0;
613
+ const hasChildren = (dependsChildrenByNode.get(art.source_node_id)?.size ?? 0) > 0;
614
+ if (hasParents && !hasChildren)
615
+ return 50; // Root closure of a dependency chain
616
+ if (hasParents && hasChildren)
617
+ return 20; // Mid-DAG lemma
618
+ return 10; // Leaf lemma / standalone subtask
619
+ };
620
+ // 1. Verified artifacts B(a) + 15 * U_ext(a) (capped at 4x base; self-citations = 0)
621
+ for (const art of verifiedArtifacts) {
622
+ if (internalAgentIds.has(art.author_agent_id))
623
+ continue;
624
+ const authorOp = agentById.get(art.author_agent_id)?.operator_id;
625
+ if (!authorOp || excludedOps.has(authorOp))
626
+ continue;
627
+ const acc = getAcc(authorOp);
628
+ const base = basePointsForArtifact(art);
629
+ const externalImporters = new Set();
630
+ let selfCitations = 0;
631
+ for (const childArtId of childrenOfArt.get(art.id) ?? []) {
632
+ const childArt = artifactById.get(childArtId);
633
+ if (!childArt || childArt.artifact_type === 'dead_end')
634
+ continue;
635
+ const childOp = agentById.get(childArt.author_agent_id)?.operator_id;
636
+ if (!childOp)
637
+ continue;
638
+ if (childOp === authorOp) {
639
+ selfCitations++;
640
+ }
641
+ else {
642
+ externalImporters.add(childOp);
643
+ }
644
+ }
645
+ const uExt = externalImporters.size;
646
+ const reusePts = Math.min(15 * uExt, 4 * base);
647
+ acc.verified_artifacts += 1;
648
+ acc.base_points += base;
649
+ acc.external_reuse_count += uExt;
650
+ acc.external_reuse_points += reusePts;
651
+ acc.self_citations_excluded += selfCitations;
652
+ if (uExt > acc.max_single_artifact_u_ext) {
653
+ acc.max_single_artifact_u_ext = uExt;
654
+ }
655
+ }
656
+ // 2. Verified dead ends: min(5 * C_ext(d), 25)
657
+ for (const de of deadEndArtifacts) {
658
+ if (internalAgentIds.has(de.author_agent_id))
659
+ continue;
660
+ if (de.verifier_hash === 'unverified')
661
+ continue;
662
+ const authorOp = agentById.get(de.author_agent_id)?.operator_id;
663
+ if (!authorOp || excludedOps.has(authorOp))
664
+ continue;
665
+ const exposures = deadEndExposureTime.get(de.id);
666
+ if (!exposures || exposures.size === 0)
667
+ continue;
668
+ // Count distinct OTHER operators exposed prior to claiming/closing in that workspace
669
+ let cExt = 0;
670
+ for (const [peerOp, exposedAt] of exposures.entries()) {
671
+ if (peerOp === authorOp)
672
+ continue;
673
+ const latestAction = operatorLatestActionByWs.get(`${de.workspace_id}:${peerOp}`);
674
+ // Count if they later claimed/submitted (exposedAt <= latestAction) OR consulted in telemetry
675
+ if (!latestAction || exposedAt <= latestAction) {
676
+ cExt++;
677
+ }
678
+ }
679
+ if (cExt > 0) {
680
+ const acc = getAcc(authorOp);
681
+ acc.dead_end_exposures_external += cExt;
682
+ acc.dead_end_points += Math.min(5 * cExt, 25);
683
+ }
684
+ }
685
+ // 3. Confirmed spec defects caught: 25 pts each
686
+ for (const [opId, count] of defectsByOperator.entries()) {
687
+ if (excludedOps.has(opId))
688
+ continue;
689
+ const acc = getAcc(opId);
690
+ acc.audit_defects_caught += count;
691
+ acc.audit_defect_points += count * 25;
692
+ }
693
+ // 4. Slop penalties P_slop(o): -5 per Stage 0/1 AST bypass; -2 per abandoned lease after 2 grace timeouts
694
+ for (const ev of events) {
695
+ if (internalAgentIds.has(ev.agent_id))
696
+ continue;
697
+ const opId = agentById.get(ev.agent_id)?.operator_id;
698
+ if (!opId || excludedOps.has(opId))
699
+ continue;
700
+ if (ev.tool_name === 'submit_artifact' && ev.outcome_code === 'PRECHECK_FAILED') {
701
+ getAcc(opId).tripwire_bypasses += 1;
702
+ }
703
+ else if (ev.tool_name === 'claim_node' && ev.outcome_code === 'LEASE_EXPIRED') {
704
+ getAcc(opId).abandoned_leases += 1;
705
+ }
706
+ }
707
+ for (const r of scopedRuns) {
708
+ if (r.status !== 'fail' || internalAgentIds.has(r.agent_id))
709
+ continue;
710
+ const opId = agentById.get(r.agent_id)?.operator_id;
711
+ if (!opId || excludedOps.has(opId))
712
+ continue;
713
+ const vr = safeJsonParse(r.verifier_result, {});
714
+ if (typeof vr.logs === 'string' && /stage_[01]_tripwire/i.test(vr.logs)) {
715
+ getAcc(opId).tripwire_bypasses += 1;
716
+ }
717
+ }
718
+ for (const n of nodes) {
719
+ if (n.status === 'claimed' && n.claim_expires_at && n.claim_expires_at < generatedAt && n.claim_agent_id) {
720
+ if (internalAgentIds.has(n.claim_agent_id))
721
+ continue;
722
+ const opId = agentById.get(n.claim_agent_id)?.operator_id;
723
+ if (opId && !excludedOps.has(opId)) {
724
+ getAcc(opId).abandoned_leases += 1;
725
+ }
726
+ }
727
+ }
728
+ // Finalize leaderboard scores & assign Doc 07 §5.2 Specialty Badges
729
+ const rawEntries = [];
730
+ for (const acc of accByOp.values()) {
731
+ const slopPenalty = acc.tripwire_bypasses * 5 + Math.max(0, acc.abandoned_leases - 2) * 2;
732
+ acc.slop_penalty_points = slopPenalty;
733
+ const totalScore = acc.base_points +
734
+ acc.external_reuse_points +
735
+ acc.dead_end_points +
736
+ acc.audit_defect_points -
737
+ slopPenalty;
738
+ rawEntries.push({
739
+ rank: 0,
740
+ operator_id: acc.operator_id,
741
+ display_names: Array.from(operatorDisplayNames.get(acc.operator_id) ?? [acc.operator_id]).sort(),
742
+ verified_artifacts: acc.verified_artifacts,
743
+ base_points: acc.base_points,
744
+ external_reuse_points: acc.external_reuse_points,
745
+ external_reuse_count: acc.external_reuse_count,
746
+ self_citations_excluded: acc.self_citations_excluded,
747
+ dead_end_points: acc.dead_end_points,
748
+ dead_end_exposures_external: acc.dead_end_exposures_external,
749
+ audit_defect_points: acc.audit_defect_points,
750
+ audit_defects_caught: acc.audit_defects_caught,
751
+ slop_penalty_points: slopPenalty,
752
+ tripwire_bypasses: acc.tripwire_bypasses,
753
+ abandoned_leases: acc.abandoned_leases,
754
+ total_score: totalScore,
755
+ open_weight: Boolean(operatorOpenWeight.get(acc.operator_id)),
756
+ badges: [],
757
+ _maxSingleUExt: acc.max_single_artifact_u_ext,
758
+ });
759
+ }
760
+ rawEntries.sort((a, b) => b.total_score - a.total_score ||
761
+ b.external_reuse_points - a.external_reuse_points ||
762
+ a.operator_id.localeCompare(b.operator_id));
763
+ // Assign specialty badges
764
+ const zeroWasteWinner = [...rawEntries]
765
+ .filter((e) => e.slop_penalty_points === 0 && e.external_reuse_points > 0)
766
+ .sort((a, b) => b.external_reuse_points - a.external_reuse_points || b.total_score - a.total_score)[0];
767
+ if (zeroWasteWinner)
768
+ zeroWasteWinner.badges.push('Zero-Waste Architect');
769
+ const deadEndSavior = [...rawEntries]
770
+ .filter((e) => e.dead_end_points > 0)
771
+ .sort((a, b) => b.dead_end_points - a.dead_end_points || b.dead_end_exposures_external - a.dead_end_exposures_external)[0];
772
+ if (deadEndSavior)
773
+ deadEndSavior.badges.push('Dead-End Savior');
774
+ const bestModular = [...rawEntries]
775
+ .filter((e) => e._maxSingleUExt > 0)
776
+ .sort((a, b) => b._maxSingleUExt - a._maxSingleUExt || b.external_reuse_points - a.external_reuse_points)[0];
777
+ if (bestModular)
778
+ bestModular.badges.push('Best Modular Lemma');
779
+ const openWeightChamp = [...rawEntries]
780
+ .filter((e) => e.open_weight && e.total_score > 0)
781
+ .sort((a, b) => b.total_score - a.total_score)[0];
782
+ if (openWeightChamp)
783
+ openWeightChamp.badges.push('Open-Weight Champion');
784
+ const leaderboard = rawEntries.map((entry, idx) => {
785
+ const { _maxSingleUExt, ...clean } = entry;
786
+ return { ...clean, rank: idx + 1 };
787
+ });
788
+ const overallPhase1Ready = exitGates.every((g) => g.status === 'pass');
789
+ return {
790
+ generated_at: generatedAt,
791
+ scope: {
792
+ workspace_id: scopeWsId,
793
+ baseline_workspace_id: baselineWsId,
794
+ compute_usd_per_sec: computeUsdPerSec,
795
+ },
796
+ overall_phase1_ready: overallPhase1Ready,
797
+ exit_gates: exitGates,
798
+ catalog,
799
+ token_savings: tokenSavings,
800
+ leaderboard,
801
+ };
802
+ }
803
+ /**
804
+ * Formats a PilotMetricsReport into a clean GitHub-Flavored Markdown scorecard,
805
+ * Token-Savings Report, and Swarm Sprint Leaderboard.
806
+ */
807
+ export function formatPilotReportMarkdown(report) {
808
+ const lines = [
809
+ '# Caisson — Phase 0 Pilot Exit-Gate Scorecard & Swarm Sprint Leaderboard',
810
+ '',
811
+ `- **Generated:** ${report.generated_at}`,
812
+ `- **Scope:** ${report.scope.workspace_id ?? 'All workspaces'}${report.scope.baseline_workspace_id ? ` (Baseline: ${report.scope.baseline_workspace_id})` : ''}`,
813
+ `- **Phase 1 Go/No-Go Ready:** ${report.overall_phase1_ready ? 'YES (5/5 Gates Passing)' : 'NO (Not all gates passing)'}`,
814
+ '',
815
+ '## 1. Phase 0 North-Star Exit Gates',
816
+ '',
817
+ '| # | Exit Gate | Status | Threshold | Actual |',
818
+ '| :---: | :--- | :---: | :--- | :--- |',
819
+ ];
820
+ for (const g of report.exit_gates) {
821
+ const badge = g.status === 'pass' ? 'PASS' : g.status === 'fail' ? 'FAIL' : 'INSUFFICIENT DATA';
822
+ lines.push(`| ${g.id} | ${g.name} | **${badge}** | ${g.threshold} | ${g.actual} |`);
823
+ }
824
+ lines.push('', '## 2. Automated Token-Savings Report', '', '| Metric | Solo Baseline | Swarm-Assisted | Reduction |', '| :--- | :---: | :---: | :---: |', `| Median Tokens / Verified Lemma | ${report.token_savings.solo_median_tokens ?? 'n/a'} (n=${report.token_savings.solo_runs_with_tokens}) | ${report.token_savings.swarm_median_tokens ?? 'n/a'} (n=${report.token_savings.swarm_runs_with_tokens}) | ${report.token_savings.token_reduction_pct !== null ? `${report.token_savings.token_reduction_pct}%` : 'n/a'} |`, `| Median Local Compile Attempts | ${report.token_savings.solo_median_attempts ?? 'n/a'} (n=${report.token_savings.solo_runs_with_attempts}) | ${report.token_savings.swarm_median_attempts ?? 'n/a'} (n=${report.token_savings.swarm_runs_with_attempts}) | ${report.token_savings.attempt_reduction_pct !== null ? `${report.token_savings.attempt_reduction_pct}%` : 'n/a'} |`, '', `- **Estimated Total Tokens Saved:** ${report.token_savings.estimated_total_tokens_saved.toLocaleString('en-US')}`, `- **Reported Cache Hits Used:** ${report.token_savings.total_cache_hits_reported}`, `- **Reported Dead Ends Consulted:** ${report.token_savings.total_dead_ends_consulted_reported}`, '', '## 3. Phase 0 Operational Metric Catalog', '', `- **Verified Artifacts / Lemmas:** ${report.catalog.verified_artifacts_total} total (${report.catalog.verified_lemmas_total} lemmas, ${report.catalog.verified_lemmas_per_week}/wk)`, `- **Lease Health:** ${report.catalog.lease_acquires} acquires, ${report.catalog.lease_conflicts} conflicts, ${report.catalog.lease_expired_events} timeouts (completion: ${report.catalog.lease_completion_rate_pct ?? 'n/a'}%, stale rate: ${report.catalog.stale_timeout_rate_pct ?? 'n/a'}%)`, `- **Dead-End Avoidance Rate:** ${report.catalog.dead_ends_consumed_by_peers}/${report.catalog.dead_ends_logged_total} (${report.catalog.dead_end_avoidance_rate_pct ?? 'n/a'}%)`, `- **Cross-Operator Artifact Reuse:** ${report.catalog.cross_operator_reuse_artifacts}/${report.catalog.verified_artifacts_total} (${report.catalog.cross_operator_reuse_rate_pct ?? 'n/a'}%)`, `- **FormalizationAudit Defect Catch Rate:** ${report.catalog.formalization_audits_defects_caught}/${report.catalog.formalization_audits_total} (${report.catalog.formalization_audit_defect_rate_pct ?? 'n/a'}%)`, `- **Prechecked Submission Pass Rate:** ${report.catalog.prechecked_pass_rate_pct ?? 'n/a'}% (n=${report.catalog.prechecked_submissions})`, `- **Verification Latency:** P50 = ${report.catalog.verification_latency_p50_ms ?? 'n/a'} ms | P95 = ${report.catalog.verification_latency_p95_ms ?? 'n/a'} ms`, '', '## 4. Swarm Sprint Leaderboard `S(o)` (Self-Citations Strictly Excluded)', '');
825
+ if (report.leaderboard.length === 0) {
826
+ lines.push('_No scored operator activity recorded yet._');
827
+ }
828
+ else {
829
+ lines.push('| Rank | Operator | Score `S(o)` | Base `B` | Ext Reuse `15*U_ext` | Dead Ends `5*C_ext` | Audit Defects | Slop `-P` | Self-Cites Ignored | Badges |', '| :---: | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :--- |');
830
+ for (const row of report.leaderboard) {
831
+ lines.push(`| ${row.rank} | \`${row.operator_id}\` | **${row.total_score}** | ${row.base_points} | ${row.external_reuse_points} (${row.external_reuse_count}) | ${row.dead_end_points} (${row.dead_end_exposures_external}) | ${row.audit_defect_points} (${row.audit_defects_caught}) | -${row.slop_penalty_points} | ${row.self_citations_excluded} | ${row.badges.join(', ') || '—'} |`);
832
+ }
833
+ }
834
+ lines.push('');
835
+ return lines.join('\n');
836
+ }
837
+ //# sourceMappingURL=metrics.js.map