// src/memory-projection-store.ts
import path from "path";
import fs from "fs";

// src/runtime/better-sqlite.ts
import { createRequire } from "module";
var cachedCtor = null;
function loadBetterSqlite3() {
  if (cachedCtor) return cachedCtor;
  const require2 = createRequire(import.meta.url);
  try {
    cachedCtor = requireBetterSqlite3Ctor(require2);
    return cachedCtor;
  } catch (error) {
    throw unavailableError(error);
  }
}
function openBetterSqlite3(file, options) {
  const Database = loadBetterSqlite3();
  return new Database(file, options);
}
function requireBetterSqlite3Ctor(require2) {
  const loaded = require2("better-sqlite3");
  const ctor = typeof loaded === "function" ? loaded : loaded.default;
  if (typeof ctor !== "function") {
    throw new Error("module did not export a constructor");
  }
  return ctor;
}
function isLikelyBetterSqlite3NativeBindingError(error) {
  const detail = errorDetail(error);
  return detail.includes("Could not locate the bindings file") || detail.includes("better_sqlite3.node") || detail.includes("node-v") && detail.includes("better-sqlite3") || detail.includes("NODE_MODULE_VERSION") && detail.includes("better-sqlite3") || detail.includes("was compiled against a different Node.js version");
}
function unavailableError(error) {
  const detail = errorDetail(error);
  const nativeBindingHint = isLikelyBetterSqlite3NativeBindingError(error) ? " This usually means the better-sqlite3 native binding was not compiled for this Node.js/platform combination. Run `node scripts/ensure-better-sqlite3.mjs` from the Remnic install directory, or run `npx node-gyp rebuild --directory=node_modules/better-sqlite3` if the verification script is unavailable." : "";
  return new Error(
    "better-sqlite3 is unavailable. Remnic attempted to load the native SQLite binding and could not." + nativeBindingHint + (detail ? ` Original error: ${detail}` : ""),
    { cause: error instanceof Error ? error : void 0 }
  );
}
function errorDetail(error) {
  if (error instanceof Error) {
    const stack = error.stack && error.stack !== error.message ? `
${error.stack}` : "";
    return `${error.message}${stack}`;
  }
  return String(error ?? "");
}

// src/memory-projection-store.ts
var MEMORY_PROJECTION_SCHEMA_VERSION = 2;
function getMemoryProjectionPath(memoryDir) {
  return path.join(memoryDir, "state", "memory-projection.sqlite");
}
function listTableColumns(db, tableName) {
  try {
    const rows = db.prepare(`PRAGMA table_info(${tableName})`).all();
    return new Set(rows.map((row) => row.name).filter((name) => typeof name === "string"));
  } catch {
    return /* @__PURE__ */ new Set();
  }
}
function migrateMemoryCurrentTable(db) {
  const columns = listTableColumns(db, "memory_current");
  if (columns.size === 0) return;
  if (!columns.has("tags_json")) {
    db.exec(`ALTER TABLE memory_current ADD COLUMN tags_json TEXT NOT NULL DEFAULT '[]'`);
  }
  if (!columns.has("preview_text")) {
    db.exec(`ALTER TABLE memory_current ADD COLUMN preview_text TEXT NOT NULL DEFAULT ''`);
  }
}
function memoryCurrentRequiresMigration(db) {
  const columns = listTableColumns(db, "memory_current");
  return columns.size > 0 && (!columns.has("tags_json") || !columns.has("preview_text"));
}
function migrateProjectionSchemaIfNeeded(memoryDir) {
  const dbPath = getMemoryProjectionPath(memoryDir);
  try {
    const db = openBetterSqlite3(dbPath, { fileMustExist: true });
    try {
      if (!memoryCurrentRequiresMigration(db)) return;
      initializeMemoryProjectionDb(db);
    } finally {
      db.close();
    }
  } catch {
  }
}
function memoryCurrentSelectExpressions(db) {
  const columns = listTableColumns(db, "memory_current");
  return {
    tagsJson: columns.has("tags_json") ? "tags_json" : `'[]' AS tags_json`,
    previewText: columns.has("preview_text") ? "preview_text" : `'' AS preview_text`
  };
}
function initializeMemoryProjectionDb(db) {
  db.exec(`
    CREATE TABLE IF NOT EXISTS meta (
      key TEXT PRIMARY KEY,
      value TEXT NOT NULL
    );

    CREATE TABLE IF NOT EXISTS memory_current (
      memory_id TEXT PRIMARY KEY,
      category TEXT NOT NULL,
      status TEXT NOT NULL,
      lifecycle_state TEXT,
      path_rel TEXT NOT NULL,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      archived_at TEXT,
      superseded_at TEXT,
      entity_ref TEXT,
      source TEXT NOT NULL,
      confidence REAL NOT NULL,
      confidence_tier TEXT NOT NULL,
      memory_kind TEXT,
      access_count INTEGER,
      last_accessed TEXT,
      tags_json TEXT NOT NULL DEFAULT '[]',
      preview_text TEXT NOT NULL DEFAULT ''
    );

    CREATE INDEX IF NOT EXISTS idx_memory_current_status
      ON memory_current(status);

    CREATE INDEX IF NOT EXISTS idx_memory_current_category
      ON memory_current(category);

    CREATE INDEX IF NOT EXISTS idx_memory_current_updated
      ON memory_current(updated_at DESC);

    CREATE TABLE IF NOT EXISTS memory_timeline (
      event_id TEXT PRIMARY KEY,
      memory_id TEXT NOT NULL,
      event_type TEXT NOT NULL,
      timestamp TEXT NOT NULL,
      event_order INTEGER NOT NULL,
      actor TEXT NOT NULL,
      reason_code TEXT,
      rule_version TEXT NOT NULL,
      related_memory_ids_json TEXT,
      before_json TEXT,
      after_json TEXT,
      correlation_id TEXT
    );

    CREATE INDEX IF NOT EXISTS idx_memory_timeline_memory_ts
      ON memory_timeline(memory_id, timestamp, event_order);

    CREATE TABLE IF NOT EXISTS memory_entity_mentions (
      memory_id TEXT NOT NULL,
      entity_ref TEXT NOT NULL,
      mention_source TEXT NOT NULL,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL,
      PRIMARY KEY (memory_id, entity_ref, mention_source)
    );

    CREATE INDEX IF NOT EXISTS idx_memory_entity_mentions_entity
      ON memory_entity_mentions(entity_ref, updated_at DESC);

    CREATE TABLE IF NOT EXISTS native_knowledge_chunks (
      chunk_id TEXT PRIMARY KEY,
      source_path TEXT NOT NULL,
      title TEXT NOT NULL,
      source_kind TEXT NOT NULL,
      start_line INTEGER NOT NULL,
      end_line INTEGER NOT NULL,
      derived_date TEXT,
      session_key TEXT,
      workflow_key TEXT,
      author TEXT,
      agent TEXT,
      namespace TEXT,
      privacy_class TEXT,
      source_hash TEXT,
      preview_text TEXT NOT NULL
    );

    CREATE INDEX IF NOT EXISTS idx_native_knowledge_source_kind
      ON native_knowledge_chunks(source_kind);

    CREATE INDEX IF NOT EXISTS idx_native_knowledge_namespace
      ON native_knowledge_chunks(namespace);

    CREATE TABLE IF NOT EXISTS memory_review_runs (
      run_id TEXT PRIMARY KEY,
      created_at TEXT NOT NULL,
      mode TEXT NOT NULL,
      summary_json TEXT NOT NULL,
      metrics_json TEXT NOT NULL,
      applied_actions_json TEXT NOT NULL,
      report_markdown TEXT NOT NULL
    );

    CREATE INDEX IF NOT EXISTS idx_memory_review_runs_created
      ON memory_review_runs(created_at DESC);

    CREATE TABLE IF NOT EXISTS memory_review_queue (
      entry_id TEXT PRIMARY KEY,
      run_id TEXT NOT NULL,
      memory_id TEXT NOT NULL,
      path TEXT NOT NULL,
      reason_code TEXT NOT NULL,
      severity TEXT NOT NULL,
      suggested_action TEXT NOT NULL,
      suggested_status TEXT,
      related_memory_ids_json TEXT NOT NULL
    );

    CREATE INDEX IF NOT EXISTS idx_memory_review_queue_run
      ON memory_review_queue(run_id, reason_code, memory_id);

    CREATE TABLE IF NOT EXISTS memory_review_actions (
      row_key TEXT PRIMARY KEY,
      run_id TEXT NOT NULL,
      action TEXT NOT NULL,
      memory_id TEXT NOT NULL,
      reason_code TEXT NOT NULL,
      before_status TEXT NOT NULL,
      after_status TEXT,
      original_path TEXT NOT NULL,
      current_path TEXT NOT NULL
    );

    CREATE INDEX IF NOT EXISTS idx_memory_review_actions_run
      ON memory_review_actions(run_id, memory_id);
  `);
  migrateMemoryCurrentTable(db);
  db.prepare("INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)").run("schemaVersion", String(MEMORY_PROJECTION_SCHEMA_VERSION));
}
function openProjectionReadonly(memoryDir) {
  const dbPath = getMemoryProjectionPath(memoryDir);
  try {
    return openBetterSqlite3(dbPath, { readonly: true, fileMustExist: true });
  } catch {
    return null;
  }
}
function withProjectionReadonly(memoryDir, reader) {
  const db = openProjectionReadonly(memoryDir);
  if (!db) return null;
  let needsMigration = false;
  try {
    needsMigration = memoryCurrentRequiresMigration(db);
    return reader(db);
  } catch {
    return null;
  } finally {
    db.close();
    if (needsMigration) {
      migrateProjectionSchemaIfNeeded(memoryDir);
    }
  }
}
function parseStringArray(value) {
  if (typeof value !== "string" || value.length === 0) return [];
  try {
    const parsed = JSON.parse(value);
    return Array.isArray(parsed) ? parsed.filter((entry) => typeof entry === "string") : [];
  } catch {
    return [];
  }
}
function parseJsonObject(value) {
  if (typeof value !== "string" || value.length === 0) return void 0;
  try {
    return JSON.parse(value);
  } catch {
    return void 0;
  }
}
function parseCurrentRow(memoryDir, row) {
  if (!row) return null;
  if (typeof row.memory_id !== "string" || typeof row.category !== "string" || typeof row.status !== "string" || typeof row.path_rel !== "string" || typeof row.created_at !== "string" || typeof row.updated_at !== "string" || typeof row.source !== "string" || typeof row.confidence !== "number" || typeof row.confidence_tier !== "string") {
    return null;
  }
  return {
    memoryId: row.memory_id,
    category: row.category,
    status: row.status,
    lifecycleState: typeof row.lifecycle_state === "string" ? row.lifecycle_state : void 0,
    path: path.join(memoryDir, row.path_rel),
    pathRel: row.path_rel,
    created: row.created_at,
    updated: row.updated_at,
    archivedAt: typeof row.archived_at === "string" ? row.archived_at : void 0,
    supersededAt: typeof row.superseded_at === "string" ? row.superseded_at : void 0,
    entityRef: typeof row.entity_ref === "string" ? row.entity_ref : void 0,
    source: row.source,
    confidence: row.confidence,
    confidenceTier: row.confidence_tier,
    memoryKind: typeof row.memory_kind === "string" ? row.memory_kind : void 0,
    accessCount: typeof row.access_count === "number" ? row.access_count : void 0,
    lastAccessed: typeof row.last_accessed === "string" ? row.last_accessed : void 0,
    tags: parseStringArray(row.tags_json),
    preview: typeof row.preview_text === "string" ? row.preview_text : ""
  };
}
function parseTimelineRows(rows) {
  const out = [];
  for (const row of rows) {
    if (typeof row.event_id !== "string" || typeof row.memory_id !== "string" || typeof row.event_type !== "string" || typeof row.timestamp !== "string" || typeof row.actor !== "string" || typeof row.rule_version !== "string") {
      continue;
    }
    out.push({
      eventId: row.event_id,
      memoryId: row.memory_id,
      eventType: row.event_type,
      timestamp: row.timestamp,
      actor: row.actor,
      reasonCode: typeof row.reason_code === "string" ? row.reason_code : void 0,
      ruleVersion: row.rule_version,
      relatedMemoryIds: parseStringArray(row.related_memory_ids_json),
      before: parseJsonObject(row.before_json),
      after: parseJsonObject(row.after_json),
      correlationId: typeof row.correlation_id === "string" ? row.correlation_id : void 0
    });
  }
  return out;
}
function readProjectedMemoryState(memoryDir, memoryId) {
  return withProjectionReadonly(memoryDir, (db) => {
    const currentSelect = memoryCurrentSelectExpressions(db);
    const row = db.prepare(
      `
          SELECT
            memory_id,
            category,
            status,
            lifecycle_state,
            path_rel,
            created_at,
            updated_at,
            archived_at,
            superseded_at,
            entity_ref,
            source,
            confidence,
            confidence_tier,
            memory_kind,
            access_count,
            last_accessed,
            ${currentSelect.tagsJson},
            ${currentSelect.previewText}
          FROM memory_current
          WHERE memory_id = ?
        `
    ).get(memoryId);
    return parseCurrentRow(memoryDir, row);
  });
}
function readProjectedMemoryTimeline(memoryDir, memoryId, limit) {
  const db = openProjectionReadonly(memoryDir);
  if (!db) return null;
  try {
    const rows = db.prepare(
      `
          SELECT * FROM (
            SELECT
              event_id,
              memory_id,
              event_type,
              timestamp,
              event_order,
              actor,
              reason_code,
              rule_version,
              related_memory_ids_json,
              before_json,
              after_json,
              correlation_id
            FROM memory_timeline
            WHERE memory_id = ?
            ORDER BY timestamp DESC, event_order DESC
            LIMIT ?
          )
          ORDER BY timestamp ASC, event_order ASC
        `
    ).all(memoryId, limit);
    if (rows.length === 0) return null;
    return parseTimelineRows(rows);
  } catch {
    return null;
  } finally {
    db.close();
  }
}
function readProjectedMemoryBrowse(memoryDir, options) {
  return withProjectionReadonly(memoryDir, (db) => {
    const normalizedQuery = options.query?.trim().toLowerCase() ?? "";
    const currentSelect = memoryCurrentSelectExpressions(db);
    const whereClauses = [];
    const params = [];
    if (options.status) {
      whereClauses.push("status = ?");
      params.push(options.status);
    }
    if (options.category) {
      whereClauses.push("category = ?");
      params.push(options.category);
    }
    const sort = options.sort ?? "updated_desc";
    const orderBySql = (() => {
      switch (sort) {
        case "updated_asc":
          return "updated_at ASC, created_at ASC, memory_id ASC";
        case "created_desc":
          return "created_at DESC, updated_at DESC, memory_id ASC";
        case "created_asc":
          return "created_at ASC, updated_at ASC, memory_id ASC";
        case "updated_desc":
        default:
          return "updated_at DESC, created_at DESC, memory_id ASC";
      }
    })();
    const whereSql = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
    if (normalizedQuery) {
      const allRows = db.prepare(`
          SELECT
            memory_id,
            path_rel,
            category,
            status,
            created_at,
            updated_at,
            entity_ref,
            ${currentSelect.tagsJson},
            ${currentSelect.previewText}
          FROM memory_current
          ${whereSql}
          ORDER BY ${orderBySql}
        `).all(...params);
      const filtered = allRows.filter((row) => {
        if (typeof row.memory_id !== "string" || typeof row.path_rel !== "string") return false;
        const preview = typeof row.preview_text === "string" ? row.preview_text.toLowerCase() : "";
        const category = typeof row.category === "string" ? row.category.toLowerCase() : "";
        const entityRef = typeof row.entity_ref === "string" ? row.entity_ref.toLowerCase() : "";
        const tags = typeof row.tags_json === "string" ? row.tags_json.toLowerCase() : "";
        if (preview.includes(normalizedQuery) || category.includes(normalizedQuery) || entityRef.includes(normalizedQuery) || tags.includes(normalizedQuery)) {
          return true;
        }
        try {
          const filePath = path.join(memoryDir, row.path_rel);
          const content = fs.readFileSync(filePath, "utf-8").toLowerCase();
          return content.includes(normalizedQuery);
        } catch {
          return false;
        }
      });
      const pageRows = filtered.slice(options.offset, options.offset + options.limit);
      return {
        total: filtered.length,
        memories: pageRows.filter(
          (row) => typeof row.memory_id === "string" && typeof row.path_rel === "string" && typeof row.category === "string" && typeof row.status === "string"
        ).map((row) => ({
          id: row.memory_id,
          path: path.join(memoryDir, row.path_rel),
          category: row.category,
          status: row.status,
          created: typeof row.created_at === "string" ? row.created_at : void 0,
          updated: typeof row.updated_at === "string" ? row.updated_at : void 0,
          tags: parseStringArray(row.tags_json),
          entityRef: typeof row.entity_ref === "string" ? row.entity_ref : void 0,
          preview: typeof row.preview_text === "string" ? row.preview_text : ""
        }))
      };
    }
    const totalRow = db.prepare(`SELECT COUNT(*) AS total FROM memory_current ${whereSql}`).get(...params);
    const rows = db.prepare(`
        SELECT
          memory_id,
          path_rel,
          category,
          status,
          created_at,
          updated_at,
          entity_ref,
          ${currentSelect.tagsJson},
          ${currentSelect.previewText}
        FROM memory_current
        ${whereSql}
        ORDER BY ${orderBySql}
        LIMIT ? OFFSET ?
      `).all(...params, options.limit, options.offset);
    return {
      total: typeof totalRow?.total === "number" ? totalRow.total : 0,
      memories: rows.filter(
        (row) => typeof row.memory_id === "string" && typeof row.path_rel === "string" && typeof row.category === "string" && typeof row.status === "string"
      ).map((row) => ({
        id: row.memory_id,
        path: path.join(memoryDir, row.path_rel),
        category: row.category,
        status: row.status,
        created: typeof row.created_at === "string" ? row.created_at : void 0,
        updated: typeof row.updated_at === "string" ? row.updated_at : void 0,
        tags: parseStringArray(row.tags_json),
        entityRef: typeof row.entity_ref === "string" ? row.entity_ref : void 0,
        preview: typeof row.preview_text === "string" ? row.preview_text : ""
      }))
    };
  });
}
function readProjectedEntityMentions(memoryDir, memoryIds) {
  const db = openProjectionReadonly(memoryDir);
  if (!db) return null;
  try {
    const rows = db.prepare(`
        SELECT
          memory_id,
          entity_ref,
          mention_source,
          created_at,
          updated_at
        FROM memory_entity_mentions
        ORDER BY entity_ref ASC, updated_at DESC, memory_id ASC
      `).all();
    return rows.filter(
      (row) => typeof row.memory_id === "string" && typeof row.entity_ref === "string" && typeof row.mention_source === "string" && typeof row.created_at === "string" && typeof row.updated_at === "string" && (!memoryIds || memoryIds.has(row.memory_id))
    ).map((row) => ({
      memoryId: row.memory_id,
      entityRef: row.entity_ref,
      mentionSource: row.mention_source,
      created: row.created_at,
      updated: row.updated_at
    }));
  } catch {
    return null;
  } finally {
    db.close();
  }
}
function readProjectedNativeKnowledgeChunks(memoryDir) {
  const db = openProjectionReadonly(memoryDir);
  if (!db) return null;
  try {
    const rows = db.prepare(`
        SELECT
          chunk_id,
          source_path,
          title,
          source_kind,
          start_line,
          end_line,
          derived_date,
          session_key,
          workflow_key,
          author,
          agent,
          namespace,
          privacy_class,
          source_hash,
          preview_text
        FROM native_knowledge_chunks
        ORDER BY source_kind ASC, source_path ASC, start_line ASC
      `).all();
    return rows.filter(
      (row) => typeof row.chunk_id === "string" && typeof row.source_path === "string" && typeof row.title === "string" && typeof row.source_kind === "string" && typeof row.start_line === "number" && typeof row.end_line === "number" && typeof row.preview_text === "string"
    ).map((row) => ({
      chunkId: row.chunk_id,
      sourcePath: row.source_path,
      title: row.title,
      sourceKind: row.source_kind,
      startLine: row.start_line,
      endLine: row.end_line,
      derivedDate: typeof row.derived_date === "string" ? row.derived_date : void 0,
      sessionKey: typeof row.session_key === "string" ? row.session_key : void 0,
      workflowKey: typeof row.workflow_key === "string" ? row.workflow_key : void 0,
      author: typeof row.author === "string" ? row.author : void 0,
      agent: typeof row.agent === "string" ? row.agent : void 0,
      namespace: typeof row.namespace === "string" ? row.namespace : void 0,
      privacyClass: typeof row.privacy_class === "string" ? row.privacy_class : void 0,
      sourceHash: typeof row.source_hash === "string" ? row.source_hash : void 0,
      preview: row.preview_text
    }));
  } catch {
    return null;
  } finally {
    db.close();
  }
}
function readProjectedLatestReviewQueue(memoryDir) {
  const db = openProjectionReadonly(memoryDir);
  if (!db) return null;
  try {
    const latestRunId = db.prepare(`SELECT value FROM meta WHERE key = 'latestGovernanceRunId'`).get()?.value ?? db.prepare(`SELECT run_id AS value FROM memory_review_runs ORDER BY created_at DESC LIMIT 1`).get()?.value;
    if (!latestRunId) {
      return { found: false };
    }
    const runRow = db.prepare(`
        SELECT
          run_id,
          summary_json,
          metrics_json,
          applied_actions_json,
          report_markdown
        FROM memory_review_runs
        WHERE run_id = ?
      `).get(latestRunId);
    if (!runRow || typeof runRow.run_id !== "string") {
      return { found: false };
    }
    const queueRows = db.prepare(`
        SELECT
          entry_id,
          memory_id,
          path,
          reason_code,
          severity,
          suggested_action,
          suggested_status,
          related_memory_ids_json
        FROM memory_review_queue
        WHERE run_id = ?
        ORDER BY reason_code ASC, memory_id ASC
      `).all(latestRunId);
    const actionRows = db.prepare(`
        SELECT
          row_key,
          action,
          memory_id,
          reason_code,
          before_status,
          after_status,
          original_path,
          current_path
        FROM memory_review_actions
        WHERE run_id = ?
        ORDER BY memory_id ASC, action ASC
      `).all(latestRunId);
    const reviewQueue = queueRows.filter(
      (row) => typeof row.entry_id === "string" && typeof row.memory_id === "string" && typeof row.path === "string" && typeof row.reason_code === "string" && typeof row.severity === "string" && typeof row.suggested_action === "string"
    ).map((row) => ({
      entryId: row.entry_id,
      memoryId: row.memory_id,
      path: row.path,
      reasonCode: row.reason_code,
      severity: row.severity,
      suggestedAction: row.suggested_action,
      suggestedStatus: typeof row.suggested_status === "string" ? row.suggested_status : void 0,
      relatedMemoryIds: parseStringArray(row.related_memory_ids_json)
    }));
    return {
      found: true,
      runId: latestRunId,
      summary: parseJsonObject(runRow.summary_json),
      metrics: parseJsonObject(runRow.metrics_json),
      reviewQueue,
      appliedActions: actionRows.length > 0 ? actionRows.filter(
        (row) => typeof row.action === "string" && typeof row.memory_id === "string" && typeof row.reason_code === "string" && typeof row.before_status === "string" && typeof row.original_path === "string" && typeof row.current_path === "string"
      ).map((row) => ({
        action: row.action,
        memoryId: row.memory_id,
        reasonCode: row.reason_code,
        beforeStatus: row.before_status,
        afterStatus: typeof row.after_status === "string" ? row.after_status : void 0,
        originalPath: row.original_path,
        currentPath: row.current_path
      })) : parseJsonObject(runRow.applied_actions_json) ?? [],
      report: typeof runRow.report_markdown === "string" ? runRow.report_markdown : void 0
    };
  } catch {
    return null;
  } finally {
    db.close();
  }
}
function readProjectedGovernanceRecord(memoryDir) {
  const snapshot = readProjectedLatestReviewQueue(memoryDir);
  if (!snapshot?.found || !snapshot.runId) return null;
  return {
    runId: snapshot.runId,
    summary: snapshot.summary ?? {},
    metrics: snapshot.metrics ?? {},
    reviewQueueRows: (snapshot.reviewQueue ?? []).map((entry) => ({
      runId: snapshot.runId,
      entryId: entry.entryId,
      memoryId: entry.memoryId,
      path: entry.path,
      reasonCode: entry.reasonCode,
      severity: entry.severity,
      suggestedAction: entry.suggestedAction,
      suggestedStatus: entry.suggestedStatus,
      relatedMemoryIds: [...entry.relatedMemoryIds]
    })),
    appliedActionRows: (snapshot.appliedActions ?? []).map((action) => ({
      runId: snapshot.runId,
      rowKey: [
        action.action,
        action.memoryId,
        action.reasonCode,
        action.originalPath,
        action.currentPath
      ].join("::"),
      action: action.action,
      memoryId: action.memoryId,
      reasonCode: action.reasonCode,
      beforeStatus: action.beforeStatus,
      afterStatus: action.afterStatus,
      originalPath: action.originalPath,
      currentPath: action.currentPath
    })),
    report: snapshot.report ?? ""
  };
}

export {
  openBetterSqlite3,
  MEMORY_PROJECTION_SCHEMA_VERSION,
  getMemoryProjectionPath,
  memoryCurrentSelectExpressions,
  initializeMemoryProjectionDb,
  parseCurrentRow,
  parseTimelineRows,
  readProjectedMemoryState,
  readProjectedMemoryTimeline,
  readProjectedMemoryBrowse,
  readProjectedEntityMentions,
  readProjectedNativeKnowledgeChunks,
  readProjectedLatestReviewQueue,
  readProjectedGovernanceRecord
};
//# sourceMappingURL=chunk-XJKFSSDW.js.map