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,672 @@
|
|
|
1
|
+
// src/memo/embeddings.ts
|
|
2
|
+
// Hybrid Semantic Memoization Search (query_cache v2) — Epic 3 / E3-2.
|
|
3
|
+
// Embeds verified artifacts & dead ends, stores dense vectors (SQLite BLOB / Postgres pgvector),
|
|
4
|
+
// and fuses vector cosine similarity + FTS/BM25 lexical scores via Reciprocal Rank Fusion (RRF)
|
|
5
|
+
// with domain, environment_version, environment_lock_hash, tag, and privacy airlock enforcement.
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { decodeFloat32Blob, dotCosineSimilarity, encodeFloat32Blob, } from '../db/adapter.js';
|
|
8
|
+
import { nowIso, sha256Hex } from '../db/sqlite.js';
|
|
9
|
+
export const DEFAULT_EMBEDDING_DIM = 384;
|
|
10
|
+
/**
|
|
11
|
+
* Domain-aware concept clusters so semantically equivalent mathematical / formal-verification /
|
|
12
|
+
* systems terms share semantic basis coordinates even when exact surface tokens diverge.
|
|
13
|
+
*/
|
|
14
|
+
const DOMAIN_CONCEPT_CLUSTERS = [
|
|
15
|
+
{ concept: 'c_prime', terms: ['prime', 'primes', 'primality', 'natprime', 'chebyshev', 'pnt', 'vonmangoldt', 'mangoldt', 'sieve'] },
|
|
16
|
+
{ concept: 'c_zeta', terms: ['zeta', 'riemann', 'riemannzeta', 'dirichlet', 'euler', 'lfunction', 'zeros', 'critical', 'strip'] },
|
|
17
|
+
{ concept: 'c_analytic', terms: ['analytic', 'meromorphic', 'holomorphic', 'continuation', 'extension', 'complex', 'residue', 'contour', 'mellin', 'fourier', 'laplace'] },
|
|
18
|
+
{ concept: 'c_bound', terms: ['bound', 'bounds', 'bounded', 'inequality', 'estimate', 'asymptotic', 'upper', 'lower', 'growth', 'majorant', 'minorant'] },
|
|
19
|
+
{ concept: 'c_deadend', terms: ['dead', 'deadend', 'obstruction', 'counterexample', 'refute', 'refutes', 'refutation', 'falsify', 'fails', 'failure', 'diverges', 'resonance', 'blocked'] },
|
|
20
|
+
{ concept: 'c_algebra', terms: ['group', 'ring', 'field', 'module', 'ideal', 'homomorphism', 'isomorphism', 'polynomial', 'matrix', 'linear', 'eigenvalue'] },
|
|
21
|
+
{ concept: 'c_calculus', terms: ['integral', 'integrate', 'derivative', 'differentiable', 'limit', 'converge', 'convergence', 'series', 'summable', 'sum', 'summation', 'measure'] },
|
|
22
|
+
{ concept: 'c_logic', terms: ['theorem', 'lemma', 'corollary', 'conjecture', 'proof', 'induction', 'recursion', 'axiom', 'decidable', 'tactic', 'lean', 'mathlib'] },
|
|
23
|
+
{ concept: 'c_sat', terms: ['sat', 'cnf', 'dimacs', 'clause', 'assignment', 'boolean', 'witness', 'solver', 'graph', 'coloring', 'ramsey'] },
|
|
24
|
+
{ concept: 'c_infra', terms: ['sandbox', 'microvm', 'firecracker', 'kvm', 'gvisor', 'docker', 'container', 'jailer', 'rootfs', 'ext4', 'worker', 'queue'] },
|
|
25
|
+
{ concept: 'c_search', terms: ['cache', 'memoization', 'embedding', 'vector', 'pgvector', 'semantic', 'hybrid', 'fts', 'bm25', 'lineage', 'provenance'] },
|
|
26
|
+
{ concept: 'c_conj', terms: ['conjugate', 'conj', 'symmetry', 'functional', 'reflection', 'involution', 'adjoint', 'hermitian'] },
|
|
27
|
+
];
|
|
28
|
+
const TERM_TO_CONCEPTS = new Map();
|
|
29
|
+
for (const cluster of DOMAIN_CONCEPT_CLUSTERS) {
|
|
30
|
+
for (const term of cluster.terms) {
|
|
31
|
+
const existing = TERM_TO_CONCEPTS.get(term) ?? [];
|
|
32
|
+
existing.push(cluster.concept);
|
|
33
|
+
TERM_TO_CONCEPTS.set(term, existing);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const STOP_WORDS = new Set([
|
|
37
|
+
'the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'onto', 'are', 'was', 'were',
|
|
38
|
+
'been', 'have', 'has', 'had', 'not', 'but', 'all', 'any', 'can', 'will', 'use', 'using',
|
|
39
|
+
'used', 'via', 'per', 'its', 'our', 'their', 'when', 'where', 'which', 'while', 'over',
|
|
40
|
+
]);
|
|
41
|
+
export function normalizeVector(vec) {
|
|
42
|
+
let sumSq = 0;
|
|
43
|
+
for (let i = 0; i < vec.length; i++) {
|
|
44
|
+
sumSq += vec[i] * vec[i];
|
|
45
|
+
}
|
|
46
|
+
const norm = Math.sqrt(sumSq);
|
|
47
|
+
if (norm === 0)
|
|
48
|
+
return vec;
|
|
49
|
+
const out = new Float32Array(vec.length);
|
|
50
|
+
for (let i = 0; i < vec.length; i++) {
|
|
51
|
+
out[i] = vec[i] / norm;
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
export function cosineSimilarity(a, b) {
|
|
56
|
+
return dotCosineSimilarity(a, b);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Splits mathematical, Lean 4, and code identifiers (`Nat.Prime`, `riemannZeta`, `upper_bound`)
|
|
60
|
+
* into normalized lowercase tokens.
|
|
61
|
+
*/
|
|
62
|
+
export function tokenizeSemanticText(text) {
|
|
63
|
+
const expanded = text
|
|
64
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
65
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
|
|
66
|
+
.replace(/[._/\\:;,()[\]{}<>=+*&|!?@#"'`~-]+/g, ' ')
|
|
67
|
+
.toLowerCase();
|
|
68
|
+
return expanded
|
|
69
|
+
.split(/\s+/)
|
|
70
|
+
.map((t) => t.trim())
|
|
71
|
+
.filter((t) => t.length >= 2 && !STOP_WORDS.has(t));
|
|
72
|
+
}
|
|
73
|
+
function hashFeature(feature) {
|
|
74
|
+
const digest = crypto.createHash('sha256').update(feature, 'utf8').digest();
|
|
75
|
+
const idx1 = digest.readUInt32LE(0);
|
|
76
|
+
const sign1 = (digest[4] & 1) === 0 ? 1 : -1;
|
|
77
|
+
const idx2 = digest.readUInt32LE(8);
|
|
78
|
+
const sign2 = (digest[12] & 1) === 0 ? 1 : -1;
|
|
79
|
+
return { idx1, sign1, idx2, sign2 };
|
|
80
|
+
}
|
|
81
|
+
function addWeightedFeature(vec, feature, weight) {
|
|
82
|
+
const dim = vec.length;
|
|
83
|
+
const { idx1, sign1, idx2, sign2 } = hashFeature(feature);
|
|
84
|
+
vec[idx1 % dim] += sign1 * weight;
|
|
85
|
+
vec[idx2 % dim] += sign2 * (weight * 0.5);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Deterministic offline semantic embedder (384 dimensions).
|
|
89
|
+
* Combines token unigrams, phrase bigrams, subword character n-grams, and mathematical/engineering
|
|
90
|
+
* concept clusters into an L2-normalized dense unit vector. Zero external network dependency.
|
|
91
|
+
*/
|
|
92
|
+
export class LocalSemanticEmbeddingProvider {
|
|
93
|
+
modelId;
|
|
94
|
+
dimensions;
|
|
95
|
+
constructor(dimensions = DEFAULT_EMBEDDING_DIM, modelId = 'caisson-local-semantic-v2') {
|
|
96
|
+
this.dimensions = dimensions;
|
|
97
|
+
this.modelId = modelId;
|
|
98
|
+
}
|
|
99
|
+
embedSync(text) {
|
|
100
|
+
const vec = new Float32Array(this.dimensions);
|
|
101
|
+
const tokens = tokenizeSemanticText(text);
|
|
102
|
+
if (tokens.length === 0) {
|
|
103
|
+
return vec;
|
|
104
|
+
}
|
|
105
|
+
// Track term frequencies with sublinear TF scaling (1 + ln(tf))
|
|
106
|
+
const tf = new Map();
|
|
107
|
+
for (const tok of tokens) {
|
|
108
|
+
tf.set(tok, (tf.get(tok) ?? 0) + 1);
|
|
109
|
+
}
|
|
110
|
+
for (const [tok, count] of tf.entries()) {
|
|
111
|
+
const w = 1 + Math.log(count);
|
|
112
|
+
addWeightedFeature(vec, `tok:${tok}`, 2.4 * w);
|
|
113
|
+
// Stem-like prefix for morphological proximity
|
|
114
|
+
if (tok.length >= 5) {
|
|
115
|
+
addWeightedFeature(vec, `pre:${tok.slice(0, 5)}`, 1.1 * w);
|
|
116
|
+
}
|
|
117
|
+
// Character 4-grams capture subword & identifier overlap (e.g. riemannZeta / zeta_conj)
|
|
118
|
+
if (tok.length >= 4) {
|
|
119
|
+
const padded = `^${tok}$`;
|
|
120
|
+
const maxGrams = Math.min(padded.length - 3, 12);
|
|
121
|
+
for (let i = 0; i < maxGrams; i++) {
|
|
122
|
+
addWeightedFeature(vec, `c4:${padded.slice(i, i + 4)}`, 0.45 * w);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// Concept-cluster expansion for true cross-terminology semantic recall
|
|
126
|
+
const concepts = TERM_TO_CONCEPTS.get(tok);
|
|
127
|
+
if (concepts) {
|
|
128
|
+
for (const c of concepts) {
|
|
129
|
+
addWeightedFeature(vec, `con:${c}`, 2.8 * w);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
// Also check prefix matches against concept terms (e.g., 'primes' / 'analyticity')
|
|
134
|
+
for (const [term, cList] of TERM_TO_CONCEPTS.entries()) {
|
|
135
|
+
if (term.length >= 4 && (tok.startsWith(term) || term.startsWith(tok))) {
|
|
136
|
+
for (const c of cList) {
|
|
137
|
+
addWeightedFeature(vec, `con:${c}`, 1.6 * w);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// Token bigrams for multi-word phrase precision
|
|
144
|
+
const bigramLimit = Math.min(tokens.length - 1, 80);
|
|
145
|
+
for (let i = 0; i < bigramLimit; i++) {
|
|
146
|
+
addWeightedFeature(vec, `bi:${tokens[i]}_${tokens[i + 1]}`, 1.2);
|
|
147
|
+
}
|
|
148
|
+
return normalizeVector(vec);
|
|
149
|
+
}
|
|
150
|
+
async embed(text) {
|
|
151
|
+
return this.embedSync(text);
|
|
152
|
+
}
|
|
153
|
+
async embedBatch(texts) {
|
|
154
|
+
return texts.map((t) => this.embedSync(t));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* OpenAI-compatible HTTP Embedding provider (works with OpenAI, Voyage, Ollama, vLLM, TEI).
|
|
159
|
+
*/
|
|
160
|
+
export class HttpEmbeddingProvider {
|
|
161
|
+
modelId;
|
|
162
|
+
dimensions;
|
|
163
|
+
apiUrl;
|
|
164
|
+
apiKey;
|
|
165
|
+
timeoutMs;
|
|
166
|
+
constructor(cfg) {
|
|
167
|
+
this.apiUrl = cfg.apiUrl;
|
|
168
|
+
this.apiKey = cfg.apiKey;
|
|
169
|
+
this.modelId = cfg.modelId;
|
|
170
|
+
this.dimensions = cfg.dimensions ?? DEFAULT_EMBEDDING_DIM;
|
|
171
|
+
this.timeoutMs = cfg.timeoutMs ?? 15_000;
|
|
172
|
+
}
|
|
173
|
+
async embed(text) {
|
|
174
|
+
const [vec] = await this.embedBatch([text]);
|
|
175
|
+
return vec;
|
|
176
|
+
}
|
|
177
|
+
async embedBatch(texts) {
|
|
178
|
+
if (texts.length === 0)
|
|
179
|
+
return [];
|
|
180
|
+
const controller = new AbortController();
|
|
181
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
182
|
+
try {
|
|
183
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
184
|
+
if (this.apiKey)
|
|
185
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
186
|
+
const res = await fetch(this.apiUrl, {
|
|
187
|
+
method: 'POST',
|
|
188
|
+
headers,
|
|
189
|
+
signal: controller.signal,
|
|
190
|
+
body: JSON.stringify({
|
|
191
|
+
model: this.modelId,
|
|
192
|
+
input: texts,
|
|
193
|
+
dimensions: this.dimensions,
|
|
194
|
+
}),
|
|
195
|
+
});
|
|
196
|
+
if (!res.ok) {
|
|
197
|
+
const body = await res.text().catch(() => '');
|
|
198
|
+
throw new Error(`Embedding HTTP API failed (${res.status}): ${body.slice(0, 300)}`);
|
|
199
|
+
}
|
|
200
|
+
const parsed = (await res.json());
|
|
201
|
+
if (!Array.isArray(parsed.data) || parsed.data.length !== texts.length) {
|
|
202
|
+
throw new Error('Malformed embedding API response: missing data array');
|
|
203
|
+
}
|
|
204
|
+
const sorted = [...parsed.data].sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
|
|
205
|
+
return sorted.map((item) => normalizeVector(Float32Array.from(item.embedding ?? [])));
|
|
206
|
+
}
|
|
207
|
+
finally {
|
|
208
|
+
clearTimeout(timer);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const DEFAULT_LOCAL_PROVIDER = new LocalSemanticEmbeddingProvider();
|
|
213
|
+
export function createDefaultEmbeddingProvider() {
|
|
214
|
+
const mode = (process.env.CAISSON_EMBEDDING_PROVIDER ?? 'local').toLowerCase();
|
|
215
|
+
const apiUrl = process.env.CAISSON_EMBEDDING_API_URL?.trim();
|
|
216
|
+
if (mode === 'http' && apiUrl) {
|
|
217
|
+
return new HttpEmbeddingProvider({
|
|
218
|
+
apiUrl,
|
|
219
|
+
apiKey: process.env.CAISSON_EMBEDDING_API_KEY?.trim(),
|
|
220
|
+
modelId: process.env.CAISSON_EMBEDDING_MODEL?.trim() || 'text-embedding-3-small',
|
|
221
|
+
dimensions: Number(process.env.CAISSON_EMBEDDING_DIMENSIONS ?? DEFAULT_EMBEDDING_DIM),
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
return DEFAULT_LOCAL_PROVIDER;
|
|
225
|
+
}
|
|
226
|
+
export function buildArtifactEmbeddingText(artifact) {
|
|
227
|
+
let tags = [];
|
|
228
|
+
if (Array.isArray(artifact.semantic_tags)) {
|
|
229
|
+
tags = artifact.semantic_tags.map(String);
|
|
230
|
+
}
|
|
231
|
+
else if (typeof artifact.semantic_tags === 'string') {
|
|
232
|
+
try {
|
|
233
|
+
const parsed = JSON.parse(artifact.semantic_tags);
|
|
234
|
+
if (Array.isArray(parsed))
|
|
235
|
+
tags = parsed.map(String);
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
tags = [artifact.semantic_tags];
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return [
|
|
242
|
+
artifact.title ?? '',
|
|
243
|
+
artifact.summary ?? '',
|
|
244
|
+
tags.join(' '),
|
|
245
|
+
artifact.artifact_type ?? '',
|
|
246
|
+
artifact.domain_pack_ref ?? '',
|
|
247
|
+
String(artifact.payload_preview ?? '').slice(0, 2000),
|
|
248
|
+
]
|
|
249
|
+
.filter(Boolean)
|
|
250
|
+
.join('\n');
|
|
251
|
+
}
|
|
252
|
+
function hasEmbeddingsTable(db) {
|
|
253
|
+
const row = db
|
|
254
|
+
.prepare(`SELECT 1 AS hit FROM sqlite_master WHERE type = 'table' AND name = 'artifact_embeddings'`)
|
|
255
|
+
.get();
|
|
256
|
+
return Boolean(row?.hit);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Synchronously computes and upserts an embedding for a single SQLite artifact (verified or dead end).
|
|
260
|
+
* Safe no-op if `artifact_embeddings` table is not present on a legacy DB.
|
|
261
|
+
*/
|
|
262
|
+
export function indexArtifactEmbeddingSync(db, artifactId, provider = DEFAULT_LOCAL_PROVIDER) {
|
|
263
|
+
if (!hasEmbeddingsTable(db))
|
|
264
|
+
return false;
|
|
265
|
+
const art = db.prepare('SELECT * FROM artifacts WHERE id = ?').get(artifactId);
|
|
266
|
+
if (!art)
|
|
267
|
+
return false;
|
|
268
|
+
const text = buildArtifactEmbeddingText(art);
|
|
269
|
+
const contentSha256 = sha256Hex(`${provider.modelId}:${text}`);
|
|
270
|
+
const existing = db
|
|
271
|
+
.prepare('SELECT content_sha256, model FROM artifact_embeddings WHERE artifact_id = ?')
|
|
272
|
+
.get(artifactId);
|
|
273
|
+
if (existing && existing.content_sha256 === contentSha256 && existing.model === provider.modelId) {
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
const vector = provider.embedSync(text);
|
|
277
|
+
db.prepare(`
|
|
278
|
+
INSERT INTO artifact_embeddings (artifact_id, model, dimensions, vector_blob, content_sha256, updated_at)
|
|
279
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
280
|
+
ON CONFLICT(artifact_id) DO UPDATE SET
|
|
281
|
+
model = excluded.model,
|
|
282
|
+
dimensions = excluded.dimensions,
|
|
283
|
+
vector_blob = excluded.vector_blob,
|
|
284
|
+
content_sha256 = excluded.content_sha256,
|
|
285
|
+
updated_at = excluded.updated_at
|
|
286
|
+
`).run(artifactId, provider.modelId, provider.dimensions, encodeFloat32Blob(vector), contentSha256, nowIso());
|
|
287
|
+
return true;
|
|
288
|
+
}
|
|
289
|
+
/** Backfills embeddings for all unindexed artifacts (verified + dead ends) in SQLite. */
|
|
290
|
+
export function backfillArtifactEmbeddingsSync(db, provider = DEFAULT_LOCAL_PROVIDER) {
|
|
291
|
+
if (!hasEmbeddingsTable(db))
|
|
292
|
+
return 0;
|
|
293
|
+
const missing = db
|
|
294
|
+
.prepare(`
|
|
295
|
+
SELECT a.*
|
|
296
|
+
FROM artifacts a
|
|
297
|
+
LEFT JOIN artifact_embeddings e ON e.artifact_id = a.id
|
|
298
|
+
WHERE e.artifact_id IS NULL OR e.model <> ?
|
|
299
|
+
`)
|
|
300
|
+
.all(provider.modelId);
|
|
301
|
+
if (missing.length === 0)
|
|
302
|
+
return 0;
|
|
303
|
+
const stmt = db.prepare(`
|
|
304
|
+
INSERT INTO artifact_embeddings (artifact_id, model, dimensions, vector_blob, content_sha256, updated_at)
|
|
305
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
306
|
+
ON CONFLICT(artifact_id) DO UPDATE SET
|
|
307
|
+
model = excluded.model,
|
|
308
|
+
dimensions = excluded.dimensions,
|
|
309
|
+
vector_blob = excluded.vector_blob,
|
|
310
|
+
content_sha256 = excluded.content_sha256,
|
|
311
|
+
updated_at = excluded.updated_at
|
|
312
|
+
`);
|
|
313
|
+
const now = nowIso();
|
|
314
|
+
db.transaction(() => {
|
|
315
|
+
for (const art of missing) {
|
|
316
|
+
const text = buildArtifactEmbeddingText(art);
|
|
317
|
+
const vector = provider.embedSync(text);
|
|
318
|
+
stmt.run(art.id, provider.modelId, provider.dimensions, encodeFloat32Blob(vector), sha256Hex(`${provider.modelId}:${text}`), now);
|
|
319
|
+
}
|
|
320
|
+
})();
|
|
321
|
+
return missing.length;
|
|
322
|
+
}
|
|
323
|
+
/** Async embedding indexer working across both SQLite and PostgreSQL + pgvector via `StorageAdapter`. */
|
|
324
|
+
export async function indexArtifactEmbedding(adapter, artifactId, provider = createDefaultEmbeddingProvider()) {
|
|
325
|
+
const art = await adapter.queryOne('SELECT * FROM artifacts WHERE id = ?', [artifactId]);
|
|
326
|
+
if (!art)
|
|
327
|
+
return false;
|
|
328
|
+
const text = buildArtifactEmbeddingText(art);
|
|
329
|
+
const contentSha256 = sha256Hex(`${provider.modelId}:${text}`);
|
|
330
|
+
const existing = await adapter.getArtifactEmbedding(artifactId);
|
|
331
|
+
if (existing && existing.contentSha256 === contentSha256 && existing.model === provider.modelId) {
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
const vector = await provider.embed(text);
|
|
335
|
+
await adapter.upsertArtifactEmbedding({
|
|
336
|
+
artifactId,
|
|
337
|
+
model: provider.modelId,
|
|
338
|
+
dimensions: provider.dimensions,
|
|
339
|
+
vector,
|
|
340
|
+
contentSha256,
|
|
341
|
+
updatedAt: nowIso(),
|
|
342
|
+
});
|
|
343
|
+
return true;
|
|
344
|
+
}
|
|
345
|
+
/** Async backfill for all unindexed artifacts (verified + dead ends) via `StorageAdapter`. */
|
|
346
|
+
export async function backfillArtifactEmbeddings(adapter, provider = createDefaultEmbeddingProvider()) {
|
|
347
|
+
const rows = await adapter.query(`
|
|
348
|
+
SELECT a.*
|
|
349
|
+
FROM artifacts a
|
|
350
|
+
LEFT JOIN artifact_embeddings e ON e.artifact_id = a.id
|
|
351
|
+
WHERE e.artifact_id IS NULL OR e.model <> ?
|
|
352
|
+
`, [provider.modelId]);
|
|
353
|
+
if (rows.length === 0)
|
|
354
|
+
return 0;
|
|
355
|
+
const texts = rows.map((art) => buildArtifactEmbeddingText(art));
|
|
356
|
+
const vectors = await provider.embedBatch(texts);
|
|
357
|
+
const now = nowIso();
|
|
358
|
+
for (let i = 0; i < rows.length; i++) {
|
|
359
|
+
await adapter.upsertArtifactEmbedding({
|
|
360
|
+
artifactId: String(rows[i].id),
|
|
361
|
+
model: provider.modelId,
|
|
362
|
+
dimensions: provider.dimensions,
|
|
363
|
+
vector: vectors[i],
|
|
364
|
+
contentSha256: sha256Hex(`${provider.modelId}:${texts[i]}`),
|
|
365
|
+
updatedAt: now,
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
return rows.length;
|
|
369
|
+
}
|
|
370
|
+
function parseRowTags(raw) {
|
|
371
|
+
if (Array.isArray(raw))
|
|
372
|
+
return raw.map(String);
|
|
373
|
+
if (typeof raw === 'string') {
|
|
374
|
+
try {
|
|
375
|
+
const parsed = JSON.parse(raw);
|
|
376
|
+
return Array.isArray(parsed) ? parsed.map(String) : [];
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
return [];
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return [];
|
|
383
|
+
}
|
|
384
|
+
function fuseLexicalAndSemantic(params) {
|
|
385
|
+
const byId = new Map();
|
|
386
|
+
params.lexicalRows.forEach((entry, idx) => {
|
|
387
|
+
const id = String(entry.row.id);
|
|
388
|
+
byId.set(id, {
|
|
389
|
+
row: entry.row,
|
|
390
|
+
lexicalScore: entry.lexicalScore,
|
|
391
|
+
lexicalRank: idx + 1,
|
|
392
|
+
semanticScore: 0,
|
|
393
|
+
semanticRank: null,
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
params.semanticRows.forEach((entry, idx) => {
|
|
397
|
+
const id = String(entry.row.id);
|
|
398
|
+
const existing = byId.get(id);
|
|
399
|
+
if (existing) {
|
|
400
|
+
existing.semanticScore = entry.semanticScore;
|
|
401
|
+
existing.semanticRank = idx + 1;
|
|
402
|
+
}
|
|
403
|
+
else if (entry.semanticScore >= params.minSemanticScore) {
|
|
404
|
+
byId.set(id, {
|
|
405
|
+
row: entry.row,
|
|
406
|
+
lexicalScore: 0,
|
|
407
|
+
lexicalRank: null,
|
|
408
|
+
semanticScore: entry.semanticScore,
|
|
409
|
+
semanticRank: idx + 1,
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
const hits = [];
|
|
414
|
+
const maxRrf = (params.lexicalWeight + params.semanticWeight) / (params.rrfK + 1);
|
|
415
|
+
for (const item of byId.values()) {
|
|
416
|
+
const hasLex = item.lexicalRank !== null;
|
|
417
|
+
const hasSem = item.semanticRank !== null && item.semanticScore >= params.minSemanticScore;
|
|
418
|
+
if (params.searchMode === 'lexical' && !hasLex)
|
|
419
|
+
continue;
|
|
420
|
+
if (params.searchMode === 'semantic' && !hasSem)
|
|
421
|
+
continue;
|
|
422
|
+
if (params.searchMode === 'hybrid' && !hasLex && !hasSem)
|
|
423
|
+
continue;
|
|
424
|
+
let relevance;
|
|
425
|
+
if (params.searchMode === 'lexical') {
|
|
426
|
+
relevance = item.lexicalScore;
|
|
427
|
+
}
|
|
428
|
+
else if (params.searchMode === 'semantic') {
|
|
429
|
+
relevance = Math.max(0, Math.min(1, item.semanticScore));
|
|
430
|
+
}
|
|
431
|
+
else {
|
|
432
|
+
const rrfScore = (item.lexicalRank !== null ? params.lexicalWeight / (params.rrfK + item.lexicalRank) : 0) +
|
|
433
|
+
(hasSem && item.semanticRank !== null
|
|
434
|
+
? params.semanticWeight / (params.rrfK + item.semanticRank)
|
|
435
|
+
: 0);
|
|
436
|
+
const rrfNorm = maxRrf > 0 ? rrfScore / maxRrf : 0;
|
|
437
|
+
const linearBlend = params.lexicalWeight * item.lexicalScore +
|
|
438
|
+
params.semanticWeight * Math.max(0, item.semanticScore);
|
|
439
|
+
// Combine normalized RRF (rank consensus) with calibrated linear signal
|
|
440
|
+
relevance = Math.max(0, Math.min(1, 0.55 * linearBlend + 0.45 * rrfNorm));
|
|
441
|
+
}
|
|
442
|
+
const matchSource = hasLex && hasSem ? 'hybrid' : hasLex ? 'lexical' : 'semantic';
|
|
443
|
+
hits.push({
|
|
444
|
+
row: item.row,
|
|
445
|
+
relevance_score: Number(relevance.toFixed(4)),
|
|
446
|
+
lexical_score: Number(item.lexicalScore.toFixed(4)),
|
|
447
|
+
semantic_score: Number(Math.max(0, item.semanticScore).toFixed(4)),
|
|
448
|
+
match_source: matchSource,
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
hits.sort((a, b) => b.relevance_score - a.relevance_score ||
|
|
452
|
+
b.semantic_score - a.semantic_score ||
|
|
453
|
+
String(a.row.id).localeCompare(String(b.row.id)));
|
|
454
|
+
return hits;
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Synchronous Hybrid Search (FTS5 BM25 + Vector Cosine RRF) for SQLite control plane (`query_cache` v2).
|
|
458
|
+
* Enforces strict private-workspace airlock, domain, environment_version, environment_lock_hash,
|
|
459
|
+
* dead-end toggle, artifact_types, and semantic_tags filters.
|
|
460
|
+
*/
|
|
461
|
+
export function hybridSearchArtifactsSync(db, opts) {
|
|
462
|
+
const provider = opts.provider ?? DEFAULT_LOCAL_PROVIDER;
|
|
463
|
+
const searchMode = opts.searchMode ?? 'hybrid';
|
|
464
|
+
const minSemanticScore = opts.minSemanticScore ?? 0.22;
|
|
465
|
+
const rrfK = opts.rrfK ?? 30;
|
|
466
|
+
const lexicalWeight = opts.lexicalWeight ?? 0.5;
|
|
467
|
+
const semanticWeight = opts.semanticWeight ?? 0.5;
|
|
468
|
+
const baseFilters = [
|
|
469
|
+
`(a.visibility = 'public' OR EXISTS (
|
|
470
|
+
SELECT 1 FROM workspace_members wm
|
|
471
|
+
WHERE wm.workspace_id = a.workspace_id AND wm.agent_id = ?
|
|
472
|
+
))`,
|
|
473
|
+
];
|
|
474
|
+
const baseParams = [opts.agentId];
|
|
475
|
+
if (opts.workspaceId) {
|
|
476
|
+
baseFilters.push('a.workspace_id = ?');
|
|
477
|
+
baseParams.push(opts.workspaceId);
|
|
478
|
+
}
|
|
479
|
+
if (opts.domain) {
|
|
480
|
+
baseFilters.push('a.domain_pack_ref LIKE ?');
|
|
481
|
+
baseParams.push(`${opts.domain}%`);
|
|
482
|
+
}
|
|
483
|
+
if (opts.environmentVersion) {
|
|
484
|
+
baseFilters.push('a.environment_version LIKE ?');
|
|
485
|
+
baseParams.push(`${opts.environmentVersion}%`);
|
|
486
|
+
}
|
|
487
|
+
if (opts.environmentLockHash) {
|
|
488
|
+
baseFilters.push('a.environment_lock_hash = ?');
|
|
489
|
+
baseParams.push(opts.environmentLockHash);
|
|
490
|
+
}
|
|
491
|
+
if (opts.includeDeadEnds === false) {
|
|
492
|
+
baseFilters.push(`a.artifact_type <> 'dead_end'`);
|
|
493
|
+
}
|
|
494
|
+
if (opts.artifactTypes?.length) {
|
|
495
|
+
baseFilters.push(`a.artifact_type IN (${opts.artifactTypes.map(() => '?').join(',')})`);
|
|
496
|
+
baseParams.push(...opts.artifactTypes);
|
|
497
|
+
}
|
|
498
|
+
const filterTagMatch = (row) => {
|
|
499
|
+
if (!opts.tags?.length)
|
|
500
|
+
return true;
|
|
501
|
+
const rowTags = parseRowTags(row.semantic_tags);
|
|
502
|
+
return opts.tags.every((t) => rowTags.includes(t));
|
|
503
|
+
};
|
|
504
|
+
// Channel 1: FTS5 BM25 lexical ranking
|
|
505
|
+
const lexicalRows = [];
|
|
506
|
+
if (searchMode === 'hybrid' || searchMode === 'lexical') {
|
|
507
|
+
const safeFts = opts.query
|
|
508
|
+
.replace(/["*^():-]/g, ' ')
|
|
509
|
+
.trim()
|
|
510
|
+
.split(/\s+/)
|
|
511
|
+
.filter(Boolean)
|
|
512
|
+
.map((tok) => `"${tok}"`)
|
|
513
|
+
.join(' OR ');
|
|
514
|
+
if (safeFts) {
|
|
515
|
+
const ftsRows = db
|
|
516
|
+
.prepare(`
|
|
517
|
+
SELECT a.*, bm25(artifacts_fts, 4.0, 2.0, 2.0, 1.0) AS rank_score
|
|
518
|
+
FROM artifacts_fts
|
|
519
|
+
JOIN artifacts a ON a.rowid = artifacts_fts.rowid
|
|
520
|
+
WHERE artifacts_fts MATCH ?
|
|
521
|
+
AND ${baseFilters.join(' AND ')}
|
|
522
|
+
ORDER BY rank_score ASC, a.id ASC
|
|
523
|
+
`)
|
|
524
|
+
.all(safeFts, ...baseParams);
|
|
525
|
+
for (const r of ftsRows) {
|
|
526
|
+
if (!filterTagMatch(r))
|
|
527
|
+
continue;
|
|
528
|
+
// SQLite FTS5 bm25() returns negative values where more-negative = stronger match
|
|
529
|
+
const lexScore = 1 / (1 + Math.exp(Number(r.rank_score ?? 0) * 0.35));
|
|
530
|
+
lexicalRows.push({ row: r, lexicalScore: lexScore });
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
// Channel 2: Dense semantic vector similarity
|
|
535
|
+
const semanticRows = [];
|
|
536
|
+
if (searchMode === 'hybrid' || searchMode === 'semantic') {
|
|
537
|
+
if (opts.autoIndex !== false && hasEmbeddingsTable(db)) {
|
|
538
|
+
backfillArtifactEmbeddingsSync(db, provider);
|
|
539
|
+
}
|
|
540
|
+
const queryVec = provider.embedSync(opts.query);
|
|
541
|
+
if (hasEmbeddingsTable(db)) {
|
|
542
|
+
const embRows = db
|
|
543
|
+
.prepare(`
|
|
544
|
+
SELECT a.*, e.vector_blob
|
|
545
|
+
FROM artifact_embeddings e
|
|
546
|
+
JOIN artifacts a ON a.id = e.artifact_id
|
|
547
|
+
WHERE ${baseFilters.join(' AND ')}
|
|
548
|
+
`)
|
|
549
|
+
.all(...baseParams);
|
|
550
|
+
for (const r of embRows) {
|
|
551
|
+
if (!filterTagMatch(r))
|
|
552
|
+
continue;
|
|
553
|
+
const vec = decodeFloat32Blob(r.vector_blob);
|
|
554
|
+
const sim = dotCosineSimilarity(queryVec, vec);
|
|
555
|
+
const { vector_blob: _blob, ...artifact } = r;
|
|
556
|
+
semanticRows.push({ row: artifact, semanticScore: sim });
|
|
557
|
+
}
|
|
558
|
+
semanticRows.sort((a, b) => b.semanticScore - a.semanticScore || String(a.row.id).localeCompare(String(b.row.id)));
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
return fuseLexicalAndSemantic({
|
|
562
|
+
lexicalRows,
|
|
563
|
+
semanticRows,
|
|
564
|
+
searchMode,
|
|
565
|
+
minSemanticScore,
|
|
566
|
+
rrfK,
|
|
567
|
+
lexicalWeight,
|
|
568
|
+
semanticWeight,
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Async Hybrid Search across both SQLite and PostgreSQL + pgvector via `StorageAdapter`.
|
|
573
|
+
* On PostgreSQL, combines `ts_rank_cd(search_tsv, plainto_tsquery(...))` with `pgvector` `<=>` cosine search.
|
|
574
|
+
*/
|
|
575
|
+
export async function hybridSearchArtifactsAsync(adapter, opts) {
|
|
576
|
+
const sqlite = adapter.rawSqlite();
|
|
577
|
+
if (sqlite && (!opts.provider || opts.provider instanceof LocalSemanticEmbeddingProvider)) {
|
|
578
|
+
return hybridSearchArtifactsSync(sqlite, {
|
|
579
|
+
...opts,
|
|
580
|
+
provider: opts.provider,
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
const provider = opts.provider ?? createDefaultEmbeddingProvider();
|
|
584
|
+
const searchMode = opts.searchMode ?? 'hybrid';
|
|
585
|
+
const minSemanticScore = opts.minSemanticScore ?? 0.22;
|
|
586
|
+
const rrfK = opts.rrfK ?? 30;
|
|
587
|
+
const lexicalWeight = opts.lexicalWeight ?? 0.5;
|
|
588
|
+
const semanticWeight = opts.semanticWeight ?? 0.5;
|
|
589
|
+
if (opts.autoIndex !== false) {
|
|
590
|
+
await backfillArtifactEmbeddings(adapter, provider);
|
|
591
|
+
}
|
|
592
|
+
const lexicalRows = [];
|
|
593
|
+
if (searchMode === 'hybrid' || searchMode === 'lexical') {
|
|
594
|
+
const filters = [
|
|
595
|
+
`(a.visibility = 'public' OR EXISTS (
|
|
596
|
+
SELECT 1 FROM workspace_members wm
|
|
597
|
+
WHERE wm.workspace_id = a.workspace_id AND wm.agent_id = ?
|
|
598
|
+
))`,
|
|
599
|
+
];
|
|
600
|
+
const params = [opts.query, opts.agentId];
|
|
601
|
+
if (opts.workspaceId) {
|
|
602
|
+
filters.push('a.workspace_id = ?');
|
|
603
|
+
params.push(opts.workspaceId);
|
|
604
|
+
}
|
|
605
|
+
if (opts.domain) {
|
|
606
|
+
filters.push('a.domain_pack_ref LIKE ?');
|
|
607
|
+
params.push(`${opts.domain}%`);
|
|
608
|
+
}
|
|
609
|
+
if (opts.environmentVersion) {
|
|
610
|
+
filters.push('a.environment_version LIKE ?');
|
|
611
|
+
params.push(`${opts.environmentVersion}%`);
|
|
612
|
+
}
|
|
613
|
+
if (opts.environmentLockHash) {
|
|
614
|
+
filters.push('a.environment_lock_hash = ?');
|
|
615
|
+
params.push(opts.environmentLockHash);
|
|
616
|
+
}
|
|
617
|
+
if (opts.includeDeadEnds === false) {
|
|
618
|
+
filters.push(`a.artifact_type <> 'dead_end'`);
|
|
619
|
+
}
|
|
620
|
+
if (opts.artifactTypes?.length) {
|
|
621
|
+
filters.push(`a.artifact_type IN (${opts.artifactTypes.map(() => '?').join(',')})`);
|
|
622
|
+
params.push(...opts.artifactTypes);
|
|
623
|
+
}
|
|
624
|
+
const pgLexRows = await adapter.query(`
|
|
625
|
+
SELECT a.*, ts_rank_cd(a.search_tsv, websearch_to_tsquery('english', ?)) AS lex_rank
|
|
626
|
+
FROM artifacts a
|
|
627
|
+
WHERE a.search_tsv @@ websearch_to_tsquery('english', $1)
|
|
628
|
+
AND ${filters.join(' AND ')}
|
|
629
|
+
ORDER BY lex_rank DESC, a.id ASC
|
|
630
|
+
LIMIT 100
|
|
631
|
+
`, params);
|
|
632
|
+
for (const r of pgLexRows) {
|
|
633
|
+
if (opts.tags?.length) {
|
|
634
|
+
const rowTags = parseRowTags(r.semantic_tags);
|
|
635
|
+
if (!opts.tags.every((t) => rowTags.includes(t)))
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
const rawRank = Number(r.lex_rank ?? 0);
|
|
639
|
+
const norm = rawRank / (rawRank + 0.5);
|
|
640
|
+
lexicalRows.push({ row: r, lexicalScore: norm });
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
const semanticRows = [];
|
|
644
|
+
if (searchMode === 'hybrid' || searchMode === 'semantic') {
|
|
645
|
+
const queryVector = await provider.embed(opts.query);
|
|
646
|
+
const vecHits = await adapter.vectorSearchArtifacts({
|
|
647
|
+
queryVector,
|
|
648
|
+
agentId: opts.agentId,
|
|
649
|
+
workspaceId: opts.workspaceId,
|
|
650
|
+
domain: opts.domain,
|
|
651
|
+
environmentVersion: opts.environmentVersion,
|
|
652
|
+
environmentLockHash: opts.environmentLockHash,
|
|
653
|
+
includeDeadEnds: opts.includeDeadEnds,
|
|
654
|
+
artifactTypes: opts.artifactTypes,
|
|
655
|
+
tags: opts.tags,
|
|
656
|
+
limit: 100,
|
|
657
|
+
});
|
|
658
|
+
for (const hit of vecHits) {
|
|
659
|
+
semanticRows.push({ row: hit.artifact, semanticScore: hit.similarity });
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return fuseLexicalAndSemantic({
|
|
663
|
+
lexicalRows,
|
|
664
|
+
semanticRows,
|
|
665
|
+
searchMode,
|
|
666
|
+
minSemanticScore,
|
|
667
|
+
rrfK,
|
|
668
|
+
lexicalWeight,
|
|
669
|
+
semanticWeight,
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
//# sourceMappingURL=embeddings.js.map
|