import { i as __exportAll } from "./tool-display-DMBmPBI-.js";
import { t as applySqlitePragmas } from "./sqlite-pragmas-DDlIB_V6.js";
import { t as requireNodeSqlite } from "./sqlite-CVrhPija.js";
import { n as buildFtsQuery } from "./hybrid-DSp5ZIQe.js";

//#region src/memory/typed-schema.ts
/**
* Typed memory object schema — 8 object types + 5 relationship types.
*
* Extends (does not replace) the existing message ledger. Uses the same
* node:sqlite pattern (DatabaseSync singleton, WAL pragmas).
*
* Object types:  entity | fact | event | preference | task | belief | interaction | skill
* Relationship types: related_to | caused_by | part_of | precedes | contradicts
*
* @module
*/
var typed_schema_exports = /* @__PURE__ */ __exportAll({
	createObject: () => createObject,
	createObjectInDb: () => createObjectInDb,
	createRelationship: () => createRelationship,
	createRelationshipInDb: () => createRelationshipInDb,
	deleteObject: () => deleteObject,
	deleteObjectInDb: () => deleteObjectInDb,
	getObject: () => getObject,
	getObjectInDb: () => getObjectInDb,
	getOrOpenDb: () => getOrOpenDb,
	getRelated: () => getRelated,
	getRelatedInDb: () => getRelatedInDb,
	getTypedMemoryDb: () => getTypedMemoryDb,
	listAllObjectsInDb: () => listAllObjectsInDb,
	listAllRelationshipsInDb: () => listAllRelationshipsInDb,
	listObjectsByType: () => listObjectsByType,
	listObjectsByTypeInDb: () => listObjectsByTypeInDb,
	openTypedMemoryDb: () => openTypedMemoryDb,
	searchObjects: () => searchObjects,
	searchObjectsInDb: () => searchObjectsInDb,
	updateObject: () => updateObject,
	updateObjectInDb: () => updateObjectInDb
});
const INIT_SQL = `
CREATE TABLE IF NOT EXISTS memory_objects (
  id         TEXT    PRIMARY KEY,
  type       TEXT    NOT NULL CHECK(type IN ('entity','fact','event','preference','task','belief','interaction','skill')),
  label      TEXT    NOT NULL,
  data       TEXT    NOT NULL DEFAULT '{}',
  created_at INTEGER NOT NULL,
  updated_at INTEGER NOT NULL,
  ttl        INTEGER
);

CREATE INDEX IF NOT EXISTS idx_memory_objects_type      ON memory_objects(type);
CREATE INDEX IF NOT EXISTS idx_memory_objects_label     ON memory_objects(label);
CREATE INDEX IF NOT EXISTS idx_memory_objects_ttl       ON memory_objects(ttl) WHERE ttl IS NOT NULL;

CREATE TABLE IF NOT EXISTS memory_relationships (
  from_id    TEXT    NOT NULL REFERENCES memory_objects(id) ON DELETE CASCADE,
  to_id      TEXT    NOT NULL REFERENCES memory_objects(id) ON DELETE CASCADE,
  rel_type   TEXT    NOT NULL CHECK(rel_type IN ('related_to','caused_by','part_of','precedes','contradicts')),
  weight     REAL    NOT NULL DEFAULT 1.0,
  created_at INTEGER NOT NULL,
  PRIMARY KEY (from_id, to_id, rel_type)
);

CREATE INDEX IF NOT EXISTS idx_memory_rels_from ON memory_relationships(from_id);
CREATE INDEX IF NOT EXISTS idx_memory_rels_to   ON memory_relationships(to_id);

CREATE VIRTUAL TABLE IF NOT EXISTS memory_objects_fts USING fts5(
  id UNINDEXED,
  label,
  content='memory_objects',
  content_rowid='rowid'
);
`;
let db = null;
function openTypedMemoryDb(dbPath) {
	const { DatabaseSync } = requireNodeSqlite();
	db = new DatabaseSync(dbPath);
	applySqlitePragmas(db);
	db.exec("PRAGMA foreign_keys = ON");
	db.exec(INIT_SQL);
}
function getTypedMemoryDb() {
	return db;
}
function requireDb() {
	if (!db) throw new Error("Typed memory DB not initialised — call openTypedMemoryDb() first");
	return db;
}
function nowMs() {
	return Date.now();
}
function encodeData(data) {
	try {
		return JSON.stringify(data);
	} catch {
		return "{}";
	}
}
function decodeData(raw) {
	if (typeof raw !== "string") return {};
	try {
		const parsed = JSON.parse(raw);
		return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
	} catch {
		return {};
	}
}
function rowToMemoryObject(row) {
	return {
		id: String(row["id"]),
		type: row["type"],
		label: String(row["label"]),
		data: decodeData(row["data"]),
		createdAt: Number(row["created_at"]),
		updatedAt: Number(row["updated_at"]),
		ttl: row["ttl"] == null ? null : Number(row["ttl"])
	};
}
function rowToRelationship(row) {
	return {
		fromId: String(row["from_id"]),
		toId: String(row["to_id"]),
		relType: row["rel_type"],
		weight: Number(row["weight"]),
		createdAt: Number(row["created_at"])
	};
}
/** Create a new memory object. Returns the id. */
function createObject(params) {
	const now = nowMs();
	requireDb().prepare(`INSERT INTO memory_objects (id, type, label, data, created_at, updated_at, ttl)
     VALUES (?, ?, ?, ?, ?, ?, ?)`).run(params.id, params.type, params.label, encodeData(params.data ?? {}), now, now, params.ttl ?? null);
	return params.id;
}
/** Get a memory object by id. Returns null if not found. */
function getObject(id) {
	const row = requireDb().prepare("SELECT * FROM memory_objects WHERE id = ?").get(id);
	return row ? rowToMemoryObject(row) : null;
}
/** Update label and/or data for an existing object. */
function updateObject(id, updates) {
	const obj = getObject(id);
	if (!obj) return;
	const newLabel = updates.label ?? obj.label;
	const newData = updates.data !== void 0 ? updates.data : obj.data;
	const newTtl = "ttl" in updates ? updates.ttl ?? null : obj.ttl;
	requireDb().prepare(`UPDATE memory_objects SET label = ?, data = ?, ttl = ?, updated_at = ? WHERE id = ?`).run(newLabel, encodeData(newData), newTtl, nowMs(), id);
}
/** Delete a memory object (and cascade-delete its relationships). */
function deleteObject(id) {
	requireDb().prepare("DELETE FROM memory_objects WHERE id = ?").run(id);
}
/** List all objects of a given type. */
function listObjectsByType(type) {
	return requireDb().prepare("SELECT * FROM memory_objects WHERE type = ? ORDER BY updated_at DESC").all(type).map(rowToMemoryObject);
}
/** Create or replace a relationship between two objects. */
function createRelationship(params) {
	const now = nowMs();
	requireDb().prepare(`INSERT OR REPLACE INTO memory_relationships (from_id, to_id, rel_type, weight, created_at)
     VALUES (?, ?, ?, ?, ?)`).run(params.fromId, params.toId, params.relType, params.weight ?? 1, now);
}
/** Get all objects related to the given id, optionally filtered by relationship type. */
function getRelated(id, relType) {
	const db = requireDb();
	return (relType ? db.prepare(`SELECT o.* FROM memory_objects o
           JOIN memory_relationships r ON o.id = r.to_id
           WHERE r.from_id = ? AND r.rel_type = ?
           ORDER BY r.weight DESC`).all(id, relType) : db.prepare(`SELECT o.* FROM memory_objects o
           JOIN memory_relationships r ON o.id = r.to_id
           WHERE r.from_id = ?
           ORDER BY r.weight DESC`).all(id)).map(rowToMemoryObject);
}
/**
* Full-text search over memory object labels.
* Searches across all types unless a type filter is provided.
*/
function searchObjects(query, type) {
	const db = requireDb();
	db.exec("INSERT INTO memory_objects_fts(memory_objects_fts) VALUES('rebuild')");
	const ftsQuery = buildFtsQuery(query);
	if (!ftsQuery) return [];
	return (type ? db.prepare(`SELECT * FROM memory_objects
           WHERE rowid IN (
             SELECT rowid FROM memory_objects_fts WHERE memory_objects_fts MATCH ?
           ) AND type = ?`).all(ftsQuery, type) : db.prepare(`SELECT * FROM memory_objects
           WHERE rowid IN (
             SELECT rowid FROM memory_objects_fts WHERE memory_objects_fts MATCH ?
           )`).all(ftsQuery)).map(rowToMemoryObject);
}
const _registry = /* @__PURE__ */ new Map();
/**
* Open (or return from cache) a DatabaseSync instance for the given path.
* The instance is initialised with WAL pragmas and the typed memory schema.
*/
function getOrOpenDb(dbPath) {
	let registeredDb = _registry.get(dbPath);
	if (!registeredDb) {
		const { DatabaseSync } = requireNodeSqlite();
		registeredDb = new DatabaseSync(dbPath);
		applySqlitePragmas(registeredDb);
		registeredDb.exec("PRAGMA foreign_keys = ON");
		registeredDb.exec(INIT_SQL);
		_registry.set(dbPath, registeredDb);
	}
	return registeredDb;
}
function createObjectInDb(db, params) {
	const now = nowMs();
	db.prepare(`INSERT INTO memory_objects (id, type, label, data, created_at, updated_at, ttl)
     VALUES (?, ?, ?, ?, ?, ?, ?)`).run(params.id, params.type, params.label, encodeData(params.data ?? {}), now, now, params.ttl ?? null);
	return params.id;
}
function getObjectInDb(db, id) {
	const row = db.prepare("SELECT * FROM memory_objects WHERE id = ?").get(id);
	return row ? rowToMemoryObject(row) : null;
}
function updateObjectInDb(db, id, updates) {
	const obj = getObjectInDb(db, id);
	if (!obj) return;
	const newLabel = updates.label ?? obj.label;
	const newData = updates.data !== void 0 ? updates.data : obj.data;
	const newTtl = "ttl" in updates ? updates.ttl ?? null : obj.ttl;
	db.prepare(`UPDATE memory_objects SET label = ?, data = ?, ttl = ?, updated_at = ? WHERE id = ?`).run(newLabel, encodeData(newData), newTtl, nowMs(), id);
}
function deleteObjectInDb(db, id) {
	db.prepare("DELETE FROM memory_objects WHERE id = ?").run(id);
}
function listObjectsByTypeInDb(db, type) {
	return db.prepare("SELECT * FROM memory_objects WHERE type = ? ORDER BY updated_at DESC").all(type).map(rowToMemoryObject);
}
/** List all memory objects, newest first. */
function listAllObjectsInDb(db) {
	return db.prepare("SELECT * FROM memory_objects ORDER BY updated_at DESC").all().map(rowToMemoryObject);
}
/** List all relationships. */
function listAllRelationshipsInDb(db) {
	return db.prepare("SELECT * FROM memory_relationships").all().map(rowToRelationship);
}
function getRelatedInDb(db, id, relType) {
	return (relType ? db.prepare(`SELECT o.* FROM memory_objects o
           JOIN memory_relationships r ON o.id = r.to_id
           WHERE r.from_id = ? AND r.rel_type = ?
           ORDER BY r.weight DESC`).all(id, relType) : db.prepare(`SELECT o.* FROM memory_objects o
           JOIN memory_relationships r ON o.id = r.to_id
           WHERE r.from_id = ?
           ORDER BY r.weight DESC`).all(id)).map(rowToMemoryObject);
}
function createRelationshipInDb(db, params) {
	const now = nowMs();
	db.prepare(`INSERT OR REPLACE INTO memory_relationships (from_id, to_id, rel_type, weight, created_at)
     VALUES (?, ?, ?, ?, ?)`).run(params.fromId, params.toId, params.relType, params.weight ?? 1, now);
}
function searchObjectsInDb(db, query, type) {
	db.exec("INSERT INTO memory_objects_fts(memory_objects_fts) VALUES('rebuild')");
	const ftsQuery = buildFtsQuery(query);
	if (!ftsQuery) return [];
	return (type ? db.prepare(`SELECT * FROM memory_objects
           WHERE rowid IN (
             SELECT rowid FROM memory_objects_fts WHERE memory_objects_fts MATCH ?
           ) AND type = ?`).all(ftsQuery, type) : db.prepare(`SELECT * FROM memory_objects
           WHERE rowid IN (
             SELECT rowid FROM memory_objects_fts WHERE memory_objects_fts MATCH ?
           )`).all(ftsQuery)).map(rowToMemoryObject);
}

//#endregion
export { searchObjects as _, deleteObject as a, updateObject as b, getObjectInDb as c, getRelatedInDb as d, getTypedMemoryDb as f, listObjectsByTypeInDb as g, listObjectsByType as h, createRelationshipInDb as i, getOrOpenDb as l, listAllRelationshipsInDb as m, createObjectInDb as n, deleteObjectInDb as o, listAllObjectsInDb as p, createRelationship as r, getObject as s, createObject as t, getRelated as u, searchObjectsInDb as v, updateObjectInDb as x, typed_schema_exports as y };