caisson-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.math-mvp.md +28 -0
- package/README.md +37 -2
- package/dist/admin/adminRoutes.d.ts +10 -0
- package/dist/admin/adminRoutes.js +194 -0
- package/dist/admin/adminRoutes.js.map +1 -0
- package/dist/admin/index.d.ts +2 -0
- package/dist/admin/index.js +4 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/admin/workspaceAdmin.d.ts +417 -0
- package/dist/admin/workspaceAdmin.js +569 -0
- package/dist/admin/workspaceAdmin.js.map +1 -0
- package/dist/analytics/index.d.ts +1 -0
- package/dist/analytics/index.js +3 -0
- package/dist/analytics/index.js.map +1 -0
- package/dist/analytics/metrics.d.ts +105 -0
- package/dist/analytics/metrics.js +837 -0
- package/dist/analytics/metrics.js.map +1 -0
- package/dist/audit/index.d.ts +4 -0
- package/dist/audit/index.js +6 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/pipeline.d.ts +90 -0
- package/dist/audit/pipeline.js +424 -0
- package/dist/audit/pipeline.js.map +1 -0
- package/dist/audit/receiptSchema.d.ts +441 -0
- package/dist/audit/receiptSchema.js +208 -0
- package/dist/audit/receiptSchema.js.map +1 -0
- package/dist/audit/stageA.d.ts +50 -0
- package/dist/audit/stageA.js +218 -0
- package/dist/audit/stageA.js.map +1 -0
- package/dist/audit/stageB.d.ts +48 -0
- package/dist/audit/stageB.js +113 -0
- package/dist/audit/stageB.js.map +1 -0
- package/dist/auth/agentAuth.d.ts +18 -0
- package/dist/auth/agentAuth.js +59 -0
- package/dist/auth/agentAuth.js.map +1 -0
- package/dist/auth/agentCardSigner.d.ts +55 -0
- package/dist/auth/agentCardSigner.js +188 -0
- package/dist/auth/agentCardSigner.js.map +1 -0
- package/dist/billing/billingRoutes.d.ts +11 -0
- package/dist/billing/billingRoutes.js +303 -0
- package/dist/billing/billingRoutes.js.map +1 -0
- package/dist/billing/bountyRoutes.d.ts +9 -0
- package/dist/billing/bountyRoutes.js +332 -0
- package/dist/billing/bountyRoutes.js.map +1 -0
- package/dist/billing/index.d.ts +3 -0
- package/dist/billing/index.js +4 -0
- package/dist/billing/index.js.map +1 -0
- package/dist/billing/subscriptions.d.ts +226 -0
- package/dist/billing/subscriptions.js +673 -0
- package/dist/billing/subscriptions.js.map +1 -0
- package/dist/cli/caissonCli.d.ts +10 -0
- package/dist/cli/caissonCli.js +471 -0
- package/dist/cli/caissonCli.js.map +1 -0
- package/dist/cli/inviteCard.d.ts +12 -0
- package/dist/cli/inviteCard.js +49 -0
- package/dist/cli/inviteCard.js.map +1 -0
- package/dist/cli/mcpProxy.d.ts +36 -0
- package/dist/cli/mcpProxy.js +292 -0
- package/dist/cli/mcpProxy.js.map +1 -0
- package/dist/config.d.ts +19 -0
- package/dist/config.js +28 -0
- package/dist/config.js.map +1 -0
- package/dist/db/adapter.d.ts +210 -0
- package/dist/db/adapter.js +769 -0
- package/dist/db/adapter.js.map +1 -0
- package/dist/db/sqlite.d.ts +7 -0
- package/dist/db/sqlite.js +60 -0
- package/dist/db/sqlite.js.map +1 -0
- package/dist/db/telemetry.d.ts +11 -0
- package/dist/db/telemetry.js +9 -0
- package/dist/db/telemetry.js.map +1 -0
- package/dist/economy/bountyEngine.d.ts +248 -0
- package/dist/economy/bountyEngine.js +836 -0
- package/dist/economy/bountyEngine.js.map +1 -0
- package/dist/economy/index.d.ts +5 -0
- package/dist/economy/index.js +6 -0
- package/dist/economy/index.js.map +1 -0
- package/dist/economy/scLedger.d.ts +183 -0
- package/dist/economy/scLedger.js +528 -0
- package/dist/economy/scLedger.js.map +1 -0
- package/dist/economy/scMinting.d.ts +177 -0
- package/dist/economy/scMinting.js +659 -0
- package/dist/economy/scMinting.js.map +1 -0
- package/dist/economy/scSinks.d.ts +135 -0
- package/dist/economy/scSinks.js +314 -0
- package/dist/economy/scSinks.js.map +1 -0
- package/dist/economy/usdLedger.d.ts +211 -0
- package/dist/economy/usdLedger.js +604 -0
- package/dist/economy/usdLedger.js.map +1 -0
- package/dist/mcp/handlers.d.ts +134 -0
- package/dist/mcp/handlers.js +781 -0
- package/dist/mcp/handlers.js.map +1 -0
- package/dist/mcp/httpServer.d.ts +25 -0
- package/dist/mcp/httpServer.js +368 -0
- package/dist/mcp/httpServer.js.map +1 -0
- package/dist/mcp/serverFactory.d.ts +4 -0
- package/dist/mcp/serverFactory.js +53 -0
- package/dist/mcp/serverFactory.js.map +1 -0
- package/dist/mcp/stdioServer.d.ts +2 -0
- package/dist/mcp/stdioServer.js +24 -0
- package/dist/mcp/stdioServer.js.map +1 -0
- package/dist/mcp/toolMetadata.d.ts +15 -0
- package/dist/mcp/toolMetadata.js +73 -0
- package/dist/mcp/toolMetadata.js.map +1 -0
- package/dist/memo/artifactIndex.d.ts +51 -0
- package/dist/memo/artifactIndex.js +162 -0
- package/dist/memo/artifactIndex.js.map +1 -0
- package/dist/memo/dependencyBundle.d.ts +33 -0
- package/dist/memo/dependencyBundle.js +86 -0
- package/dist/memo/dependencyBundle.js.map +1 -0
- package/dist/memo/embeddings.d.ts +110 -0
- package/dist/memo/embeddings.js +672 -0
- package/dist/memo/embeddings.js.map +1 -0
- package/dist/packs/foundryEvm.d.ts +21 -0
- package/dist/packs/foundryEvm.js +274 -0
- package/dist/packs/foundryEvm.js.map +1 -0
- package/dist/packs/index.d.ts +8 -0
- package/dist/packs/index.js +19 -0
- package/dist/packs/index.js.map +1 -0
- package/dist/packs/mathLean4.d.ts +7 -0
- package/dist/packs/mathLean4.js +145 -0
- package/dist/packs/mathLean4.js.map +1 -0
- package/dist/packs/rustKani.d.ts +17 -0
- package/dist/packs/rustKani.js +257 -0
- package/dist/packs/rustKani.js.map +1 -0
- package/dist/packs/sdk.d.ts +314 -0
- package/dist/packs/sdk.js +271 -0
- package/dist/packs/sdk.js.map +1 -0
- package/dist/preflight/leanTripwire.d.ts +19 -0
- package/dist/preflight/leanTripwire.js +105 -0
- package/dist/preflight/leanTripwire.js.map +1 -0
- package/dist/storage/blobStore.d.ts +11 -0
- package/dist/storage/blobStore.js +39 -0
- package/dist/storage/blobStore.js.map +1 -0
- package/dist/storage/gitStore.d.ts +68 -0
- package/dist/storage/gitStore.js +228 -0
- package/dist/storage/gitStore.js.map +1 -0
- package/dist/types/errors.d.ts +16 -0
- package/dist/types/errors.js +23 -0
- package/dist/types/errors.js.map +1 -0
- package/dist/types/schemas.d.ts +453 -0
- package/dist/types/schemas.js +197 -0
- package/dist/types/schemas.js.map +1 -0
- package/dist/web/discoveryRoutes.d.ts +20 -0
- package/dist/web/discoveryRoutes.js +456 -0
- package/dist/web/discoveryRoutes.js.map +1 -0
- package/dist/web/explorer/dagLayout.d.ts +41 -0
- package/dist/web/explorer/dagLayout.js +183 -0
- package/dist/web/explorer/dagLayout.js.map +1 -0
- package/dist/web/explorer/index.d.ts +45 -0
- package/dist/web/explorer/index.js +512 -0
- package/dist/web/explorer/index.js.map +1 -0
- package/dist/web/explorer/renderers.d.ts +35 -0
- package/dist/web/explorer/renderers.js +397 -0
- package/dist/web/explorer/renderers.js.map +1 -0
- package/dist/web/repoBrowser.d.ts +19 -0
- package/dist/web/repoBrowser.js +128 -0
- package/dist/web/repoBrowser.js.map +1 -0
- package/dist/worker/executionAdapter.d.ts +14 -0
- package/dist/worker/executionAdapter.js +162 -0
- package/dist/worker/executionAdapter.js.map +1 -0
- package/dist/worker/finalize.d.ts +21 -0
- package/dist/worker/finalize.js +146 -0
- package/dist/worker/finalize.js.map +1 -0
- package/dist/worker/firecrackerAdapter.d.ts +180 -0
- package/dist/worker/firecrackerAdapter.js +421 -0
- package/dist/worker/firecrackerAdapter.js.map +1 -0
- package/dist/worker/loop.d.ts +56 -0
- package/dist/worker/loop.js +239 -0
- package/dist/worker/loop.js.map +1 -0
- package/dist/worker/postMergeSync.d.ts +17 -0
- package/dist/worker/postMergeSync.js +52 -0
- package/dist/worker/postMergeSync.js.map +1 -0
- package/dist/worker/prepareInput.d.ts +41 -0
- package/dist/worker/prepareInput.js +130 -0
- package/dist/worker/prepareInput.js.map +1 -0
- package/dist/worker/queue.d.ts +83 -0
- package/dist/worker/queue.js +278 -0
- package/dist/worker/queue.js.map +1 -0
- package/dist/worker/sandbox.d.ts +2 -0
- package/dist/worker/sandbox.js +3 -0
- package/dist/worker/sandbox.js.map +1 -0
- package/dist/worker/webhook.d.ts +14 -0
- package/dist/worker/webhook.js +110 -0
- package/dist/worker/webhook.js.map +1 -0
- package/migrations/001_init.sql +193 -0
- package/migrations/002_epic3_scale.sql +34 -0
- package/migrations/003_swarm_credits.sql +153 -0
- package/migrations/004_usd_bounties.sql +216 -0
- package/migrations_pg/001_init.sql +229 -0
- package/migrations_pg/002_multitenant_rls.sql +63 -0
- package/migrations_pg/003_swarm_credits.sql +135 -0
- package/migrations_pg/004_usd_bounties.sql +201 -0
- package/package.json +55 -4
- package/packs/foundry-evm/pack.json +60 -0
- package/packs/foundry-evm/verifier/Dockerfile +9 -0
- package/packs/foundry-evm/verifier/run.py +160 -0
- package/packs/math-lean4/pack.json +68 -0
- package/packs/rust-kani/pack.json +53 -0
- package/packs/rust-kani/verifier/Dockerfile +7 -0
- package/packs/rust-kani/verifier/run.py +159 -0
- package/public/.well-known/agent-card.json +153 -0
- package/public/llms.txt +35 -0
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
// src/db/adapter.ts
|
|
2
|
+
// Unified Storage Adapter Layer for SQLite WAL (local dev/tests) and PostgreSQL + pgvector (production).
|
|
3
|
+
// Epic 3 / E3-1: Provides 100% behavioral parity across SQLite and PostgreSQL backends including:
|
|
4
|
+
// - Parameter placeholder normalization (? <-> $1, $2, ...)
|
|
5
|
+
// - Schema migrations (migrations/ vs migrations_pg/)
|
|
6
|
+
// - Transactional execution with optional tenant RLS scoping
|
|
7
|
+
// - Native vector storage & cosine similarity search (BLOB+JS cosine on SQLite, pgvector <=> on Postgres)
|
|
8
|
+
// - SKIP LOCKED resilient worker queue claiming, heartbeat tracking & stall recovery
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { nowIso, openDatabase } from './sqlite.js';
|
|
12
|
+
/**
|
|
13
|
+
* Converts SQLite-style `?` positional placeholders into PostgreSQL `$1, $2, ...` placeholders
|
|
14
|
+
* while leaving `?` inside single-quoted string literals and `--` / `/* *\/` comments untouched.
|
|
15
|
+
*/
|
|
16
|
+
export function toPgPlaceholders(sql) {
|
|
17
|
+
let out = '';
|
|
18
|
+
let paramIndex = 0;
|
|
19
|
+
let inSingle = false;
|
|
20
|
+
let inDouble = false;
|
|
21
|
+
let inLineComment = false;
|
|
22
|
+
let inBlockComment = false;
|
|
23
|
+
for (let i = 0; i < sql.length; i++) {
|
|
24
|
+
const ch = sql[i];
|
|
25
|
+
const next = sql[i + 1];
|
|
26
|
+
if (inLineComment) {
|
|
27
|
+
out += ch;
|
|
28
|
+
if (ch === '\n')
|
|
29
|
+
inLineComment = false;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
if (inBlockComment) {
|
|
33
|
+
out += ch;
|
|
34
|
+
if (ch === '*' && next === '/') {
|
|
35
|
+
out += '/';
|
|
36
|
+
i++;
|
|
37
|
+
inBlockComment = false;
|
|
38
|
+
}
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (!inSingle && !inDouble) {
|
|
42
|
+
if (ch === '-' && next === '-') {
|
|
43
|
+
out += '--';
|
|
44
|
+
i++;
|
|
45
|
+
inLineComment = true;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (ch === '/' && next === '*') {
|
|
49
|
+
out += '/*';
|
|
50
|
+
i++;
|
|
51
|
+
inBlockComment = true;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (ch === "'" && !inDouble) {
|
|
56
|
+
out += ch;
|
|
57
|
+
if (inSingle && next === "'") {
|
|
58
|
+
out += "'";
|
|
59
|
+
i++;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
inSingle = !inSingle;
|
|
63
|
+
}
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (ch === '"' && !inSingle) {
|
|
67
|
+
out += ch;
|
|
68
|
+
inDouble = !inDouble;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (ch === '?' && !inSingle && !inDouble) {
|
|
72
|
+
paramIndex += 1;
|
|
73
|
+
out += `$${paramIndex}`;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
out += ch;
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
/** Serializes a Float32Array into pgvector text wire format: `[0.123456,-0.234567,...]`. */
|
|
81
|
+
export function formatPgVector(vector) {
|
|
82
|
+
const parts = new Array(vector.length);
|
|
83
|
+
for (let i = 0; i < vector.length; i++) {
|
|
84
|
+
const v = Number.isFinite(vector[i]) ? vector[i] : 0;
|
|
85
|
+
parts[i] = Number(v).toFixed(6);
|
|
86
|
+
}
|
|
87
|
+
return `[${parts.join(',')}]`;
|
|
88
|
+
}
|
|
89
|
+
/** Parses a pgvector string (`[0.1,0.2]`), number[], or Buffer into a Float32Array. */
|
|
90
|
+
export function parsePgVector(raw) {
|
|
91
|
+
if (raw instanceof Float32Array)
|
|
92
|
+
return raw;
|
|
93
|
+
if (Buffer.isBuffer(raw)) {
|
|
94
|
+
const ab = raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength);
|
|
95
|
+
return new Float32Array(ab);
|
|
96
|
+
}
|
|
97
|
+
if (Array.isArray(raw)) {
|
|
98
|
+
return Float32Array.from(raw);
|
|
99
|
+
}
|
|
100
|
+
const trimmed = raw.trim().replace(/^\[/, '').replace(/\]$/, '');
|
|
101
|
+
if (!trimmed)
|
|
102
|
+
return new Float32Array(0);
|
|
103
|
+
const nums = trimmed.split(',').map((s) => Number(s.trim()));
|
|
104
|
+
return Float32Array.from(nums);
|
|
105
|
+
}
|
|
106
|
+
/** Encodes a Float32Array into a compact little-endian Buffer for SQLite BLOB storage. */
|
|
107
|
+
export function encodeFloat32Blob(vec) {
|
|
108
|
+
const buf = Buffer.allocUnsafe(vec.length * 4);
|
|
109
|
+
for (let i = 0; i < vec.length; i++) {
|
|
110
|
+
buf.writeFloatLE(vec[i], i * 4);
|
|
111
|
+
}
|
|
112
|
+
return buf;
|
|
113
|
+
}
|
|
114
|
+
/** Decodes a SQLite BLOB Buffer back into a Float32Array. */
|
|
115
|
+
export function decodeFloat32Blob(buf) {
|
|
116
|
+
const b = Buffer.isBuffer(buf) ? buf : Buffer.from(buf);
|
|
117
|
+
const len = Math.floor(b.byteLength / 4);
|
|
118
|
+
const out = new Float32Array(len);
|
|
119
|
+
for (let i = 0; i < len; i++) {
|
|
120
|
+
out[i] = b.readFloatLE(i * 4);
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
/** Computes cosine similarity in [-1, 1] between two equal-length Float32Arrays. */
|
|
125
|
+
export function dotCosineSimilarity(a, b) {
|
|
126
|
+
const len = Math.min(a.length, b.length);
|
|
127
|
+
if (len === 0)
|
|
128
|
+
return 0;
|
|
129
|
+
let dot = 0;
|
|
130
|
+
let normA = 0;
|
|
131
|
+
let normB = 0;
|
|
132
|
+
for (let i = 0; i < len; i++) {
|
|
133
|
+
const av = a[i];
|
|
134
|
+
const bv = b[i];
|
|
135
|
+
dot += av * bv;
|
|
136
|
+
normA += av * av;
|
|
137
|
+
normB += bv * bv;
|
|
138
|
+
}
|
|
139
|
+
const denom = Math.sqrt(normA) * Math.sqrt(normB);
|
|
140
|
+
return denom > 0 ? dot / denom : 0;
|
|
141
|
+
}
|
|
142
|
+
function normalizeSemanticTags(raw) {
|
|
143
|
+
if (Array.isArray(raw))
|
|
144
|
+
return raw.map(String);
|
|
145
|
+
if (typeof raw === 'string') {
|
|
146
|
+
try {
|
|
147
|
+
const parsed = JSON.parse(raw);
|
|
148
|
+
return Array.isArray(parsed) ? parsed.map(String) : [];
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return [];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return [];
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* SQLite WAL implementation of `StorageAdapter`.
|
|
158
|
+
* Wraps `better-sqlite3` and exposes async parity with `PostgresStorageAdapter`.
|
|
159
|
+
*/
|
|
160
|
+
export class SqliteStorageAdapter {
|
|
161
|
+
db;
|
|
162
|
+
defaultMigrationsDir;
|
|
163
|
+
dialect = 'sqlite';
|
|
164
|
+
ownsDb;
|
|
165
|
+
constructor(db, defaultMigrationsDir, ownsDb = false) {
|
|
166
|
+
this.db = db;
|
|
167
|
+
this.defaultMigrationsDir = defaultMigrationsDir;
|
|
168
|
+
this.ownsDb = ownsDb;
|
|
169
|
+
}
|
|
170
|
+
static open(dbPath, migrationsDir) {
|
|
171
|
+
const db = openDatabase(dbPath, migrationsDir);
|
|
172
|
+
return new SqliteStorageAdapter(db, migrationsDir, true);
|
|
173
|
+
}
|
|
174
|
+
rawSqlite() {
|
|
175
|
+
return this.db;
|
|
176
|
+
}
|
|
177
|
+
async migrate(migrationsDir) {
|
|
178
|
+
const dir = migrationsDir ?? this.defaultMigrationsDir;
|
|
179
|
+
if (!dir || !fs.existsSync(dir))
|
|
180
|
+
return [];
|
|
181
|
+
this.db.exec(`
|
|
182
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
183
|
+
version TEXT PRIMARY KEY,
|
|
184
|
+
applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
|
185
|
+
);
|
|
186
|
+
`);
|
|
187
|
+
const files = fs
|
|
188
|
+
.readdirSync(dir)
|
|
189
|
+
.filter((f) => f.endsWith('.sql'))
|
|
190
|
+
.sort();
|
|
191
|
+
const applied = new Set(this.db
|
|
192
|
+
.prepare('SELECT version FROM schema_migrations')
|
|
193
|
+
.all()
|
|
194
|
+
.map((r) => String(r.version)));
|
|
195
|
+
const newlyApplied = [];
|
|
196
|
+
for (const file of files) {
|
|
197
|
+
if (applied.has(file))
|
|
198
|
+
continue;
|
|
199
|
+
const sql = fs.readFileSync(path.join(dir, file), 'utf8');
|
|
200
|
+
this.db.transaction(() => {
|
|
201
|
+
this.db.exec(sql);
|
|
202
|
+
this.db.prepare('INSERT OR IGNORE INTO schema_migrations (version) VALUES (?)').run(file);
|
|
203
|
+
})();
|
|
204
|
+
newlyApplied.push(file);
|
|
205
|
+
}
|
|
206
|
+
return newlyApplied;
|
|
207
|
+
}
|
|
208
|
+
async query(sql, params = []) {
|
|
209
|
+
return this.db.prepare(sql).all(...params);
|
|
210
|
+
}
|
|
211
|
+
async queryOne(sql, params = []) {
|
|
212
|
+
const row = this.db.prepare(sql).get(...params);
|
|
213
|
+
return row ?? null;
|
|
214
|
+
}
|
|
215
|
+
async execute(sql, params = []) {
|
|
216
|
+
const info = this.db.prepare(sql).run(...params);
|
|
217
|
+
return { changes: info.changes };
|
|
218
|
+
}
|
|
219
|
+
async transaction(fn) {
|
|
220
|
+
// SQLite transactions in better-sqlite3 are synchronous at the driver level;
|
|
221
|
+
// use explicit BEGIN IMMEDIATE / COMMIT / ROLLBACK so async callbacks work cleanly.
|
|
222
|
+
const inTx = this.db.inTransaction;
|
|
223
|
+
if (!inTx) {
|
|
224
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
225
|
+
}
|
|
226
|
+
try {
|
|
227
|
+
const result = await fn(this);
|
|
228
|
+
if (!inTx) {
|
|
229
|
+
this.db.exec('COMMIT');
|
|
230
|
+
}
|
|
231
|
+
return result;
|
|
232
|
+
}
|
|
233
|
+
catch (err) {
|
|
234
|
+
if (!inTx && this.db.inTransaction) {
|
|
235
|
+
this.db.exec('ROLLBACK');
|
|
236
|
+
}
|
|
237
|
+
throw err;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
async healthCheck() {
|
|
241
|
+
const t0 = performance.now();
|
|
242
|
+
const row = this.db.prepare('SELECT 1 AS ok').get();
|
|
243
|
+
return {
|
|
244
|
+
ok: row?.ok === 1,
|
|
245
|
+
dialect: 'sqlite',
|
|
246
|
+
latencyMs: Number((performance.now() - t0).toFixed(3)),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
async close() {
|
|
250
|
+
if (this.ownsDb && this.db.open) {
|
|
251
|
+
this.db.close();
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
async upsertArtifactEmbedding(record) {
|
|
255
|
+
const updatedAt = record.updatedAt ?? nowIso();
|
|
256
|
+
this.db
|
|
257
|
+
.prepare(`
|
|
258
|
+
INSERT INTO artifact_embeddings (artifact_id, model, dimensions, vector_blob, content_sha256, updated_at)
|
|
259
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
260
|
+
ON CONFLICT(artifact_id) DO UPDATE SET
|
|
261
|
+
model = excluded.model,
|
|
262
|
+
dimensions = excluded.dimensions,
|
|
263
|
+
vector_blob = excluded.vector_blob,
|
|
264
|
+
content_sha256 = excluded.content_sha256,
|
|
265
|
+
updated_at = excluded.updated_at
|
|
266
|
+
`)
|
|
267
|
+
.run(record.artifactId, record.model, record.dimensions, encodeFloat32Blob(record.vector), record.contentSha256, updatedAt);
|
|
268
|
+
}
|
|
269
|
+
async getArtifactEmbedding(artifactId) {
|
|
270
|
+
const row = this.db
|
|
271
|
+
.prepare('SELECT * FROM artifact_embeddings WHERE artifact_id = ?')
|
|
272
|
+
.get(artifactId);
|
|
273
|
+
if (!row)
|
|
274
|
+
return null;
|
|
275
|
+
return {
|
|
276
|
+
artifactId: row.artifact_id,
|
|
277
|
+
model: row.model,
|
|
278
|
+
dimensions: Number(row.dimensions),
|
|
279
|
+
vector: decodeFloat32Blob(row.vector_blob),
|
|
280
|
+
contentSha256: row.content_sha256,
|
|
281
|
+
updatedAt: row.updated_at,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
async vectorSearchArtifacts(params) {
|
|
285
|
+
const agent = params.agentId ?? null;
|
|
286
|
+
const filters = [
|
|
287
|
+
`(a.visibility = 'public' OR (? IS NOT NULL AND EXISTS (
|
|
288
|
+
SELECT 1 FROM workspace_members wm
|
|
289
|
+
WHERE wm.workspace_id = a.workspace_id AND wm.agent_id = ?
|
|
290
|
+
)))`,
|
|
291
|
+
];
|
|
292
|
+
const sqlParams = [agent, agent];
|
|
293
|
+
if (params.workspaceId) {
|
|
294
|
+
filters.push('a.workspace_id = ?');
|
|
295
|
+
sqlParams.push(params.workspaceId);
|
|
296
|
+
}
|
|
297
|
+
if (params.domain) {
|
|
298
|
+
filters.push('a.domain_pack_ref LIKE ?');
|
|
299
|
+
sqlParams.push(`${params.domain}%`);
|
|
300
|
+
}
|
|
301
|
+
if (params.environmentVersion) {
|
|
302
|
+
filters.push('a.environment_version LIKE ?');
|
|
303
|
+
sqlParams.push(`${params.environmentVersion}%`);
|
|
304
|
+
}
|
|
305
|
+
if (params.environmentLockHash) {
|
|
306
|
+
filters.push('a.environment_lock_hash = ?');
|
|
307
|
+
sqlParams.push(params.environmentLockHash);
|
|
308
|
+
}
|
|
309
|
+
if (params.includeDeadEnds === false) {
|
|
310
|
+
filters.push(`a.artifact_type <> 'dead_end'`);
|
|
311
|
+
}
|
|
312
|
+
if (params.artifactTypes?.length) {
|
|
313
|
+
filters.push(`a.artifact_type IN (${params.artifactTypes.map(() => '?').join(',')})`);
|
|
314
|
+
sqlParams.push(...params.artifactTypes);
|
|
315
|
+
}
|
|
316
|
+
const rows = this.db
|
|
317
|
+
.prepare(`
|
|
318
|
+
SELECT a.*, e.vector_blob
|
|
319
|
+
FROM artifact_embeddings e
|
|
320
|
+
JOIN artifacts a ON a.id = e.artifact_id
|
|
321
|
+
WHERE ${filters.join(' AND ')}
|
|
322
|
+
`)
|
|
323
|
+
.all(...sqlParams);
|
|
324
|
+
const scored = [];
|
|
325
|
+
for (const row of rows) {
|
|
326
|
+
if (params.tags?.length) {
|
|
327
|
+
const rowTags = normalizeSemanticTags(row.semantic_tags);
|
|
328
|
+
if (!params.tags.every((t) => rowTags.includes(t)))
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
const vec = decodeFloat32Blob(row.vector_blob);
|
|
332
|
+
const sim = dotCosineSimilarity(params.queryVector, vec);
|
|
333
|
+
const { vector_blob: _blob, ...artifact } = row;
|
|
334
|
+
scored.push({ artifact, similarity: sim });
|
|
335
|
+
}
|
|
336
|
+
scored.sort((a, b) => b.similarity - a.similarity || String(a.artifact.id).localeCompare(String(b.artifact.id)));
|
|
337
|
+
const limit = Math.max(1, params.limit ?? 50);
|
|
338
|
+
return scored.slice(0, limit);
|
|
339
|
+
}
|
|
340
|
+
async claimNextVerificationRun(params) {
|
|
341
|
+
const now = params.now ?? nowIso();
|
|
342
|
+
const caps = params.tierConcurrencyCaps ?? {};
|
|
343
|
+
const claimTx = this.db.transaction(() => {
|
|
344
|
+
const activeCounts = new Map();
|
|
345
|
+
const activeRows = this.db
|
|
346
|
+
.prepare(`
|
|
347
|
+
SELECT a.rate_limit_tier AS tier, COUNT(*) AS cnt
|
|
348
|
+
FROM verification_runs r
|
|
349
|
+
JOIN agent_identities a ON a.id = r.agent_id
|
|
350
|
+
WHERE r.status = 'running'
|
|
351
|
+
GROUP BY a.rate_limit_tier
|
|
352
|
+
`)
|
|
353
|
+
.all();
|
|
354
|
+
for (const r of activeRows) {
|
|
355
|
+
activeCounts.set(r.tier, Number(r.cnt));
|
|
356
|
+
}
|
|
357
|
+
const candidates = this.db
|
|
358
|
+
.prepare(`
|
|
359
|
+
SELECT r.*, a.rate_limit_tier
|
|
360
|
+
FROM verification_runs r
|
|
361
|
+
JOIN agent_identities a ON a.id = r.agent_id
|
|
362
|
+
WHERE r.status = 'queued'
|
|
363
|
+
AND (r.next_attempt_at IS NULL OR r.next_attempt_at <= ?)
|
|
364
|
+
ORDER BY
|
|
365
|
+
CASE a.rate_limit_tier
|
|
366
|
+
WHEN 'pro_team' THEN 100
|
|
367
|
+
WHEN 'pro' THEN 50
|
|
368
|
+
ELSE 0
|
|
369
|
+
END DESC,
|
|
370
|
+
r.created_at ASC,
|
|
371
|
+
r.id ASC
|
|
372
|
+
LIMIT 50
|
|
373
|
+
`)
|
|
374
|
+
.all(now);
|
|
375
|
+
for (const cand of candidates) {
|
|
376
|
+
const tier = cand.rate_limit_tier ?? 'standard';
|
|
377
|
+
const cap = caps[tier];
|
|
378
|
+
const active = activeCounts.get(tier) ?? 0;
|
|
379
|
+
if (typeof cap === 'number' && cap >= 0 && active >= cap) {
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
const upd = this.db
|
|
383
|
+
.prepare(`
|
|
384
|
+
UPDATE verification_runs
|
|
385
|
+
SET status = 'running',
|
|
386
|
+
worker_id = ?,
|
|
387
|
+
claimed_at = ?,
|
|
388
|
+
heartbeat_at = ?,
|
|
389
|
+
attempt_count = attempt_count + 1
|
|
390
|
+
WHERE id = ? AND status = 'queued'
|
|
391
|
+
`)
|
|
392
|
+
.run(params.workerId, now, now, cand.id);
|
|
393
|
+
if (upd.changes === 1) {
|
|
394
|
+
return {
|
|
395
|
+
...cand,
|
|
396
|
+
status: 'running',
|
|
397
|
+
worker_id: params.workerId,
|
|
398
|
+
claimed_at: now,
|
|
399
|
+
heartbeat_at: now,
|
|
400
|
+
attempt_count: Number(cand.attempt_count ?? 0) + 1,
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return null;
|
|
405
|
+
});
|
|
406
|
+
return claimTx.immediate();
|
|
407
|
+
}
|
|
408
|
+
async heartbeatVerificationRun(runId, workerId, now = nowIso()) {
|
|
409
|
+
const info = this.db
|
|
410
|
+
.prepare(`
|
|
411
|
+
UPDATE verification_runs
|
|
412
|
+
SET heartbeat_at = ?
|
|
413
|
+
WHERE id = ? AND status = 'running' AND worker_id = ?
|
|
414
|
+
`)
|
|
415
|
+
.run(now, runId, workerId);
|
|
416
|
+
return info.changes === 1;
|
|
417
|
+
}
|
|
418
|
+
async countActiveRunsByTier() {
|
|
419
|
+
const rows = this.db
|
|
420
|
+
.prepare(`
|
|
421
|
+
SELECT a.rate_limit_tier AS tier, COUNT(*) AS cnt
|
|
422
|
+
FROM verification_runs r
|
|
423
|
+
JOIN agent_identities a ON a.id = r.agent_id
|
|
424
|
+
WHERE r.status = 'running'
|
|
425
|
+
GROUP BY a.rate_limit_tier
|
|
426
|
+
`)
|
|
427
|
+
.all();
|
|
428
|
+
const counts = {};
|
|
429
|
+
for (const r of rows)
|
|
430
|
+
counts[r.tier] = Number(r.cnt);
|
|
431
|
+
return counts;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
class PostgresTxAdapter {
|
|
435
|
+
client;
|
|
436
|
+
dialect = 'postgres';
|
|
437
|
+
constructor(client) {
|
|
438
|
+
this.client = client;
|
|
439
|
+
}
|
|
440
|
+
async query(sql, params = []) {
|
|
441
|
+
const pgSql = toPgPlaceholders(sql);
|
|
442
|
+
const res = await this.client.query(pgSql, params);
|
|
443
|
+
return res.rows;
|
|
444
|
+
}
|
|
445
|
+
async queryOne(sql, params = []) {
|
|
446
|
+
const rows = await this.query(sql, params);
|
|
447
|
+
return rows[0] ?? null;
|
|
448
|
+
}
|
|
449
|
+
async execute(sql, params = []) {
|
|
450
|
+
const pgSql = toPgPlaceholders(sql);
|
|
451
|
+
const res = await this.client.query(pgSql, params);
|
|
452
|
+
return { changes: res.rowCount ?? 0 };
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* PostgreSQL 16+ & `pgvector` implementation of `StorageAdapter`.
|
|
457
|
+
* Works with any `pg.Pool` (`node-postgres`) or compatible `PgPoolLike` driver.
|
|
458
|
+
*/
|
|
459
|
+
export class PostgresStorageAdapter {
|
|
460
|
+
pool;
|
|
461
|
+
defaultMigrationsDir;
|
|
462
|
+
dialect = 'postgres';
|
|
463
|
+
constructor(pool, defaultMigrationsDir) {
|
|
464
|
+
this.pool = pool;
|
|
465
|
+
this.defaultMigrationsDir = defaultMigrationsDir;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Opens a PostgreSQL connection pool via dynamic `import('pg')` so `pg` remains optional
|
|
469
|
+
* in lightweight SQLite-only dev environments.
|
|
470
|
+
*/
|
|
471
|
+
static async connect(databaseUrl, migrationsDir, poolOpts) {
|
|
472
|
+
let pgMod;
|
|
473
|
+
try {
|
|
474
|
+
// Dynamic specifier prevents tsc from requiring @types/pg when pg is installed as optional prod dep
|
|
475
|
+
const moduleName = 'pg';
|
|
476
|
+
pgMod = await import(moduleName);
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
throw new Error('PostgreSQL driver "pg" is not installed. Run `npm install pg` to use DATABASE_URL / CAISSON_DB_DRIVER=postgres.');
|
|
480
|
+
}
|
|
481
|
+
const PoolCtor = pgMod.Pool ?? pgMod.default?.Pool;
|
|
482
|
+
if (!PoolCtor) {
|
|
483
|
+
throw new Error('Could not resolve Pool constructor from "pg" package.');
|
|
484
|
+
}
|
|
485
|
+
const pool = new PoolCtor({
|
|
486
|
+
connectionString: databaseUrl,
|
|
487
|
+
max: poolOpts?.max ?? Number(process.env.CAISSON_PG_POOL_MAX ?? 20),
|
|
488
|
+
idleTimeoutMillis: poolOpts?.idleTimeoutMillis ?? 30_000,
|
|
489
|
+
connectionTimeoutMillis: poolOpts?.connectionTimeoutMillis ?? 10_000,
|
|
490
|
+
});
|
|
491
|
+
const adapter = new PostgresStorageAdapter(pool, migrationsDir);
|
|
492
|
+
if (migrationsDir) {
|
|
493
|
+
await adapter.migrate(migrationsDir);
|
|
494
|
+
}
|
|
495
|
+
return adapter;
|
|
496
|
+
}
|
|
497
|
+
rawSqlite() {
|
|
498
|
+
return null;
|
|
499
|
+
}
|
|
500
|
+
async migrate(migrationsDir) {
|
|
501
|
+
const dir = migrationsDir ?? this.defaultMigrationsDir;
|
|
502
|
+
if (!dir || !fs.existsSync(dir))
|
|
503
|
+
return [];
|
|
504
|
+
await this.pool.query(`
|
|
505
|
+
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
506
|
+
version TEXT PRIMARY KEY,
|
|
507
|
+
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
508
|
+
);
|
|
509
|
+
`);
|
|
510
|
+
const files = fs
|
|
511
|
+
.readdirSync(dir)
|
|
512
|
+
.filter((f) => f.endsWith('.sql'))
|
|
513
|
+
.sort();
|
|
514
|
+
const appliedRes = await this.pool.query('SELECT version FROM schema_migrations');
|
|
515
|
+
const applied = new Set(appliedRes.rows.map((r) => String(r.version)));
|
|
516
|
+
const newlyApplied = [];
|
|
517
|
+
for (const file of files) {
|
|
518
|
+
if (applied.has(file))
|
|
519
|
+
continue;
|
|
520
|
+
const sql = fs.readFileSync(path.join(dir, file), 'utf8');
|
|
521
|
+
await this.transaction(async (tx) => {
|
|
522
|
+
await tx.execute(sql);
|
|
523
|
+
await tx.execute('INSERT INTO schema_migrations (version) VALUES ($1) ON CONFLICT (version) DO NOTHING', [file]);
|
|
524
|
+
});
|
|
525
|
+
newlyApplied.push(file);
|
|
526
|
+
}
|
|
527
|
+
return newlyApplied;
|
|
528
|
+
}
|
|
529
|
+
async query(sql, params = []) {
|
|
530
|
+
const pgSql = toPgPlaceholders(sql);
|
|
531
|
+
const res = await this.pool.query(pgSql, params);
|
|
532
|
+
return res.rows;
|
|
533
|
+
}
|
|
534
|
+
async queryOne(sql, params = []) {
|
|
535
|
+
const rows = await this.query(sql, params);
|
|
536
|
+
return rows[0] ?? null;
|
|
537
|
+
}
|
|
538
|
+
async execute(sql, params = []) {
|
|
539
|
+
const pgSql = toPgPlaceholders(sql);
|
|
540
|
+
const res = await this.pool.query(pgSql, params);
|
|
541
|
+
return { changes: res.rowCount ?? 0 };
|
|
542
|
+
}
|
|
543
|
+
async transaction(fn, opts) {
|
|
544
|
+
const client = await this.pool.connect();
|
|
545
|
+
const tx = new PostgresTxAdapter(client);
|
|
546
|
+
try {
|
|
547
|
+
await client.query('BEGIN');
|
|
548
|
+
if (opts?.tenantAgentId) {
|
|
549
|
+
await client.query(`SELECT set_config('caisson.enforce_rls', 'on', true)`);
|
|
550
|
+
await client.query(`SELECT set_config('caisson.agent_id', $1, true)`, [
|
|
551
|
+
opts.tenantAgentId,
|
|
552
|
+
]);
|
|
553
|
+
}
|
|
554
|
+
const result = await fn(tx);
|
|
555
|
+
await client.query('COMMIT');
|
|
556
|
+
return result;
|
|
557
|
+
}
|
|
558
|
+
catch (err) {
|
|
559
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
560
|
+
throw err;
|
|
561
|
+
}
|
|
562
|
+
finally {
|
|
563
|
+
client.release();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
async healthCheck() {
|
|
567
|
+
const t0 = performance.now();
|
|
568
|
+
const res = await this.pool.query('SELECT 1 AS ok');
|
|
569
|
+
return {
|
|
570
|
+
ok: Number(res.rows[0]?.ok) === 1,
|
|
571
|
+
dialect: 'postgres',
|
|
572
|
+
latencyMs: Number((performance.now() - t0).toFixed(3)),
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
async close() {
|
|
576
|
+
await this.pool.end();
|
|
577
|
+
}
|
|
578
|
+
async upsertArtifactEmbedding(record) {
|
|
579
|
+
const updatedAt = record.updatedAt ?? nowIso();
|
|
580
|
+
const vectorLiteral = formatPgVector(record.vector);
|
|
581
|
+
await this.pool.query(`
|
|
582
|
+
INSERT INTO artifact_embeddings (artifact_id, model, dimensions, embedding, content_sha256, updated_at)
|
|
583
|
+
VALUES ($1, $2, $3, $4::vector, $5, $6)
|
|
584
|
+
ON CONFLICT (artifact_id) DO UPDATE SET
|
|
585
|
+
model = EXCLUDED.model,
|
|
586
|
+
dimensions = EXCLUDED.dimensions,
|
|
587
|
+
embedding = EXCLUDED.embedding,
|
|
588
|
+
content_sha256 = EXCLUDED.content_sha256,
|
|
589
|
+
updated_at = EXCLUDED.updated_at
|
|
590
|
+
`, [record.artifactId, record.model, record.dimensions, vectorLiteral, record.contentSha256, updatedAt]);
|
|
591
|
+
}
|
|
592
|
+
async getArtifactEmbedding(artifactId) {
|
|
593
|
+
const res = await this.pool.query('SELECT artifact_id, model, dimensions, embedding, content_sha256, updated_at FROM artifact_embeddings WHERE artifact_id = $1', [artifactId]);
|
|
594
|
+
const row = res.rows[0];
|
|
595
|
+
if (!row)
|
|
596
|
+
return null;
|
|
597
|
+
return {
|
|
598
|
+
artifactId: String(row.artifact_id),
|
|
599
|
+
model: String(row.model),
|
|
600
|
+
dimensions: Number(row.dimensions),
|
|
601
|
+
vector: parsePgVector(row.embedding),
|
|
602
|
+
contentSha256: String(row.content_sha256),
|
|
603
|
+
updatedAt: String(row.updated_at),
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
async vectorSearchArtifacts(params) {
|
|
607
|
+
const vectorLiteral = formatPgVector(params.queryVector);
|
|
608
|
+
const agent = params.agentId ?? null;
|
|
609
|
+
const limit = Math.max(1, params.limit ?? 50);
|
|
610
|
+
const values = [vectorLiteral, agent];
|
|
611
|
+
let idx = 2;
|
|
612
|
+
const nextParam = (val) => {
|
|
613
|
+
values.push(val);
|
|
614
|
+
idx += 1;
|
|
615
|
+
return `$${idx}`;
|
|
616
|
+
};
|
|
617
|
+
const filters = [
|
|
618
|
+
`(a.visibility = 'public' OR ($2::text IS NOT NULL AND EXISTS (
|
|
619
|
+
SELECT 1 FROM workspace_members wm
|
|
620
|
+
WHERE wm.workspace_id = a.workspace_id AND wm.agent_id = $2
|
|
621
|
+
)))`,
|
|
622
|
+
];
|
|
623
|
+
if (params.workspaceId) {
|
|
624
|
+
filters.push(`a.workspace_id = ${nextParam(params.workspaceId)}`);
|
|
625
|
+
}
|
|
626
|
+
if (params.domain) {
|
|
627
|
+
filters.push(`a.domain_pack_ref LIKE ${nextParam(`${params.domain}%`)}`);
|
|
628
|
+
}
|
|
629
|
+
if (params.environmentVersion) {
|
|
630
|
+
filters.push(`a.environment_version LIKE ${nextParam(`${params.environmentVersion}%`)}`);
|
|
631
|
+
}
|
|
632
|
+
if (params.environmentLockHash) {
|
|
633
|
+
filters.push(`a.environment_lock_hash = ${nextParam(params.environmentLockHash)}`);
|
|
634
|
+
}
|
|
635
|
+
if (params.includeDeadEnds === false) {
|
|
636
|
+
filters.push(`a.artifact_type <> 'dead_end'`);
|
|
637
|
+
}
|
|
638
|
+
if (params.artifactTypes?.length) {
|
|
639
|
+
const placeholders = params.artifactTypes.map((t) => nextParam(t)).join(',');
|
|
640
|
+
filters.push(`a.artifact_type IN (${placeholders})`);
|
|
641
|
+
}
|
|
642
|
+
if (params.tags?.length) {
|
|
643
|
+
filters.push(`a.semantic_tags @> ${nextParam(JSON.stringify(params.tags))}::jsonb`);
|
|
644
|
+
}
|
|
645
|
+
const limitParam = nextParam(limit);
|
|
646
|
+
const sql = `
|
|
647
|
+
SELECT a.*, (1.0 - (e.embedding <=> $1::vector)) AS cosine_similarity
|
|
648
|
+
FROM artifact_embeddings e
|
|
649
|
+
JOIN artifacts a ON a.id = e.artifact_id
|
|
650
|
+
WHERE ${filters.join(' AND ')}
|
|
651
|
+
ORDER BY e.embedding <=> $1::vector ASC, a.id ASC
|
|
652
|
+
LIMIT ${limitParam}
|
|
653
|
+
`;
|
|
654
|
+
const res = await this.pool.query(sql, values);
|
|
655
|
+
return res.rows.map((row) => {
|
|
656
|
+
const { cosine_similarity, ...artifact } = row;
|
|
657
|
+
return {
|
|
658
|
+
artifact,
|
|
659
|
+
similarity: Number(cosine_similarity ?? 0),
|
|
660
|
+
};
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Uses PostgreSQL `FOR UPDATE SKIP LOCKED` to claim the next eligible queued run
|
|
665
|
+
* across concurrent multi-host worker fleets with zero lock contention.
|
|
666
|
+
*/
|
|
667
|
+
async claimNextVerificationRun(params) {
|
|
668
|
+
const now = params.now ?? nowIso();
|
|
669
|
+
const caps = params.tierConcurrencyCaps ?? {};
|
|
670
|
+
return this.transaction(async (tx) => {
|
|
671
|
+
const activeRows = await tx.query(`
|
|
672
|
+
SELECT a.rate_limit_tier AS tier, COUNT(*) AS cnt
|
|
673
|
+
FROM verification_runs r
|
|
674
|
+
JOIN agent_identities a ON a.id = r.agent_id
|
|
675
|
+
WHERE r.status = 'running'
|
|
676
|
+
GROUP BY a.rate_limit_tier
|
|
677
|
+
`);
|
|
678
|
+
const activeCounts = new Map();
|
|
679
|
+
for (const r of activeRows) {
|
|
680
|
+
activeCounts.set(String(r.tier), Number(r.cnt));
|
|
681
|
+
}
|
|
682
|
+
const saturatedTiers = [];
|
|
683
|
+
for (const [tier, cap] of Object.entries(caps)) {
|
|
684
|
+
if (typeof cap === 'number' && cap >= 0 && (activeCounts.get(tier) ?? 0) >= cap) {
|
|
685
|
+
saturatedTiers.push(tier);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
const values = [now];
|
|
689
|
+
let tierClause = '';
|
|
690
|
+
if (saturatedTiers.length > 0) {
|
|
691
|
+
const placeholders = saturatedTiers.map((_, i) => `$${i + 2}`).join(',');
|
|
692
|
+
values.push(...saturatedTiers);
|
|
693
|
+
tierClause = `AND a.rate_limit_tier NOT IN (${placeholders})`;
|
|
694
|
+
}
|
|
695
|
+
const candidate = await tx.queryOne(`
|
|
696
|
+
SELECT r.*, a.rate_limit_tier
|
|
697
|
+
FROM verification_runs r
|
|
698
|
+
JOIN agent_identities a ON a.id = r.agent_id
|
|
699
|
+
WHERE r.status = 'queued'
|
|
700
|
+
AND (r.next_attempt_at IS NULL OR r.next_attempt_at <= $1)
|
|
701
|
+
${tierClause}
|
|
702
|
+
ORDER BY
|
|
703
|
+
CASE a.rate_limit_tier
|
|
704
|
+
WHEN 'pro_team' THEN 100
|
|
705
|
+
WHEN 'pro' THEN 50
|
|
706
|
+
ELSE 0
|
|
707
|
+
END DESC,
|
|
708
|
+
r.created_at ASC,
|
|
709
|
+
r.id ASC
|
|
710
|
+
FOR UPDATE OF r SKIP LOCKED
|
|
711
|
+
LIMIT 1
|
|
712
|
+
`, values);
|
|
713
|
+
if (!candidate)
|
|
714
|
+
return null;
|
|
715
|
+
await tx.execute(`
|
|
716
|
+
UPDATE verification_runs
|
|
717
|
+
SET status = 'running',
|
|
718
|
+
worker_id = $1,
|
|
719
|
+
claimed_at = $2,
|
|
720
|
+
heartbeat_at = $2,
|
|
721
|
+
attempt_count = attempt_count + 1
|
|
722
|
+
WHERE id = $3
|
|
723
|
+
`, [params.workerId, now, candidate.id]);
|
|
724
|
+
return {
|
|
725
|
+
...candidate,
|
|
726
|
+
status: 'running',
|
|
727
|
+
worker_id: params.workerId,
|
|
728
|
+
claimed_at: now,
|
|
729
|
+
heartbeat_at: now,
|
|
730
|
+
attempt_count: Number(candidate.attempt_count ?? 0) + 1,
|
|
731
|
+
};
|
|
732
|
+
});
|
|
733
|
+
}
|
|
734
|
+
async heartbeatVerificationRun(runId, workerId, now = nowIso()) {
|
|
735
|
+
const res = await this.execute(`
|
|
736
|
+
UPDATE verification_runs
|
|
737
|
+
SET heartbeat_at = $1
|
|
738
|
+
WHERE id = $2 AND status = 'running' AND worker_id = $3
|
|
739
|
+
`, [now, runId, workerId]);
|
|
740
|
+
return res.changes === 1;
|
|
741
|
+
}
|
|
742
|
+
async countActiveRunsByTier() {
|
|
743
|
+
const rows = await this.query(`
|
|
744
|
+
SELECT a.rate_limit_tier AS tier, COUNT(*) AS cnt
|
|
745
|
+
FROM verification_runs r
|
|
746
|
+
JOIN agent_identities a ON a.id = r.agent_id
|
|
747
|
+
WHERE r.status = 'running'
|
|
748
|
+
GROUP BY a.rate_limit_tier
|
|
749
|
+
`);
|
|
750
|
+
const counts = {};
|
|
751
|
+
for (const r of rows)
|
|
752
|
+
counts[String(r.tier)] = Number(r.cnt);
|
|
753
|
+
return counts;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Factory opening the configured storage backend (SQLite WAL by default, or PostgreSQL + pgvector
|
|
758
|
+
* when `cfg.dbDriver === 'postgres'` and `cfg.databaseUrl` is set).
|
|
759
|
+
*/
|
|
760
|
+
export async function openStorageAdapter(cfg) {
|
|
761
|
+
if (cfg.dbDriver === 'postgres') {
|
|
762
|
+
if (!cfg.databaseUrl) {
|
|
763
|
+
throw new Error('DATABASE_URL is required when CAISSON_DB_DRIVER=postgres');
|
|
764
|
+
}
|
|
765
|
+
return PostgresStorageAdapter.connect(cfg.databaseUrl, cfg.pgMigrationsDir);
|
|
766
|
+
}
|
|
767
|
+
return SqliteStorageAdapter.open(cfg.dbPath, cfg.migrationsDir);
|
|
768
|
+
}
|
|
769
|
+
//# sourceMappingURL=adapter.js.map
|