import { a as getBrainDb } from './connections2-D22b0xbS.js';
import { p as parseJsonBody, i as isParseError, e as err, r as requireString, b as optionalString, a as optionalStringArray, o as ok, s as shortId } from './_lafs-C3_fBF_X.js';
import { json } from '@sveltejs/kit';
import './dual-scope-db-ATrwq0LH.js';
import './paths-2M_UxD_H.js';
import 'node:fs';
import 'node:path';
import 'node:os';
import 'node:events';
import 'node:diagnostics_channel';
import 'fs';
import 'events';
import 'util';
import 'path';
import 'assert';
import 'worker_threads';
import 'module';
import 'node:url';
import 'url';
import 'buffer';
import 'node:module';
import 'node:child_process';
import 'node:crypto';
import 'node:process';
import 'node:async_hooks';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';
import './dist4-CiQ5cizO.js';
import './adapters-D2gEs_5L.js';
import './registry2-BSyCTA3q.js';
import './data-accessor-CVbz8X_7.js';
import './tasks-CnwUAUXf.js';
import './conduit-Ca_OFWR_.js';
import './unique-constraint-BM-Apx1H.js';
import './chunk-DDP5xfzh.js';
import './sqlite-Dsbe0wec.js';
import './memory-schema-Bi7cChwo.js';
import './agent-registry-BtE5uhMO.js';
import './nexus-sqlite2-DgTuv9BQ.js';
import './nexus-schema2-BEd-ol6e.js';
import './logger-ChCwlV5k.js';
import 'node:sqlite';
import './lock-BoHF25mx.js';
import './index-IVoIz4D5.js';
import 'constants';
import 'stream';
import 'node:fs/promises';
import 'jsonc-parser';
import '@cleocode/cant';
import 'node:util';
import 'node:buffer';
import 'child_process';
import './branch-lock-qP1EkZ7p.js';
import './src2-DK8DKufK.js';
import 'llmtxt/identity';
import './sessions-j73dkbCI.js';
import './index-Ca4C2M45.js';
import './mvi-helpers-BNsJ8ZpQ.js';
import './session-store-OwQWMSf_.js';
import './session-manifest-ZHrj54LR.js';
import './storage-B9UA3BHR.js';
import './config-B0nEjgSh.js';
import './json-DXl7iDYg.js';
import './data-safety-central-vmfu_Y4J.js';
import './sqlite-data-accessor-C59wZ0zp.js';
import './cross-db-cleanup-C_FLyd-6.js';
import './query-ops-BDMaTdYw.js';
import 'node:net';
import './src3-CMSGYxDI.js';
import './local-model-fit2-J1xCIhC_.js';
import './credential-pool-B04qO8at.js';
import './catalog-model-resolver2-Cexk2TN0.js';
import './role-resolver-DF9BQ_U6.js';
import './identity2-DeAB5RXE.js';
import './role-executor-C4-3bmgC.js';
import 'node:stream';
import 'crypto';
import 'os';
import 'node:http2';
import 'fs/promises';
import './models-catalog-DG3aPok8.js';
import './catalog-resolver2-c0qfF34B.js';
import './providers-CmIcBfg-.js';
import './brain-maintenance-bSR6GwAG.js';
import './graph-auto-populate2-DYsUNGSL.js';
import './temporal-supersession-BZ46j30w.js';
import './typed-query-l1D_QElt.js';
import './llm-backend-resolver-BPbvttS4.js';
import '@ai-sdk/provider-utils';
import './observer-reflector2-D8nxuglX.js';
import './learnings2-2m2p7lzT.js';
import './memory-accessor2-BzlgmY-Z.js';
import './quality-scoring-CCPuRQmJ.js';
import './patterns2-DYKfsbwN.js';
import './graph-memory-bridge2-C7Y32Mk4.js';
import './sigil2-DftKm7Um.js';
import './services-Dlf3Gefq.js';
import './audit4-S87oN-BC.js';
import 'process';
import './cleo-home-BCqJ5rg1.js';

//#region src/routes/api/memory/pattern-store/+server.ts
/**
* Memory pattern-store write endpoint (T990 Wave 1D).
*
* @remarks T9616 follow-up: `storePattern` from
* `packages/core/src/memory/patterns.ts` is not yet promoted to the CORE
* public API (`packages/core/src/memory/public-api.ts`). Once promoted, this
* handler should be migrated to call `storePattern` rather than issuing raw
* SQL. See docs/plans/E-CORE-FIRST-ARCH.md Task 2.
*
* POST /api/memory/pattern-store
*   body: {
*     pattern: string,
*     context: string,
*     type?: 'workflow' | 'blocker' | 'success' | 'failure' | 'optimization',
*     impact?: 'low' | 'medium' | 'high',
*     antiPattern?: string,
*     mitigation?: string,
*     examples?: string[]
*   }
*   → LAFS envelope { success, data: { id, deduplicated, createdAt } }
*
* Inserts a new row into `brain_patterns` (note: table uses
* `extracted_at` rather than `created_at`). Dedup is best-effort —
* match on lowercased-pattern + type; if hit, increment frequency and
* return `deduplicated: true` without inserting.
*
* @task T990
* @wave 1D
*/
var VALID_TYPES = new Set([
	"workflow",
	"blocker",
	"success",
	"failure",
	"optimization"
]);
var VALID_IMPACTS = new Set([
	"low",
	"medium",
	"high"
]);
var POST = async ({ locals, request }) => {
	const body = await parseJsonBody(request);
	if (isParseError(body)) return json(err("E_VALIDATION", body._parseError), { status: 400 });
	const patternR = requireString(body, "pattern", 2e3);
	if (!patternR.ok) return json(err("E_VALIDATION", patternR.message), { status: 400 });
	const contextR = requireString(body, "context", 4e3);
	if (!contextR.ok) return json(err("E_VALIDATION", contextR.message), { status: 400 });
	const typeIn = optionalString(body, "type") ?? "workflow";
	const type = VALID_TYPES.has(typeIn) ? typeIn : "workflow";
	const impactIn = optionalString(body, "impact") ?? "medium";
	const impact = VALID_IMPACTS.has(impactIn) ? impactIn : "medium";
	const antiPattern = optionalString(body, "antiPattern");
	const mitigation = optionalString(body, "mitigation");
	const examples = optionalStringArray(body, "examples");
	const db = getBrainDb(locals.projectCtx);
	if (!db) return json(err("E_BRAIN_UNAVAILABLE", "brain.db is unavailable for this project"), { status: 503 });
	try {
		const dupe = db.prepare(`SELECT id, frequency FROM brain_patterns
         WHERE LOWER(pattern) = LOWER(?) AND type = ?
         LIMIT 1`).get(patternR.value, type);
		const createdAt = (/* @__PURE__ */ new Date()).toISOString();
		if (dupe) {
			db.prepare(`UPDATE brain_patterns SET frequency = frequency + 1 WHERE id = ?`).run(dupe.id);
			return json(ok({
				id: dupe.id,
				deduplicated: true,
				createdAt
			}));
		}
		const id = `P-${shortId()}`;
		db.prepare(`INSERT INTO brain_patterns
         (id, type, pattern, context, impact, anti_pattern, mitigation, examples,
          frequency, memory_tier, verified, prune_candidate, extracted_at)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?,
               1, 'short', 0, 0, ?)`).run(id, type, patternR.value, contextR.value, impact, antiPattern ?? null, mitigation ?? null, examples ? JSON.stringify(examples) : null, createdAt);
		return json(ok({
			id,
			deduplicated: false,
			createdAt
		}));
	} catch (e) {
		return json(err("E_BRAIN_WRITE", e instanceof Error ? e.message : "Insert failed"), { status: 500 });
	}
};

export { POST };
//# sourceMappingURL=_server.ts-2_cGOXa8.js.map
