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.
- package/README.math-mvp.md +28 -0
- package/README.md +56 -3
- 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 +28 -0
- package/dist/auth/agentAuth.js +88 -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 +15 -0
- package/dist/cli/caissonCli.js +528 -0
- package/dist/cli/caissonCli.js.map +1 -0
- package/dist/cli/doctor.d.ts +31 -0
- package/dist/cli/doctor.js +321 -0
- package/dist/cli/doctor.js.map +1 -0
- package/dist/cli/inviteCard.d.ts +25 -0
- package/dist/cli/inviteCard.js +111 -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 +136 -0
- package/dist/mcp/handlers.js +809 -0
- package/dist/mcp/handlers.js.map +1 -0
- package/dist/mcp/httpServer.d.ts +29 -0
- package/dist/mcp/httpServer.js +384 -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 +24 -0
- package/dist/web/discoveryRoutes.js +532 -0
- package/dist/web/discoveryRoutes.js.map +1 -0
- package/dist/web/docsRoutes.d.ts +14 -0
- package/dist/web/docsRoutes.js +451 -0
- package/dist/web/docsRoutes.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 +399 -0
- package/dist/web/explorer/renderers.js.map +1 -0
- package/dist/web/landing.d.ts +36 -0
- package/dist/web/landing.js +532 -0
- package/dist/web/landing.js.map +1 -0
- package/dist/web/onboardingRoutes.d.ts +96 -0
- package/dist/web/onboardingRoutes.js +629 -0
- package/dist/web/onboardingRoutes.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 +58 -6
- 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 +162 -0
- package/public/llms.txt +40 -0
|
@@ -0,0 +1,809 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { assertWorkspaceAccess } from '../auth/agentAuth.js';
|
|
3
|
+
import { getOperatorEntitlements } from '../billing/subscriptions.js';
|
|
4
|
+
import { newId, nowIso, sha256Hex } from '../db/sqlite.js';
|
|
5
|
+
import { logMcpEvent } from '../db/telemetry.js';
|
|
6
|
+
import { attachRunToAntiSlopStake, burnOverflowCompute, getActiveBountyForNode, getOperatorBalance, lockAntiSlopStake, OVERFLOW_COMPUTE_HEAVY_SC, OVERFLOW_COMPUTE_STANDARD_SC, refundAntiSlopStake, scToUnits, slashAntiSlopStake, } from '../economy/index.js';
|
|
7
|
+
import { SwarmError } from '../types/errors.js';
|
|
8
|
+
import { getArtifactLineage, lookupByContentHash } from '../memo/artifactIndex.js';
|
|
9
|
+
import { hybridSearchArtifactsSync, indexArtifactEmbeddingSync } from '../memo/embeddings.js';
|
|
10
|
+
import { defaultDomainPackRegistry } from '../packs/index.js';
|
|
11
|
+
import { ClaimNodeInput, LogDeadEndInput, QueryCacheInput, ReadGraphInput, SubmitArtifactInput, } from '../types/schemas.js';
|
|
12
|
+
export class SwarmToolHandlers {
|
|
13
|
+
db;
|
|
14
|
+
git;
|
|
15
|
+
blobs;
|
|
16
|
+
packRegistry;
|
|
17
|
+
constructor(db, git, blobs, packRegistry = defaultDomainPackRegistry) {
|
|
18
|
+
this.db = db;
|
|
19
|
+
this.git = git;
|
|
20
|
+
this.blobs = blobs;
|
|
21
|
+
this.packRegistry = packRegistry;
|
|
22
|
+
}
|
|
23
|
+
assertWritableAgent(agent, toolName) {
|
|
24
|
+
if (agent.readOnly) {
|
|
25
|
+
throw new SwarmError('UNAUTHORIZED', `Read-only demo mode cannot invoke ${toolName}. Mint a free sandbox API key at https://caisson.tools/start (or POST /v1/onboarding/register) to claim nodes, submit artifacts, and log dead ends.`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
checkHourlyQuota(agent, ws) {
|
|
29
|
+
const tierFallbackCap = agent.rateLimitTier === 'internal'
|
|
30
|
+
? 1000
|
|
31
|
+
: agent.rateLimitTier === 'pro_team'
|
|
32
|
+
? 500
|
|
33
|
+
: agent.rateLimitTier === 'pro'
|
|
34
|
+
? 120
|
|
35
|
+
: agent.rateLimitTier === 'trusted'
|
|
36
|
+
? 100
|
|
37
|
+
: agent.rateLimitTier === 'sandbox'
|
|
38
|
+
? 10
|
|
39
|
+
: 20;
|
|
40
|
+
const entitlements = getOperatorEntitlements(this.db, agent.operatorId);
|
|
41
|
+
// Sandbox self-serve tokens remain bounded to 10/hr unless upgraded past the free plan
|
|
42
|
+
const cap = agent.rateLimitTier === 'sandbox' && entitlements.plan_tier === 'free'
|
|
43
|
+
? tierFallbackCap
|
|
44
|
+
: Math.max(tierFallbackCap, entitlements.hourly_verification_quota);
|
|
45
|
+
const since = new Date(Date.now() - 3600_000).toISOString();
|
|
46
|
+
const row = this.db
|
|
47
|
+
.prepare('SELECT COUNT(*) AS cnt FROM verification_runs WHERE agent_id = ? AND created_at >= ?')
|
|
48
|
+
.get(agent.agentId, since);
|
|
49
|
+
if (row.cnt < cap) {
|
|
50
|
+
return { overflowRequired: false, overflowTier: 'standard', cap };
|
|
51
|
+
}
|
|
52
|
+
// Check if operator opted into 1–2 SC overflow compute burn (E4-3)
|
|
53
|
+
const agRow = this.db
|
|
54
|
+
.prepare('SELECT model_metadata FROM agent_identities WHERE id = ?')
|
|
55
|
+
.get(agent.agentId);
|
|
56
|
+
let meta = {};
|
|
57
|
+
try {
|
|
58
|
+
meta = agRow?.model_metadata ? JSON.parse(agRow.model_metadata) : {};
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
meta = {};
|
|
62
|
+
}
|
|
63
|
+
const overflowTier = ws.merge_target === 'repo_root' ? 'heavy' : 'standard';
|
|
64
|
+
const costSc = overflowTier === 'heavy' ? OVERFLOW_COMPUTE_HEAVY_SC : OVERFLOW_COMPUTE_STANDARD_SC;
|
|
65
|
+
if (meta.sc_overflow_compute === true) {
|
|
66
|
+
const bal = getOperatorBalance(this.db, agent.operatorId);
|
|
67
|
+
if (bal.balance_units >= scToUnits(costSc)) {
|
|
68
|
+
return { overflowRequired: true, overflowTier, cap };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
throw new SwarmError('RATE_LIMITED', `Hourly verification quota (${cap}/hr) exceeded (upgrade to Pro or enable sc_overflow_compute with >= ${costSc} SC)`, true);
|
|
72
|
+
}
|
|
73
|
+
/** 1. read_graph */
|
|
74
|
+
readGraph(rawInput, agent) {
|
|
75
|
+
const t0 = performance.now();
|
|
76
|
+
const input = ReadGraphInput.parse(rawInput);
|
|
77
|
+
const ws = assertWorkspaceAccess(this.db, input.workspace_id, agent);
|
|
78
|
+
const f = input.filter;
|
|
79
|
+
const limit = f?.limit ?? 50;
|
|
80
|
+
const where = ['workspace_id = ?'];
|
|
81
|
+
const params = [ws.id];
|
|
82
|
+
if (f?.root_node_id) {
|
|
83
|
+
const maxDepth = f.max_depth ?? 3;
|
|
84
|
+
const reachable = this.db
|
|
85
|
+
.prepare(`
|
|
86
|
+
WITH RECURSIVE sub(node_id, depth) AS (
|
|
87
|
+
SELECT ?, 0
|
|
88
|
+
UNION
|
|
89
|
+
SELECT e.child_node_id, sub.depth + 1
|
|
90
|
+
FROM node_edges e
|
|
91
|
+
JOIN sub ON e.parent_node_id = sub.node_id
|
|
92
|
+
WHERE e.workspace_id = ? AND sub.depth < ?
|
|
93
|
+
UNION
|
|
94
|
+
SELECT e.parent_node_id, sub.depth + 1
|
|
95
|
+
FROM node_edges e
|
|
96
|
+
JOIN sub ON e.child_node_id = sub.node_id
|
|
97
|
+
WHERE e.workspace_id = ? AND sub.depth < ?
|
|
98
|
+
)
|
|
99
|
+
SELECT DISTINCT node_id FROM sub
|
|
100
|
+
`)
|
|
101
|
+
.all(f.root_node_id, ws.id, maxDepth, ws.id, maxDepth)
|
|
102
|
+
.map((r) => r.node_id);
|
|
103
|
+
if (reachable.length === 0) {
|
|
104
|
+
where.push('1 = 0');
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
where.push(`id IN (${reachable.map(() => '?').join(',')})`);
|
|
108
|
+
params.push(...reachable);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (f?.statuses?.length) {
|
|
112
|
+
where.push(`status IN (${f.statuses.map(() => '?').join(',')})`);
|
|
113
|
+
params.push(...f.statuses);
|
|
114
|
+
}
|
|
115
|
+
if (f?.node_types?.length) {
|
|
116
|
+
where.push(`type IN (${f.node_types.map(() => '?').join(',')})`);
|
|
117
|
+
params.push(...f.node_types);
|
|
118
|
+
}
|
|
119
|
+
if (f?.updated_since) {
|
|
120
|
+
where.push('updated_at >= ?');
|
|
121
|
+
params.push(f.updated_since);
|
|
122
|
+
}
|
|
123
|
+
if (f?.cursor) {
|
|
124
|
+
let decoded;
|
|
125
|
+
try {
|
|
126
|
+
decoded = JSON.parse(Buffer.from(f.cursor, 'base64url').toString('utf8'));
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
throw new SwarmError('INVALID_INPUT', 'Invalid read_graph pagination cursor');
|
|
130
|
+
}
|
|
131
|
+
if (typeof decoded.updated_at !== 'string' || typeof decoded.id !== 'string') {
|
|
132
|
+
throw new SwarmError('INVALID_INPUT', 'Malformed read_graph pagination cursor');
|
|
133
|
+
}
|
|
134
|
+
where.push('(updated_at < ? OR (updated_at = ? AND id > ?))');
|
|
135
|
+
params.push(decoded.updated_at, decoded.updated_at, decoded.id);
|
|
136
|
+
}
|
|
137
|
+
const rawRows = this.db
|
|
138
|
+
.prepare(`SELECT * FROM nodes WHERE ${where.join(' AND ')} ORDER BY updated_at DESC, id ASC LIMIT ?`)
|
|
139
|
+
.all(...params, limit + 1);
|
|
140
|
+
const hasMore = rawRows.length > limit;
|
|
141
|
+
const nodeRows = hasMore ? rawRows.slice(0, limit) : rawRows;
|
|
142
|
+
const lastRow = nodeRows[nodeRows.length - 1];
|
|
143
|
+
const nextCursor = hasMore && lastRow
|
|
144
|
+
? Buffer.from(JSON.stringify({ updated_at: lastRow.updated_at, id: lastRow.id }), 'utf8').toString('base64url')
|
|
145
|
+
: null;
|
|
146
|
+
const edges = this.db
|
|
147
|
+
.prepare('SELECT parent_node_id, child_node_id, edge_type FROM node_edges WHERE workspace_id = ?')
|
|
148
|
+
.all(ws.id);
|
|
149
|
+
const parentsByChild = new Map();
|
|
150
|
+
for (const e of edges) {
|
|
151
|
+
const list = parentsByChild.get(e.child_node_id) ?? [];
|
|
152
|
+
list.push(e.parent_node_id);
|
|
153
|
+
parentsByChild.set(e.child_node_id, list);
|
|
154
|
+
}
|
|
155
|
+
const now = nowIso();
|
|
156
|
+
const nodes = nodeRows.map((n) => {
|
|
157
|
+
const leaseActive = n.status === 'claimed' && n.claim_expires_at && n.claim_expires_at > now;
|
|
158
|
+
return {
|
|
159
|
+
node_id: n.id,
|
|
160
|
+
type: n.type,
|
|
161
|
+
status: n.status === 'claimed' && !leaseActive ? 'open' : n.status,
|
|
162
|
+
title: n.title,
|
|
163
|
+
spec_summary: n.spec_summary,
|
|
164
|
+
parent_ids: parentsByChild.get(n.id) ?? [],
|
|
165
|
+
claim_lease: leaseActive ? { agent_id: n.claim_agent_id, expires_at: n.claim_expires_at } : null,
|
|
166
|
+
payload_ref: n.payload_ref ?? null,
|
|
167
|
+
payload: f?.include_payloads && n.payload_ref
|
|
168
|
+
? { content: this.git.readFileAtCommit(ws.git_repo_uri, ws.git_head_sha, n.payload_ref) }
|
|
169
|
+
: null,
|
|
170
|
+
spec_content: f?.include_payloads && n.spec_git_path
|
|
171
|
+
? (this.git.readFileAtCommit(ws.git_repo_uri, ws.git_head_sha, n.spec_git_path)?.slice(0, 16384) ?? null)
|
|
172
|
+
: null,
|
|
173
|
+
verifier_result: n.verifier_result ? JSON.parse(n.verifier_result) : null,
|
|
174
|
+
bounty_config: n.bounty_config ? JSON.parse(n.bounty_config) : null,
|
|
175
|
+
updated_at: n.updated_at,
|
|
176
|
+
};
|
|
177
|
+
});
|
|
178
|
+
const deadEnds = f?.include_dead_ends !== false
|
|
179
|
+
? this.db
|
|
180
|
+
.prepare(`
|
|
181
|
+
SELECT id AS artifact_id, source_node_id AS node_id, summary AS approach_summary, verifier_hash, semantic_tags
|
|
182
|
+
FROM artifacts WHERE workspace_id = ? AND artifact_type = 'dead_end'
|
|
183
|
+
ORDER BY created_at DESC LIMIT 50
|
|
184
|
+
`)
|
|
185
|
+
.all(ws.id).map((d) => {
|
|
186
|
+
let tags = [];
|
|
187
|
+
try {
|
|
188
|
+
tags = JSON.parse(d.semantic_tags || '[]');
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
tags = [];
|
|
192
|
+
}
|
|
193
|
+
const superseded = tags.some((t) => t === 'superseded' || t === 'infra_resolved');
|
|
194
|
+
return {
|
|
195
|
+
artifact_id: d.artifact_id,
|
|
196
|
+
node_id: d.node_id,
|
|
197
|
+
approach_summary: d.approach_summary,
|
|
198
|
+
verified: d.verifier_hash !== 'unverified',
|
|
199
|
+
...(superseded ? { superseded: true } : {}),
|
|
200
|
+
};
|
|
201
|
+
})
|
|
202
|
+
: [];
|
|
203
|
+
const verifierCfg = JSON.parse(ws.verifier_config);
|
|
204
|
+
if (!agent.readOnly) {
|
|
205
|
+
logMcpEvent(this.db, {
|
|
206
|
+
agentId: agent.agentId,
|
|
207
|
+
workspaceId: ws.id,
|
|
208
|
+
toolName: 'read_graph',
|
|
209
|
+
outcomeCode: 'OK',
|
|
210
|
+
returnedIds: deadEnds.map((d) => d.artifact_id),
|
|
211
|
+
latencyMs: performance.now() - t0,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
workspace: {
|
|
216
|
+
workspace_id: ws.id,
|
|
217
|
+
title: ws.title,
|
|
218
|
+
problem_summary: ws.problem_statement_md.slice(0, 500),
|
|
219
|
+
visibility: ws.visibility,
|
|
220
|
+
domain_pack: ws.domain_pack_ref,
|
|
221
|
+
verifier_type: verifierCfg.type,
|
|
222
|
+
require_precheck: Boolean(verifierCfg.require_precheck ?? verifierCfg.required_precheck),
|
|
223
|
+
merge_target: ws.merge_target,
|
|
224
|
+
environment_version: ws.environment_version,
|
|
225
|
+
environment_lock_hash: ws.environment_lock_hash,
|
|
226
|
+
git_head_sha: ws.git_head_sha,
|
|
227
|
+
},
|
|
228
|
+
nodes,
|
|
229
|
+
edges,
|
|
230
|
+
dead_end_summaries: deadEnds,
|
|
231
|
+
next_cursor: nextCursor,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
/** 2. query_cache (Hybrid Semantic + FTS5 BM25 v2 + Content-Hash Index + Lineage Traversal + Privacy Airlock + Pagination) */
|
|
235
|
+
queryCache(rawInput, agent) {
|
|
236
|
+
const t0 = performance.now();
|
|
237
|
+
const input = QueryCacheInput.parse(rawInput);
|
|
238
|
+
if (!input.query && !input.content_hash && !input.lineage_of) {
|
|
239
|
+
throw new SwarmError('INVALID_INPUT', 'Provide at least one of query, content_hash, or lineage_of');
|
|
240
|
+
}
|
|
241
|
+
if (input.workspace_id) {
|
|
242
|
+
assertWorkspaceAccess(this.db, input.workspace_id, agent);
|
|
243
|
+
}
|
|
244
|
+
let offset = 0;
|
|
245
|
+
if (input.cursor) {
|
|
246
|
+
let decoded;
|
|
247
|
+
try {
|
|
248
|
+
decoded = JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8'));
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
throw new SwarmError('INVALID_INPUT', 'Invalid query_cache pagination cursor');
|
|
252
|
+
}
|
|
253
|
+
if (typeof decoded.offset !== 'number' || !Number.isInteger(decoded.offset) || decoded.offset < 0) {
|
|
254
|
+
throw new SwarmError('INVALID_INPUT', 'Malformed query_cache pagination cursor');
|
|
255
|
+
}
|
|
256
|
+
offset = decoded.offset;
|
|
257
|
+
}
|
|
258
|
+
const lineage = input.lineage_of
|
|
259
|
+
? getArtifactLineage(this.db, input.lineage_of, agent.agentId)
|
|
260
|
+
: undefined;
|
|
261
|
+
const formatArtifact = (r) => {
|
|
262
|
+
const derivedFrom = this.db
|
|
263
|
+
.prepare('SELECT parent_artifact_id FROM artifact_lineage WHERE artifact_id = ?')
|
|
264
|
+
.all(r.artifact_id)
|
|
265
|
+
.map((l) => l.parent_artifact_id);
|
|
266
|
+
return {
|
|
267
|
+
artifact_id: r.artifact_id,
|
|
268
|
+
content_hash: r.content_hash,
|
|
269
|
+
artifact_type: r.artifact_type,
|
|
270
|
+
title: r.title,
|
|
271
|
+
summary: r.summary,
|
|
272
|
+
payload_preview: r.payload_preview,
|
|
273
|
+
payload_uri: r.payload_uri,
|
|
274
|
+
environment_version: r.environment_version,
|
|
275
|
+
...(r.environment_lock_hash ? { environment_lock_hash: r.environment_lock_hash } : {}),
|
|
276
|
+
verifier_hash: r.verifier_hash,
|
|
277
|
+
semantic_tags: r.semantic_tags,
|
|
278
|
+
derived_from: derivedFrom,
|
|
279
|
+
reuse_count: r.reuse_count,
|
|
280
|
+
author_agent_id: r.author_agent_id,
|
|
281
|
+
relevance_score: r.relevance_score,
|
|
282
|
+
...(r.match_signals ? { match_signals: r.match_signals } : {}),
|
|
283
|
+
};
|
|
284
|
+
};
|
|
285
|
+
const matchesFilters = (item) => {
|
|
286
|
+
if (input.workspace_id && item.workspace_id !== input.workspace_id)
|
|
287
|
+
return false;
|
|
288
|
+
if (input.domain && !(item.domain_pack_ref ?? '').startsWith(input.domain))
|
|
289
|
+
return false;
|
|
290
|
+
if (input.environment_version && !item.environment_version.startsWith(input.environment_version))
|
|
291
|
+
return false;
|
|
292
|
+
if (input.environment_lock_hash && item.environment_lock_hash !== input.environment_lock_hash)
|
|
293
|
+
return false;
|
|
294
|
+
if (!input.include_dead_ends && item.artifact_type === 'dead_end')
|
|
295
|
+
return false;
|
|
296
|
+
if (input.artifact_types?.length && !input.artifact_types.includes(item.artifact_type))
|
|
297
|
+
return false;
|
|
298
|
+
if (input.tags?.length && !input.tags.every((t) => item.semantic_tags.includes(t)))
|
|
299
|
+
return false;
|
|
300
|
+
return true;
|
|
301
|
+
};
|
|
302
|
+
let allMatched = [];
|
|
303
|
+
if (input.content_hash) {
|
|
304
|
+
const hits = lookupByContentHash(this.db, input.content_hash, agent.agentId);
|
|
305
|
+
allMatched = hits
|
|
306
|
+
.filter((h) => matchesFilters(h))
|
|
307
|
+
.map((h) => formatArtifact({ ...h, relevance_score: 1.0 }));
|
|
308
|
+
}
|
|
309
|
+
else if (input.query) {
|
|
310
|
+
const hybridHits = hybridSearchArtifactsSync(this.db, {
|
|
311
|
+
query: input.query,
|
|
312
|
+
agentId: agent.agentId,
|
|
313
|
+
workspaceId: input.workspace_id,
|
|
314
|
+
domain: input.domain,
|
|
315
|
+
environmentVersion: input.environment_version,
|
|
316
|
+
environmentLockHash: input.environment_lock_hash,
|
|
317
|
+
includeDeadEnds: input.include_dead_ends,
|
|
318
|
+
artifactTypes: input.artifact_types,
|
|
319
|
+
tags: input.tags,
|
|
320
|
+
searchMode: input.search_mode,
|
|
321
|
+
});
|
|
322
|
+
allMatched = hybridHits.map((hit) => formatArtifact({
|
|
323
|
+
artifact_id: hit.row.id,
|
|
324
|
+
content_hash: hit.row.content_hash,
|
|
325
|
+
artifact_type: hit.row.artifact_type,
|
|
326
|
+
title: hit.row.title,
|
|
327
|
+
summary: hit.row.summary,
|
|
328
|
+
payload_preview: hit.row.payload_preview,
|
|
329
|
+
payload_uri: hit.row.payload_uri,
|
|
330
|
+
environment_version: hit.row.environment_version,
|
|
331
|
+
environment_lock_hash: hit.row.environment_lock_hash,
|
|
332
|
+
verifier_hash: hit.row.verifier_hash,
|
|
333
|
+
semantic_tags: JSON.parse(hit.row.semantic_tags),
|
|
334
|
+
reuse_count: hit.row.reuse_count,
|
|
335
|
+
author_agent_id: hit.row.author_agent_id,
|
|
336
|
+
relevance_score: hit.relevance_score,
|
|
337
|
+
match_signals: {
|
|
338
|
+
lexical_score: hit.lexical_score,
|
|
339
|
+
semantic_score: hit.semantic_score,
|
|
340
|
+
match_source: hit.match_source,
|
|
341
|
+
},
|
|
342
|
+
}));
|
|
343
|
+
}
|
|
344
|
+
else if (lineage) {
|
|
345
|
+
const ids = Array.from(new Set([lineage.artifact_id, ...lineage.ancestors, ...lineage.descendants]));
|
|
346
|
+
const rows = this.db
|
|
347
|
+
.prepare(`SELECT * FROM artifacts WHERE id IN (${ids.map(() => '?').join(',')})`)
|
|
348
|
+
.all(...ids);
|
|
349
|
+
const byId = new Map(rows.map((r) => [r.id, r]));
|
|
350
|
+
allMatched = ids
|
|
351
|
+
.map((id) => byId.get(id))
|
|
352
|
+
.filter((r) => Boolean(r))
|
|
353
|
+
.filter((r) => matchesFilters({
|
|
354
|
+
workspace_id: r.workspace_id,
|
|
355
|
+
domain_pack_ref: r.domain_pack_ref,
|
|
356
|
+
environment_version: r.environment_version,
|
|
357
|
+
environment_lock_hash: r.environment_lock_hash,
|
|
358
|
+
artifact_type: r.artifact_type,
|
|
359
|
+
semantic_tags: JSON.parse(r.semantic_tags),
|
|
360
|
+
}))
|
|
361
|
+
.map((r) => formatArtifact({
|
|
362
|
+
artifact_id: r.id,
|
|
363
|
+
content_hash: r.content_hash,
|
|
364
|
+
artifact_type: r.artifact_type,
|
|
365
|
+
title: r.title,
|
|
366
|
+
summary: r.summary,
|
|
367
|
+
payload_preview: r.payload_preview,
|
|
368
|
+
payload_uri: r.payload_uri,
|
|
369
|
+
environment_version: r.environment_version,
|
|
370
|
+
environment_lock_hash: r.environment_lock_hash,
|
|
371
|
+
verifier_hash: r.verifier_hash,
|
|
372
|
+
semantic_tags: JSON.parse(r.semantic_tags),
|
|
373
|
+
reuse_count: r.reuse_count,
|
|
374
|
+
author_agent_id: r.author_agent_id,
|
|
375
|
+
relevance_score: r.id === lineage.artifact_id ? 1.0 : 0.8,
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
const totalMatches = allMatched.length;
|
|
379
|
+
const paged = allMatched.slice(offset, offset + input.limit);
|
|
380
|
+
const nextCursor = offset + input.limit < totalMatches
|
|
381
|
+
? Buffer.from(JSON.stringify({ offset: offset + input.limit }), 'utf8').toString('base64url')
|
|
382
|
+
: null;
|
|
383
|
+
if (!agent.readOnly) {
|
|
384
|
+
logMcpEvent(this.db, {
|
|
385
|
+
agentId: agent.agentId,
|
|
386
|
+
workspaceId: input.workspace_id ?? null,
|
|
387
|
+
toolName: 'query_cache',
|
|
388
|
+
outcomeCode: 'OK',
|
|
389
|
+
returnedIds: paged.map((r) => r.artifact_id),
|
|
390
|
+
latencyMs: performance.now() - t0,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
return {
|
|
394
|
+
results: paged,
|
|
395
|
+
total_matches: totalMatches,
|
|
396
|
+
next_cursor: nextCursor,
|
|
397
|
+
...(input.lineage_of ? { lineage } : {}),
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
/** 3. claim_node (Atomic CAS TTL Lease) */
|
|
401
|
+
claimNode(rawInput, agent) {
|
|
402
|
+
const t0 = performance.now();
|
|
403
|
+
this.assertWritableAgent(agent, 'claim_node');
|
|
404
|
+
const input = ClaimNodeInput.parse(rawInput);
|
|
405
|
+
const node = this.db.prepare('SELECT * FROM nodes WHERE id = ?').get(input.node_id);
|
|
406
|
+
if (!node)
|
|
407
|
+
throw new SwarmError('NOT_FOUND', `Node ${input.node_id} not found`);
|
|
408
|
+
const ws = assertWorkspaceAccess(this.db, node.workspace_id, agent, true);
|
|
409
|
+
const now = nowIso();
|
|
410
|
+
const expiresAt = new Date(Date.now() + input.ttl_seconds * 1000).toISOString();
|
|
411
|
+
if (input.action === 'release') {
|
|
412
|
+
if (!input.lease_token)
|
|
413
|
+
throw new SwarmError('INVALID_INPUT', 'lease_token required to release');
|
|
414
|
+
const res = this.db.prepare(`
|
|
415
|
+
UPDATE nodes
|
|
416
|
+
SET status = 'open', claim_agent_id = NULL, claim_lease_token_hash = NULL,
|
|
417
|
+
claim_intent_summary = NULL, claim_expires_at = NULL, version = version + 1, updated_at = ?
|
|
418
|
+
WHERE id = ? AND status = 'claimed' AND claim_agent_id = ? AND claim_lease_token_hash = ?
|
|
419
|
+
`).run(now, node.id, agent.agentId, sha256Hex(input.lease_token));
|
|
420
|
+
if (res.changes === 0) {
|
|
421
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'claim_node', outcomeCode: 'LEASE_EXPIRED', latencyMs: performance.now() - t0 });
|
|
422
|
+
throw new SwarmError('LEASE_EXPIRED', 'Active lease not held by this agent/token');
|
|
423
|
+
}
|
|
424
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'claim_node', outcomeCode: 'OK', latencyMs: performance.now() - t0 });
|
|
425
|
+
return { node_id: node.id, status: 'open', lease_active: false, lease_token: null, expires_at: null, node_spec: null };
|
|
426
|
+
}
|
|
427
|
+
if (input.action === 'renew') {
|
|
428
|
+
if (!input.lease_token)
|
|
429
|
+
throw new SwarmError('INVALID_INPUT', 'lease_token required to renew');
|
|
430
|
+
const res = this.db.prepare(`
|
|
431
|
+
UPDATE nodes
|
|
432
|
+
SET claim_expires_at = ?, version = version + 1, updated_at = ?
|
|
433
|
+
WHERE id = ? AND status = 'claimed' AND claim_agent_id = ?
|
|
434
|
+
AND claim_lease_token_hash = ? AND claim_expires_at > ?
|
|
435
|
+
`).run(expiresAt, now, node.id, agent.agentId, sha256Hex(input.lease_token), now);
|
|
436
|
+
if (res.changes === 0) {
|
|
437
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'claim_node', outcomeCode: 'LEASE_EXPIRED', latencyMs: performance.now() - t0 });
|
|
438
|
+
throw new SwarmError('LEASE_EXPIRED', 'Lease expired or invalid token');
|
|
439
|
+
}
|
|
440
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'claim_node', outcomeCode: 'OK', latencyMs: performance.now() - t0 });
|
|
441
|
+
return { node_id: node.id, status: 'claimed', lease_active: true, lease_token: input.lease_token, expires_at: expiresAt, node_spec: null };
|
|
442
|
+
}
|
|
443
|
+
// Action: acquire (atomic CAS)
|
|
444
|
+
const rawToken = `lse_${crypto.randomBytes(24).toString('hex')}`;
|
|
445
|
+
const res = this.db.prepare(`
|
|
446
|
+
UPDATE nodes
|
|
447
|
+
SET status = 'claimed',
|
|
448
|
+
claim_agent_id = ?,
|
|
449
|
+
claim_lease_token_hash = ?,
|
|
450
|
+
claim_intent_summary = ?,
|
|
451
|
+
claim_expires_at = ?,
|
|
452
|
+
version = version + 1,
|
|
453
|
+
updated_at = ?
|
|
454
|
+
WHERE id = ?
|
|
455
|
+
AND (status = 'open' OR (status = 'claimed' AND claim_expires_at < ?))
|
|
456
|
+
`).run(agent.agentId, sha256Hex(rawToken), input.intent_summary ?? null, expiresAt, now, node.id, now);
|
|
457
|
+
if (res.changes === 0) {
|
|
458
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'claim_node', outcomeCode: 'LEASE_CONFLICT', latencyMs: performance.now() - t0 });
|
|
459
|
+
throw new SwarmError('LEASE_CONFLICT', `Node ${node.id} is currently ${node.status}`, true, {
|
|
460
|
+
current_status: node.status,
|
|
461
|
+
claim_expires_at: node.claim_expires_at,
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
const specContent = this.git.readFileAtCommit(ws.git_repo_uri, ws.git_head_sha, node.spec_git_path) ?? node.spec_summary;
|
|
465
|
+
const parentArtifacts = this.db
|
|
466
|
+
.prepare(`
|
|
467
|
+
SELECT a.id FROM artifacts a
|
|
468
|
+
JOIN node_edges e ON e.parent_node_id = a.source_node_id
|
|
469
|
+
WHERE e.child_node_id = ? AND a.artifact_type <> 'dead_end'
|
|
470
|
+
`)
|
|
471
|
+
.all(node.id)
|
|
472
|
+
.map((r) => r.id);
|
|
473
|
+
const verifierCfg = JSON.parse(ws.verifier_config);
|
|
474
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'claim_node', outcomeCode: 'OK', latencyMs: performance.now() - t0 });
|
|
475
|
+
return {
|
|
476
|
+
node_id: node.id,
|
|
477
|
+
status: 'claimed',
|
|
478
|
+
lease_active: true,
|
|
479
|
+
lease_token: rawToken,
|
|
480
|
+
expires_at: expiresAt,
|
|
481
|
+
node_spec: {
|
|
482
|
+
title: node.title,
|
|
483
|
+
type: node.type,
|
|
484
|
+
spec_content: specContent,
|
|
485
|
+
required_precheck: Boolean(verifierCfg.require_precheck ?? verifierCfg.required_precheck),
|
|
486
|
+
parent_artifacts: parentArtifacts,
|
|
487
|
+
},
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
/** 4. submit_artifact (Stage 0 Control-Plane Preflight + Enqueue + Optional Sync Wait) */
|
|
491
|
+
async submitArtifact(rawInput, agent) {
|
|
492
|
+
const t0 = performance.now();
|
|
493
|
+
this.assertWritableAgent(agent, 'submit_artifact');
|
|
494
|
+
const input = SubmitArtifactInput.parse(rawInput);
|
|
495
|
+
const node = this.db.prepare('SELECT * FROM nodes WHERE id = ?').get(input.node_id);
|
|
496
|
+
if (!node)
|
|
497
|
+
throw new SwarmError('NOT_FOUND', `Node ${input.node_id} not found`);
|
|
498
|
+
const ws = assertWorkspaceAccess(this.db, node.workspace_id, agent, true);
|
|
499
|
+
const verifierCfg = JSON.parse(ws.verifier_config);
|
|
500
|
+
// Stage 0.1: Quota & active lease verification
|
|
501
|
+
const quotaDecision = this.checkHourlyQuota(agent, ws);
|
|
502
|
+
const now = nowIso();
|
|
503
|
+
if (node.status === 'verified') {
|
|
504
|
+
throw new SwarmError('LEASE_CONFLICT', 'Node is already verified');
|
|
505
|
+
}
|
|
506
|
+
if (node.status === 'claimed' && node.claim_expires_at > now) {
|
|
507
|
+
if (node.claim_agent_id !== agent.agentId ||
|
|
508
|
+
!input.lease_token ||
|
|
509
|
+
sha256Hex(input.lease_token) !== node.claim_lease_token_hash) {
|
|
510
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'submit_artifact', outcomeCode: 'LEASE_CONFLICT', latencyMs: performance.now() - t0 });
|
|
511
|
+
throw new SwarmError('LEASE_CONFLICT', 'Valid lease_token held by calling agent is required');
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
// Stage 0.2: Domain Pack prerequisite DAG gate (e.g., FormalizationAudit for math-lean4@v1,
|
|
515
|
+
// AuditSpec for foundry-evm@v1, SafetySpec for rust-kani@v1) via public DomainPackRegistry (E5-3)
|
|
516
|
+
const workspacePack = this.packRegistry.get(ws.domain_pack_ref);
|
|
517
|
+
if (workspacePack) {
|
|
518
|
+
const prereqGate = workspacePack.validatePreSubmit({
|
|
519
|
+
db: this.db,
|
|
520
|
+
workspace: { id: ws.id, domain_pack_ref: ws.domain_pack_ref, verifier_config: verifierCfg },
|
|
521
|
+
node: { id: node.id, type: node.type, title: node.title },
|
|
522
|
+
files: [],
|
|
523
|
+
});
|
|
524
|
+
if (!prereqGate.ok) {
|
|
525
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'submit_artifact', outcomeCode: prereqGate.code, latencyMs: performance.now() - t0 });
|
|
526
|
+
throw new SwarmError(prereqGate.code, prereqGate.message, false, prereqGate.details ?? {});
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
// Stage 0.3: Materialize files & validate precheck_proof
|
|
530
|
+
const files = [];
|
|
531
|
+
if (input.payload.format === 'inline_files' && input.payload.files?.length) {
|
|
532
|
+
for (const f of input.payload.files) {
|
|
533
|
+
files.push({
|
|
534
|
+
path: f.path,
|
|
535
|
+
content: Buffer.from(f.content, f.encoding === 'base64' ? 'base64' : 'utf8'),
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
else if (input.payload.format === 'blob_refs' && input.payload.blob_refs?.length && this.blobs) {
|
|
540
|
+
for (const ref of input.payload.blob_refs) {
|
|
541
|
+
const content = this.blobs.getBlob(ref.sha256);
|
|
542
|
+
if (!content) {
|
|
543
|
+
throw new SwarmError('INVALID_INPUT', `Missing blob ${ref.sha256} for ${ref.path}`);
|
|
544
|
+
}
|
|
545
|
+
files.push({ path: ref.path, content });
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
else if (input.payload.format === 'markdown' && input.payload.markdown) {
|
|
549
|
+
files.push({ path: input.payload.entrypoint ?? 'submission.md', content: Buffer.from(input.payload.markdown, 'utf8') });
|
|
550
|
+
}
|
|
551
|
+
else {
|
|
552
|
+
throw new SwarmError('INVALID_INPUT', 'Submission payload must contain inline_files, blob_refs, or markdown');
|
|
553
|
+
}
|
|
554
|
+
// Stage 0.3a: Lock anti-slop USD stake if node carries an active staked USD bounty (E5-2)
|
|
555
|
+
let lockedStake = null;
|
|
556
|
+
const activeBounty = getActiveBountyForNode(this.db, node.id);
|
|
557
|
+
if (activeBounty && activeBounty.anti_slop_stake_cents > 0) {
|
|
558
|
+
lockedStake = lockAntiSlopStake(this.db, {
|
|
559
|
+
bountyId: activeBounty.id,
|
|
560
|
+
nodeId: node.id,
|
|
561
|
+
agentId: agent.agentId,
|
|
562
|
+
operatorId: agent.operatorId,
|
|
563
|
+
stakeCents: activeBounty.anti_slop_stake_cents,
|
|
564
|
+
now,
|
|
565
|
+
}).stake;
|
|
566
|
+
}
|
|
567
|
+
const refundStakeIfLocked = (reason) => {
|
|
568
|
+
if (lockedStake) {
|
|
569
|
+
refundAntiSlopStake(this.db, { stakeId: lockedStake.id, reason, now });
|
|
570
|
+
lockedStake = null;
|
|
571
|
+
}
|
|
572
|
+
};
|
|
573
|
+
const slashStakeIfLocked = (reason) => {
|
|
574
|
+
if (lockedStake) {
|
|
575
|
+
slashAntiSlopStake(this.db, { stakeId: lockedStake.id, reason, now });
|
|
576
|
+
lockedStake = null;
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
// Stage 0.3b: Always-on Domain Pack Stage 0 static tripwire dispatch (E5-3)
|
|
580
|
+
const envLockCfg = (verifierCfg.environment_lock ?? {});
|
|
581
|
+
if (workspacePack) {
|
|
582
|
+
const packCheck = workspacePack.validatePreSubmit({
|
|
583
|
+
db: this.db,
|
|
584
|
+
workspace: { id: ws.id, domain_pack_ref: ws.domain_pack_ref, verifier_config: verifierCfg },
|
|
585
|
+
node: { id: node.id, type: node.type, title: node.title },
|
|
586
|
+
files,
|
|
587
|
+
});
|
|
588
|
+
if (!packCheck.ok) {
|
|
589
|
+
if (packCheck.slashable) {
|
|
590
|
+
slashStakeIfLocked(`stage_0_tripwire:${packCheck.details?.rule ?? 'pack_violation'} in ${packCheck.details?.file ?? node.id}`);
|
|
591
|
+
}
|
|
592
|
+
else {
|
|
593
|
+
refundStakeIfLocked('pack_precheck_failed');
|
|
594
|
+
}
|
|
595
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'submit_artifact', outcomeCode: packCheck.code, latencyMs: performance.now() - t0 });
|
|
596
|
+
throw new SwarmError(packCheck.code, packCheck.message, false, {
|
|
597
|
+
...(packCheck.details ?? {}),
|
|
598
|
+
...(activeBounty && activeBounty.anti_slop_stake_cents > 0 && packCheck.slashable
|
|
599
|
+
? { anti_slop_stake_slashed: true }
|
|
600
|
+
: {}),
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
for (const f of files) {
|
|
605
|
+
const filePack = this.packRegistry.resolveForFile(f.path);
|
|
606
|
+
if (!filePack || filePack.manifest.id === workspacePack?.manifest.id)
|
|
607
|
+
continue;
|
|
608
|
+
const scan = filePack.scanStaticTripwire(f.path, f.content.toString('utf8'), envLockCfg);
|
|
609
|
+
if (!scan.ok) {
|
|
610
|
+
const isSlashable = (scan.severity ?? 'reward_hack') === 'reward_hack';
|
|
611
|
+
if (isSlashable) {
|
|
612
|
+
slashStakeIfLocked(`stage_0_tripwire:${scan.rule} in ${f.path}`);
|
|
613
|
+
}
|
|
614
|
+
else {
|
|
615
|
+
refundStakeIfLocked('file_pack_precheck_failed');
|
|
616
|
+
}
|
|
617
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'submit_artifact', outcomeCode: 'PRECHECK_FAILED', latencyMs: performance.now() - t0 });
|
|
618
|
+
throw new SwarmError('PRECHECK_FAILED', `${scan.message} in ${f.path}`, false, {
|
|
619
|
+
pack_id: filePack.manifest.id,
|
|
620
|
+
rule: scan.rule,
|
|
621
|
+
line: scan.line,
|
|
622
|
+
file: f.path,
|
|
623
|
+
...(activeBounty && activeBounty.anti_slop_stake_cents > 0 && isSlashable
|
|
624
|
+
? { anti_slop_stake_slashed: true }
|
|
625
|
+
: {}),
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
const requirePrecheck = Boolean(verifierCfg.require_precheck ?? verifierCfg.required_precheck);
|
|
630
|
+
if (requirePrecheck || input.precheck_proof) {
|
|
631
|
+
if (!input.precheck_proof) {
|
|
632
|
+
refundStakeIfLocked('missing_precheck_proof');
|
|
633
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'submit_artifact', outcomeCode: 'PRECHECK_FAILED', latencyMs: performance.now() - t0 });
|
|
634
|
+
throw new SwarmError('PRECHECK_FAILED', 'Workspace requires precheck_proof from caisson-lean precheck');
|
|
635
|
+
}
|
|
636
|
+
if (input.precheck_proof.environment_lock_hash !== ws.environment_lock_hash) {
|
|
637
|
+
refundStakeIfLocked('environment_lock_mismatch');
|
|
638
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'submit_artifact', outcomeCode: 'PRECHECK_FAILED', latencyMs: performance.now() - t0 });
|
|
639
|
+
throw new SwarmError('PRECHECK_FAILED', 'environment_lock_hash mismatch with pinned workspace lock', false, {
|
|
640
|
+
expected: ws.environment_lock_hash,
|
|
641
|
+
received: input.precheck_proof.environment_lock_hash,
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
for (const f of files) {
|
|
645
|
+
const expectedHash = input.precheck_proof.file_hashes[f.path];
|
|
646
|
+
if (!expectedHash || sha256Hex(f.content) !== expectedHash) {
|
|
647
|
+
refundStakeIfLocked('precheck_file_hash_mismatch');
|
|
648
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'submit_artifact', outcomeCode: 'PRECHECK_FAILED', latencyMs: performance.now() - t0 });
|
|
649
|
+
throw new SwarmError('PRECHECK_FAILED', `File hash mismatch for ${f.path}`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
// Stage 0.4: repo_root optimistic base_git_sha & protected path checks (04 v1.1)
|
|
654
|
+
const baseSha = ws.merge_target === 'repo_root' ? input.base_git_sha ?? ws.git_head_sha : ws.git_head_sha;
|
|
655
|
+
if (ws.merge_target === 'repo_root') {
|
|
656
|
+
if (!input.base_git_sha) {
|
|
657
|
+
refundStakeIfLocked('missing_base_git_sha');
|
|
658
|
+
throw new SwarmError('INVALID_INPUT', 'base_git_sha is required when workspace.merge_target == repo_root');
|
|
659
|
+
}
|
|
660
|
+
const targetPaths = files.map((f) => f.path);
|
|
661
|
+
const protectedViolations = this.git.findProtectedViolations(targetPaths, verifierCfg.protected_paths ?? []);
|
|
662
|
+
if (protectedViolations.length > 0) {
|
|
663
|
+
slashStakeIfLocked(`protected_path_violation: ${protectedViolations.join(',')}`);
|
|
664
|
+
throw new SwarmError('UNAUTHORIZED', 'Attempted write to protected repository paths', false, {
|
|
665
|
+
protected_paths: protectedViolations,
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
const conflicts = this.git.detectStaleBaseConflicts(ws.git_repo_uri, input.base_git_sha, targetPaths);
|
|
669
|
+
if (conflicts.length > 0) {
|
|
670
|
+
refundStakeIfLocked('stale_base');
|
|
671
|
+
logMcpEvent(this.db, { agentId: agent.agentId, workspaceId: ws.id, nodeId: node.id, toolName: 'submit_artifact', outcomeCode: 'STALE_BASE', latencyMs: performance.now() - t0 });
|
|
672
|
+
throw new SwarmError('STALE_BASE', 'main modified overlapping files since base_git_sha; rebase and resubmit', true, {
|
|
673
|
+
conflicting_paths: conflicts,
|
|
674
|
+
current_head_sha: this.git.getHeadSha(ws.git_repo_uri),
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
// Write isolated attempt ref (never touches main)
|
|
679
|
+
const runId = newId('run');
|
|
680
|
+
if (quotaDecision.overflowRequired) {
|
|
681
|
+
burnOverflowCompute(this.db, {
|
|
682
|
+
operatorId: agent.operatorId,
|
|
683
|
+
tier: quotaDecision.overflowTier,
|
|
684
|
+
workspaceId: ws.id,
|
|
685
|
+
runId,
|
|
686
|
+
now,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
const { ref } = this.git.writeAttemptRef(ws.git_repo_uri, runId, baseSha, files, `attempt(${node.id}): ${runId} by ${agent.agentId}`);
|
|
690
|
+
this.db.transaction(() => {
|
|
691
|
+
this.db.prepare(`
|
|
692
|
+
INSERT INTO verification_runs
|
|
693
|
+
(id, workspace_id, node_id, agent_id, base_git_sha, submission_git_ref,
|
|
694
|
+
precheck_proof, payload_meta, verifier_hash, status, created_at)
|
|
695
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?)
|
|
696
|
+
`).run(runId, ws.id, node.id, agent.agentId, baseSha, ref, input.precheck_proof ? JSON.stringify(input.precheck_proof) : null, JSON.stringify({
|
|
697
|
+
artifact_type: input.artifact_type,
|
|
698
|
+
summary: input.summary ?? node.title,
|
|
699
|
+
semantic_tags: input.semantic_tags ?? [],
|
|
700
|
+
derived_from: input.derived_from,
|
|
701
|
+
entrypoint: input.payload.entrypoint ?? files[0]?.path,
|
|
702
|
+
...(lockedStake ? { anti_slop_stake_id: lockedStake.id } : {}),
|
|
703
|
+
}), verifierCfg.digest ?? sha256Hex(ws.verifier_config), now);
|
|
704
|
+
if (lockedStake) {
|
|
705
|
+
attachRunToAntiSlopStake(this.db, lockedStake.id, runId);
|
|
706
|
+
}
|
|
707
|
+
this.db.prepare(`UPDATE nodes SET status = 'verifying', updated_at = ? WHERE id = ?`).run(now, node.id);
|
|
708
|
+
})();
|
|
709
|
+
const deadline = Date.now() + input.wait_timeout_seconds * 1000;
|
|
710
|
+
let runRow = this.db.prepare('SELECT * FROM verification_runs WHERE id = ?').get(runId);
|
|
711
|
+
while ((runRow.status === 'queued' || runRow.status === 'running') && Date.now() < deadline) {
|
|
712
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
713
|
+
runRow = this.db.prepare('SELECT * FROM verification_runs WHERE id = ?').get(runId);
|
|
714
|
+
}
|
|
715
|
+
const updatedNode = this.db.prepare('SELECT * FROM nodes WHERE id = ?').get(node.id);
|
|
716
|
+
const artifact = runRow.status === 'pass'
|
|
717
|
+
? this.db
|
|
718
|
+
.prepare('SELECT id, content_hash, payload_uri FROM artifacts WHERE source_node_id = ? ORDER BY created_at DESC LIMIT 1')
|
|
719
|
+
.get(node.id)
|
|
720
|
+
: null;
|
|
721
|
+
logMcpEvent(this.db, {
|
|
722
|
+
agentId: agent.agentId,
|
|
723
|
+
workspaceId: ws.id,
|
|
724
|
+
nodeId: node.id,
|
|
725
|
+
toolName: 'submit_artifact',
|
|
726
|
+
outcomeCode: runRow.status === 'fail' ? 'VERIFICATION_FAILED' : 'OK',
|
|
727
|
+
returnedIds: artifact ? [artifact.id] : [],
|
|
728
|
+
latencyMs: performance.now() - t0,
|
|
729
|
+
});
|
|
730
|
+
return {
|
|
731
|
+
run_id: runId,
|
|
732
|
+
node_id: node.id,
|
|
733
|
+
node_status: updatedNode.status,
|
|
734
|
+
merged: runRow.status === 'pass' && Boolean(artifact),
|
|
735
|
+
artifact_id: artifact?.id ?? null,
|
|
736
|
+
content_hash: artifact?.content_hash ?? null,
|
|
737
|
+
git_commit_sha: runRow.status === 'pass' ? this.git.getHeadSha(ws.git_repo_uri) : null,
|
|
738
|
+
verifier_result: runRow.verifier_result ? JSON.parse(runRow.verifier_result) : null,
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
/** 5. log_dead_end */
|
|
742
|
+
logDeadEnd(rawInput, agent) {
|
|
743
|
+
const t0 = performance.now();
|
|
744
|
+
this.assertWritableAgent(agent, 'log_dead_end');
|
|
745
|
+
const input = LogDeadEndInput.parse(rawInput);
|
|
746
|
+
const node = this.db.prepare('SELECT * FROM nodes WHERE id = ?').get(input.node_id);
|
|
747
|
+
if (!node)
|
|
748
|
+
throw new SwarmError('NOT_FOUND', `Node ${input.node_id} not found`);
|
|
749
|
+
const ws = assertWorkspaceAccess(this.db, node.workspace_id, agent, true);
|
|
750
|
+
const artifactId = newId('art');
|
|
751
|
+
const now = nowIso();
|
|
752
|
+
const evidence = input.counterexample_or_evidence;
|
|
753
|
+
const contentHash = sha256Hex(`${ws.environment_lock_hash}:${evidence.evidence_type}:${evidence.content}`);
|
|
754
|
+
const record = {
|
|
755
|
+
artifact_id: artifactId,
|
|
756
|
+
node_id: node.id,
|
|
757
|
+
author_agent_id: agent.agentId,
|
|
758
|
+
approach_summary: input.approach_summary,
|
|
759
|
+
evidence,
|
|
760
|
+
derived_from: input.derived_from,
|
|
761
|
+
created_at: now,
|
|
762
|
+
};
|
|
763
|
+
const commitSha = this.git.commitDeadEndRecord(ws.git_repo_uri, node.id, artifactId, record);
|
|
764
|
+
const payloadUri = `git://${ws.slug}@${commitSha}/nodes/${node.id}/dead_ends/${artifactId}.json`;
|
|
765
|
+
const nextStatus = input.release_lease ? 'open' : node.status;
|
|
766
|
+
this.db.transaction(() => {
|
|
767
|
+
this.db.prepare(`UPDATE workspaces SET git_head_sha = ?, updated_at = ? WHERE id = ?`).run(commitSha, now, ws.id);
|
|
768
|
+
this.db.prepare(`
|
|
769
|
+
INSERT OR IGNORE INTO artifacts
|
|
770
|
+
(id, workspace_id, source_node_id, author_agent_id, content_hash, artifact_type,
|
|
771
|
+
visibility, domain_pack_ref, title, summary, payload_preview, payload_uri,
|
|
772
|
+
environment_version, environment_lock_hash, verifier_hash, semantic_tags, created_at)
|
|
773
|
+
VALUES (?, ?, ?, ?, ?, 'dead_end', ?, ?, ?, ?, ?, ?, ?, ?, 'unverified', ?, ?)
|
|
774
|
+
`).run(artifactId, ws.id, node.id, agent.agentId, contentHash, ws.visibility, ws.domain_pack_ref, `Dead end on ${node.title}`, input.approach_summary, evidence.content.slice(0, 4000), payloadUri, ws.environment_version, ws.environment_lock_hash, JSON.stringify(input.semantic_tags ?? [evidence.evidence_type]), now);
|
|
775
|
+
for (const parentArtId of input.derived_from) {
|
|
776
|
+
this.db
|
|
777
|
+
.prepare('INSERT OR IGNORE INTO artifact_lineage (artifact_id, parent_artifact_id) VALUES (?, ?)')
|
|
778
|
+
.run(artifactId, parentArtId);
|
|
779
|
+
}
|
|
780
|
+
if (input.release_lease && node.status === 'claimed') {
|
|
781
|
+
this.db.prepare(`
|
|
782
|
+
UPDATE nodes SET status = 'open', claim_agent_id = NULL, claim_lease_token_hash = NULL,
|
|
783
|
+
claim_expires_at = NULL, updated_at = ?
|
|
784
|
+
WHERE id = ? AND claim_agent_id = ?
|
|
785
|
+
`).run(now, node.id, agent.agentId);
|
|
786
|
+
}
|
|
787
|
+
})();
|
|
788
|
+
// Index semantic embedding for the logged dead end (E3-2)
|
|
789
|
+
indexArtifactEmbeddingSync(this.db, artifactId);
|
|
790
|
+
logMcpEvent(this.db, {
|
|
791
|
+
agentId: agent.agentId,
|
|
792
|
+
workspaceId: ws.id,
|
|
793
|
+
nodeId: node.id,
|
|
794
|
+
toolName: 'log_dead_end',
|
|
795
|
+
outcomeCode: 'OK',
|
|
796
|
+
returnedIds: [artifactId],
|
|
797
|
+
latencyMs: performance.now() - t0,
|
|
798
|
+
});
|
|
799
|
+
return {
|
|
800
|
+
artifact_id: artifactId,
|
|
801
|
+
content_hash: contentHash,
|
|
802
|
+
node_id: node.id,
|
|
803
|
+
node_status: nextStatus,
|
|
804
|
+
evidence_verified: false,
|
|
805
|
+
verifier_result: null,
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
//# sourceMappingURL=handlers.js.map
|