import { b as getLogger } from './paths-2M_UxD_H.js';
import './sqlite-Dsbe0wec.js';
import './memory-schema-Bi7cChwo.js';
import 'node:crypto';
import './graph-auto-populate2-DYsUNGSL.js';

//#region ../core/dist/memory/brain-maintenance.js
var log = getLogger("maintenance");
/**
* Default maximum number of rows deleted per {@link runPruneSweep} invocation.
* Configurable via the `brain.sweeper.maxDeletePerRun` project config key.
*/
var DEFAULT_MAX_DELETE_PER_RUN = 500;
/**
* Hard-sweeper: DELETE brain entries that are confirmed noise.
*
* A row qualifies for deletion when ALL of:
*   - `prune_candidate = 1`  (flagged by `correlateOutcomes` Step 9a.5)
*   - `quality_score < 0.2`  (low quality)
*   - `citation_count = 0`   (never cited)
*   - age > 30 days          (`julianday('now') - julianday(created_at) > 30`)
*
* Safety mechanisms:
*   - **Dry-run mode** (`options.dryRun = true`) — counts qualifying rows and
*     returns without mutating the database.
*   - **Per-run cap** (`options.maxDeletePerRun`, default 500) — limits total
*     deletes across all tables per invocation to prevent runaway deletes.
*   - **Audit trail** — inserts a row into `brain_consolidation_events` with
*     `trigger = 'step-9f'` after each real (non-dry) delete run.
*
* This function is idempotent: rows that already do not exist or that no
* longer meet the predicate are silently skipped.
*
* @param projectRoot - Absolute path to the project root (locates brain.db)
* @param options     - Dry-run and per-run cap controls
* @returns           - Deleted/would-delete counts plus per-table breakdown
*
* @task T995
* @epic T991
*/
async function runPruneSweep(projectRoot, options) {
	const dryRun = options?.dryRun ?? false;
	const cap = options?.maxDeletePerRun ?? DEFAULT_MAX_DELETE_PER_RUN;
	const byTable = {};
	let deleted = 0;
	let wouldDelete = 0;
	const { getBrainDb, getBrainNativeDb } = await import('./memory-sqlite-Dg5uGJCo.js');
	await getBrainDb(projectRoot);
	const nativeDb = getBrainNativeDb();
	if (!nativeDb) return {
		deleted: 0,
		wouldDelete: 0,
		dryRun,
		byTable: {}
	};
	const tables = [
		{
			table: "brain_decisions",
			dateCol: "created_at"
		},
		{
			table: "brain_patterns",
			dateCol: "extracted_at"
		},
		{
			table: "brain_learnings",
			dateCol: "created_at"
		},
		{
			table: "brain_observations",
			dateCol: "created_at"
		}
	];
	for (const { table, dateCol } of tables) try {
		const count = nativeDb.prepare(`SELECT COUNT(*) AS cnt
           FROM ${table}
           WHERE prune_candidate = 1
             AND COALESCE(quality_score, 0.5) < 0.2
             AND COALESCE(citation_count, 0) = 0
             AND julianday('now') - julianday(${dateCol}) > 30`).all()[0]?.cnt ?? 0;
		wouldDelete += count;
		byTable[table] = count;
	} catch {
		byTable[table] = 0;
	}
	if (dryRun) {
		log.info(`[prune-sweep] dry-run: would delete ${wouldDelete} entries across 4 tables (cap=${cap})`);
		return {
			deleted: 0,
			wouldDelete,
			dryRun,
			byTable
		};
	}
	let remaining = cap;
	const actualByTable = {};
	for (const { table, dateCol } of tables) {
		if (remaining <= 0) {
			actualByTable[table] = 0;
			continue;
		}
		try {
			const tableLimit = Math.min(byTable[table] ?? 0, remaining);
			if (tableLimit <= 0) {
				actualByTable[table] = 0;
				continue;
			}
			const changes = nativeDb.prepare(`DELETE FROM ${table}
           WHERE id IN (
             SELECT id FROM ${table}
             WHERE prune_candidate = 1
               AND COALESCE(quality_score, 0.5) < 0.2
               AND COALESCE(citation_count, 0) = 0
               AND julianday('now') - julianday(${dateCol}) > 30
             LIMIT ?
           )`).run(tableLimit).changes ?? 0;
			actualByTable[table] = changes;
			deleted += changes;
			remaining -= changes;
		} catch {
			actualByTable[table] = 0;
		}
	}
	log.info(`[prune-sweep] step-9f: deleted ${deleted} entries (would-qualify=${wouldDelete}, cap=${cap})`);
	return {
		deleted,
		wouldDelete,
		dryRun,
		byTable: actualByTable
	};
}

export { runPruneSweep as r };
//# sourceMappingURL=brain-maintenance-bSR6GwAG.js.map
