mayura 1.2.0 → 1.2.1
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/docs/README.md +1 -0
- package/docs/concepts/workflows.md +60 -1
- package/docs/guides/durable-workflows.md +1 -1
- package/docs/guides/rag-production.md +29 -0
- package/docs/guides/rag.md +12 -2
- package/docs/guides/release-readiness.md +8 -22
- package/docs/guides/workflow-composition.md +1 -1
- package/docs/integrations/vector-pinecone.md +1 -1
- package/lib/adapter-code-docker/image/Dockerfile +1 -1
- package/lib/adapter-code-docker/package.json +1 -1
- package/lib/adapter-code-quickjs/package.json +1 -1
- package/lib/adapter-mcp/package.json +1 -1
- package/lib/ag-ui/package.json +1 -1
- package/lib/artifacts/package.json +1 -1
- package/lib/auth/package.json +1 -1
- package/lib/authz/package.json +1 -1
- package/lib/browser/package.json +1 -1
- package/lib/cli/dist/operations.d.ts +1 -0
- package/lib/cli/dist/operations.d.ts.map +1 -1
- package/lib/cli/dist/operations.js +13 -5
- package/lib/cli/dist/operations.js.map +1 -1
- package/lib/cli/package.json +1 -1
- package/lib/cli/src/operations.ts +9 -5
- package/lib/client/dist/index.d.ts.map +1 -1
- package/lib/client/dist/index.js +12 -4
- package/lib/client/dist/index.js.map +1 -1
- package/lib/client/dist/workflow-limits.d.ts +6 -0
- package/lib/client/dist/workflow-limits.d.ts.map +1 -0
- package/lib/client/dist/workflow-limits.js +15 -0
- package/lib/client/dist/workflow-limits.js.map +1 -0
- package/lib/client/dist/workflows.d.ts +3 -0
- package/lib/client/dist/workflows.d.ts.map +1 -1
- package/lib/client/dist/workflows.js +15 -7
- package/lib/client/dist/workflows.js.map +1 -1
- package/lib/client/package.json +1 -1
- package/lib/client/src/index.ts +7 -4
- package/lib/client/src/workflow-limits.ts +12 -0
- package/lib/client/src/workflows.ts +12 -6
- package/lib/client-react/package.json +1 -1
- package/lib/code-mode/package.json +1 -1
- package/lib/code-mode-workflows/package.json +1 -1
- package/lib/context/package.json +1 -1
- package/lib/core/dist/host.d.ts +1 -0
- package/lib/core/dist/host.d.ts.map +1 -1
- package/lib/core/dist/host.js +1 -0
- package/lib/core/dist/host.js.map +1 -1
- package/lib/core/dist/index.d.ts +1 -0
- package/lib/core/dist/index.d.ts.map +1 -1
- package/lib/core/dist/index.js +1 -0
- package/lib/core/dist/index.js.map +1 -1
- package/lib/core/dist/workflow-environment.d.ts +9 -0
- package/lib/core/dist/workflow-environment.d.ts.map +1 -0
- package/lib/core/dist/workflow-environment.js +15 -0
- package/lib/core/dist/workflow-environment.js.map +1 -0
- package/lib/core/dist/workflow-limits.d.ts +7 -0
- package/lib/core/dist/workflow-limits.d.ts.map +1 -0
- package/lib/core/dist/workflow-limits.js +17 -0
- package/lib/core/dist/workflow-limits.js.map +1 -0
- package/lib/core/package.json +1 -1
- package/lib/core/src/host.ts +1 -0
- package/lib/core/src/index.ts +1 -0
- package/lib/core/src/workflow-environment.ts +15 -0
- package/lib/core/src/workflow-limits.ts +16 -0
- package/lib/exporter-otlp/dist/otlp-http-json.js +1 -1
- package/lib/exporter-otlp/dist/otlp-http-json.js.map +1 -1
- package/lib/exporter-otlp/dist/signals.js +2 -2
- package/lib/exporter-otlp/dist/signals.js.map +1 -1
- package/lib/exporter-otlp/package.json +1 -1
- package/lib/exporter-otlp/src/otlp-http-json.ts +1 -1
- package/lib/exporter-otlp/src/signals.ts +2 -2
- package/lib/files/package.json +1 -1
- package/lib/guardrails/package.json +1 -1
- package/lib/helpers/package.json +1 -1
- package/lib/keys/package.json +1 -1
- package/lib/memory/package.json +1 -1
- package/lib/memory-remote/package.json +1 -1
- package/lib/observability/package.json +1 -1
- package/lib/provider-anthropic/package.json +1 -1
- package/lib/provider-openai/package.json +1 -1
- package/lib/rag/dist/bm25.d.ts +13 -0
- package/lib/rag/dist/bm25.d.ts.map +1 -0
- package/lib/rag/dist/bm25.js +76 -0
- package/lib/rag/dist/bm25.js.map +1 -0
- package/lib/rag/dist/document-lexical.d.ts +7 -0
- package/lib/rag/dist/document-lexical.d.ts.map +1 -0
- package/lib/rag/dist/document-lexical.js +33 -0
- package/lib/rag/dist/document-lexical.js.map +1 -0
- package/lib/rag/dist/evidence-window.d.ts +15 -0
- package/lib/rag/dist/evidence-window.d.ts.map +1 -0
- package/lib/rag/dist/evidence-window.js +52 -0
- package/lib/rag/dist/evidence-window.js.map +1 -0
- package/lib/rag/dist/retrieval.d.ts +6 -0
- package/lib/rag/dist/retrieval.d.ts.map +1 -1
- package/lib/rag/dist/retrieval.js +60 -6
- package/lib/rag/dist/retrieval.js.map +1 -1
- package/lib/rag/dist/vectors.d.ts +8 -0
- package/lib/rag/dist/vectors.d.ts.map +1 -1
- package/lib/rag/dist/vectors.js +121 -4
- package/lib/rag/dist/vectors.js.map +1 -1
- package/lib/rag/package.json +1 -1
- package/lib/rag/src/bm25.ts +35 -0
- package/lib/rag/src/document-lexical.ts +17 -0
- package/lib/rag/src/evidence-window.ts +41 -0
- package/lib/rag/src/retrieval.ts +56 -7
- package/lib/rag/src/vectors.ts +62 -4
- package/lib/runtime/package.json +1 -1
- package/lib/sandbox/package.json +1 -1
- package/lib/sdk/package.json +1 -1
- package/lib/server/dist/index.d.ts +2 -0
- package/lib/server/dist/index.d.ts.map +1 -1
- package/lib/server/dist/index.js +12 -4
- package/lib/server/dist/index.js.map +1 -1
- package/lib/server/dist/inspector-bundle.d.ts +1 -1
- package/lib/server/dist/inspector-bundle.d.ts.map +1 -1
- package/lib/server/dist/inspector-bundle.js +4 -4
- package/lib/server/dist/inspector-bundle.js.map +1 -1
- package/lib/server/package.json +1 -1
- package/lib/server/src/index.ts +9 -4
- package/lib/server/src/inspector-bundle.ts +4 -4
- package/lib/server-node/package.json +1 -1
- package/lib/skills/package.json +1 -1
- package/lib/storage/package.json +1 -1
- package/lib/storage-contracts/dist/scheduled-workflow-contracts.d.ts +2 -0
- package/lib/storage-contracts/dist/scheduled-workflow-contracts.d.ts.map +1 -1
- package/lib/storage-contracts/dist/scheduled-workflow-contracts.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-format2.d.ts +2 -0
- package/lib/storage-contracts/dist/workflow-format2.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-format2.js +8 -7
- package/lib/storage-contracts/dist/workflow-format2.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-format3.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-format3.js +9 -7
- package/lib/storage-contracts/dist/workflow-format3.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-format4.d.ts +2 -0
- package/lib/storage-contracts/dist/workflow-format4.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-format4.js +9 -8
- package/lib/storage-contracts/dist/workflow-format4.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-format5.d.ts +4 -0
- package/lib/storage-contracts/dist/workflow-format5.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-format5.js +9 -8
- package/lib/storage-contracts/dist/workflow-format5.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-graph-contracts.d.ts +2 -0
- package/lib/storage-contracts/dist/workflow-graph-contracts.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-graph-contracts.js.map +1 -1
- package/lib/storage-contracts/dist/workflow-tree-contracts.d.ts +2 -0
- package/lib/storage-contracts/dist/workflow-tree-contracts.d.ts.map +1 -1
- package/lib/storage-contracts/dist/workflow-tree-contracts.js +5 -3
- package/lib/storage-contracts/dist/workflow-tree-contracts.js.map +1 -1
- package/lib/storage-contracts/package.json +1 -1
- package/lib/storage-contracts/src/scheduled-workflow-contracts.ts +2 -0
- package/lib/storage-contracts/src/workflow-format2.ts +10 -7
- package/lib/storage-contracts/src/workflow-format3.ts +9 -7
- package/lib/storage-contracts/src/workflow-format4.ts +11 -8
- package/lib/storage-contracts/src/workflow-format5.ts +13 -8
- package/lib/storage-contracts/src/workflow-graph-contracts.ts +2 -0
- package/lib/storage-contracts/src/workflow-tree-contracts.ts +7 -3
- package/lib/storage-postgres/package.json +1 -1
- package/lib/storage-sql/dist/scheduled-database.js +1 -1
- package/lib/storage-sql/dist/scheduled-database.js.map +1 -1
- package/lib/storage-sql/dist/workflow-tree-database.d.ts.map +1 -1
- package/lib/storage-sql/dist/workflow-tree-database.js +37 -1
- package/lib/storage-sql/dist/workflow-tree-database.js.map +1 -1
- package/lib/storage-sql/package.json +1 -1
- package/lib/storage-sql/src/scheduled-database.ts +1 -1
- package/lib/storage-sql/src/workflow-tree-database.ts +15 -1
- package/lib/storage-sqlite/package.json +1 -1
- package/lib/terminal/package.json +1 -1
- package/lib/testing/package.json +1 -1
- package/lib/threads/package.json +1 -1
- package/lib/tools/package.json +1 -1
- package/lib/voice/package.json +1 -1
- package/lib/workflows/dist/children-definition.d.ts +5 -1
- package/lib/workflows/dist/children-definition.d.ts.map +1 -1
- package/lib/workflows/dist/children-definition.js +6 -2
- package/lib/workflows/dist/children-definition.js.map +1 -1
- package/lib/workflows/dist/children-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/children-runtime.js +4 -3
- package/lib/workflows/dist/children-runtime.js.map +1 -1
- package/lib/workflows/dist/definition.d.ts +4 -0
- package/lib/workflows/dist/definition.d.ts.map +1 -1
- package/lib/workflows/dist/definition.js +6 -3
- package/lib/workflows/dist/definition.js.map +1 -1
- package/lib/workflows/dist/graph-definition.d.ts +5 -1
- package/lib/workflows/dist/graph-definition.d.ts.map +1 -1
- package/lib/workflows/dist/graph-definition.js +8 -4
- package/lib/workflows/dist/graph-definition.js.map +1 -1
- package/lib/workflows/dist/lifecycle-definition.d.ts +5 -1
- package/lib/workflows/dist/lifecycle-definition.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-definition.js +5 -2
- package/lib/workflows/dist/lifecycle-definition.js.map +1 -1
- package/lib/workflows/dist/lifecycle-runtime.d.ts.map +1 -1
- package/lib/workflows/dist/lifecycle-runtime.js +4 -5
- package/lib/workflows/dist/lifecycle-runtime.js.map +1 -1
- package/lib/workflows/dist/node-batches.d.ts +9 -0
- package/lib/workflows/dist/node-batches.d.ts.map +1 -0
- package/lib/workflows/dist/node-batches.js +19 -0
- package/lib/workflows/dist/node-batches.js.map +1 -0
- package/lib/workflows/dist/operator-transports.d.ts +1 -0
- package/lib/workflows/dist/operator-transports.d.ts.map +1 -1
- package/lib/workflows/dist/operator-transports.js +1 -0
- package/lib/workflows/dist/operator-transports.js.map +1 -1
- package/lib/workflows/dist/runtime.d.ts.map +1 -1
- package/lib/workflows/dist/runtime.js +6 -7
- package/lib/workflows/dist/runtime.js.map +1 -1
- package/lib/workflows/dist/scheduled-helpers.d.ts.map +1 -1
- package/lib/workflows/dist/scheduled-helpers.js +3 -2
- package/lib/workflows/dist/scheduled-helpers.js.map +1 -1
- package/lib/workflows/dist/scheduled.d.ts.map +1 -1
- package/lib/workflows/dist/scheduled.js +2 -1
- package/lib/workflows/dist/scheduled.js.map +1 -1
- package/lib/workflows/package.json +1 -1
- package/lib/workflows/src/children-definition.ts +10 -3
- package/lib/workflows/src/children-runtime.ts +3 -2
- package/lib/workflows/src/definition.ts +9 -2
- package/lib/workflows/src/graph-definition.ts +10 -3
- package/lib/workflows/src/lifecycle-definition.ts +10 -3
- package/lib/workflows/src/lifecycle-runtime.ts +4 -4
- package/lib/workflows/src/node-batches.ts +21 -0
- package/lib/workflows/src/operator-transports.ts +3 -1
- package/lib/workflows/src/runtime.ts +6 -6
- package/lib/workflows/src/scheduled-helpers.ts +3 -2
- package/lib/workflows/src/scheduled.ts +2 -1
- package/lib/workstream/package.json +1 -1
- package/llms-full.txt +116 -28
- package/llms.txt +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retrieval.js","sourceRoot":"","sources":["../src/retrieval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,E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AE,CAAC,MAAM,CAAC,IAAI,WAAW,CAAC,WAAW,EAAC,uCAAuC,CAAC,CAAC,CAAC;YACjG,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAC,KAAK,EAAC,EAAC,IAAI,EAAC,IAAI,EAAC,CAAC,CAAC;YAAC,IAAI,MAAM,CAAC,OAAO;gBAAE,KAAK,EAAE,CAAC;YAChF,KAAK,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,cAAc,EAAC,mCAAmC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACtR,CAAC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAC,QAAQ,CAAC,KAAK,EAAC,UAAU,EAAC,IAAI,EAAC,QAAQ,EAAE,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["import { MayuraError } from '@mayura/core';\nimport type { RagAccess, RagCatalog, RagEmbedder, RagHit, RagMetadata, RagQueryTransform, RagReranker, RetrievalResult, Retriever, VectorStore } from './contracts.js';\nimport { access, cancelled, chunk, id, integer, matches, metadata, snapshot, text, vector } from './validation.js';\nexport interface RetrieverOptions extends RagAccess {\n readonly store: VectorStore; readonly catalog: RagCatalog; readonly embedder: RagEmbedder; readonly space: string;\n readonly parentDocuments?: boolean;\n readonly mode?: 'semantic' | 'hybrid'; readonly filter?: RagMetadata; readonly limit: number; readonly candidateLimit: number;\n readonly transform?: RagQueryTransform; readonly reranker?: RagReranker;\n readonly maxQueries: number; readonly maxCostMicros: number; readonly timeoutMs: number; readonly maxConcurrent: number;\n}\n/** Reserve declared worst-case cost before any callback. Returned costs are reservations, never a bill estimate. */\nexport function createRetriever(options: RetrieverOptions): Retriever {\n const boundary = access(options); const store = options.store; const embedder = options.embedder; const space = id(options.space);\n const limit = integer(options.limit,1,100); const candidates = integer(options.candidateLimit,limit,100);\n const queries = integer(options.maxQueries,1,4); const timeout = integer(options.timeoutMs,1,30_000); const cap = integer(options.maxConcurrent,1,128);\n const filter = metadata(options.filter ?? {}); const transform = options.transform; const reranker = options.reranker;\n if(options.mode!==undefined && !['semantic','hybrid'].includes(options.mode) || transform && (!['rewrite','multi-query','hyde'].includes(transform.mode) || transform.mode==='multi-query' && queries<2)) throw new MayuraError('INVALID_CONFIG','Invalid RAG retrieval mode or query budget.');\n if(!['local','hosted'].includes(store.location)||!['local','hosted'].includes(embedder.location)||reranker&&!['local','hosted'].includes(reranker.location))throw new MayuraError('INVALID_CONFIG','RAG adapter location must be explicit.');\n integer(embedder.maxBatch,1,2048); integer(embedder.dimensions,1,4096); id(embedder.id);\n if (store.dimensions !== embedder.dimensions || options.mode === 'hybrid' && !store.lexical) throw new MayuraError('INVALID_CONFIG','RAG index dimensions or hybrid capability do not match.');\n const cost = integer(embedder.costMicros,0,Number.MAX_SAFE_INTEGER) * Math.ceil(queries / embedder.maxBatch)\n + queries * (options.mode === 'hybrid' ? 2 : 1) * integer(store.costMicros,0,Number.MAX_SAFE_INTEGER)\n + (transform ? integer(transform.costMicros,0,Number.MAX_SAFE_INTEGER) : 0) + (reranker ? integer(reranker.costMicros,0,Number.MAX_SAFE_INTEGER) : 0);\n integer(cost,0,integer(options.maxCostMicros,0,Number.MAX_SAFE_INTEGER)); let active = 0;\n const retrieve: Retriever['retrieve'] = async (raw, supplied = {}) => {\n const query = text(raw,2000); boundary.require('rag:read'); if (embedder.location === 'hosted') boundary.require('rag:embed');\n if (transform) boundary.require(`rag:transform:${id(transform.id)}`); if (reranker) boundary.require(`rag:rerank:${id(reranker.id)}`);\n if (active >= cap) throw new MayuraError('BUDGET_EXCEEDED','RAG concurrent retrieval limit exceeded.');\n const control = new AbortController(); const relay = () => control.abort(); supplied.signal?.addEventListener('abort',relay,{ once:true }); if (supplied.signal?.aborted) relay();\n const timer = setTimeout(relay,timeout); const signal = control.signal; const started = Date.now(); active++;\n const work = async () => {\n await boundary.authorize('search','collection',signal);\n let texts = [query];\n if (transform) {\n const changed = await transform.transform(query,signal); cancelled(signal);\n if (!Array.isArray(changed) || changed.length < 1 || changed.length > queries - (transform.mode === 'multi-query' ? 1 : 0)) throw new MayuraError('INVALID_OUTPUT','RAG query transform exceeded its query budget.');\n texts = [...new Set([...(transform.mode === 'multi-query' ? [query] : []), ...changed.map(value => text(value,2000))])];\n }\n const lists: (readonly RagHit[])[] = [];\n for (let offset = 0; offset < texts.length; offset += embedder.maxBatch) {\n await boundary.authorize('search','collection',signal); const batch = texts.slice(offset,offset + embedder.maxBatch); const embedded = await embedder.embed(batch,signal); cancelled(signal);\n if (!Array.isArray(embedded) || embedded.length !== batch.length) throw new MayuraError('INVALID_OUTPUT','Invalid RAG embedding batch.');\n for (let index = 0; index < batch.length; index++) {\n const q = { scope: boundary.scope, space, vector: vector(embedded[index]!,embedder.dimensions), limit: candidates, filter, signal };\n lists.push(await store.query(q)); cancelled(signal);\n if (options.mode === 'hybrid') { lists.push(await store.lexical!({ scope: boundary.scope, space, text: batch[index]!, limit:candidates,filter,signal })); cancelled(signal); }\n }\n }\n const combined = new Map<string,RagHit>(); let seen = 0;\n for (const list of lists) {\n if (!Array.isArray(list) || list.length > candidates) throw new MayuraError('INVALID_OUTPUT','RAG store exceeded its candidate budget.');\n const unique = new Set<string>();\n for (let rank = 0; rank < list.length; rank++) {\n const hit = list[rank]!; const item = chunk(hit.chunk);\n if (!Number.isFinite(hit.score) || unique.has(item.id)) throw new MayuraError('INVALID_OUTPUT','Invalid or duplicate RAG search hit.'); unique.add(item.id);\n if (!matches(item.metadata,filter) || !boundary.profile.includes(item.sensitivity)) continue;\n const published = await options.catalog.read(boundary.scope,item.documentId,signal); cancelled(signal);\n if (!published || published.deleted || published.revision !== item.revision || published.space !== space || !published.chunkIds.includes(item.id)) continue;\n if (options.authorization) {\n const decision = await options.authorization.authorize(boundary.scope,'read',{ kind:'rag_document',id:item.documentId,scope:boundary.scope },{ signal }); cancelled(signal);\n if (decision.effect !== 'allow') {\n if (['unavailable','cancelled','limit_exceeded'].includes(decision.reason)) throw new MayuraError('PERMISSION_DENIED','RAG authorization is unavailable.');\n continue;\n }\n }\n seen++; const previous = combined.get(item.id); combined.set(item.id,{ chunk:item, score:(previous?.score ?? 0) + 1 / (60 + rank + 1) });\n }\n }\n let hits = [...combined.values()].sort((a,b) => b.score - a.score || a.chunk.id.localeCompare(b.chunk.id)).slice(0,candidates);\n if (reranker && hits.length) {\n if (reranker.location === 'hosted' && hits.some(hit => !boundary.hosted.includes(hit.chunk.sensitivity))) throw new MayuraError('PERMISSION_DENIED','RAG hosted reranking sensitivity is not admitted.');\n for(const hit of hits)await boundary.authorize('read',hit.chunk.documentId,signal);\n const ranked = await reranker.rank(query,hits.map(hit => (hit.chunk.context ? hit.chunk.context+'\\n' : '')+hit.chunk.text),signal); cancelled(signal);\n if (!Array.isArray(ranked) || ranked.length > hits.length || new Set(ranked.map(row => row.index)).size !== ranked.length) throw new MayuraError('INVALID_OUTPUT','Invalid RAG reranking result.');\n hits = ranked.map(row => { integer(row.index,0,hits.length - 1); if (!Number.isFinite(row.score)) throw new MayuraError('INVALID_OUTPUT','Invalid reranking score.'); return { chunk:hits[row.index]!.chunk,score:row.score }; }).sort((a,b) => b.score - a.score || a.chunk.id.localeCompare(b.chunk.id));\n }\n // Recheck publication and policy after hosted work before releasing evidence.\n const released: RagHit[] = [];\n for (const hit of hits.slice(0,limit)) {\n const current = await options.catalog.read(boundary.scope,hit.chunk.documentId,signal); cancelled(signal);\n if (!current || current.deleted || current.revision !== hit.chunk.revision || current.space !== space || !current.chunkIds.includes(hit.chunk.id)) continue;\n await boundary.authorize('read',hit.chunk.documentId,signal); released.push({...hit,...(options.parentDocuments && hit.chunk.parent ? {parent:hit.chunk.parent} : {})});\n }\n return snapshot({ hits:released, metrics:{ queries:texts.length,candidates:seen,returned:released.length,reservedCostMicros:cost,durationMs:Date.now() - started } });\n };\n // Keep the admission occupied until an abort-ignoring adapter actually settles.\n const pending = work().finally(() => { active--; clearTimeout(timer); supplied.signal?.removeEventListener('abort',relay); });\n return await new Promise<RetrievalResult>((resolve,reject) => {\n const abort = () => reject(new MayuraError('CANCELLED','RAG retrieval cancelled or timed out.'));\n signal.addEventListener('abort',abort,{once:true}); if (signal.aborted) abort();\n void pending.then(result => { signal.removeEventListener('abort',abort); if (!signal.aborted) resolve(result); }, () => { signal.removeEventListener('abort',abort); reject(new MayuraError(signal.aborted ? 'CANCELLED' : 'MODEL_FAILED','RAG retrieval could not complete.')); });\n });\n };\n return Object.freeze({ scope:boundary.scope,costMicros:cost,retrieve });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"retrieval.js","sourceRoot":"","sources":["../src/retrieval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACnH,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAc3D,oHAAoH;AACpH,MAAM,UAAU,eAAe,CAAC,OAAyB;IACvD,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IAAC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAAC,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;IAAC,MAAM,KAAK,GAAG,EAAE,CAAC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C;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,KAAK,EAAC,QAAQ,CAAC,KAAK,EAAC,UAAU,EAAC,IAAI,EAAC,QAAQ,EAAE,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["import { MayuraError } from '@mayura/core';\nimport type { RagAccess, RagCatalog, RagEmbedder, RagHit, RagMetadata, RagQueryTransform, RagReranker, RagRevision, RetrievalResult, Retriever, VectorStore } from './contracts.js';\nimport { access, cancelled, chunk, id, integer, matches, metadata, snapshot, text, vector } from './validation.js';\nimport { surroundingEvidence } from './evidence-window.js';\nexport interface RetrieverOptions extends RagAccess {\n readonly store: VectorStore; readonly catalog: RagCatalog; readonly embedder: RagEmbedder; readonly space: string;\n readonly parentDocuments?: boolean;\n /** Select at most one authorized chunk per document, after optional reranking and before the result limit. */\n readonly distinctDocuments?: boolean;\n /** Opt-in document-level reciprocal-rank fusion: one authorized document vote per source list. Requires distinctDocuments. */\n readonly fusionLevel?: 'chunk' | 'document';\n /** Reciprocal-rank smoothing, 1–100; default 60. Lower values emphasize leading source ranks. */\n readonly fusionRankConstant?: number;\n readonly mode?: 'semantic' | 'hybrid'; readonly filter?: RagMetadata; readonly limit: number; readonly candidateLimit: number;\n readonly transform?: RagQueryTransform; readonly reranker?: RagReranker;\n readonly maxQueries: number; readonly maxCostMicros: number; readonly timeoutMs: number; readonly maxConcurrent: number;\n}\n/** Reserve declared worst-case cost before any callback. Returned costs are reservations, never a bill estimate. */\nexport function createRetriever(options: RetrieverOptions): Retriever {\n const boundary = access(options); const store = options.store; const embedder = options.embedder; const space = id(options.space);\n const limit = integer(options.limit,1,100); const candidates = integer(options.candidateLimit,limit,100);\n const queries = integer(options.maxQueries,1,4); const timeout = integer(options.timeoutMs,1,30_000); const cap = integer(options.maxConcurrent,1,128);\n const filter = metadata(options.filter ?? {}); const transform = options.transform; const reranker = options.reranker;\n const rankConstant=integer(options.fusionRankConstant??60,1,100);\n if (options.distinctDocuments !== undefined && typeof options.distinctDocuments !== 'boolean') throw new MayuraError('INVALID_CONFIG','Document diversity must be an explicit boolean.');\n if(options.fusionLevel!==undefined&&!['chunk','document'].includes(options.fusionLevel)||options.fusionLevel==='document'&&options.distinctDocuments!==true)throw new MayuraError('INVALID_CONFIG','Document fusion requires explicit document diversity.');\n if(options.mode!==undefined && !['semantic','hybrid'].includes(options.mode) || transform && (!['rewrite','multi-query','hyde'].includes(transform.mode) || transform.mode==='multi-query' && queries<2)) throw new MayuraError('INVALID_CONFIG','Invalid RAG retrieval mode or query budget.');\n if(!['local','hosted'].includes(store.location)||!['local','hosted'].includes(embedder.location)||reranker&&!['local','hosted'].includes(reranker.location))throw new MayuraError('INVALID_CONFIG','RAG adapter location must be explicit.');\n integer(embedder.maxBatch,1,2048); integer(embedder.dimensions,1,4096); id(embedder.id);\n if (store.dimensions !== embedder.dimensions || options.mode === 'hybrid' && !store.lexical) throw new MayuraError('INVALID_CONFIG','RAG index dimensions or hybrid capability do not match.');\n const cost = integer(embedder.costMicros,0,Number.MAX_SAFE_INTEGER) * Math.ceil(queries / embedder.maxBatch)\n + queries * (options.mode === 'hybrid' ? 2 : 1) * integer(store.costMicros,0,Number.MAX_SAFE_INTEGER)\n + (transform ? integer(transform.costMicros,0,Number.MAX_SAFE_INTEGER) : 0) + (reranker ? integer(reranker.costMicros,0,Number.MAX_SAFE_INTEGER) : 0);\n integer(cost,0,integer(options.maxCostMicros,0,Number.MAX_SAFE_INTEGER)); let active = 0;\n const retrieve: Retriever['retrieve'] = async (raw, supplied = {}) => {\n const query = text(raw,2000); boundary.require('rag:read'); if (embedder.location === 'hosted') boundary.require('rag:embed');\n if (transform) boundary.require(`rag:transform:${id(transform.id)}`); if (reranker) boundary.require(`rag:rerank:${id(reranker.id)}`);\n if (active >= cap) throw new MayuraError('BUDGET_EXCEEDED','RAG concurrent retrieval limit exceeded.');\n const control = new AbortController(); const relay = () => control.abort(); supplied.signal?.addEventListener('abort',relay,{ once:true }); if (supplied.signal?.aborted) relay();\n const timer = setTimeout(relay,timeout); const signal = control.signal; const started = Date.now(); active++;\n const work = async () => {\n await boundary.authorize('search','collection',signal);\n let texts = [query];\n if (transform) {\n const changed = await transform.transform(query,signal); cancelled(signal);\n if (!Array.isArray(changed) || changed.length < 1 || changed.length > queries - (transform.mode === 'multi-query' ? 1 : 0)) throw new MayuraError('INVALID_OUTPUT','RAG query transform exceeded its query budget.');\n texts = [...new Set([...(transform.mode === 'multi-query' ? [query] : []), ...changed.map(value => text(value,2000))])];\n }\n const lists: (readonly RagHit[])[] = [];\n for (let offset = 0; offset < texts.length; offset += embedder.maxBatch) {\n await boundary.authorize('search','collection',signal); const batch = texts.slice(offset,offset + embedder.maxBatch); const embedded = await embedder.embed(batch,signal); cancelled(signal);\n if (!Array.isArray(embedded) || embedded.length !== batch.length) throw new MayuraError('INVALID_OUTPUT','Invalid RAG embedding batch.');\n for (let index = 0; index < batch.length; index++) {\n const q = { scope: boundary.scope, space, vector: vector(embedded[index]!,embedder.dimensions), limit: candidates, filter, signal };\n lists.push(await store.query(q)); cancelled(signal);\n if (options.mode === 'hybrid') { lists.push(await store.lexical!({ scope: boundary.scope, space, text: batch[index]!, limit:candidates,filter,signal })); cancelled(signal); }\n }\n }\n const combined = new Map<string,RagHit>(); let seen = 0;\n const documentScores=new Map<string,number>();\n // Candidate chunks frequently share a document. Reuse its initial visibility snapshot within this\n // request only; the release pass below still performs fresh reads to fence deletion/republication.\n const publishedCandidates = new Map<string,RagRevision | undefined>();\n for (const list of lists) {\n if (!Array.isArray(list) || list.length > candidates) throw new MayuraError('INVALID_OUTPUT','RAG store exceeded its candidate budget.');\n const unique = new Set<string>();\n const documentRanks=new Set<string>();\n for (let rank = 0; rank < list.length; rank++) {\n const hit = list[rank]!; const item = chunk(hit.chunk);\n if (!Number.isFinite(hit.score) || unique.has(item.id)) throw new MayuraError('INVALID_OUTPUT','Invalid or duplicate RAG search hit.'); unique.add(item.id);\n if (!matches(item.metadata,filter) || !boundary.profile.includes(item.sensitivity)) continue;\n if (!publishedCandidates.has(item.documentId)) {\n publishedCandidates.set(item.documentId,await options.catalog.read(boundary.scope,item.documentId,signal));\n }\n const published = publishedCandidates.get(item.documentId); cancelled(signal);\n if (!published || published.deleted || published.revision !== item.revision || published.space !== space || !published.chunkIds.includes(item.id)) continue;\n if (options.authorization) {\n const decision = await options.authorization.authorize(boundary.scope,'read',{ kind:'rag_document',id:item.documentId,scope:boundary.scope },{ signal }); cancelled(signal);\n if (decision.effect !== 'allow') {\n if (['unavailable','cancelled','limit_exceeded'].includes(decision.reason)) throw new MayuraError('PERMISSION_DENIED','RAG authorization is unavailable.');\n continue;\n }\n }\n seen++; const previous = combined.get(item.id); combined.set(item.id,{ chunk:item, score:(previous?.score ?? 0) + 1 / (rankConstant + rank + 1) });\n if(options.fusionLevel==='document'&&!documentRanks.has(item.documentId)){\n documentRanks.add(item.documentId);documentScores.set(item.documentId,(documentScores.get(item.documentId)??0)+1/(rankConstant+documentRanks.size));\n }\n }\n }\n let hits = [...combined.values()].sort((a,b) => b.score - a.score || a.chunk.id.localeCompare(b.chunk.id)).slice(0,candidates);\n if(options.fusionLevel==='document'){\n // Choose an actual authorized passage as witness. Fusion never manufactures context or citations;\n // rerankers see that passage, and the release fence still validates its exact revision/chunk ID.\n const witnesses=new Map<string,RagHit>();\n for(const hit of combined.values()){const old=witnesses.get(hit.chunk.documentId);\n if(!old||hit.score>old.score||hit.score===old.score&&hit.chunk.id.localeCompare(old.chunk.id)<0)witnesses.set(hit.chunk.documentId,hit);}\n hits=[...witnesses].map(([id,hit])=>({...hit,score:documentScores.get(id)!}))\n .sort((a,b)=>b.score-a.score||a.chunk.id.localeCompare(b.chunk.id)).slice(0,candidates);\n }\n if (reranker && hits.length) {\n if (reranker.location === 'hosted' && hits.some(hit => !boundary.hosted.includes(hit.chunk.sensitivity))) throw new MayuraError('PERMISSION_DENIED','RAG hosted reranking sensitivity is not admitted.');\n const admitted:RagHit[]=[],rerankTexts:string[]=[];\n for(const hit of hits){\n await boundary.authorize('read',hit.chunk.documentId,signal);\n const context=options.parentDocuments?surroundingEvidence(hit,[...combined.values()]):undefined;\n if(context){\n // Parent context must be published before it crosses the reranker boundary, not only\n // when it is returned. Deletion/republication can invalidate any contributing passage.\n const current=await options.catalog.read(boundary.scope,hit.chunk.documentId,signal);cancelled(signal);\n if(!current||current.deleted||current.revision!==hit.chunk.revision||current.space!==space||\n !current.chunkIds.includes(hit.chunk.id)||!context.contributorIds.every(id=>current.chunkIds.includes(id)))continue;\n }\n admitted.push(hit);rerankTexts.push((hit.chunk.context?hit.chunk.context+'\\n':'')+(context?.parent.text??hit.chunk.text));\n }\n hits=admitted;\n const ranked = hits.length?await reranker.rank(query,rerankTexts,signal):[]; cancelled(signal);\n if (!Array.isArray(ranked) || ranked.length > hits.length || new Set(ranked.map(row => row.index)).size !== ranked.length) throw new MayuraError('INVALID_OUTPUT','Invalid RAG reranking result.');\n hits = ranked.map(row => { integer(row.index,0,hits.length - 1); if (!Number.isFinite(row.score)) throw new MayuraError('INVALID_OUTPUT','Invalid reranking score.'); return { hit:{chunk:hits[row.index]!.chunk,score:row.score},index:row.index }; })\n .sort((a,b) => b.hit.score - a.hit.score || (options.distinctDocuments ? a.index - b.index : a.hit.chunk.id.localeCompare(b.hit.chunk.id))).map(row=>row.hit);\n }\n if(options.distinctDocuments){\n const documents=new Set<string>();hits=hits.filter(hit=>{if(documents.has(hit.chunk.documentId))return false;documents.add(hit.chunk.documentId);return true;});\n }\n // Recheck publication and policy after hosted work before releasing evidence.\n const released: RagHit[] = [];\n for (const hit of hits.slice(0,limit)) {\n const context=options.parentDocuments?surroundingEvidence(hit,[...combined.values()]):undefined;\n const current = await options.catalog.read(boundary.scope,hit.chunk.documentId,signal); cancelled(signal);\n if (!current || current.deleted || current.revision !== hit.chunk.revision || current.space !== space || !current.chunkIds.includes(hit.chunk.id)) continue;\n if(context&&!context.contributorIds.every(id=>current.chunkIds.includes(id)))continue;\n await boundary.authorize('read',hit.chunk.documentId,signal); released.push({...hit,...(options.parentDocuments && hit.chunk.parent ? {parent:context?.parent??hit.chunk.parent} : {})});\n }\n return snapshot({ hits:released, metrics:{ queries:texts.length,candidates:seen,returned:released.length,reservedCostMicros:cost,durationMs:Date.now() - started } });\n };\n // Keep the admission occupied until an abort-ignoring adapter actually settles.\n const pending = work().finally(() => { active--; clearTimeout(timer); supplied.signal?.removeEventListener('abort',relay); });\n return await new Promise<RetrievalResult>((resolve,reject) => {\n const abort = () => reject(new MayuraError('CANCELLED','RAG retrieval cancelled or timed out.'));\n signal.addEventListener('abort',abort,{once:true}); if (signal.aborted) abort();\n void pending.then(result => { signal.removeEventListener('abort',abort); if (!signal.aborted) resolve(result); }, () => { signal.removeEventListener('abort',abort); reject(new MayuraError(signal.aborted ? 'CANCELLED' : 'MODEL_FAILED','RAG retrieval could not complete.')); });\n });\n };\n return Object.freeze({ scope:boundary.scope,costMicros:cost,retrieve });\n}\n"]}
|
|
@@ -6,6 +6,14 @@ export declare function checkedEntries(entries: readonly RagVector[], dimensions
|
|
|
6
6
|
export declare function inMemoryVectorStore(options: {
|
|
7
7
|
readonly dimensions: number;
|
|
8
8
|
readonly maxVectors: number;
|
|
9
|
+
/** Default is normalized term frequency. BM25 maintains statistics within each scope/index partition. */
|
|
10
|
+
readonly lexicalScoring?: 'term-frequency' | 'bm25';
|
|
11
|
+
/** Default is chunk. Document BM25 merges consistent source intervals and returns a real passage witness. */
|
|
12
|
+
readonly lexicalUnit?: 'chunk' | 'document';
|
|
13
|
+
/** Return the best exact-cosine passage per document before applying the candidate limit. */
|
|
14
|
+
readonly semanticUnit?: 'chunk' | 'document';
|
|
15
|
+
/** Document scoring defaults to max; mean averages every matching chunk cosine without new embeddings. */
|
|
16
|
+
readonly documentScore?: 'max' | 'mean';
|
|
9
17
|
}): VectorStore;
|
|
10
18
|
/** Compose a semantic backend with a lexical mirror. Publication stays hidden until both staged writes succeed. */
|
|
11
19
|
export declare function hybridVectorStore(options: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vectors.d.ts","sourceRoot":"","sources":["../src/vectors.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"vectors.d.ts","sourceRoot":"","sources":["../src/vectors.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAoB,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAIzF,wBAAgB,MAAM,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,CAA+E;AAChK,wBAAgB,YAAY,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,GAAG,QAAQ,CAE1E;AACD,wBAAgB,cAAc,CAAC,OAAO,EAAE,SAAS,SAAS,EAAE,EAAE,UAAU,EAAE,MAAM,GAAG,SAAS,SAAS,EAAE,CAKtG;AACD,iHAAiH;AACjH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE;IAC3C,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IACzD,yGAAyG;IACzG,QAAQ,CAAC,cAAc,CAAC,EAAE,gBAAgB,GAAG,MAAM,CAAC;IACpD,6GAA6G;IAC7G,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC;IAC5C,6FAA6F;IAC7F,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC;IAC7C,0GAA0G;IAC1G,QAAQ,CAAC,aAAa,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;CACzC,GAAG,WAAW,CA2Ed;AAED,mHAAmH;AACnH,wBAAgB,iBAAiB,CAAC,OAAO,EAAC;IAAC,QAAQ,CAAC,QAAQ,EAAC,WAAW,CAAC;IAAA,QAAQ,CAAC,OAAO,EAAC,WAAW,CAAA;CAAC,GAAE,WAAW,CAQlH"}
|
package/lib/rag/dist/vectors.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { MayuraError } from '../../core/dist/index.js';
|
|
2
2
|
import { cancelled, chunk, id, integer, matches, metadata, scopeKey, snapshot, vector } from './validation.js';
|
|
3
|
+
import { Bm25Index } from './bm25.js';
|
|
4
|
+
import { lexicalDocumentKey, lexicalDocumentText, sourceGroupIdentity } from './document-lexical.js';
|
|
3
5
|
export function cosine(left, right) { return left.reduce((sum, value, index) => sum + value * right[index], 0); }
|
|
4
6
|
export function checkedQuery(input, dimensions) {
|
|
5
7
|
cancelled(input.signal);
|
|
@@ -17,6 +19,16 @@ export function checkedEntries(entries, dimensions) {
|
|
|
17
19
|
export function inMemoryVectorStore(options) {
|
|
18
20
|
const dimensions = integer(options.dimensions, 1, 4096);
|
|
19
21
|
const cap = integer(options.maxVectors, 1, 100_000);
|
|
22
|
+
if (options.lexicalScoring !== undefined && !['term-frequency', 'bm25'].includes(options.lexicalScoring))
|
|
23
|
+
throw new MayuraError('INVALID_CONFIG', 'Invalid lexical scoring mode.');
|
|
24
|
+
if (options.lexicalUnit !== undefined && !['chunk', 'document'].includes(options.lexicalUnit) || options.lexicalUnit === 'document' && options.lexicalScoring !== 'bm25')
|
|
25
|
+
throw new MayuraError('INVALID_CONFIG', 'Document lexical units require BM25 scoring.');
|
|
26
|
+
if (options.semanticUnit !== undefined && !['chunk', 'document'].includes(options.semanticUnit))
|
|
27
|
+
throw new MayuraError('INVALID_CONFIG', 'Invalid semantic candidate unit.');
|
|
28
|
+
if (options.documentScore !== undefined && !['max', 'mean'].includes(options.documentScore) || options.documentScore === 'mean' && options.semanticUnit !== 'document')
|
|
29
|
+
throw new MayuraError('INVALID_CONFIG', 'Mean semantic scoring requires document candidates.');
|
|
30
|
+
const lexicalIndexes = new Map();
|
|
31
|
+
const documentGroups = new Map();
|
|
20
32
|
const partitions = new Map();
|
|
21
33
|
let count = 0;
|
|
22
34
|
const ordered = (hits, limit) => snapshot(hits.sort((a, b) => b.score - a.score || a.chunk.id.localeCompare(b.chunk.id)).slice(0, limit));
|
|
@@ -29,6 +41,44 @@ export function inMemoryVectorStore(options) {
|
|
|
29
41
|
const added = checked.filter(entry => !current.has(entry.chunk.id)).length;
|
|
30
42
|
if (count + added > cap)
|
|
31
43
|
throw new MayuraError('BUDGET_EXCEEDED', 'RAG vector capacity exceeded.');
|
|
44
|
+
if (options.lexicalScoring === 'bm25') {
|
|
45
|
+
// Validate every affected revision before changing any row or posting, including overwrites.
|
|
46
|
+
const existing = documentGroups.get(key) ?? new Map();
|
|
47
|
+
const updates = new Map();
|
|
48
|
+
const group = (id) => { let value = updates.get(id); if (!value) {
|
|
49
|
+
value = new Map(existing.get(id));
|
|
50
|
+
updates.set(id, value);
|
|
51
|
+
} return value; };
|
|
52
|
+
if (options.lexicalUnit === 'document')
|
|
53
|
+
for (const entry of checked) {
|
|
54
|
+
const old = current.get(entry.chunk.id);
|
|
55
|
+
if (old)
|
|
56
|
+
group(lexicalDocumentKey(old.chunk)).delete(old.chunk.id);
|
|
57
|
+
group(lexicalDocumentKey(entry.chunk)).set(entry.chunk.id, entry.chunk);
|
|
58
|
+
}
|
|
59
|
+
const texts = new Map([...updates].map(([id, rows]) => [id, lexicalDocumentText(rows)]));
|
|
60
|
+
let index = lexicalIndexes.get(key);
|
|
61
|
+
if (!index) {
|
|
62
|
+
index = new Bm25Index();
|
|
63
|
+
lexicalIndexes.set(key, index);
|
|
64
|
+
}
|
|
65
|
+
if (options.lexicalUnit === 'document') {
|
|
66
|
+
for (const [id, rows] of updates) {
|
|
67
|
+
if (rows.size) {
|
|
68
|
+
existing.set(id, rows);
|
|
69
|
+
index.set(id, texts.get(id));
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
existing.delete(id);
|
|
73
|
+
index.delete(id);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
documentGroups.set(key, existing);
|
|
77
|
+
}
|
|
78
|
+
else
|
|
79
|
+
for (const entry of checked)
|
|
80
|
+
index.set(entry.chunk.id, entry.chunk.text);
|
|
81
|
+
}
|
|
32
82
|
checked.forEach(entry => current.set(entry.chunk.id, entry));
|
|
33
83
|
partitions.set(key, current);
|
|
34
84
|
count += added;
|
|
@@ -36,12 +86,55 @@ export function inMemoryVectorStore(options) {
|
|
|
36
86
|
async query(raw) {
|
|
37
87
|
const q = checkedQuery(raw, dimensions);
|
|
38
88
|
const rows = partitions.get(scopeKey(q.scope, q.space));
|
|
39
|
-
|
|
89
|
+
let hits = [...(rows?.values() ?? [])].filter(row => matches(row.chunk.metadata, q.filter)).map(row => ({ chunk: row.chunk, score: cosine(q.vector, row.values) }));
|
|
90
|
+
if (options.semanticUnit === 'document') {
|
|
91
|
+
// Reduce within the verified partition/filter, keeping an actual stored passage and stable ties.
|
|
92
|
+
const totals = new Map();
|
|
93
|
+
const best = new Map();
|
|
94
|
+
for (const hit of hits) {
|
|
95
|
+
const key = sourceGroupIdentity(hit.chunk);
|
|
96
|
+
const old = best.get(key);
|
|
97
|
+
const total = totals.get(key) ?? { sum: 0, count: 0 };
|
|
98
|
+
total.sum += hit.score;
|
|
99
|
+
total.count++;
|
|
100
|
+
totals.set(key, total);
|
|
101
|
+
if (!old || hit.score > old.score || hit.score === old.score && hit.chunk.id.localeCompare(old.chunk.id) < 0)
|
|
102
|
+
best.set(key, hit);
|
|
103
|
+
}
|
|
104
|
+
const documents = new Map();
|
|
105
|
+
for (const [key, witness] of best) {
|
|
106
|
+
const hit = options.documentScore === 'mean' ? { ...witness, score: totals.get(key).sum / totals.get(key).count } : witness;
|
|
107
|
+
const old = documents.get(hit.chunk.documentId);
|
|
108
|
+
if (!old || hit.score > old.score || hit.score === old.score && hit.chunk.id.localeCompare(old.chunk.id) < 0)
|
|
109
|
+
documents.set(hit.chunk.documentId, hit);
|
|
110
|
+
}
|
|
111
|
+
hits = [...documents.values()];
|
|
112
|
+
}
|
|
113
|
+
return ordered(hits, q.limit);
|
|
40
114
|
},
|
|
41
115
|
async lexical(q) {
|
|
42
116
|
cancelled(q.signal);
|
|
43
117
|
metadata(q.filter);
|
|
44
118
|
integer(q.limit, 1, 100);
|
|
119
|
+
if (options.lexicalScoring === 'bm25') {
|
|
120
|
+
const key = scopeKey(q.scope, q.space);
|
|
121
|
+
const rows = partitions.get(key);
|
|
122
|
+
const scores = lexicalIndexes.get(key)?.scores(q.text);
|
|
123
|
+
if (options.lexicalUnit === 'document') {
|
|
124
|
+
const groups = documentGroups.get(key);
|
|
125
|
+
const index = lexicalIndexes.get(key);
|
|
126
|
+
// Bound passage scoring to documents that can reach the limit. Include cutoff ties so the
|
|
127
|
+
// final real-witness ID tie-break stays identical to scoring the entire partition.
|
|
128
|
+
const eligible = [...(scores ?? [])].filter(([id]) => { const first = groups?.get(id)?.values().next().value; return first && matches(first.metadata, q.filter); }).sort((a, b) => b[1] - a[1]);
|
|
129
|
+
const cutoff = eligible[q.limit - 1]?.[1] ?? -Infinity;
|
|
130
|
+
return ordered(eligible.filter(([, score]) => score >= cutoff).flatMap(([id, score]) => {
|
|
131
|
+
const allowed = [...(groups?.get(id)?.values() ?? [])].filter(c => matches(c.metadata, q.filter));
|
|
132
|
+
const witness = allowed.map(chunk => ({ chunk, score: index.scoreText(q.text, chunk.text) })).sort((a, b) => b.score - a.score || a.chunk.id.localeCompare(b.chunk.id))[0];
|
|
133
|
+
return witness && witness.score > 0 ? [{ chunk: witness.chunk, score }] : [];
|
|
134
|
+
}), q.limit);
|
|
135
|
+
}
|
|
136
|
+
return ordered([...(scores ?? [])].flatMap(([id, score]) => { const row = rows?.get(id); return row && matches(row.chunk.metadata, q.filter) ? [{ chunk: row.chunk, score }] : []; }), q.limit);
|
|
137
|
+
}
|
|
45
138
|
const terms = [...new Set(q.text.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [])].slice(0, 64);
|
|
46
139
|
return ordered([...(partitions.get(scopeKey(q.scope, q.space))?.values() ?? [])].filter(row => matches(row.chunk.metadata, q.filter)).map(row => {
|
|
47
140
|
const words = row.chunk.text.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? [];
|
|
@@ -55,11 +148,35 @@ export function inMemoryVectorStore(options) {
|
|
|
55
148
|
const checked = ids.map(id);
|
|
56
149
|
const key = scopeKey(scope, space);
|
|
57
150
|
const rows = partitions.get(key);
|
|
58
|
-
|
|
59
|
-
|
|
151
|
+
const groups = documentGroups.get(key);
|
|
152
|
+
const affected = new Set();
|
|
153
|
+
for (const value of checked) {
|
|
154
|
+
const old = rows?.get(value);
|
|
155
|
+
if (rows?.delete(value)) {
|
|
60
156
|
count--;
|
|
61
|
-
|
|
157
|
+
if (options.lexicalUnit === 'document' && old) {
|
|
158
|
+
const id = lexicalDocumentKey(old.chunk);
|
|
159
|
+
groups?.get(id)?.delete(value);
|
|
160
|
+
affected.add(id);
|
|
161
|
+
}
|
|
162
|
+
else
|
|
163
|
+
lexicalIndexes.get(key)?.delete(value);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
for (const id of affected) {
|
|
167
|
+
const group = groups?.get(id);
|
|
168
|
+
if (group?.size)
|
|
169
|
+
lexicalIndexes.get(key)?.set(id, lexicalDocumentText(group));
|
|
170
|
+
else {
|
|
171
|
+
groups?.delete(id);
|
|
172
|
+
lexicalIndexes.get(key)?.delete(id);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
if (rows?.size === 0) {
|
|
62
176
|
partitions.delete(key);
|
|
177
|
+
lexicalIndexes.delete(key);
|
|
178
|
+
documentGroups.delete(key);
|
|
179
|
+
}
|
|
63
180
|
},
|
|
64
181
|
});
|
|
65
182
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vectors.js","sourceRoot":"","sources":["../src/vectors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAc,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,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["import { MayuraError, type Scope } from '@mayura/core';\nimport type { RagHit, RagQuery, RagVector, VectorStore } from './contracts.js';\nimport { cancelled, chunk, id, integer, matches, metadata, scopeKey, snapshot, vector } from './validation.js';\nexport function cosine(left: readonly number[], right: readonly number[]): number { return left.reduce((sum, value, index) => sum + value * right[index]!, 0); }\nexport function checkedQuery(input: RagQuery, dimensions: number): RagQuery {\n cancelled(input.signal); return { ...input, scope: snapshot(input.scope), space: id(input.space), vector: vector(input.vector, dimensions), limit: integer(input.limit, 1, 100), filter: metadata(input.filter) };\n}\nexport function checkedEntries(entries: readonly RagVector[], dimensions: number): readonly RagVector[] {\n if (!Array.isArray(entries) || entries.length < 1 || entries.length > 128) throw new MayuraError('INVALID_INPUT', 'RAG vector batch must contain 1–128 chunks.');\n const output = entries.map(entry => ({ chunk: chunk(entry.chunk), values: vector(entry.values, dimensions) }));\n if (new Set(output.map(entry => entry.chunk.id)).size !== output.length) throw new MayuraError('INVALID_INPUT', 'Duplicate RAG chunk ids.');\n return snapshot(output);\n}\n/** Scope-partitioned exact cosine and lexical reference backend. Writes are synchronous and atomic per batch. */\nexport function inMemoryVectorStore(options: { readonly dimensions: number; readonly maxVectors: number }): VectorStore {\n const dimensions = integer(options.dimensions, 1, 4096); const cap = integer(options.maxVectors, 1, 100_000);\n const partitions = new Map<string, Map<string, RagVector>>(); let count = 0;\n const ordered = (hits: RagHit[], limit: number) => snapshot(hits.sort((a,b) => b.score - a.score || a.chunk.id.localeCompare(b.chunk.id)).slice(0,limit));\n return Object.freeze({ id: 'mayura.rag.memory', dimensions, costMicros: 0, location: 'local' as const,\n async upsert(scope: Scope, space: string, entries: readonly RagVector[], signal: AbortSignal) {\n cancelled(signal); const key = scopeKey(scope, space); const checked = checkedEntries(entries, dimensions); const current = partitions.get(key) ?? new Map<string,RagVector>();\n const added = checked.filter(entry => !current.has(entry.chunk.id)).length;\n if (count + added > cap) throw new MayuraError('BUDGET_EXCEEDED','RAG vector capacity exceeded.');\n checked.forEach(entry => current.set(entry.chunk.id, entry)); partitions.set(key,current); count += added;\n },\n async query(raw: RagQuery) {\n const q = checkedQuery(raw,dimensions); const rows = partitions.get(scopeKey(q.scope,q.space));\n return ordered([...(rows?.values() ?? [])].filter(row => matches(row.chunk.metadata,q.filter)).map(row => ({ chunk: row.chunk, score: cosine(q.vector,row.values) })), q.limit);\n },\n async lexical(q: Omit<RagQuery,'vector'> & { readonly text: string }) {\n cancelled(q.signal); metadata(q.filter); integer(q.limit,1,100);\n const terms = [...new Set(q.text.toLowerCase().match(/[\\p{L}\\p{N}_]+/gu) ?? [])].slice(0,64);\n return ordered([...(partitions.get(scopeKey(q.scope,q.space))?.values() ?? [])].filter(row => matches(row.chunk.metadata,q.filter)).map(row => {\n const words = row.chunk.text.toLowerCase().match(/[\\p{L}\\p{N}_]+/gu) ?? [];\n return { chunk: row.chunk, score: terms.reduce((sum, term) => sum + words.filter(word => word === term).length / (words.length + 1), 0) };\n }).filter(hit => hit.score > 0),q.limit);\n },\n async delete(scope: Scope, space: string, ids: readonly string[], signal: AbortSignal) {\n cancelled(signal); if (ids.length > 128) throw new MayuraError('INVALID_INPUT','RAG deletion batch is too large.');\n const checked = ids.map(id); const key = scopeKey(scope,space); const rows = partitions.get(key);\n for (const value of checked) if (rows?.delete(value)) count--; if (rows?.size === 0) partitions.delete(key);\n },\n });\n}\n\n/** Compose a semantic backend with a lexical mirror. Publication stays hidden until both staged writes succeed. */\nexport function hybridVectorStore(options:{readonly semantic:VectorStore;readonly lexical:VectorStore}):VectorStore {\n const a=options.semantic;const b=options.lexical;if(a.dimensions!==b.dimensions||!b.lexical)throw new MayuraError('INVALID_CONFIG','Hybrid RAG requires matching dimensions and an explicit lexical backend.');\n const costMicros=integer(a.costMicros+b.costMicros,0,Number.MAX_SAFE_INTEGER);\n return Object.freeze({id:`hybrid.${a.id}.${b.id}`,dimensions:a.dimensions,costMicros,location:a.location==='hosted'||b.location==='hosted'?'hosted' as const:'local' as const,\n async upsert(scope:Scope,space:string,entries:readonly RagVector[],signal:AbortSignal){const admitted=checkedEntries(entries,a.dimensions);await a.upsert(scope,space,admitted,signal);cancelled(signal);await b.upsert(scope,space,admitted,signal);cancelled(signal);},\n query:a.query.bind(a),lexical:b.lexical.bind(b),\n async delete(scope:Scope,space:string,ids:readonly string[],signal:AbortSignal){await a.delete(scope,space,ids,signal);cancelled(signal);await b.delete(scope,space,ids,signal);cancelled(signal);},\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"vectors.js","sourceRoot":"","sources":["../src/vectors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAc,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAC/G,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAC,mBAAmB,EAAC,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACnG,MAAM,UAAU,MAAM,CAAC,IAAuB,EAAE,KAAwB,IAAY,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,GAAG,GAAG,KAAK,GAAG,KAAK,CAAC,KAAK,CAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AAChK,MAAM,UAAU,YAAY,CAAC,KAAe,EAAE,UAAkB;IAC9D,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAAC,OAAO,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,UAAU,CAAC,EAAE,KAAK,EAAE,OAAO,CAA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,CAAC,CAAA,OAAgB;QAC3K,KAAK,CAAC,MAAM,CAAC,KAAW,EAAC,KAAY,EAAC,OAA4B,EAAC,MAAkB,IAAE,MAAM,QAAQ,GAAC,cAAc,CAAC,OAAO,EAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAA,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,EAAC,KAAK,EAAC,QAAQ,EAAC,MAAM,CAAC,CAAC,CAAA,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,EAAC,KAAK,EAAC,QAAQ,EAAC,MAAM,CAAC,CAAC,CAAA,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA,CAAC;QACxQ,KAAK,EAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAC,OAAO,EAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QAC/C,KAAK,CAAC,MAAM,CAAC,KAAW,EAAC,KAAY,EAAC,GAAqB,EAAC,MAAkB,IAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,EAAC,KAAK,EAAC,GAAG,EAAC,MAAM,CAAC,CAAC,CAAA,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,EAAC,KAAK,EAAC,GAAG,EAAC,MAAM,CAAC,CAAC,CAAA,SAAS,CAAC,MAAM,CAAC,CAAC,CAAA,CAAC;KACpM,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { MayuraError, type Scope } from '@mayura/core';\nimport type { RagChunk, RagHit, RagQuery, RagVector, VectorStore } from './contracts.js';\nimport { cancelled, chunk, id, integer, matches, metadata, scopeKey, snapshot, vector } from './validation.js';\nimport { Bm25Index } from './bm25.js';\nimport { lexicalDocumentKey,lexicalDocumentText,sourceGroupIdentity } from './document-lexical.js';\nexport function cosine(left: readonly number[], right: readonly number[]): number { return left.reduce((sum, value, index) => sum + value * right[index]!, 0); }\nexport function checkedQuery(input: RagQuery, dimensions: number): RagQuery {\n cancelled(input.signal); return { ...input, scope: snapshot(input.scope), space: id(input.space), vector: vector(input.vector, dimensions), limit: integer(input.limit, 1, 100), filter: metadata(input.filter) };\n}\nexport function checkedEntries(entries: readonly RagVector[], dimensions: number): readonly RagVector[] {\n if (!Array.isArray(entries) || entries.length < 1 || entries.length > 128) throw new MayuraError('INVALID_INPUT', 'RAG vector batch must contain 1–128 chunks.');\n const output = entries.map(entry => ({ chunk: chunk(entry.chunk), values: vector(entry.values, dimensions) }));\n if (new Set(output.map(entry => entry.chunk.id)).size !== output.length) throw new MayuraError('INVALID_INPUT', 'Duplicate RAG chunk ids.');\n return snapshot(output);\n}\n/** Scope-partitioned exact cosine and lexical reference backend. Writes are synchronous and atomic per batch. */\nexport function inMemoryVectorStore(options: {\n readonly dimensions: number; readonly maxVectors: number;\n /** Default is normalized term frequency. BM25 maintains statistics within each scope/index partition. */\n readonly lexicalScoring?: 'term-frequency' | 'bm25';\n /** Default is chunk. Document BM25 merges consistent source intervals and returns a real passage witness. */\n readonly lexicalUnit?: 'chunk' | 'document';\n /** Return the best exact-cosine passage per document before applying the candidate limit. */\n readonly semanticUnit?: 'chunk' | 'document';\n /** Document scoring defaults to max; mean averages every matching chunk cosine without new embeddings. */\n readonly documentScore?: 'max' | 'mean';\n}): VectorStore {\n const dimensions = integer(options.dimensions, 1, 4096); const cap = integer(options.maxVectors, 1, 100_000);\n if(options.lexicalScoring!==undefined&&!['term-frequency','bm25'].includes(options.lexicalScoring))throw new MayuraError('INVALID_CONFIG','Invalid lexical scoring mode.');\n if(options.lexicalUnit!==undefined&&!['chunk','document'].includes(options.lexicalUnit)||options.lexicalUnit==='document'&&options.lexicalScoring!=='bm25')throw new MayuraError('INVALID_CONFIG','Document lexical units require BM25 scoring.');\n if(options.semanticUnit!==undefined&&!['chunk','document'].includes(options.semanticUnit))throw new MayuraError('INVALID_CONFIG','Invalid semantic candidate unit.');\n if(options.documentScore!==undefined&&!['max','mean'].includes(options.documentScore)||options.documentScore==='mean'&&options.semanticUnit!=='document')throw new MayuraError('INVALID_CONFIG','Mean semantic scoring requires document candidates.');\n const lexicalIndexes=new Map<string,Bm25Index>();\n const documentGroups=new Map<string,Map<string,Map<string,RagChunk>>>();\n const partitions = new Map<string, Map<string, RagVector>>(); let count = 0;\n const ordered = (hits: RagHit[], limit: number) => snapshot(hits.sort((a,b) => b.score - a.score || a.chunk.id.localeCompare(b.chunk.id)).slice(0,limit));\n return Object.freeze({ id: 'mayura.rag.memory', dimensions, costMicros: 0, location: 'local' as const,\n async upsert(scope: Scope, space: string, entries: readonly RagVector[], signal: AbortSignal) {\n cancelled(signal); const key = scopeKey(scope, space); const checked = checkedEntries(entries, dimensions); const current = partitions.get(key) ?? new Map<string,RagVector>();\n const added = checked.filter(entry => !current.has(entry.chunk.id)).length;\n if (count + added > cap) throw new MayuraError('BUDGET_EXCEEDED','RAG vector capacity exceeded.');\n if(options.lexicalScoring==='bm25'){\n // Validate every affected revision before changing any row or posting, including overwrites.\n const existing=documentGroups.get(key)??new Map<string,Map<string,RagChunk>>();const updates=new Map<string,Map<string,RagChunk>>();\n const group=(id:string)=>{let value=updates.get(id);if(!value){value=new Map(existing.get(id));updates.set(id,value);}return value;};\n if(options.lexicalUnit==='document')for(const entry of checked){const old=current.get(entry.chunk.id);if(old)group(lexicalDocumentKey(old.chunk)).delete(old.chunk.id);group(lexicalDocumentKey(entry.chunk)).set(entry.chunk.id,entry.chunk);}\n const texts=new Map([...updates].map(([id,rows])=>[id,lexicalDocumentText(rows)]));\n let index=lexicalIndexes.get(key);if(!index){index=new Bm25Index();lexicalIndexes.set(key,index);}\n if(options.lexicalUnit==='document'){for(const [id,rows]of updates){if(rows.size){existing.set(id,rows);index.set(id,texts.get(id)!);}else{existing.delete(id);index.delete(id);}}documentGroups.set(key,existing);}\n else for(const entry of checked)index.set(entry.chunk.id,entry.chunk.text);\n }\n checked.forEach(entry => current.set(entry.chunk.id, entry)); partitions.set(key,current); count += added;\n },\n async query(raw: RagQuery) {\n const q = checkedQuery(raw,dimensions); const rows = partitions.get(scopeKey(q.scope,q.space));\n let hits=[...(rows?.values() ?? [])].filter(row => matches(row.chunk.metadata,q.filter)).map(row => ({ chunk: row.chunk, score: cosine(q.vector,row.values) }));\n if(options.semanticUnit==='document'){\n // Reduce within the verified partition/filter, keeping an actual stored passage and stable ties.\n const totals=new Map<string,{sum:number;count:number}>();const best=new Map<string,RagHit>();for(const hit of hits){const key=sourceGroupIdentity(hit.chunk);const old=best.get(key);\n const total=totals.get(key)??{sum:0,count:0};total.sum+=hit.score;total.count++;totals.set(key,total);\n if(!old||hit.score>old.score||hit.score===old.score&&hit.chunk.id.localeCompare(old.chunk.id)<0)best.set(key,hit);}\n const documents=new Map<string,RagHit>();\n for(const [key,witness]of best){const hit=options.documentScore==='mean'?{...witness,score:totals.get(key)!.sum/totals.get(key)!.count}:witness;const old=documents.get(hit.chunk.documentId);\n if(!old||hit.score>old.score||hit.score===old.score&&hit.chunk.id.localeCompare(old.chunk.id)<0)documents.set(hit.chunk.documentId,hit);}\n hits=[...documents.values()];\n }\n return ordered(hits,q.limit);\n },\n async lexical(q: Omit<RagQuery,'vector'> & { readonly text: string }) {\n cancelled(q.signal); metadata(q.filter); integer(q.limit,1,100);\n if(options.lexicalScoring==='bm25'){\n const key=scopeKey(q.scope,q.space);const rows=partitions.get(key);const scores=lexicalIndexes.get(key)?.scores(q.text);\n if(options.lexicalUnit==='document'){\n const groups=documentGroups.get(key);const index=lexicalIndexes.get(key)!;\n // Bound passage scoring to documents that can reach the limit. Include cutoff ties so the\n // final real-witness ID tie-break stays identical to scoring the entire partition.\n const eligible=[...(scores??[])].filter(([id])=>{const first=groups?.get(id)?.values().next().value;return first&&matches(first.metadata,q.filter);}).sort((a,b)=>b[1]-a[1]);\n const cutoff=eligible[q.limit-1]?.[1]??-Infinity;\n return ordered(eligible.filter(([,score])=>score>=cutoff).flatMap(([id,score])=>{\n const allowed=[...(groups?.get(id)?.values()??[])].filter(c=>matches(c.metadata,q.filter));\n const witness=allowed.map(chunk=>({chunk,score:index.scoreText(q.text,chunk.text)})).sort((a,b)=>b.score-a.score||a.chunk.id.localeCompare(b.chunk.id))[0];\n return witness&&witness.score>0?[{chunk:witness.chunk,score}]:[];\n }),q.limit);\n }\n return ordered([...(scores??[])].flatMap(([id,score])=>{const row=rows?.get(id);return row&&matches(row.chunk.metadata,q.filter)?[{chunk:row.chunk,score}]:[];}),q.limit);\n }\n const terms = [...new Set(q.text.toLowerCase().match(/[\\p{L}\\p{N}_]+/gu) ?? [])].slice(0,64);\n return ordered([...(partitions.get(scopeKey(q.scope,q.space))?.values() ?? [])].filter(row => matches(row.chunk.metadata,q.filter)).map(row => {\n const words = row.chunk.text.toLowerCase().match(/[\\p{L}\\p{N}_]+/gu) ?? [];\n return { chunk: row.chunk, score: terms.reduce((sum, term) => sum + words.filter(word => word === term).length / (words.length + 1), 0) };\n }).filter(hit => hit.score > 0),q.limit);\n },\n async delete(scope: Scope, space: string, ids: readonly string[], signal: AbortSignal) {\n cancelled(signal); if (ids.length > 128) throw new MayuraError('INVALID_INPUT','RAG deletion batch is too large.');\n const checked = ids.map(id); const key = scopeKey(scope,space); const rows = partitions.get(key);\n const groups=documentGroups.get(key);const affected=new Set<string>();\n for (const value of checked){const old=rows?.get(value);if(rows?.delete(value)){count--;if(options.lexicalUnit==='document'&&old){const id=lexicalDocumentKey(old.chunk);groups?.get(id)?.delete(value);affected.add(id);}else lexicalIndexes.get(key)?.delete(value);}}\n for(const id of affected){const group=groups?.get(id);if(group?.size)lexicalIndexes.get(key)?.set(id,lexicalDocumentText(group));else{groups?.delete(id);lexicalIndexes.get(key)?.delete(id);}}\n if (rows?.size === 0){partitions.delete(key);lexicalIndexes.delete(key);documentGroups.delete(key);}\n },\n });\n}\n\n/** Compose a semantic backend with a lexical mirror. Publication stays hidden until both staged writes succeed. */\nexport function hybridVectorStore(options:{readonly semantic:VectorStore;readonly lexical:VectorStore}):VectorStore {\n const a=options.semantic;const b=options.lexical;if(a.dimensions!==b.dimensions||!b.lexical)throw new MayuraError('INVALID_CONFIG','Hybrid RAG requires matching dimensions and an explicit lexical backend.');\n const costMicros=integer(a.costMicros+b.costMicros,0,Number.MAX_SAFE_INTEGER);\n return Object.freeze({id:`hybrid.${a.id}.${b.id}`,dimensions:a.dimensions,costMicros,location:a.location==='hosted'||b.location==='hosted'?'hosted' as const:'local' as const,\n async upsert(scope:Scope,space:string,entries:readonly RagVector[],signal:AbortSignal){const admitted=checkedEntries(entries,a.dimensions);await a.upsert(scope,space,admitted,signal);cancelled(signal);await b.upsert(scope,space,admitted,signal);cancelled(signal);},\n query:a.query.bind(a),lexical:b.lexical.bind(b),\n async delete(scope:Scope,space:string,ids:readonly string[],signal:AbortSignal){await a.delete(scope,space,ids,signal);cancelled(signal);await b.delete(scope,space,ids,signal);cancelled(signal);},\n });\n}\n"]}
|
package/lib/rag/package.json
CHANGED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Scope-local BM25 statistics for the optional reference lexical scorer. No global corpus statistics. */
|
|
2
|
+
export class Bm25Index {
|
|
3
|
+
private readonly documents = new Map<string,{length:number;terms:ReadonlyMap<string,number>}>();
|
|
4
|
+
private readonly postings = new Map<string,Map<string,number>>();
|
|
5
|
+
private length = 0;
|
|
6
|
+
private words(text:string):string[] { return text.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []; }
|
|
7
|
+
set(id:string,text:string):void {
|
|
8
|
+
this.delete(id);const words=this.words(text);const terms=new Map<string,number>();
|
|
9
|
+
for(const word of words)terms.set(word,(terms.get(word)??0)+1);
|
|
10
|
+
this.documents.set(id,{length:words.length,terms});this.length+=words.length;
|
|
11
|
+
for(const [term,count]of terms){let posting=this.postings.get(term);if(!posting){posting=new Map();this.postings.set(term,posting);}posting.set(id,count);}
|
|
12
|
+
}
|
|
13
|
+
delete(id:string):void {
|
|
14
|
+
const doc=this.documents.get(id);if(!doc)return;this.length-=doc.length;this.documents.delete(id);
|
|
15
|
+
for(const term of doc.terms.keys()){const posting=this.postings.get(term)!;posting.delete(id);if(!posting.size)this.postings.delete(term);}
|
|
16
|
+
}
|
|
17
|
+
scores(text:string):ReadonlyMap<string,number> {
|
|
18
|
+
const scores=new Map<string,number>();const n=this.documents.size;if(!n)return scores;
|
|
19
|
+
const average=this.length/n||1;
|
|
20
|
+
for(const term of [...new Set(this.words(text))].slice(0,64)){
|
|
21
|
+
const posting=this.postings.get(term);if(!posting)continue;
|
|
22
|
+
const idf=Math.log(1+(n-posting.size+.5)/(posting.size+.5));
|
|
23
|
+
for(const [id,tf]of posting){const doc=this.documents.get(id)!;
|
|
24
|
+
const score=idf*tf*2.2/(tf+1.2*(.25+.75*doc.length/average));scores.set(id,(scores.get(id)??0)+score);}
|
|
25
|
+
}return scores;
|
|
26
|
+
}
|
|
27
|
+
/** Choose a real passage using the same partition-local document-frequency statistics. */
|
|
28
|
+
scoreText(query:string,text:string):number {
|
|
29
|
+
const words=this.words(text);const tf=new Map<string,number>();for(const word of words)tf.set(word,(tf.get(word)??0)+1);
|
|
30
|
+
const n=this.documents.size;if(!n)return 0;const average=this.length/n||1;let score=0;
|
|
31
|
+
for(const term of [...new Set(this.words(query))].slice(0,64)){const count=tf.get(term)??0;const df=this.postings.get(term)?.size??0;
|
|
32
|
+
if(count&&df)score+=Math.log(1+(n-df+.5)/(df+.5))*count*2.2/(count+1.2*(.25+.75*words.length/average));}
|
|
33
|
+
return score;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {MayuraError} from '@mayura/core';
|
|
2
|
+
import type {RagChunk} from './contracts.js';
|
|
3
|
+
export const lexicalDocumentKey=(c:RagChunk):string=>JSON.stringify([c.documentId,c.revision]);
|
|
4
|
+
/** Aggregation never mixes revisions, references, sensitivity profiles or source metadata. */
|
|
5
|
+
export const sourceGroupIdentity=(c:RagChunk):string=>JSON.stringify([c.documentId,c.revision,c.reference,c.sensitivity,Object.entries(c.metadata).sort(([a],[b])=>a.localeCompare(b))]);
|
|
6
|
+
/** Reconstruct only known, mutually consistent intervals; gaps become lexical separators, never evidence. */
|
|
7
|
+
export function lexicalDocumentText(rows:ReadonlyMap<string,RagChunk>):string {
|
|
8
|
+
if(rows.size>128)throw new MayuraError('BUDGET_EXCEEDED','Document lexical indexing admits at most 128 chunks per revision.');
|
|
9
|
+
const chunks=[...rows.values()].sort((a,b)=>a.start-b.start||a.end-b.end||a.id.localeCompare(b.id));const first=chunks[0];if(!first)return '';
|
|
10
|
+
const expected=sourceGroupIdentity(first);const segments:{start:number;end:number;text:string}[]=[];
|
|
11
|
+
for(const c of chunks){if(sourceGroupIdentity(c)!==expected)throw new MayuraError('INVALID_INPUT','Document lexical chunks must share source metadata and sensitivity.');
|
|
12
|
+
const last=segments.at(-1);if(!last||c.start>last.end){segments.push({start:c.start,end:c.end,text:c.text});continue;}
|
|
13
|
+
const overlap=Math.min(last.end,c.end)-c.start;
|
|
14
|
+
if(last.text.slice(c.start-last.start,c.start-last.start+overlap)!==c.text.slice(0,overlap))throw new MayuraError('INVALID_INPUT','Document lexical intervals disagree.');
|
|
15
|
+
if(c.end>last.end){last.text+=c.text.slice(overlap);last.end=c.end;}
|
|
16
|
+
}return segments.map(s=>s.text).join('\n');
|
|
17
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { RagHit } from './contracts.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Assemble bounded surrounding context from already authorized, same-revision candidate passages.
|
|
5
|
+
* No source is fetched, no gap is invented, and conflicting overlaps are never combined. The
|
|
6
|
+
* returned contributor IDs must all pass the publication fence before this context is released.
|
|
7
|
+
*/
|
|
8
|
+
export function surroundingEvidence(anchor: RagHit, candidates: readonly RagHit[]): {
|
|
9
|
+
readonly parent: { readonly text: string; readonly start: number; readonly end: number };
|
|
10
|
+
readonly contributorIds: readonly string[];
|
|
11
|
+
} | undefined {
|
|
12
|
+
// Parent expansion remains explicitly selected at ingestion. A plain chunk does not gain context.
|
|
13
|
+
if (!anchor.chunk.parent) return undefined;
|
|
14
|
+
const compatible = [anchor,...candidates].filter(hit => hit.chunk.documentId === anchor.chunk.documentId
|
|
15
|
+
&& hit.chunk.revision === anchor.chunk.revision && hit.chunk.sensitivity === anchor.chunk.sensitivity
|
|
16
|
+
&& hit.chunk.reference === anchor.chunk.reference);
|
|
17
|
+
const spans = compatible.map(hit => ({ id: hit.chunk.id, ...(hit.chunk.parent ?? { text:hit.chunk.text,start:hit.chunk.start,end:hit.chunk.end }) }))
|
|
18
|
+
.sort((a,b) => a.start-b.start || b.end-a.end || a.id.localeCompare(b.id));
|
|
19
|
+
let start=anchor.chunk.parent.start,end=anchor.chunk.parent.end,body=anchor.chunk.parent.text;
|
|
20
|
+
const contributors=new Set([anchor.chunk.id]);
|
|
21
|
+
// Grow only the connected component containing the anchor. Candidates are bounded by retrieval admission.
|
|
22
|
+
for(let changed=true;changed;){changed=false;
|
|
23
|
+
for(const span of spans){
|
|
24
|
+
if(span.end<start||span.start>end||contributors.has(span.id))continue;
|
|
25
|
+
const left=Math.max(start,span.start),right=Math.min(end,span.end);
|
|
26
|
+
if(body.slice(left-start,right-start)!==span.text.slice(left-span.start,right-span.start))continue;
|
|
27
|
+
if(span.start<start){body=span.text.slice(0,start-span.start)+body;start=span.start;changed=true;}
|
|
28
|
+
if(span.end>end){body+=span.text.slice(end-span.start);end=span.end;changed=true;}
|
|
29
|
+
contributors.add(span.id);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const maximum=Math.min(8000,Math.max(...compatible.map(h=>h.chunk.parent?.text.length??h.chunk.text.length)));
|
|
33
|
+
const spare=Math.max(0,maximum-(anchor.chunk.end-anchor.chunk.start));
|
|
34
|
+
let windowStart=Math.max(start,Math.min(anchor.chunk.start-Math.floor(spare/2),end-maximum));
|
|
35
|
+
let windowEnd=Math.min(end,windowStart+maximum);
|
|
36
|
+
// Moving inward preserves the hard byte-independent UTF-16 budget without splitting a surrogate pair.
|
|
37
|
+
if(windowStart>start&&/[\uDC00-\uDFFF]/u.test(body[windowStart-start]??''))windowStart++;
|
|
38
|
+
if(windowEnd<end&&/[\uD800-\uDBFF]/u.test(body[windowEnd-start-1]??''))windowEnd--;
|
|
39
|
+
if(windowStart>anchor.chunk.start||windowEnd<anchor.chunk.end)return undefined;
|
|
40
|
+
return{parent:{text:body.slice(windowStart-start,windowEnd-start),start:windowStart,end:windowEnd},contributorIds:[...contributors]};
|
|
41
|
+
}
|