"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/storage/sqlite/index.ts
var sqlite_exports = {};
__export(sqlite_exports, {
  createSqliteDocumentStore: () => createSqliteDocumentStore,
  createSqliteMemoryStore: () => createSqliteMemoryStore,
  createSqliteSourceStore: () => createSqliteSourceStore,
  createSqliteStore: () => createSqliteStore
});
module.exports = __toCommonJS(sqlite_exports);

// src/storage/sqlite/migrations.ts
var CREATE_TABLES = `
CREATE TABLE IF NOT EXISTS documents (
  id TEXT PRIMARY KEY,
  type TEXT NOT NULL,
  data TEXT NOT NULL,
  created_at INTEGER NOT NULL DEFAULT (unixepoch())
);

CREATE TABLE IF NOT EXISTS chunks (
  id TEXT PRIMARY KEY,
  document_id TEXT NOT NULL,
  type TEXT NOT NULL,
  text TEXT NOT NULL,
  metadata TEXT NOT NULL DEFAULT '{}',
  embedding BLOB,
  FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS conversation_turns (
  id TEXT PRIMARY KEY,
  conversation_id TEXT NOT NULL,
  role TEXT NOT NULL,
  content TEXT NOT NULL,
  tool_name TEXT,
  tool_result TEXT,
  timestamp INTEGER NOT NULL,
  embedding BLOB
);

CREATE TABLE IF NOT EXISTS source_spans (
  id TEXT PRIMARY KEY,
  document_id TEXT NOT NULL,
  source_kind TEXT,
  chunk_id TEXT,
  kind TEXT NOT NULL,
  text TEXT NOT NULL,
  hash TEXT NOT NULL,
  text_hash TEXT,
  page_start INTEGER,
  page_end INTEGER,
  section_id TEXT,
  form_number TEXT,
  source_unit TEXT,
  parent_span_id TEXT,
  table_location TEXT,
  location TEXT,
  bbox TEXT,
  metadata TEXT NOT NULL DEFAULT '{}',
  embedding BLOB
);

CREATE TABLE IF NOT EXISTS source_chunks (
  id TEXT PRIMARY KEY,
  document_id TEXT NOT NULL,
  source_span_ids TEXT NOT NULL,
  text TEXT NOT NULL,
  text_hash TEXT NOT NULL,
  page_start INTEGER,
  page_end INTEGER,
  metadata TEXT NOT NULL DEFAULT '{}'
);

CREATE INDEX IF NOT EXISTS idx_chunks_document_id ON chunks(document_id);
CREATE INDEX IF NOT EXISTS idx_chunks_type ON chunks(type);
CREATE INDEX IF NOT EXISTS idx_turns_conversation_id ON conversation_turns(conversation_id);
CREATE INDEX IF NOT EXISTS idx_turns_timestamp ON conversation_turns(timestamp);
CREATE INDEX IF NOT EXISTS idx_source_spans_document_id ON source_spans(document_id);
CREATE INDEX IF NOT EXISTS idx_source_spans_chunk_id ON source_spans(chunk_id);
CREATE INDEX IF NOT EXISTS idx_source_chunks_document_id ON source_chunks(document_id);
`;

// src/storage/sqlite/document-store.ts
function createSqliteDocumentStore(db) {
  return {
    async save(doc) {
      db.prepare("INSERT OR REPLACE INTO documents (id, type, data) VALUES (?, ?, ?)").run(
        doc.id,
        doc.type,
        JSON.stringify(doc)
      );
    },
    async get(id) {
      const row = db.prepare("SELECT data FROM documents WHERE id = ?").get(id);
      return row ? JSON.parse(row.data) : null;
    },
    async query(filters) {
      let sql = "SELECT data FROM documents WHERE 1=1";
      const params = [];
      if (filters.type) {
        sql += " AND type = ?";
        params.push(filters.type);
      }
      if (filters.carrier) {
        sql += " AND json_extract(data, '$.carrier') LIKE ?";
        params.push(`%${filters.carrier}%`);
      }
      if (filters.insuredName) {
        sql += " AND json_extract(data, '$.insuredName') LIKE ?";
        params.push(`%${filters.insuredName}%`);
      }
      if (filters.policyNumber) {
        sql += " AND json_extract(data, '$.policyNumber') = ?";
        params.push(filters.policyNumber);
      }
      if (filters.quoteNumber) {
        sql += " AND json_extract(data, '$.quoteNumber') = ?";
        params.push(filters.quoteNumber);
      }
      const rows = db.prepare(sql).all(...params);
      return rows.map((r) => JSON.parse(r.data));
    },
    async delete(id) {
      db.prepare("DELETE FROM documents WHERE id = ?").run(id);
    }
  };
}

// src/core/concurrency.ts
function pLimit(concurrency) {
  const maxConcurrency = Number.isFinite(concurrency) ? Math.max(1, Math.floor(concurrency)) : 1;
  let active = 0;
  const queue = [];
  function next() {
    if (queue.length > 0 && active < maxConcurrency) {
      active++;
      queue.shift()();
    }
  }
  return (fn) => new Promise((resolve, reject) => {
    const run = () => {
      fn().then(resolve, reject).finally(() => {
        active--;
        next();
      });
    };
    queue.push(run);
    next();
  });
}

// src/storage/sqlite/memory-store.ts
function cosineSimilarity(a, b) {
  let dot = 0, magA = 0, magB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    magA += a[i] * a[i];
    magB += b[i] * b[i];
  }
  return dot / (Math.sqrt(magA) * Math.sqrt(magB));
}
function createSqliteMemoryStore(db, embed) {
  const limit = pLimit(4);
  return {
    async addChunks(chunks) {
      const stmt = db.prepare("INSERT OR REPLACE INTO chunks (id, document_id, type, text, metadata, embedding) VALUES (?, ?, ?, ?, ?, ?)");
      const insertMany = db.transaction((items) => {
        for (const chunk of items) {
          stmt.run(chunk.id, chunk.documentId, chunk.type, chunk.text, JSON.stringify(chunk.metadata), null);
        }
      });
      insertMany(chunks);
      await Promise.all(chunks.map(
        (chunk) => limit(async () => {
          try {
            const embedding = await embed(chunk.text);
            const buf = Buffer.from(new Float64Array(embedding).buffer);
            db.prepare("UPDATE chunks SET embedding = ? WHERE id = ?").run(buf, chunk.id);
          } catch {
          }
        })
      ));
    },
    async search(query, options) {
      const queryEmbedding = await embed(query);
      const resultLimit = options?.limit ?? 10;
      let sql = "SELECT id, document_id, type, text, metadata, embedding FROM chunks WHERE embedding IS NOT NULL";
      const params = [];
      if (options?.filter?.documentId) {
        sql += " AND document_id = ?";
        params.push(options.filter.documentId);
      }
      if (options?.filter?.type) {
        sql += " AND type = ?";
        params.push(options.filter.type);
      }
      const rows = db.prepare(sql).all(...params);
      const scored = rows.map((row) => {
        const stored = Array.from(new Float64Array(row.embedding.buffer, row.embedding.byteOffset, row.embedding.byteLength / 8));
        return {
          chunk: {
            id: row.id,
            documentId: row.document_id,
            type: row.type,
            text: row.text,
            metadata: JSON.parse(row.metadata)
          },
          score: cosineSimilarity(queryEmbedding, stored)
        };
      });
      scored.sort((a, b) => b.score - a.score);
      return scored.slice(0, resultLimit).map((s) => s.chunk);
    },
    async addTurn(turn) {
      const embedding = await embed(turn.content).catch(() => null);
      const buf = embedding ? Buffer.from(new Float64Array(embedding).buffer) : null;
      db.prepare(
        "INSERT INTO conversation_turns (id, conversation_id, role, content, tool_name, tool_result, timestamp, embedding) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
      ).run(turn.id, turn.conversationId, turn.role, turn.content, turn.toolName ?? null, turn.toolResult ?? null, turn.timestamp, buf);
    },
    async getHistory(conversationId, options) {
      const resultLimit = options?.limit ?? 50;
      const rows = db.prepare(
        "SELECT id, conversation_id, role, content, tool_name, tool_result, timestamp FROM conversation_turns WHERE conversation_id = ? ORDER BY timestamp DESC LIMIT ?"
      ).all(conversationId, resultLimit);
      return rows.reverse().map((r) => ({
        id: r.id,
        conversationId: r.conversation_id,
        role: r.role,
        content: r.content,
        toolName: r.tool_name,
        toolResult: r.tool_result,
        timestamp: r.timestamp
      }));
    },
    async searchHistory(query, conversationId) {
      const queryEmbedding = await embed(query);
      let sql = "SELECT id, conversation_id, role, content, tool_name, tool_result, timestamp, embedding FROM conversation_turns WHERE embedding IS NOT NULL";
      const params = [];
      if (conversationId) {
        sql += " AND conversation_id = ?";
        params.push(conversationId);
      }
      const rows = db.prepare(sql).all(...params);
      const scored = rows.map((row) => {
        const buf = row.embedding;
        const stored = Array.from(new Float64Array(buf.buffer, buf.byteOffset, buf.byteLength / 8));
        return {
          turn: {
            id: row.id,
            conversationId: row.conversation_id,
            role: row.role,
            content: row.content,
            toolName: row.tool_name,
            toolResult: row.tool_result,
            timestamp: row.timestamp
          },
          score: cosineSimilarity(queryEmbedding, stored)
        };
      });
      scored.sort((a, b) => b.score - a.score);
      return scored.slice(0, 10).map((s) => s.turn);
    }
  };
}

// src/source/schemas.ts
var import_zod = require("zod");
var SourceSpanKindSchema = import_zod.z.enum([
  "pdf_text",
  "pdf_image",
  "html",
  "markdown",
  "plain_text",
  "structured_field"
]);
var SourceSpanUnitSchema = import_zod.z.enum([
  "page",
  "section",
  "table",
  "table_row",
  "table_cell",
  "key_value",
  "text"
]);
var SourceKindSchema = import_zod.z.enum([
  "policy_pdf",
  "application_pdf",
  "email",
  "attachment",
  "manual_note"
]);
var SourceSpanBBoxSchema = import_zod.z.object({
  page: import_zod.z.number().int().positive(),
  x: import_zod.z.number(),
  y: import_zod.z.number(),
  width: import_zod.z.number(),
  height: import_zod.z.number()
});
var SourceSpanLocationSchema = import_zod.z.object({
  page: import_zod.z.number().int().positive().optional(),
  startPage: import_zod.z.number().int().positive().optional(),
  endPage: import_zod.z.number().int().positive().optional(),
  charStart: import_zod.z.number().int().nonnegative().optional(),
  charEnd: import_zod.z.number().int().nonnegative().optional(),
  lineStart: import_zod.z.number().int().positive().optional(),
  lineEnd: import_zod.z.number().int().positive().optional(),
  fieldPath: import_zod.z.string().optional()
});
var SourceSpanTableLocationSchema = import_zod.z.object({
  tableId: import_zod.z.string().optional(),
  rowIndex: import_zod.z.number().int().nonnegative().optional(),
  columnIndex: import_zod.z.number().int().nonnegative().optional(),
  columnName: import_zod.z.string().optional(),
  rowSpanId: import_zod.z.string().optional(),
  tableSpanId: import_zod.z.string().optional(),
  isHeader: import_zod.z.boolean().optional()
});
var SourceSpanSchema = import_zod.z.object({
  id: import_zod.z.string().min(1),
  documentId: import_zod.z.string().min(1),
  sourceKind: SourceKindSchema.optional(),
  chunkId: import_zod.z.string().optional(),
  kind: SourceSpanKindSchema,
  text: import_zod.z.string(),
  hash: import_zod.z.string().min(1),
  textHash: import_zod.z.string().optional(),
  pageStart: import_zod.z.number().int().positive().optional(),
  pageEnd: import_zod.z.number().int().positive().optional(),
  sectionId: import_zod.z.string().optional(),
  formNumber: import_zod.z.string().optional(),
  sourceUnit: SourceSpanUnitSchema.optional(),
  parentSpanId: import_zod.z.string().optional(),
  table: SourceSpanTableLocationSchema.optional(),
  bbox: import_zod.z.array(SourceSpanBBoxSchema).optional(),
  location: SourceSpanLocationSchema.optional(),
  metadata: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional()
});
var SourceSpanRefSchema = import_zod.z.object({
  sourceSpanId: import_zod.z.string().min(1),
  documentId: import_zod.z.string().min(1).optional(),
  chunkId: import_zod.z.string().optional(),
  quote: import_zod.z.string().optional(),
  hash: import_zod.z.string().optional(),
  location: SourceSpanLocationSchema.optional()
});
var SourceChunkSchema = import_zod.z.object({
  id: import_zod.z.string().min(1),
  documentId: import_zod.z.string().min(1),
  sourceSpanIds: import_zod.z.array(import_zod.z.string().min(1)),
  text: import_zod.z.string(),
  textHash: import_zod.z.string().min(1),
  pageStart: import_zod.z.number().int().positive().optional(),
  pageEnd: import_zod.z.number().int().positive().optional(),
  metadata: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).default({})
});
var DocumentSourceNodeKindSchema = import_zod.z.enum([
  "document",
  "page_group",
  "page",
  "form",
  "endorsement",
  "section",
  "schedule",
  "clause",
  "table",
  "table_row",
  "table_cell",
  "text"
]);
var DocumentSourceNodeSchema = import_zod.z.object({
  id: import_zod.z.string().min(1),
  documentId: import_zod.z.string().min(1),
  parentId: import_zod.z.string().optional(),
  kind: DocumentSourceNodeKindSchema,
  title: import_zod.z.string(),
  description: import_zod.z.string(),
  textExcerpt: import_zod.z.string().optional(),
  sourceSpanIds: import_zod.z.array(import_zod.z.string().min(1)),
  pageStart: import_zod.z.number().int().positive().optional(),
  pageEnd: import_zod.z.number().int().positive().optional(),
  bbox: import_zod.z.array(SourceSpanBBoxSchema).optional(),
  order: import_zod.z.number().int().nonnegative(),
  path: import_zod.z.string(),
  metadata: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional()
});
var SourceBackedValueSchema = import_zod.z.object({
  value: import_zod.z.string(),
  normalizedValue: import_zod.z.string().optional(),
  confidence: import_zod.z.enum(["low", "medium", "high"]).default("medium"),
  sourceNodeIds: import_zod.z.array(import_zod.z.string().min(1)).default([]),
  sourceSpanIds: import_zod.z.array(import_zod.z.string().min(1)).default([])
});
var OperationalCoverageLineSchema = import_zod.z.object({
  name: import_zod.z.string(),
  coverageCode: import_zod.z.string().optional(),
  limit: import_zod.z.string().optional(),
  deductible: import_zod.z.string().optional(),
  premium: import_zod.z.string().optional(),
  formNumber: import_zod.z.string().optional(),
  sectionRef: import_zod.z.string().optional(),
  sourceNodeIds: import_zod.z.array(import_zod.z.string().min(1)).default([]),
  sourceSpanIds: import_zod.z.array(import_zod.z.string().min(1)).default([])
});
var OperationalPartySchema = import_zod.z.object({
  role: import_zod.z.string(),
  name: import_zod.z.string(),
  sourceNodeIds: import_zod.z.array(import_zod.z.string().min(1)).default([]),
  sourceSpanIds: import_zod.z.array(import_zod.z.string().min(1)).default([])
});
var OperationalEndorsementSupportSchema = import_zod.z.object({
  kind: import_zod.z.string(),
  status: import_zod.z.enum(["supported", "excluded", "requires_review"]),
  summary: import_zod.z.string(),
  sourceNodeIds: import_zod.z.array(import_zod.z.string().min(1)).default([]),
  sourceSpanIds: import_zod.z.array(import_zod.z.string().min(1)).default([])
});
var PolicyOperationalProfileSchema = import_zod.z.object({
  documentType: import_zod.z.enum(["policy", "quote"]).default("policy"),
  policyTypes: import_zod.z.array(import_zod.z.string()).default(["other"]),
  policyNumber: SourceBackedValueSchema.optional(),
  namedInsured: SourceBackedValueSchema.optional(),
  insurer: SourceBackedValueSchema.optional(),
  broker: SourceBackedValueSchema.optional(),
  effectiveDate: SourceBackedValueSchema.optional(),
  expirationDate: SourceBackedValueSchema.optional(),
  retroactiveDate: SourceBackedValueSchema.optional(),
  premium: SourceBackedValueSchema.optional(),
  coverageTypes: import_zod.z.array(import_zod.z.string()).default([]),
  coverages: import_zod.z.array(OperationalCoverageLineSchema).default([]),
  parties: import_zod.z.array(OperationalPartySchema).default([]),
  endorsementSupport: import_zod.z.array(OperationalEndorsementSupportSchema).default([]),
  sourceNodeIds: import_zod.z.array(import_zod.z.string().min(1)).default([]),
  sourceSpanIds: import_zod.z.array(import_zod.z.string().min(1)).default([]),
  warnings: import_zod.z.array(import_zod.z.string()).default([])
});

// src/source/retrieval.ts
function evidenceTieBreakId(evidence) {
  return [
    evidence.source ?? "",
    evidence.sourceSpanId ?? "",
    evidence.chunkId ?? "",
    evidence.documentId ?? "",
    evidence.turnId ?? "",
    evidence.attachmentId ?? "",
    evidence.text
  ].join("|");
}
function compareSourceEvidence(a, b) {
  const relevanceDelta = b.relevance - a.relevance;
  if (relevanceDelta !== 0) return relevanceDelta;
  return evidenceTieBreakId(a).localeCompare(evidenceTieBreakId(b));
}
function orderSourceEvidence(evidence) {
  return [...evidence].sort(compareSourceEvidence);
}

// src/storage/sqlite/source-store.ts
function cosineSimilarity2(a, b) {
  let dot = 0, magA = 0, magB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    magA += a[i] * a[i];
    magB += b[i] * b[i];
  }
  const denominator = Math.sqrt(magA) * Math.sqrt(magB);
  return denominator === 0 ? 0 : dot / denominator;
}
function embeddingToBuffer(embedding) {
  return Buffer.from(new Float64Array(embedding).buffer);
}
function bufferToEmbedding(buffer) {
  return Array.from(new Float64Array(buffer.buffer, buffer.byteOffset, buffer.byteLength / 8));
}
function parseJson(value, fallback) {
  if (!value) return fallback;
  try {
    return JSON.parse(value);
  } catch {
    return fallback;
  }
}
function rowToSourceSpan(row) {
  const metadata = parseJson(row.metadata, {});
  return {
    id: row.id,
    documentId: row.document_id,
    sourceKind: row.source_kind ?? void 0,
    chunkId: row.chunk_id ?? void 0,
    kind: row.kind,
    text: row.text,
    hash: row.hash,
    textHash: row.text_hash ?? void 0,
    pageStart: row.page_start ?? void 0,
    pageEnd: row.page_end ?? void 0,
    sectionId: row.section_id ?? void 0,
    formNumber: row.form_number ?? void 0,
    sourceUnit: row.source_unit ?? void 0,
    parentSpanId: row.parent_span_id ?? void 0,
    table: parseJson(row.table_location, void 0),
    location: parseJson(row.location, void 0),
    bbox: parseJson(row.bbox, void 0),
    metadata: Object.keys(metadata).length ? metadata : void 0
  };
}
function rowToSourceChunk(row) {
  return {
    id: row.id,
    documentId: row.document_id,
    sourceSpanIds: parseJson(row.source_span_ids, []),
    text: row.text,
    textHash: row.text_hash,
    pageStart: row.page_start,
    pageEnd: row.page_end,
    metadata: parseJson(row.metadata, {})
  };
}
function createSqliteSourceStore(db, embed) {
  const limit = pLimit(4);
  return {
    async addSourceSpans(spans) {
      const stmt = db.prepare(`
        INSERT OR REPLACE INTO source_spans (
          id, document_id, source_kind, chunk_id, kind, text, hash, text_hash,
          page_start, page_end, section_id, form_number, source_unit, parent_span_id,
          table_location, location, bbox, metadata, embedding
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `);
      const insertMany = db.transaction((items) => {
        for (const span of items) {
          stmt.run(
            span.id,
            span.documentId,
            span.sourceKind ?? null,
            span.chunkId ?? null,
            span.kind,
            span.text,
            span.hash,
            span.textHash ?? null,
            span.pageStart ?? null,
            span.pageEnd ?? null,
            span.sectionId ?? null,
            span.formNumber ?? null,
            span.sourceUnit ?? null,
            span.parentSpanId ?? null,
            span.table ? JSON.stringify(span.table) : null,
            span.location ? JSON.stringify(span.location) : null,
            span.bbox ? JSON.stringify(span.bbox) : null,
            JSON.stringify(span.metadata ?? {}),
            null
          );
        }
      });
      insertMany(spans);
      await Promise.all(spans.map(
        (span) => limit(async () => {
          try {
            const embedding = await embed(span.text);
            db.prepare("UPDATE source_spans SET embedding = ? WHERE id = ?").run(embeddingToBuffer(embedding), span.id);
          } catch {
          }
        })
      ));
    },
    async addSourceChunks(chunks) {
      const stmt = db.prepare(`
        INSERT OR REPLACE INTO source_chunks (
          id, document_id, source_span_ids, text, text_hash, page_start, page_end, metadata
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `);
      const insertMany = db.transaction((items) => {
        for (const chunk of items) {
          stmt.run(
            chunk.id,
            chunk.documentId,
            JSON.stringify(chunk.sourceSpanIds),
            chunk.text,
            chunk.textHash,
            chunk.pageStart ?? null,
            chunk.pageEnd ?? null,
            JSON.stringify(chunk.metadata ?? {})
          );
        }
      });
      insertMany(chunks);
    },
    async getSourceSpan(id) {
      const row = db.prepare("SELECT * FROM source_spans WHERE id = ?").get(id);
      return row ? rowToSourceSpan(row) : null;
    },
    async getSourceSpansByDocument(documentId) {
      const rows = db.prepare("SELECT * FROM source_spans WHERE document_id = ? ORDER BY id ASC").all(documentId);
      return rows.map(rowToSourceSpan);
    },
    async getSourceChunksByDocument(documentId) {
      const rows = db.prepare("SELECT * FROM source_chunks WHERE document_id = ? ORDER BY id ASC").all(documentId);
      return rows.map(rowToSourceChunk);
    },
    async deleteDocumentSource(documentId) {
      db.prepare("DELETE FROM source_chunks WHERE document_id = ?").run(documentId);
      db.prepare("DELETE FROM source_spans WHERE document_id = ?").run(documentId);
    },
    async searchSourceSpans(query) {
      const queryEmbedding = await embed(query.question);
      const resultLimit = query.limit ?? 10;
      let sql = "SELECT * FROM source_spans WHERE embedding IS NOT NULL";
      const params = [];
      if (query.documentIds?.length) {
        sql += ` AND document_id IN (${query.documentIds.map(() => "?").join(",")})`;
        params.push(...query.documentIds);
      }
      if (query.chunkIds?.length) {
        sql += ` AND chunk_id IN (${query.chunkIds.map(() => "?").join(",")})`;
        params.push(...query.chunkIds);
      }
      if (query.filters?.sourceKind) {
        sql += " AND source_kind = ?";
        params.push(query.filters.sourceKind);
      }
      if (query.filters?.formNumber) {
        sql += " AND form_number = ?";
        params.push(query.filters.formNumber);
      }
      if (query.filters?.sectionId) {
        sql += " AND section_id = ?";
        params.push(query.filters.sectionId);
      }
      const rows = db.prepare(sql).all(...params);
      const scored = rows.map((row) => {
        const span = rowToSourceSpan(row);
        return {
          span,
          relevance: cosineSimilarity2(queryEmbedding, bufferToEmbedding(row.embedding))
        };
      });
      return orderSourceEvidence(scored.map((result) => ({
        ...result,
        sourceSpanId: result.span.id,
        chunkId: result.span.chunkId,
        documentId: result.span.documentId,
        text: result.span.text
      }))).map(({ span, relevance }) => ({ span, relevance })).slice(0, resultLimit);
    }
  };
}

// src/storage/sqlite/index.ts
function createSqliteStore(options) {
  const BetterSqlite3 = require("better-sqlite3");
  const db = new BetterSqlite3(options.path);
  db.pragma("journal_mode = WAL");
  db.pragma("foreign_keys = ON");
  db.exec(CREATE_TABLES);
  return {
    documents: createSqliteDocumentStore(db),
    memory: createSqliteMemoryStore(db, options.embed),
    source: createSqliteSourceStore(db, options.embed),
    close: () => db.close()
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createSqliteDocumentStore,
  createSqliteMemoryStore,
  createSqliteSourceStore,
  createSqliteStore
});
//# sourceMappingURL=storage-sqlite.js.map