import { B as BRAIN_OBSERVATION_SOURCE_TYPES } from './paths-2M_UxD_H.js';
import { B as BRAIN_ATTENTION_STATUSES, k as jsonb, l as BRAIN_ATTENTION_SCOPE_KINDS, n as BRAIN_BACKFILL_RUN_STATUSES, o as BRAIN_DECISION_CATEGORIES, p as BRAIN_OUTCOME_TYPES, q as BRAIN_CONFIDENCE_LEVELS, r as BRAIN_DECISION_TYPES, D as DERIVER_QUEUE_STATUSES, t as DERIVER_QUEUE_ITEM_TYPES, u as BRAIN_LINK_TYPES, v as BRAIN_MEMORY_TYPES, w as BRAIN_OBSERVATION_TYPES, x as BRAIN_EDGE_TYPES, y as BRAIN_NODE_TYPES, z as BRAIN_IMPACT_LEVELS, A as BRAIN_PATTERN_TYPES, m as makeSchemaMetaTable, C as BRAIN_STICKY_PRIORITIES, E as BRAIN_STICKY_COLORS, F as BRAIN_STICKY_STATUSES, G as BRAIN_SOURCE_CONFIDENCE, H as BRAIN_COGNITIVE_TYPES, I as BRAIN_MEMORY_TIERS } from './memory-schema-Bi7cChwo.js';
import { s as sqliteTable, t as text, r as real, i as integer, a as index } from './indexes-aYlULWG3.js';
import { p as primaryKey, u as unique } from './unique-constraint-BM-Apx1H.js';
import { s as sql } from './utils-BvHPJOVk.js';

//#region ../core/dist/store/schema/cleo-shared/brain.js
/**
* Consolidated **`brain_*` memory family** — MIRRORED across BOTH cleo.db scopes.
*
* SG-DB-SUBSTRATE-V2 · saga T11242 · epic T11245 (E2) · task T11360 (final
* project-tier increment). This is the LAST piece of the project schema.
*
* ## Why `cleo-shared/` (the mirroring contract — read this, T11361)
*
* Per owner decision D1″, `brain_*` is the ONE domain that lives in BOTH the
* PROJECT-scope `cleo.db` (`<projectRoot>/.cleo/cleo.db` — this project's local
* memory) AND the GLOBAL-scope `cleo.db` (`$XDG_DATA_HOME/cleo/cleo.db` —
* cross-project memory). Same DDL, two physical DB files, data partitioned by
* scope. To avoid duplication, the prefixed E10-typed `brain_*` target tables
* are authored ONCE here, under `cleo-shared/`, and imported by BOTH scope
* barrels:
*   - `cleo-project/index.ts` re-exports this module (wired by THIS task, T11360).
*   - `cleo-global/index.ts` (the future global barrel, T11361) MUST re-export
*     this same module — do NOT copy these definitions; import them.
*
* Target-shape authoring only — the live runtime module
* `packages/core/src/store/schema/memory-schema.ts` keeps its physical names
* (already `brain_*`-prefixed for most tables) until the exodus migration
* (T11248) swaps the substrate; the migration-baseline test asserts the live
* existence table `brain_decisions`, so the live module is NOT changed in-place.
*
* ## Idempotent prefixer (AC1)
*
* Most source tables are already `brain_*`-prefixed → the idempotent prefixer is
* a no-op (a recognized-prefix table is NOT double-prefixed). The three source
* tables WITHOUT the prefix gain it per their `targetTable`:
*   - `sticky_tags`        → `brain_sticky_tags`
*   - `session_narrative`  → `brain_session_narrative`
*   - `deriver_queue`      → `brain_deriver_queue`
*
* ## E10 typing applied
*
* - **§5b enum-like bare-TEXT → { enum } from named const arrays (§5a):**
*   - `brain_transcript_events.role` → { enum: BRAIN_TRANSCRIPT_ROLES } (the
*     source doc-comment confirms the exhaustive set user|assistant|system).
*   - `brain_backfill_runs.kind`   → { enum: BRAIN_BACKFILL_KINDS } (5 values
*     enumerated from the source doc-comment).
*   - `brain_backfill_runs.status` → { enum: BRAIN_BACKFILL_RUN_STATUSES }
*     (reused from the source module — staged|approved|rolled-back).
*   (The nexus `sigils.role` non-conformer the report also flags is GLOBAL-only
*   — it belongs to `nexus_*`, authored in the global batch T11361, not here.)
* - **§4 timestamps — brain target = LEGACY RUNTIME shape (T11647 reversal).**
*   The brain family is the ONE consolidated domain whose RUNTIME schema
*   (`../memory-schema.ts`, applied by `drizzle-brain`) remains the source of
*   truth (see {@link establishLegacyBrainSchema}). The original T11360 §4 plan
*   converted four epoch-ms columns to canonical TEXT ISO8601, but that diverged
*   the exodus TARGET shape from the runtime shape — the runtime never moved
*   these columns, so on the first brain open it treated the migrated tables as
*   "consolidated shape", DROPped them, and destroyed every migrated row (the
*   T11647 catastrophic-data-loss bug). They are therefore kept INTEGER epoch-ms
*   to MATCH the runtime, so the discriminator returns `false` and no rebuild
*   fires:
*   - `brain_decisions.validator_run_at`         (INTEGER ms epoch — runtime shape)
*   - `brain_attention.{created_at,expires_at}`  (INTEGER ms epoch — runtime shape)
*   - `brain_session_narrative.last_updated_at`  (INTEGER ms epoch — runtime shape)
*   The remaining brain timestamps were ALREADY TEXT in the runtime schema
*   (`text('created_at')` etc.), so they stay TEXT here — that matches the live
*   brain.db, and exodus copies those values verbatim. No epoch→ISO coercion is
*   applied to any brain column.
* - **§3 booleans:** every `verified` flag, `brain_learnings.actionable`, and
*   `brain_consolidation_events.succeeded` are already
*   `integer({ mode: 'boolean' })` — preserved.
* - **§6a JSON / §6b junction (AC4):** JSON-in-TEXT columns stay serialized TEXT
*   per the JSON-Column Audit; `brain_attention.tags` keeps the EXISTING E4
*   `jsonb<T>()` JSONB-BLOB pattern from `../jsonb.js` (NOT re-invented). Per
*   §6b the json-storage-jsonb-audit routes `brain_sticky_notes.tags_json` to
*   the `brain_sticky_tags` junction — authored here mirroring the live
*   `sticky_tags` E4 junction; the legacy `tags_json` column is RETAINED for
*   whole-array compatibility (the junction is the membership SSoT).
*
* Cross-DB soft FKs (brain→tasks/sessions/nexus/conduit) are carried as plain
* TEXT id columns (resolved by the brain accessor; no DB-level FK, since the
* scopes are separate files); intra-domain self-FKs (decision supersession,
* sticky→tags) are real `.references()`.
*
* - **§7 idempotency (Pattern A · T11362):** `brain_observations` — the highest-
*   leverage retried-write target (`cleo memory observe` retries + the
*   graph-memory-bridge `setImmediate` observers re-emit on race) — gains a
*   nullable `idempotency_key TEXT` + UNIQUE so a redelivered observation is a
*   no-op via `onConflictDoNothing`. Because this family is mirrored, the dedup
*   grain is each scope's own physical `cleo.db`.
*
* @task T11360 · T11362 (§7 idempotency key)
* @epic T11245
* @saga T11242
* @see docs/migration/sqlite-schema-canonical.md §1 (mirrored) · §3 · §4 · §5b · §6 · §7 · §8.1
* @see docs/migration/sqlite-schema-columns.json (per-column affinity SSoT)
*/
/**
* Transcript message roles — minted for `brain_transcript_events.role` (§5b →
* §5a). The exhaustive set is taken from the source doc-comment ("'user' |
* 'assistant' | 'system'") which mirrors the Claude message `role` field.
*/
var BRAIN_TRANSCRIPT_ROLES = [
	"user",
	"assistant",
	"system"
];
/**
* Backfill-run kinds — minted for `brain_backfill_runs.kind` (§5b → §5a).
* Enumerated from the source doc-comment.
*/
var BRAIN_BACKFILL_KINDS = [
	"observation-promotion",
	"transcript-ingest",
	"graph-backfill",
	"noise-sweep-2440",
	"custom"
];
/** Decision confirmation states — promoted from inline literal (§5a). */
var BRAIN_DECISION_CONFIRMATION_STATES = [
	"proposed",
	"accepted",
	"superseded"
];
/** Decision decided-by actors — promoted from inline literal (§5a). */
var BRAIN_DECISION_DECIDED_BY = [
	"owner",
	"council",
	"agent"
];
/**
* Shared `quality_score` column. Standalone because its physical POSITION
* varies — `brain_decisions` emits it before `created_at`/`updated_at`,
* `brain_patterns`/`brain_learnings` emit it after, and `brain_observations`
* separates it from the tier run by `discovery_tokens`.
*/
var brainQualityScoreColumn = () => ({ qualityScore: real("quality_score") });
/**
* Shared `content_hash` dedup column. Standalone because its physical POSITION
* differs — `brain_observations` places it before the quality/tier run, the
* other three place it after `tier_promotion_reason`.
*/
var brainContentHashColumn = () => ({ contentHash: text("content_hash") });
/**
* The tier/bitemporal/source run — `memory_tier` through `tier_promotion_reason`
* (9 columns), physically CONTIGUOUS and identical (modulo the two parameterized
* defaults) in ALL FOUR brain tables. Excludes `quality_score`, which is
* variably positioned (see {@link brainQualityScoreColumn}).
*/
var brainTierRunColumns = ({ memoryTier, memoryType }) => ({
	memoryTier: text("memory_tier", { enum: BRAIN_MEMORY_TIERS }).default(memoryTier),
	memoryType: text("memory_type", { enum: BRAIN_COGNITIVE_TYPES }).default(memoryType),
	verified: integer("verified", { mode: "boolean" }).notNull().default(false),
	validAt: text("valid_at").notNull().default(sql`(datetime('now'))`),
	invalidAt: text("invalid_at"),
	sourceConfidence: text("source_confidence", { enum: BRAIN_SOURCE_CONFIDENCE }).default("agent"),
	citationCount: integer("citation_count").notNull().default(0),
	tierPromotedAt: text("tier_promoted_at"),
	tierPromotionReason: text("tier_promotion_reason")
});
/**
* The provenance/peer trio — `provenance_class`, `peer_id`, `peer_scope` (the
* 3-column tail of the shared block), physically CONTIGUOUS and identical in ALL
* FOUR brain tables.
*/
var brainPeerColumns = () => ({
	provenanceClass: text("provenance_class").default("swept-clean"),
	peerId: text("peer_id").notNull().default("global"),
	peerScope: text("peer_scope").notNull().default("project")
});
/**
* `brainMemoryColumns()` — the full 14-column quality/tier/provenance/peer
* memory block as ONE spreadable Drizzle column map, in the canonical contiguous
* order used by `brain_patterns` and `brain_learnings`.
*
* Spread into a table body to apply the block in one statement:
* ```ts
* sqliteTable('brain_patterns', {
*   // …table-specific columns…
*   ...brainMemoryColumns({ memoryTier: 'medium', memoryType: 'procedural' }),
*   // …more table-specific columns…
* })
* ```
*
* `brain_decisions` and `brain_observations` INTERLEAVE table-specific columns
* (`created_at`/`updated_at`, `discovery_tokens`, `attachments_json`,
* `stability_score`) inside this block, so they compose the underlying factories
* ({@link brainTierRunColumns}, {@link brainPeerColumns}, the shared
* `quality_score`/`content_hash` columns) directly rather than spreading this
* aggregate. Every emitted column is identical; only the physical order in those
* two tables differs.
*
* @param opts per-table `memory_tier` / `memory_type` defaults (the only
*   legitimately varying columns in the block).
* @returns the 14-column map in `brain_patterns`/`brain_learnings` order:
*   `quality_score`, `memory_tier`, `memory_type`, `verified`, `valid_at`,
*   `invalid_at`, `source_confidence`, `citation_count`, `tier_promoted_at`,
*   `tier_promotion_reason`, `content_hash`, `provenance_class`, `peer_id`,
*   `peer_scope`.
* @task T11542
* @epic T11535
* @see docs/migration/sqlite-schema-canonical.md §3
*/
function brainMemoryColumns(opts) {
	return {
		...brainQualityScoreColumn(),
		...brainTierRunColumns(opts),
		...brainContentHashColumn(),
		...brainPeerColumns()
	};
}
/**
* `brain_decisions` — architectural/technical decision records.
*
* @task T11360 (target shape) · T5127 (original)
*/
var brainDecisions = sqliteTable("brain_decisions", {
	id: text("id").primaryKey(),
	type: text("type", { enum: BRAIN_DECISION_TYPES }).notNull(),
	decision: text("decision").notNull(),
	rationale: text("rationale").notNull(),
	confidence: text("confidence", { enum: BRAIN_CONFIDENCE_LEVELS }).notNull(),
	outcome: text("outcome", { enum: BRAIN_OUTCOME_TYPES }),
	alternativesJson: text("alternatives_json"),
	contextEpicId: text("context_epic_id"),
	contextTaskId: text("context_task_id"),
	contextPhase: text("context_phase"),
	...brainQualityScoreColumn(),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at"),
	...brainTierRunColumns({
		memoryTier: "medium",
		memoryType: "semantic"
	}),
	...brainContentHashColumn(),
	...brainPeerColumns(),
	adrNumber: integer("adr_number").unique(),
	adrPath: text("adr_path"),
	supersedes: text("supersedes").references(() => brainDecisions.id),
	supersededBy: text("superseded_by").references(() => brainDecisions.id),
	confirmationState: text("confirmation_state", { enum: BRAIN_DECISION_CONFIRMATION_STATES }).notNull().default("proposed"),
	decidedBy: text("decided_by", { enum: BRAIN_DECISION_DECIDED_BY }).notNull().default("agent"),
	validatorRunAt: integer("validator_run_at"),
	decisionCategory: text("decision_category", { enum: BRAIN_DECISION_CATEGORIES }).notNull().default("architectural")
}, (table) => [
	index("idx_brain_decisions_type").on(table.type),
	index("idx_brain_decisions_confidence").on(table.confidence),
	index("idx_brain_decisions_outcome").on(table.outcome),
	index("idx_brain_decisions_context_epic").on(table.contextEpicId),
	index("idx_brain_decisions_context_task").on(table.contextTaskId),
	index("idx_brain_decisions_quality").on(table.qualityScore),
	index("idx_brain_decisions_tier").on(table.memoryTier),
	index("idx_brain_decisions_mem_type").on(table.memoryType),
	index("idx_brain_decisions_verified").on(table.verified),
	index("idx_brain_decisions_valid_at").on(table.validAt),
	index("idx_brain_decisions_source_conf").on(table.sourceConfidence),
	index("idx_brain_decisions_tier_promoted_at").on(table.tierPromotedAt),
	index("idx_brain_decisions_content_hash").on(table.contentHash),
	index("idx_brain_decisions_peer_scope").on(table.peerId, table.peerScope),
	index("idx_brain_decisions_adr_number").on(table.adrNumber),
	index("idx_brain_decisions_confirmation_state").on(table.confirmationState),
	index("idx_brain_decisions_decided_by").on(table.decidedBy),
	index("idx_brain_decisions_decision_category").on(table.decisionCategory)
]);
/**
* `brain_patterns` — workflow/process patterns.
*
* @task T11360 (target shape)
*/
var brainPatterns = sqliteTable("brain_patterns", {
	id: text("id").primaryKey(),
	type: text("type", { enum: BRAIN_PATTERN_TYPES }).notNull(),
	pattern: text("pattern").notNull(),
	context: text("context").notNull(),
	frequency: integer("frequency").notNull().default(1),
	successRate: real("success_rate"),
	impact: text("impact", { enum: BRAIN_IMPACT_LEVELS }),
	antiPattern: text("anti_pattern"),
	mitigation: text("mitigation"),
	examplesJson: text("examples_json").default("[]"),
	extractedAt: text("extracted_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at"),
	...brainMemoryColumns({
		memoryTier: "medium",
		memoryType: "procedural"
	}),
	occurrenceCount: integer("occurrence_count").notNull().default(1),
	lastSeenAt: text("last_seen_at")
}, (table) => [
	index("idx_brain_patterns_type").on(table.type),
	index("idx_brain_patterns_impact").on(table.impact),
	index("idx_brain_patterns_frequency").on(table.frequency),
	index("idx_brain_patterns_quality").on(table.qualityScore),
	index("idx_brain_patterns_occurrence_count").on(table.occurrenceCount),
	index("idx_brain_patterns_last_seen_at").on(table.lastSeenAt),
	index("idx_brain_patterns_tier").on(table.memoryTier),
	index("idx_brain_patterns_mem_type").on(table.memoryType),
	index("idx_brain_patterns_verified").on(table.verified),
	index("idx_brain_patterns_valid_at").on(table.validAt),
	index("idx_brain_patterns_source_conf").on(table.sourceConfidence),
	index("idx_brain_patterns_tier_promoted_at").on(table.tierPromotedAt),
	index("idx_brain_patterns_content_hash").on(table.contentHash),
	index("idx_brain_patterns_peer_scope").on(table.peerId, table.peerScope)
]);
/**
* `brain_learnings` — extracted insights.
*
* @task T11360 (target shape)
*/
var brainLearnings = sqliteTable("brain_learnings", {
	id: text("id").primaryKey(),
	insight: text("insight").notNull(),
	source: text("source").notNull(),
	confidence: real("confidence").notNull(),
	actionable: integer("actionable", { mode: "boolean" }).notNull().default(false),
	application: text("application"),
	applicableTypesJson: text("applicable_types_json"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at"),
	...brainMemoryColumns({
		memoryTier: "short",
		memoryType: "semantic"
	})
}, (table) => [
	index("idx_brain_learnings_confidence").on(table.confidence),
	index("idx_brain_learnings_actionable").on(table.actionable),
	index("idx_brain_learnings_quality").on(table.qualityScore),
	index("idx_brain_learnings_tier").on(table.memoryTier),
	index("idx_brain_learnings_mem_type").on(table.memoryType),
	index("idx_brain_learnings_verified").on(table.verified),
	index("idx_brain_learnings_valid_at").on(table.validAt),
	index("idx_brain_learnings_invalid").on(table.invalidAt),
	index("idx_brain_learnings_source_conf").on(table.sourceConfidence),
	index("idx_brain_learnings_tier_promoted_at").on(table.tierPromotedAt),
	index("idx_brain_learnings_content_hash").on(table.contentHash),
	index("idx_brain_learnings_peer_scope").on(table.peerId, table.peerScope)
]);
/**
* `brain_observations` — episodic event records.
*
* @task T11360 (target shape)
*/
var brainObservations = sqliteTable("brain_observations", {
	id: text("id").primaryKey(),
	type: text("type", { enum: BRAIN_OBSERVATION_TYPES }).notNull(),
	title: text("title").notNull(),
	subtitle: text("subtitle"),
	narrative: text("narrative"),
	factsJson: text("facts_json"),
	conceptsJson: text("concepts_json"),
	project: text("project"),
	filesReadJson: text("files_read_json"),
	filesModifiedJson: text("files_modified_json"),
	sourceSessionId: text("source_session_id"),
	sourceType: text("source_type", { enum: BRAIN_OBSERVATION_SOURCE_TYPES }).notNull().default("agent"),
	agent: text("agent"),
	...brainContentHashColumn(),
	discoveryTokens: integer("discovery_tokens"),
	...brainQualityScoreColumn(),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at"),
	...brainTierRunColumns({
		memoryTier: "short",
		memoryType: "episodic"
	}),
	attachmentsJson: text("attachments_json"),
	stabilityScore: real("stability_score").default(.5),
	...brainPeerColumns(),
	sourceIds: text("source_ids"),
	timesDerived: integer("times_derived").default(1),
	level: text("level").default("explicit"),
	treeId: integer("tree_id"),
	origin: text("origin"),
	validatedAt: text("validated_at"),
	provenanceChain: text("provenance_chain"),
	idempotencyKey: text("idempotency_key")
}, (table) => [
	index("idx_brain_observations_type").on(table.type),
	index("idx_brain_observations_project").on(table.project),
	index("idx_brain_observations_created_at").on(table.createdAt),
	index("idx_brain_observations_source_type").on(table.sourceType),
	index("idx_brain_observations_source_session").on(table.sourceSessionId),
	index("idx_brain_observations_content_hash_created_at").on(table.contentHash, table.createdAt),
	index("idx_brain_observations_type_project").on(table.type, table.project),
	index("idx_brain_observations_agent").on(table.agent),
	index("idx_brain_observations_quality").on(table.qualityScore),
	index("idx_brain_observations_tier").on(table.memoryTier),
	index("idx_brain_observations_mem_type").on(table.memoryType),
	index("idx_brain_observations_verified").on(table.verified),
	index("idx_brain_observations_valid_at").on(table.validAt),
	index("idx_brain_observations_invalid").on(table.invalidAt),
	index("idx_brain_observations_source_conf").on(table.sourceConfidence),
	index("idx_brain_observations_tier_promoted_at").on(table.tierPromotedAt),
	index("idx_brain_observations_stability_score").on(table.stabilityScore),
	index("idx_brain_observations_peer_scope").on(table.peerId, table.peerScope),
	index("idx_brain_observations_level").on(table.level),
	index("idx_brain_observations_tree_id").on(table.treeId),
	index("idx_brain_observations_origin").on(table.origin),
	index("idx_brain_observations_validated_at").on(table.validatedAt),
	unique("uq_brain_observations_idempotency_key").on(table.idempotencyKey)
]);
/**
* `brain_sticky_notes` — ephemeral quick-capture notes.
*
* @task T11360 (target shape)
*/
var brainStickyNotes = sqliteTable("brain_sticky_notes", {
	id: text("id").primaryKey(),
	content: text("content").notNull(),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at"),
	tagsJson: text("tags_json"),
	status: text("status", { enum: BRAIN_STICKY_STATUSES }).notNull().default("active"),
	convertedToJson: text("converted_to_json"),
	color: text("color", { enum: BRAIN_STICKY_COLORS }),
	priority: text("priority", { enum: BRAIN_STICKY_PRIORITIES }),
	sourceType: text("source_type").default("sticky-note")
}, (table) => [
	index("idx_brain_sticky_status").on(table.status),
	index("idx_brain_sticky_created").on(table.createdAt),
	index("idx_brain_sticky_tags").on(table.tagsJson)
]);
/**
* `brain_sticky_tags` — sticky→tag membership junction (§6b · AC4 · E4 pattern).
*
* Domain-prefixed target of the live `sticky_tags` junction (T11355). The
* json-storage-jsonb-audit routes `brain_sticky_notes.tags_json` here; the
* legacy column is retained for whole-array compatibility while this junction
* is the membership-query SSoT. `(sticky_id, tag)` is the natural composite
* identity. No new JSON pattern invented.
*
* @task T11360 (target shape) · T11355 (original)
*/
var brainStickyTags = sqliteTable("brain_sticky_tags", {
	stickyId: text("sticky_id").notNull().references(() => brainStickyNotes.id, { onDelete: "cascade" }),
	tag: text("tag").notNull()
}, (table) => [primaryKey({ columns: [table.stickyId, table.tag] }), index("idx_brain_sticky_tags_tag").on(table.tag)]);
/**
* `brain_attention` — Tier-2 decaying, scope-keyed working-memory buffer.
*
* `tags` keeps the EXISTING E4 `jsonb<string[]>()` JSONB-BLOB pattern (read via
* `json_each(tags)` / `jsonbText`, never raw-parsed). The `created_at` /
* `expires_at` epoch-ms timestamps are converted to canonical TEXT ISO8601
* (§4 / §8.1 — ms divisor at exodus); the decay/TTL predicate operates on the
* ISO8601 text via `datetime()` post-cutover.
*
* @task T11360 (target shape) · T11371 (original)
*/
var brainAttention = sqliteTable("brain_attention", {
	id: text("id").primaryKey(),
	content: text("content").notNull(),
	sessionId: text("session_id"),
	agentId: text("agent_id"),
	scopeKind: text("scope_kind", { enum: BRAIN_ATTENTION_SCOPE_KINDS }).notNull(),
	scopeId: text("scope_id").notNull(),
	tags: jsonb("tags").default(sql`(jsonb('[]'))`),
	createdAt: integer("created_at").notNull().default(sql`(unixepoch() * 1000)`),
	expiresAt: integer("expires_at"),
	decayScore: real("decay_score"),
	status: text("status", { enum: BRAIN_ATTENTION_STATUSES }).notNull().default("open")
}, (table) => [
	index("idx_brain_attention_scope").on(table.scopeKind, table.scopeId),
	index("idx_brain_attention_session").on(table.sessionId),
	index("idx_brain_attention_status_expires").on(table.status, table.expiresAt)
]);
/**
* `brain_memory_links` — cross-references between BRAIN entries and tasks.
*
* @task T11360 (target shape)
*/
var brainMemoryLinks = sqliteTable("brain_memory_links", {
	memoryType: text("memory_type", { enum: BRAIN_MEMORY_TYPES }).notNull(),
	memoryId: text("memory_id").notNull(),
	taskId: text("task_id").notNull(),
	linkType: text("link_type", { enum: BRAIN_LINK_TYPES }).notNull(),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`)
}, (table) => [
	primaryKey({ columns: [
		table.memoryType,
		table.memoryId,
		table.taskId,
		table.linkType
	] }),
	index("idx_brain_links_task").on(table.taskId),
	index("idx_brain_links_memory").on(table.memoryType, table.memoryId)
]);
/**
* `brain_schema_meta` — key-value schema-version store.
*
* @task T11360 (target shape)
*/
var brainSchemaMeta = makeSchemaMetaTable("brain_schema_meta");
/**
* `brain_usage_log` — quality-feedback telemetry.
*
* Tracks which memory entries are retrieved and whether the outcome was
* positive. Used by `brain-lifecycle.ts` to adjust quality scores.
*
* Previously created at runtime via `CREATE TABLE IF NOT EXISTS` in
* `quality-feedback.ts`. Added to the consolidated Drizzle schema in T11546
* so exodus migration can populate the 8 471 live rows from legacy brain.db.
*
* Schema matches `quality-feedback.ts` `ensureUsageLogTable()` exactly — the
* runtime writer uses raw SQL and does not go through Drizzle ORM.
*
* @task T11546
* @epic T11248
* @saga T11242
*/
var brainUsageLog = sqliteTable("brain_usage_log", {
	id: integer("id").primaryKey({ autoIncrement: true }),
	entryId: text("entry_id").notNull(),
	taskId: text("task_id"),
	used: integer("used").notNull().default(0),
	outcome: text("outcome").notNull().default("unknown"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`)
}, (table) => [index("idx_brain_usage_log_entry_id").on(table.entryId), index("idx_brain_usage_log_task_id").on(table.taskId)]);
/**
* `brain_page_nodes` — traversable knowledge-graph node layer.
*
* @task T11360 (target shape)
*/
var brainPageNodes = sqliteTable("brain_page_nodes", {
	id: text("id").primaryKey(),
	nodeType: text("node_type", { enum: BRAIN_NODE_TYPES }).notNull(),
	label: text("label").notNull(),
	qualityScore: real("quality_score").notNull().default(.5),
	contentHash: text("content_hash"),
	lastActivityAt: text("last_activity_at").notNull().default(sql`(datetime('now'))`),
	metadataJson: text("metadata_json"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at")
}, (table) => [
	index("idx_brain_nodes_type").on(table.nodeType),
	index("idx_brain_nodes_quality").on(table.qualityScore),
	index("idx_brain_nodes_content_hash").on(table.contentHash),
	index("idx_brain_nodes_last_activity").on(table.lastActivityAt)
]);
/** Edge plasticity classes — promoted from inline literal (§5a). */
var BRAIN_EDGE_PLASTICITY_CLASSES = [
	"static",
	"hebbian",
	"stdp"
];
/**
* `brain_page_edges` — directed, typed, weighted, plasticity-aware graph edges.
*
* @task T11360 (target shape)
*/
var brainPageEdges = sqliteTable("brain_page_edges", {
	fromId: text("from_id").notNull(),
	toId: text("to_id").notNull(),
	edgeType: text("edge_type", { enum: BRAIN_EDGE_TYPES }).notNull(),
	weight: real("weight").notNull().default(1),
	provenance: text("provenance"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	lastReinforcedAt: text("last_reinforced_at"),
	reinforcementCount: integer("reinforcement_count").notNull().default(0),
	plasticityClass: text("plasticity_class", { enum: BRAIN_EDGE_PLASTICITY_CLASSES }).notNull().default("static"),
	lastDepressedAt: text("last_depressed_at"),
	depressionCount: integer("depression_count").notNull().default(0),
	stabilityScore: real("stability_score")
}, (table) => [
	primaryKey({ columns: [
		table.fromId,
		table.toId,
		table.edgeType
	] }),
	index("idx_brain_edges_from").on(table.fromId),
	index("idx_brain_edges_to").on(table.toId),
	index("idx_brain_edges_type").on(table.edgeType),
	index("idx_brain_edges_last_reinforced").on(table.lastReinforcedAt),
	index("idx_brain_edges_plasticity_class").on(table.plasticityClass),
	index("idx_brain_edges_stability").on(table.stabilityScore)
]);
/**
* `brain_retrieval_log` — co-retrieval event log.
*
* @task T11360 (target shape)
*/
var brainRetrievalLog = sqliteTable("brain_retrieval_log", {
	id: integer("id").primaryKey({ autoIncrement: true }),
	query: text("query").notNull(),
	entryIds: text("entry_ids").notNull(),
	entryCount: integer("entry_count").notNull(),
	source: text("source").notNull(),
	tokensUsed: integer("tokens_used"),
	sessionId: text("session_id"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	retrievalOrder: integer("retrieval_order"),
	deltaMs: integer("delta_ms"),
	rewardSignal: real("reward_signal")
}, (table) => [
	index("idx_retrieval_log_created").on(table.createdAt),
	index("idx_retrieval_log_source").on(table.source),
	index("idx_retrieval_log_session").on(table.sessionId),
	index("idx_retrieval_log_reward").on(table.rewardSignal)
]);
/** STDP event kinds — promoted from inline literal (§5a). */
var BRAIN_PLASTICITY_KINDS = ["ltp", "ltd"];
/**
* `brain_plasticity_events` — STDP weight-change audit log.
*
* @task T11360 (target shape)
*/
var brainPlasticityEvents = sqliteTable("brain_plasticity_events", {
	id: integer("id").primaryKey({ autoIncrement: true }),
	sourceNode: text("source_node").notNull(),
	targetNode: text("target_node").notNull(),
	deltaW: real("delta_w").notNull(),
	kind: text("kind", { enum: BRAIN_PLASTICITY_KINDS }).notNull(),
	timestamp: text("timestamp").notNull().default(sql`(datetime('now'))`),
	sessionId: text("session_id"),
	weightBefore: real("weight_before"),
	weightAfter: real("weight_after"),
	retrievalLogId: integer("retrieval_log_id"),
	rewardSignal: real("reward_signal"),
	deltaTMs: integer("delta_t_ms")
}, (table) => [
	index("idx_plasticity_source").on(table.sourceNode),
	index("idx_plasticity_target").on(table.targetNode),
	index("idx_plasticity_timestamp").on(table.timestamp),
	index("idx_plasticity_session").on(table.sessionId),
	index("idx_plasticity_kind").on(table.kind),
	index("idx_plasticity_retrieval_log").on(table.retrievalLogId),
	index("idx_plasticity_reward").on(table.rewardSignal)
]);
/**
* `brain_weight_history` — immutable per-edge Δw audit log.
*
* @task T11360 (target shape)
*/
var brainWeightHistory = sqliteTable("brain_weight_history", {
	id: integer("id").primaryKey({ autoIncrement: true }),
	edgeFromId: text("edge_from_id").notNull(),
	edgeToId: text("edge_to_id").notNull(),
	edgeType: text("edge_type").notNull(),
	weightBefore: real("weight_before"),
	weightAfter: real("weight_after").notNull(),
	deltaWeight: real("delta_weight").notNull(),
	eventKind: text("event_kind").notNull(),
	sourcePlasticityEventId: integer("source_plasticity_event_id"),
	retrievalLogId: integer("retrieval_log_id"),
	rewardSignal: real("reward_signal"),
	changedAt: text("changed_at").notNull().default(sql`(datetime('now'))`)
}, (table) => [
	index("idx_weight_history_edge").on(table.edgeFromId, table.edgeToId, table.edgeType),
	index("idx_weight_history_from").on(table.edgeFromId),
	index("idx_weight_history_to").on(table.edgeToId),
	index("idx_weight_history_changed_at").on(table.changedAt),
	index("idx_weight_history_event_kind").on(table.eventKind),
	index("idx_weight_history_plasticity_event").on(table.sourcePlasticityEventId)
]);
/**
* `brain_modulators` — R-STDP neuromodulator event log.
*
* @task T11360 (target shape)
*/
var brainModulators = sqliteTable("brain_modulators", {
	id: integer("id").primaryKey({ autoIncrement: true }),
	modulatorType: text("modulator_type").notNull(),
	valence: real("valence").notNull(),
	magnitude: real("magnitude").notNull().default(1),
	sourceEventId: text("source_event_id"),
	sessionId: text("session_id"),
	description: text("description"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`)
}, (table) => [
	index("idx_modulators_type").on(table.modulatorType),
	index("idx_modulators_session").on(table.sessionId),
	index("idx_modulators_created_at").on(table.createdAt),
	index("idx_modulators_source_event").on(table.sourceEventId),
	index("idx_modulators_valence").on(table.valence)
]);
/**
* `brain_consolidation_events` — consolidation-pipeline run audit log.
*
* @task T11360 (target shape)
*/
var brainConsolidationEvents = sqliteTable("brain_consolidation_events", {
	id: integer("id").primaryKey({ autoIncrement: true }),
	trigger: text("trigger").notNull(),
	sessionId: text("session_id"),
	stepResultsJson: text("step_results_json").notNull(),
	durationMs: integer("duration_ms"),
	succeeded: integer("succeeded", { mode: "boolean" }).notNull().default(true),
	startedAt: text("started_at").notNull().default(sql`(datetime('now'))`)
}, (table) => [
	index("idx_consolidation_events_started_at").on(table.startedAt),
	index("idx_consolidation_events_trigger").on(table.trigger),
	index("idx_consolidation_events_session").on(table.sessionId)
]);
/**
* `brain_transcript_events` — full-fidelity Claude session ingestion.
*
* @task T11360 (target shape)
*/
var brainTranscriptEvents = sqliteTable("brain_transcript_events", {
	id: text("id").primaryKey(),
	sessionId: text("session_id").notNull(),
	seq: integer("seq").notNull(),
	role: text("role", { enum: BRAIN_TRANSCRIPT_ROLES }).notNull(),
	blockType: text("block_type").notNull(),
	content: text("content").notNull(),
	tokens: integer("tokens"),
	redactedAt: text("redacted_at"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`)
}, (table) => [
	index("idx_transcript_events_session").on(table.sessionId),
	index("idx_transcript_events_role").on(table.role),
	index("idx_transcript_events_block_type").on(table.blockType),
	index("idx_transcript_events_created_at").on(table.createdAt)
]);
/**
* `brain_promotion_log` — observation→typed promotion audit log.
*
* @task T11360 (target shape)
*/
var brainPromotionLog = sqliteTable("brain_promotion_log", {
	id: text("id").primaryKey(),
	observationId: text("observation_id").notNull(),
	fromTier: text("from_tier").notNull(),
	toTier: text("to_tier").notNull(),
	score: real("score").notNull(),
	decidedAt: text("decided_at").notNull().default(sql`(datetime('now'))`),
	decidedBy: text("decided_by").notNull().default("composite-scorer"),
	rationaleJson: text("rationale_json")
}, (table) => [
	index("idx_promotion_log_observation").on(table.observationId),
	index("idx_promotion_log_decided_at").on(table.decidedAt),
	index("idx_promotion_log_to_tier").on(table.toTier),
	index("idx_promotion_log_score").on(table.score)
]);
/**
* `brain_backfill_runs` — staged-backfill run registry.
*
* @task T11360 (target shape)
*/
var brainBackfillRuns = sqliteTable("brain_backfill_runs", {
	id: text("id").primaryKey(),
	kind: text("kind", { enum: BRAIN_BACKFILL_KINDS }).notNull(),
	status: text("status", { enum: BRAIN_BACKFILL_RUN_STATUSES }).notNull().default("staged"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	approvedAt: text("approved_at"),
	rowsAffected: integer("rows_affected").notNull().default(0),
	rollbackSnapshotJson: text("rollback_snapshot_json"),
	source: text("source").notNull().default("unknown"),
	targetTable: text("target_table").notNull().default("brain_observations"),
	approvedBy: text("approved_by")
}, (table) => [
	index("idx_backfill_runs_status").on(table.status),
	index("idx_backfill_runs_kind").on(table.kind),
	index("idx_backfill_runs_created_at").on(table.createdAt)
]);
/**
* `brain_session_narrative` — rolling per-session prose summary.
*
* Domain-prefixed target of the live `session_narrative` table. `last_updated_at`
* epoch-ms → canonical TEXT ISO8601 (§4 / §8.1 — ms divisor at exodus).
*
* @task T11360 (target shape) · T1089 (original)
*/
var brainSessionNarrative = sqliteTable("brain_session_narrative", {
	sessionId: text("session_id").primaryKey(),
	narrative: text("narrative").notNull().default(""),
	turnCount: integer("turn_count").notNull().default(0),
	lastUpdatedAt: integer("last_updated_at").notNull().default(0),
	pivotCount: integer("pivot_count").notNull().default(0)
});
/**
* `brain_deriver_queue` — durable background derivation work queue.
*
* Domain-prefixed target of the live `deriver_queue` table.
*
* @task T11360 (target shape) · T1145 (original)
*/
var brainDeriverQueue = sqliteTable("brain_deriver_queue", {
	id: text("id").primaryKey(),
	itemType: text("item_type", { enum: DERIVER_QUEUE_ITEM_TYPES }).notNull(),
	itemId: text("item_id").notNull(),
	priority: integer("priority").notNull().default(0),
	status: text("status", { enum: DERIVER_QUEUE_STATUSES }).notNull().default("pending"),
	claimedAt: text("claimed_at"),
	claimedBy: text("claimed_by"),
	errorMsg: text("error_msg"),
	retryCount: integer("retry_count").notNull().default(0),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	completedAt: text("completed_at")
}, (table) => [
	index("idx_brain_deriver_queue_status_priority").on(table.status, table.priority, table.createdAt),
	index("idx_brain_deriver_queue_item").on(table.itemType, table.itemId),
	index("idx_brain_deriver_queue_claimed_at").on(table.claimedAt)
]);
/**
* `brain_memory_trees` — hierarchical RPTree clustering nodes.
*
* @task T11360 (target shape)
*/
var brainMemoryTrees = sqliteTable("brain_memory_trees", {
	id: integer("id").primaryKey({ autoIncrement: true }),
	depth: integer("depth").notNull().default(0),
	leafIds: text("leaf_ids").notNull().default("[]"),
	centroid: text("centroid"),
	parentId: integer("parent_id"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at")
}, (table) => [index("idx_brain_trees_parent").on(table.parentId), index("idx_brain_trees_depth").on(table.depth)]);
/** Staging candidate actions — promoted from inline literal (§5a). */
var BRAIN_STAGING_ACTIONS = [
	"purge",
	"keep",
	"reclassify",
	"promote"
];
/** Staging candidate validation statuses — promoted from inline literal (§5a). */
var BRAIN_STAGING_VALIDATION_STATUSES = [
	"pending",
	"applied",
	"skipped"
];
/**
* `brain_observations_staging` — shadow-write candidate staging for noise sweeps.
*
* @task T11360 (target shape)
*/
var brainObservationsStaging = sqliteTable("brain_observations_staging", {
	id: text("id").primaryKey(),
	sourceTable: text("source_table").notNull(),
	sourceId: text("source_id").notNull(),
	sweepRunId: text("sweep_run_id").notNull(),
	action: text("action", { enum: BRAIN_STAGING_ACTIONS }).notNull(),
	newQualityScore: real("new_quality_score"),
	newInvalidAt: text("new_invalid_at"),
	newProvenanceClass: text("new_provenance_class"),
	validationStatus: text("validation_status", { enum: BRAIN_STAGING_VALIDATION_STATUSES }).notNull().default("pending"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`)
}, (table) => [
	index("idx_bos_sweep_run").on(table.sweepRunId),
	index("idx_bos_source").on(table.sourceTable, table.sourceId),
	index("idx_bos_status").on(table.validationStatus)
]);

export { brainSessionNarrative as A, BRAIN_BACKFILL_KINDS as B, brainStickyNotes as C, brainStickyTags as D, brainTranscriptEvents as E, brainUsageLog as F, brainWeightHistory as G, BRAIN_DECISION_CONFIRMATION_STATES as a, BRAIN_DECISION_DECIDED_BY as b, BRAIN_EDGE_PLASTICITY_CLASSES as c, BRAIN_PLASTICITY_KINDS as d, BRAIN_STAGING_ACTIONS as e, BRAIN_STAGING_VALIDATION_STATUSES as f, BRAIN_TRANSCRIPT_ROLES as g, brainAttention as h, brainBackfillRuns as i, brainConsolidationEvents as j, brainDecisions as k, brainDeriverQueue as l, brainLearnings as m, brainMemoryColumns as n, brainMemoryLinks as o, brainMemoryTrees as p, brainModulators as q, brainObservations as r, brainObservationsStaging as s, brainPageEdges as t, brainPageNodes as u, brainPatterns as v, brainPlasticityEvents as w, brainPromotionLog as x, brainRetrievalLog as y, brainSchemaMeta as z };
//# sourceMappingURL=cleo-shared-CG3TSIBu.js.map
