import { c as customType, s as sqliteTable, t as text, r as real, a as index, i as integer } from './indexes-aYlULWG3.js';
import { _ as __exportAll } from './chunk-DDP5xfzh.js';
import { B as BRAIN_OBSERVATION_SOURCE_TYPES } from './paths-2M_UxD_H.js';
import { s as sql } from './utils-BvHPJOVk.js';
import { p as primaryKey } from './unique-constraint-BM-Apx1H.js';

//#region ../core/dist/store/schema/jsonb.js
/**
* Reusable Drizzle `jsonb<T>()` custom column type for SQLite JSONB storage.
*
* ## Why this exists
*
* SQLite 3.45.0+ (bundled in node:sqlite 3.53.0, the runtime CLEO targets)
* fully supports the JSONB binary encoding plus the `jsonb_*()` SQL function
* family. Storing a JSON document as a JSONB BLOB rather than as serialized
* TEXT avoids re-parsing the text on every `json_extract` / `json_each` call —
* the parse happens once, at write time. For columns that are queried or
* mutated *inside SQL* (membership tests, append-heavy id-lists, scalar
* extraction in a WHERE clause), JSONB is the correct storage class.
*
* Drizzle's beta/rc line ships **no native `jsonb()` builder**, so we express
* the storage class through {@link customType}: a `blob` column whose
* `toDriver` wraps the serialized value in the SQL `jsonb()` constructor.
*
* ## The load-bearing read rule
*
* The on-disk JSONB encoding is an **opaque, version-unstable** binary format.
* Application code MUST NEVER `JSON.parse` the raw BLOB bytes returned by a
* plain `SELECT col`. Whole-value reads MUST round-trip the value back through
* the SQL `json(col)` function, which emits canonical, parseable TEXT
* regardless of the writer's SQLite version. Two safe read paths exist:
*
*   1. **Whole-value reads** — project the column with `SELECT json(col)` (or
*      use {@link jsonbText} as a select helper) and `JSON.parse` the TEXT.
*   2. **In-SQL reads** — `jsonb_extract(col, '$.path')`, `json_each(col)`,
*      etc., operate on the BLOB directly with no application-side parsing.
*
* {@link jsonb} guards the unsafe path: its `fromDriver` rejects a raw BLOB and
* directs callers to `json(col)`, so a `SELECT *` that forgets the rule fails
* loudly instead of silently parsing version-unstable bytes. When a JSONB
* column is genuinely read whole, project it with {@link jsonbText} so Drizzle
* receives TEXT (`json(col)`) and `fromDriver` parses it normally.
*
* ## Backup / export discipline (version-instability constraint)
*
* Because the binary format is not cross-version-portable, **every backup or
* export of a JSONB column MUST emit `json(col)`**, never the raw BLOB. A
* `VACUUM INTO` snapshot preserves the bytes verbatim (same SQLite engine, so
* safe), but any logical dump / cross-machine export / JSON serialization path
* MUST project through `json(col)` first.
*
* @see {@link https://sqlite.org/json1.html#jsonb} SQLite JSONB documentation
* @see `.cleo/rcasd/json-storage-jsonb-audit.md` per-field decision matrix
* @task T11354
* @epic T11286
* @saga T11283
*/
/**
* Drizzle custom column type for a SQLite JSONB BLOB holding a value of type `T`.
*
* Storage class is `blob`. Writes wrap the JSON-serialized value in the SQL
* `jsonb()` constructor so SQLite stores the parsed binary form. Reads of the
* raw BLOB are intentionally rejected by `fromDriver`: callers MUST project the
* column with `json(col)` (use {@link jsonbText}) for whole-value reads, or use
* `jsonb_extract` / `json_each` for in-SQL access.
*
* @typeParam T - The TypeScript shape of the stored JSON document.
* @param name - The physical column name.
* @returns A Drizzle column builder for the JSONB column.
*
* @example
* ```ts
* const myTable = sqliteTable('my_table', {
*   id: text('id').primaryKey(),
*   payload: jsonb<{ tags: string[] }>('payload').default(sql`jsonb('{}')`),
* });
*
* // Write — toDriver wraps in jsonb():
* await db.insert(myTable).values({ id: 'x', payload: { tags: ['a'] } });
*
* // Whole-value read — project json(col):
* const rows = await db
*   .select({ id: myTable.id, payload: jsonbText(myTable.payload) })
*   .from(myTable);
* ```
*/
var jsonb = (name) => customType({
	dataType: () => "blob",
	toDriver: (value) => sql`jsonb(${JSON.stringify(value)})`,
	fromDriver: (_value) => {
		throw new Error("jsonb column read as raw BLOB — project it with json(col) (see jsonbText) for whole-value reads, or use jsonb_extract / json_each for in-SQL access. The on-disk JSONB format is version-unstable and MUST NOT be JSON.parse-d directly.");
	}
})(name);
/**
* Build a `json(col)` projection for a JSONB column and decode the resulting
* TEXT back into the parsed document `T`.
*
* SQLite's `json(col)` emits canonical, version-stable TEXT for a JSONB BLOB;
* the `.mapWith(JSON.parse)` decoder then yields the live object so callers
* never see (or have to parse) the raw bytes. Use this in the `.select({ ... })`
* map for any whole-value read of a column declared with {@link jsonb}. It
* satisfies both the read rule and the backup/export rule by routing through
* SQLite's `json()` function.
*
* @typeParam T - The stored JSON document shape.
* @param column - A column reference (or SQL expression) for the JSONB column.
* @returns A typed SQL expression yielding the parsed JSON document of type `T`.
*
* @example
* ```ts
* const rows = await db
*   .select({ tags: jsonbText<string[]>(myTable.tags) })
*   .from(myTable);
* // rows[0].tags is string[] — already parsed
* ```
*/
function jsonbText(column) {
	return sql`json(${column})`.mapWith((text) => JSON.parse(text));
}

//#region ../core/dist/store/schema/schema-utils.js
/**
* Shared Drizzle schema-construction helpers (SOLID/DRY groundwork).
*
* This module hosts column-group and table factories that eliminate verbatim
* duplication across the consolidated residency-split schema modules
* (`cleo-project/`, `cleo-global/`, `cleo-shared/`). Factories here are
* **physical-schema-preserving**: they emit exactly the same DDL the inline
* definitions did, so applying them produces zero migration drift.
*
* @see .cleo/rcasd/adr-090-nexus-graph-residency-split.md §5 (SOLID/DRY groundwork)
* @task T11543
* @epic T11535
* @saga T11242
*/
/**
* The canonical two-column shape of a `*_schema_meta` key-value table:
* `key` (`TEXT PRIMARY KEY`) + `value` (`TEXT NOT NULL`), in that order.
*
* Factored into a single builder so every domain's `*_schema_meta` table is
* constructed from the identical column map — the source of the zero-drift
* guarantee. Spread into {@link makeSchemaMetaTable}'s `sqliteTable` call.
*/
var schemaMetaColumns = {
	key: text("key").primaryKey(),
	value: text("value").notNull()
};
/**
* Factory for the canonical schema-version key-value table.
*
* Every CLEO domain DB carries a `*_schema_meta` table with the byte-identical
* `{ key TEXT PRIMARY KEY, value TEXT NOT NULL }` shape. This factory is the
* single source of truth for that shape so the columns never drift apart across
* domains. The emitted DDL is identical to the prior inline definitions.
*
* @param tableName Fully-qualified physical table name, e.g. `'nexus_schema_meta'`.
* @returns A Drizzle SQLite table with `key` (PK) and `value` (NOT NULL) text columns.
*
* @example
* ```ts
* export const nexusSchemaMeta = makeSchemaMetaTable('nexus_schema_meta');
* ```
*/
function makeSchemaMetaTable(tableName) {
	return sqliteTable(tableName, schemaMetaColumns);
}

//#region ../core/dist/store/schema/memory-schema.js
/**
* Drizzle ORM schema for CLEO brain.db (SQLite via node:sqlite + sqlite-proxy).
*
* Tables: brain_decisions, brain_patterns, brain_learnings, brain_memory_links, brain_schema_meta
* Stores cognitive infrastructure: decisions, patterns, and learnings extracted
* from CLEO task execution. Cross-references tasks in tasks.db via soft FKs.
*
* @epic T5149
* @task T5127
*/
var memory_schema_exports = /* @__PURE__ */ __exportAll({
	BRAIN_ATTENTION_SCOPE_KINDS: () => BRAIN_ATTENTION_SCOPE_KINDS,
	BRAIN_ATTENTION_STATUSES: () => BRAIN_ATTENTION_STATUSES,
	BRAIN_BACKFILL_RUN_STATUSES: () => BRAIN_BACKFILL_RUN_STATUSES,
	BRAIN_COGNITIVE_TYPES: () => BRAIN_COGNITIVE_TYPES,
	BRAIN_CONFIDENCE_LEVELS: () => BRAIN_CONFIDENCE_LEVELS,
	BRAIN_DECISION_CATEGORIES: () => BRAIN_DECISION_CATEGORIES,
	BRAIN_DECISION_TYPES: () => BRAIN_DECISION_TYPES,
	BRAIN_EDGE_TYPES: () => BRAIN_EDGE_TYPES,
	BRAIN_IMPACT_LEVELS: () => BRAIN_IMPACT_LEVELS,
	BRAIN_LINK_TYPES: () => BRAIN_LINK_TYPES,
	BRAIN_MEMORY_TIERS: () => BRAIN_MEMORY_TIERS,
	BRAIN_MEMORY_TYPES: () => BRAIN_MEMORY_TYPES,
	BRAIN_NETWORK_TYPES: () => BRAIN_NETWORK_TYPES,
	BRAIN_NODE_TYPES: () => BRAIN_NODE_TYPES,
	BRAIN_OBSERVATIONS_STAGING_ACTIONS: () => BRAIN_OBSERVATIONS_STAGING_ACTIONS,
	BRAIN_OBSERVATIONS_STAGING_STATUSES: () => BRAIN_OBSERVATIONS_STAGING_STATUSES,
	BRAIN_OBSERVATION_SOURCE_TYPES: () => BRAIN_OBSERVATION_SOURCE_TYPES,
	BRAIN_OBSERVATION_TYPES: () => BRAIN_OBSERVATION_TYPES,
	BRAIN_OUTCOME_TYPES: () => BRAIN_OUTCOME_TYPES,
	BRAIN_PATTERN_TYPES: () => BRAIN_PATTERN_TYPES,
	BRAIN_SOURCE_CONFIDENCE: () => BRAIN_SOURCE_CONFIDENCE,
	BRAIN_STICKY_COLORS: () => BRAIN_STICKY_COLORS,
	BRAIN_STICKY_PRIORITIES: () => BRAIN_STICKY_PRIORITIES,
	BRAIN_STICKY_STATUSES: () => BRAIN_STICKY_STATUSES,
	DERIVER_QUEUE_ITEM_TYPES: () => DERIVER_QUEUE_ITEM_TYPES,
	DERIVER_QUEUE_STATUSES: () => DERIVER_QUEUE_STATUSES,
	brainAttention: () => brainAttention,
	brainBackfillRuns: () => brainBackfillRuns,
	brainConsolidationEvents: () => brainConsolidationEvents,
	brainDecisions: () => brainDecisions,
	brainLearnings: () => brainLearnings,
	brainMemoryLinks: () => brainMemoryLinks,
	brainMemoryTrees: () => brainMemoryTrees,
	brainModulators: () => brainModulators,
	brainObservations: () => brainObservations,
	brainObservationsStaging: () => brainObservationsStaging,
	brainPageEdges: () => brainPageEdges,
	brainPageNodes: () => brainPageNodes,
	brainPatterns: () => brainPatterns,
	brainPlasticityEvents: () => brainPlasticityEvents,
	brainPromotionLog: () => brainPromotionLog,
	brainRetrievalLog: () => brainRetrievalLog,
	brainSchemaMeta: () => brainSchemaMeta,
	brainStickyNotes: () => brainStickyNotes,
	brainTranscriptEvents: () => brainTranscriptEvents,
	brainWeightHistory: () => brainWeightHistory,
	deriverQueue: () => deriverQueue,
	sessionNarrative: () => sessionNarrative,
	stickyTags: () => stickyTags
});
/**
* Memory retention tiers for the tiered cognitive memory model (T549).
*
* - `short`  — Session-scoped working context. Volatile; auto-evicted after 48h if not promoted.
* - `medium` — Project-scoped verified facts. Retained for weeks; decays if unverified.
* - `long`   — Architectural bedrock. Permanent; supersession-only eviction.
*
* NULL semantics for legacy rows: treat NULL as 'medium' at query time.
* (Legacy rows survived the T523 purge, so medium is a safe tier assumption.)
*/
var BRAIN_MEMORY_TIERS = [
	"short",
	"medium",
	"long"
];
/**
* Cognitive type taxonomy for the tiered memory model (T549).
*
* Uses `BRAIN_COGNITIVE_TYPES` (not `BRAIN_MEMORY_TYPES`) to avoid collision
* with the link table enum `BRAIN_MEMORY_TYPES` (which stores entity type names).
*
* - `semantic`   — Declarative facts: "what is true about this project"
*                  → brain_decisions (always), brain_learnings (default)
* - `episodic`   — Event records: "what happened and when"
*                  → brain_observations (always), brain_learnings (transcript-derived)
* - `procedural` — Process knowledge: "how to do things"
*                  → brain_patterns (always)
*/
var BRAIN_COGNITIVE_TYPES = [
	"semantic",
	"episodic",
	"procedural"
];
/**
* Source reliability levels for the tiered memory model (T549).
*
* Separate dimension from content `quality_score` — captures source trustworthiness.
* Each level drives a quality multiplier applied at scoring time.
*
* | Level         | Meaning                                 | Quality multiplier |
* |---------------|-----------------------------------------|--------------------|
* | `owner`       | Owner explicitly stated this fact       | 1.0                |
* | `task-outcome`| Verified by completed task with result  | 0.90               |
* | `agent`       | Agent-inferred during work (default)    | 0.70               |
* | `speculative` | Agent hypothesis, not yet corroborated  | 0.40               |
*/
var BRAIN_SOURCE_CONFIDENCE = [
	"owner",
	"task-outcome",
	"agent",
	"speculative"
];
/** Decision types from ADR-009. */
var BRAIN_DECISION_TYPES = [
	"architecture",
	"technical",
	"process",
	"strategic",
	"tactical"
];
/**
* Decision category values for T1830 AGT-* dispatch / architectural separation.
*
* - `'architectural'`  — Architectural or technical decisions (default; excludes AGT-* rows).
* - `'agent_dispatch'` — Agent execution dispatch outcomes (AGT-prefixed rows).
* - `'other'`          — Miscellaneous decisions not fitting the above categories.
*/
var BRAIN_DECISION_CATEGORIES = [
	"architectural",
	"agent_dispatch",
	"other"
];
/**
* Four-network memory classification (T10405 · SG-PSYCHE-FOUNDATION Tier 5).
*
* Every BRAIN row is tagged with one of four cognitive networks. The taxonomy
* mirrors the masterplan §16.D Mem0-V3 envelope classification and lets the
* retrieval layer reason about *what kind* of fact a row holds — not just its
* cognitive type (semantic/episodic/procedural) or memory tier.
*
* - `world`       — Objective, externally-verifiable facts about the project /
*                   environment ("the release pipeline is PR-gated", "Node 24
*                   ships node:sqlite"). Highest trust; rarely contradicted.
* - `bank`        — Durable account-of-record entries: decisions, commitments,
*                   ledgered outcomes ("we adopted ADR-065", "release v2026.6.12
*                   shipped"). Append-mostly; superseded via links, not deletes.
* - `opinion`     — Subjective / evaluative beliefs that carry `confidence` and
*                   update on new evidence ("agent X is unreliable on task Y").
*                   The mutable network — opinion rows are expected to flip.
* - `observation` — Raw episodic event records ("ran the build", "saw 12 test
*                   failures"). The default network; the substrate the other
*                   three are distilled from.
*
* NULL semantics: legacy rows carry no network. Writers default new rows to
* `'observation'`; the consolidator/deriver re-classifies into world/bank/opinion
* as facts are distilled. Stored as a plain TEXT column (no SQLite CHECK — the
* enum is enforced in-app per the project's Lesson-3 convention).
*
* @task T10405
* @epic T10405
* @saga T10405
*/
var BRAIN_NETWORK_TYPES = [
	"world",
	"bank",
	"opinion",
	"observation"
];
/** Confidence levels for decisions. */
var BRAIN_CONFIDENCE_LEVELS = [
	"low",
	"medium",
	"high"
];
/** Outcome types for decision tracking. */
var BRAIN_OUTCOME_TYPES = [
	"success",
	"failure",
	"mixed",
	"pending"
];
/** Pattern types for workflow analysis. */
var BRAIN_PATTERN_TYPES = [
	"workflow",
	"blocker",
	"success",
	"failure",
	"optimization"
];
/** Impact levels for patterns. */
var BRAIN_IMPACT_LEVELS = [
	"low",
	"medium",
	"high"
];
/** Link types for cross-referencing BRAIN entries with tasks. */
var BRAIN_LINK_TYPES = [
	"produced_by",
	"applies_to",
	"informed_by",
	"contradicts"
];
/** Observation types for claude-mem compatible observations. */
var BRAIN_OBSERVATION_TYPES = [
	"discovery",
	"change",
	"feature",
	"bugfix",
	"decision",
	"refactor",
	"diary",
	"session-summary"
];
/** Memory entity types for the links table. */
var BRAIN_MEMORY_TYPES = [
	"decision",
	"pattern",
	"learning",
	"observation"
];
/** Sticky note status values. */
var BRAIN_STICKY_STATUSES = [
	"active",
	"converted",
	"archived"
];
/** Sticky note colors. */
var BRAIN_STICKY_COLORS = [
	"yellow",
	"blue",
	"green",
	"red",
	"purple"
];
/** Sticky note priority levels. */
var BRAIN_STICKY_PRIORITIES = [
	"low",
	"medium",
	"high"
];
/**
* Scope-kind taxonomy for Tier-2 attention items (T11371 · Epic T11288).
*
* Ordered NARROWEST → BROADEST. An attention item is auto-keyed to the
* narrowest scope present at write time so two concurrent agents working
* different tasks (or even the same epic) never read each other's
* task/agent-scoped jots — cross-agent leakage is structurally impossible
* because visibility is by-construction (scope-keying) rather than
* filter-after-load.
*
* - `agent`   — bound to one agent identity (`CLEO_AGENT_ID`). Narrowest.
* - `task`    — bound to a single task the agent is working.
* - `epic`    — bound to the parent epic of the current task.
* - `saga`    — bound to the saga containing that epic.
* - `session` — bound to a session id with no resolvable task.
* - `global`  — project-wide fallback when no identity resolves. Broadest.
*
* @task T11371
* @epic T11288
* @saga T11283
*/
var BRAIN_ATTENTION_SCOPE_KINDS = [
	"agent",
	"task",
	"epic",
	"saga",
	"session",
	"global"
];
/**
* Lifecycle status for a Tier-2 attention item (T11371 · Epic T11288).
*
* - `open`         — live working-memory item, surfaced in the digest.
* - `consolidated` — promoted into durable memory (e.g. an observation); no
*   longer surfaced as live attention.
* - `discarded`    — expired (past `expires_at`), decayed below threshold, or
*   explicitly dismissed; excluded from the default open-items query.
*
* @task T11371
* @epic T11288
* @saga T11283
*/
var BRAIN_ATTENTION_STATUSES = [
	"open",
	"consolidated",
	"discarded"
];
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"),
	qualityScore: real("quality_score"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at"),
	memoryTier: text("memory_tier", { enum: BRAIN_MEMORY_TIERS }).default("medium"),
	memoryType: text("memory_type", { enum: BRAIN_COGNITIVE_TYPES }).default("semantic"),
	verified: integer("verified", { mode: "boolean" }).notNull().default(false),
	validAt: text("valid_at").notNull().default(sql`(datetime('now'))`),
	invalidAt: text("invalid_at"),
	expiredAt: text("expired_at"),
	network: text("network", { enum: BRAIN_NETWORK_TYPES }).default("bank"),
	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"),
	contentHash: text("content_hash"),
	provenanceClass: text("provenance_class").default("swept-clean"),
	peerId: text("peer_id").notNull().default("global"),
	peerScope: text("peer_scope").notNull().default("project"),
	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: [
		"proposed",
		"accepted",
		"superseded"
	] }).notNull().default("proposed"),
	decidedBy: text("decided_by", { enum: [
		"owner",
		"council",
		"agent"
	] }).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_expired_at").on(table.expiredAt),
	index("idx_brain_decisions_network").on(table.network),
	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)
]);
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"),
	qualityScore: real("quality_score"),
	memoryTier: text("memory_tier", { enum: BRAIN_MEMORY_TIERS }).default("medium"),
	memoryType: text("memory_type", { enum: BRAIN_COGNITIVE_TYPES }).default("procedural"),
	verified: integer("verified", { mode: "boolean" }).notNull().default(false),
	validAt: text("valid_at").notNull().default(sql`(datetime('now'))`),
	invalidAt: text("invalid_at"),
	expiredAt: text("expired_at"),
	network: text("network", { enum: BRAIN_NETWORK_TYPES }).default("world"),
	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"),
	contentHash: text("content_hash"),
	provenanceClass: text("provenance_class").default("swept-clean"),
	peerId: text("peer_id").notNull().default("global"),
	peerScope: text("peer_scope").notNull().default("project"),
	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_expired_at").on(table.expiredAt),
	index("idx_brain_patterns_network").on(table.network),
	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)
]);
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"),
	qualityScore: real("quality_score"),
	memoryTier: text("memory_tier", { enum: BRAIN_MEMORY_TIERS }).default("short"),
	memoryType: text("memory_type", { enum: BRAIN_COGNITIVE_TYPES }).default("semantic"),
	verified: integer("verified", { mode: "boolean" }).notNull().default(false),
	validAt: text("valid_at").notNull().default(sql`(datetime('now'))`),
	invalidAt: text("invalid_at"),
	expiredAt: text("expired_at"),
	network: text("network", { enum: BRAIN_NETWORK_TYPES }).default("opinion"),
	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"),
	contentHash: text("content_hash"),
	provenanceClass: text("provenance_class").default("swept-clean"),
	peerId: text("peer_id").notNull().default("global"),
	peerScope: text("peer_scope").notNull().default("project")
}, (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_expired_at").on(table.expiredAt),
	index("idx_brain_learnings_network").on(table.network),
	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)
]);
/** General-purpose observations — replaces claude-mem's observations table. */
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"),
	contentHash: text("content_hash"),
	discoveryTokens: integer("discovery_tokens"),
	qualityScore: real("quality_score"),
	createdAt: text("created_at").notNull().default(sql`(datetime('now'))`),
	updatedAt: text("updated_at"),
	memoryTier: text("memory_tier", { enum: BRAIN_MEMORY_TIERS }).default("short"),
	memoryType: text("memory_type", { enum: BRAIN_COGNITIVE_TYPES }).default("episodic"),
	verified: integer("verified", { mode: "boolean" }).notNull().default(false),
	validAt: text("valid_at").notNull().default(sql`(datetime('now'))`),
	invalidAt: text("invalid_at"),
	expiredAt: text("expired_at"),
	network: text("network", { enum: BRAIN_NETWORK_TYPES }).default("observation"),
	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"),
	attachmentsJson: text("attachments_json"),
	stabilityScore: real("stability_score").default(.5),
	provenanceClass: text("provenance_class").default("swept-clean"),
	peerId: text("peer_id").notNull().default("global"),
	peerScope: text("peer_scope").notNull().default("project"),
	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")
}, (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_expired_at").on(table.expiredAt),
	index("idx_brain_observations_network").on(table.network),
	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)
]);
/** Ephemeral sticky notes for quick capture before formal classification. */
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)
]);
/**
* Denormalized sticky-note → tag membership edge.
*
* Replaces the load-all-then-JS-filter pattern that
* `packages/core/src/sticky/list.ts` previously used: when a tag filter was
* active the SQL `LIMIT` was dropped, every row loaded, every `tags_json`
* `JSON.parse`-d, and the result `.filter()`-d in memory. Tag filtering now
* runs in SQL via this junction with the `LIMIT` honored.
*
* `brain_sticky_notes.tags_json` is retained as the legacy whole-array
* compatibility column (read by `cleo sticky show/convert/archive/purge`);
* the junction is the membership-query SSoT and is kept in sync on every
* sticky write. `(sticky_id, tag)` is the natural composite identity — a tag
* appears at most once per sticky.
*
* @task T11355
* @epic T11286
* @saga T11283
*/
var stickyTags = sqliteTable("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_sticky_tags_tag").on(table.tag)]);
/**
* Tier-2 attention buffer — decaying, scope-keyed working-memory items.
*
* Each row is ONE jot (never a single JSON-blob aggregate) so every item
* decays and scopes independently. The item is auto-keyed to the NARROWEST
* scope present at write time (`scope_kind` + `scope_id`, ordered by
* {@link BRAIN_ATTENTION_SCOPE_KINDS}): an agent working task `T-A` writes a
* `task`-scoped item that is structurally invisible to an agent working `T-B`,
* while an `epic`/`saga`-scoped item is visible to every agent under that
* ancestor. Visibility is therefore by-construction (the scope key) rather than
* by filter-after-load — which is what makes cross-agent leakage impossible
* (Epic T11288 AC; leakage test in T11375).
*
* `tags` is a JSONB BLOB declared via the E4 {@link jsonb} helper
* (`store/schema/jsonb.ts`). It MUST be read in-SQL via `json_each(tags)` /
* `jsonb_extract` for membership filtering, or projected with `json(tags)` /
* `jsonbText` for whole-value reads — NEVER `JSON.parse`-d off the raw BLOB
* (`jsonb`'s `fromDriver` throws to enforce this). The tag filter in
* {@link BrainDataAccessor} runs `json_each(tags)` in SQL, never a
* load-all-then-JS-filter.
*
* Decay/TTL model: an item is "live" while `status = 'open'` AND
* (`expires_at IS NULL` OR `expires_at > now`) AND (`decay_score IS NULL` OR
* `decay_score >= threshold`). Items failing the predicate are excluded from
* the default open-items query and may be swept to `status = 'discarded'`.
*
* @task T11371
* @epic T11288
* @saga T11283
*/
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)
]);
/** Cross-references between BRAIN entries and tasks in tasks.db. */
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)
]);
var brainSchemaMeta = sqliteTable("brain_schema_meta", {
	key: text("key").primaryKey(),
	value: text("value").notNull()
});
/**
* Node types for the graph-native memory model.
* Mirrors typed tables (decision, pattern, learning, observation, sticky),
* adds task provenance (task, session, epic), codebase bridging (file, symbol),
* abstract/synthesized types (concept, summary), cross-substrate bridges
* (msg, llmtxt, commit), and fills in the universal semantic graph for T945.
*
* Node ID format: `<type>:<source-id>`.
*
* Supported prefixes:
* - `decision:D-<hash>`         — brain_decisions row
* - `pattern:P-<hash>`          — brain_patterns row
* - `learning:L-<hash>`         — brain_learnings row
* - `observation:O-<hash>-<n>`  — brain_observations row
* - `sticky:<id>`               — brain_sticky row (scratchpad)
* - `task:T###`                 — tasks.db row (soft FK)
* - `session:ses_<ts>_<rand>`   — tasks.db session row (soft FK)
* - `epic:T###`                 — tasks.db epic row (soft FK)
* - `file:<relative-path>`      — nexus.db file node (soft FK)
* - `symbol:<path>::<name>`     — nexus.db symbol node (soft FK)
* - `concept:<slug>`            — abstract concept (synthesized)
* - `summary:<hash>`            — synthesized summary node
* - `msg:<messageId>`           — CONDUIT message (T945 Stage A) — soft FK into conduit.db
* - `llmtxt:<sha256>`           — llmtxt blob attachment (T945 Stage A) — content-addressable
* - `commit:<sha>`              — git commit (T945 Stage A) — Tier 3 autonomy audit
*
* @task T945
*/
var BRAIN_NODE_TYPES = [
	"decision",
	"pattern",
	"learning",
	"observation",
	"sticky",
	"task",
	"session",
	"epic",
	"file",
	"symbol",
	"concept",
	"summary",
	"msg",
	"llmtxt",
	"commit"
];
/**
* Edge types for the graph-native memory model.
* Covers provenance/derivation, semantic relationships, structural links,
* graph bridging between memory entities and codebase nodes, plastic
* Hebbian/STDP edges, and T945 Stage A cross-substrate relationships.
*
* Directionality convention: `from_id` is the source/subject; `to_id` is
* the target/object. The edge type phrase reads naturally left-to-right
* (e.g. `task:T1 → blocks → task:T2` means T1 blocks T2).
*
* @task T945
*/
var BRAIN_EDGE_TYPES = [
	"derived_from",
	"produced_by",
	"informed_by",
	"supports",
	"contradicts",
	"supersedes",
	"applies_to",
	"documents",
	"summarizes",
	"part_of",
	"references",
	"modified_by",
	"code_reference",
	"affects",
	"mentions",
	"conduit_mentions_symbol",
	"co_retrieved",
	"blocks",
	"discusses",
	"cites",
	"embeds",
	"touches_code",
	"task_touches_symbol"
];
/**
* Graph nodes table — the traversable knowledge graph layer.
*
* Every entity row in a typed table (decisions, patterns, learnings,
* observations) gets a corresponding node here. The typed table row is
* the source of truth; the graph node is the index entry for traversal
* and cross-entity reasoning.
*
* Node ID convention: '<type>:<source-id>' — see BRAIN_NODE_TYPES docstring
* for the authoritative prefix list.
*
* Examples: 'decision:D-abc123', 'observation:O-mntphoj6-0',
*           'task:T523', 'symbol:src/store/memory-schema.ts::brainPageNodes',
*           'msg:msg_abc123', 'llmtxt:9f2a...sha256', 'commit:04021568a'
*/
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)
]);
/**
* Graph edges table — directed, typed, weighted, provenance-aware links
* between brain_page_nodes entries (or external nexus node IDs).
*
* The composite primary key (fromId, toId, edgeType) prevents duplicate
* edges of the same type between the same pair of nodes.
*/
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: [
		"static",
		"hebbian",
		"stdp"
	] }).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)
]);
/**
* Retrieval log tracks which brain entries are returned together in search
* results. This data drives:
*   - Co-retrieval edge strengthening (consolidation step 6)
*   - Memory quality instrumentation (retrieval frequency tracking)
*   - Citation count validation (corroboration for tier promotion)
*   - STDP plasticity — spike-timing pairs derived from retrieval timestamps (T673)
*
* Each row records one retrieval event: the query, which entries were returned,
* and the retrieval source (find/fetch/hybrid).
*
* Column notes (T673-M1):
*   entry_ids    — stored as JSON array string '["id1","id2"]' (never CSV).
*                  Writer: JSON.stringify(entryIds). Readers: JSON.parse(row.entry_ids).
*                  M1 migration converts existing CSV rows to JSON format.
*   session_id   — synced to live table via M1 ALTER (was missing from live DDL).
*   reward_signal — R-STDP third-factor: +1.0 verified | +0.5 done | -0.5 cancelled | null.
*   retrieval_order — existed in live table via self-healing DDL but was absent in Drizzle.
*                     M1 brings Drizzle into sync (schema drift fix).
*   delta_ms     — same schema drift resolution as retrieval_order.
*/
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)
]);
/**
* Records every STDP weight-change event applied to a brain_page_edges row.
*
* Each row captures the causal pair (source_node, target_node), the signed
* delta applied to the edge weight, whether it was a potentiation or
* depression event, and which session and timestamp triggered it.
*
* @task T626
* @epic T626
*/
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: ["ltp", "ltd"] }).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)
]);
/**
* Immutable audit log of every edge weight change (LTP, LTD, Hebbian, prune,
* external). Routine exponential decay writes do NOT appear here — only discrete
* plasticity events that cross the 1e-6 negligibility threshold.
*
* Retention policy: rolling 90 days. runConsolidation Step 9d DELETE sweep
* purges rows older than 90 days. Actual pruning wired in Wave 3 (T690).
*
* Spec: docs/specs/stdp-wire-up-spec.md §2.1.4 (owner Q4 mandate — in scope).
*
* @task T697
* @epic T673
*/
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)
]);
/**
* Discrete neuromodulator event log for R-STDP third-factor gating.
* Records every reward/correction/feedback signal that modulates plasticity.
* Inserted by backfillRewardSignals for each task outcome it processes.
*
* Both writes (retrieval_log UPDATE and modulators INSERT) use two separate
* SQLite connections — no ATTACH — matching the cross-db-cleanup.ts pattern.
*
* Spec: docs/specs/stdp-wire-up-spec.md §2.1.5 (Lead A §4.5).
*
* @task T699
* @epic T673
*/
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)
]);
/**
* One row per runConsolidation execution. Enables T628 auto-dream scheduling
* and pipeline observability. Required by the auto-dream cycle for scheduling.
*
* runConsolidation in brain-lifecycle.ts MUST accept an optional trigger
* parameter and INSERT one row per run with step_results_json + duration_ms.
*
* Spec: docs/specs/stdp-wire-up-spec.md §2.1.6 (Lead A + Lead C joint).
*
* @task T701
* @epic T673
*/
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)
]);
/**
* Full-fidelity transcript event store for Claude session JSONL ingestion.
*
* Each row represents one content block from a Claude session transcript:
* text, tool_use, tool_result, thinking, or system entries. Blocks that
* contain secrets are flagged via redacted_at before persistence.
*
* The (session_id, seq) pair is unique — re-ingesting the same session is
* idempotent via INSERT OR IGNORE.
*
* @task T1002
* @epic T1000
*/
var brainTranscriptEvents = sqliteTable("brain_transcript_events", {
	id: text("id").primaryKey(),
	sessionId: text("session_id").notNull(),
	seq: integer("seq").notNull(),
	role: text("role").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)
]);
/**
* Audit log for observation-to-typed-entry promotions.
*
* Every time promoteObservationsToTyped() promotes a brain_observations row
* to a typed entry (brain_learnings, brain_patterns), one row is written here
* to record what was promoted, why, and the full composite score breakdown.
*
* Pairs with T997 promote-explain CLI which reads this table.
*
* @task T1001
* @epic T1000
*/
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)
]);
/**
* Staged backfill run registry.
*
* Records every staged backfill operation: what was staged, from which source,
* targeting which table, how many rows, and the current workflow status.
*
* A backfill run is immutable once `approved` or `rolled-back`. Attempting
* to approve/rollback a completed run is a no-op that returns success with
* an `alreadySettled` flag set to `true`.
*
* Rollback safety: `rollback_snapshot_json` contains the full array of
* row IDs that were staged so approve/rollback are deterministic with no
* additional DB lookup required.
*
* @task T1003
* @epic T1000
*/
var brainBackfillRuns = sqliteTable("brain_backfill_runs", {
	id: text("id").primaryKey(),
	kind: text("kind").notNull(),
	status: text("status").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)
]);
/**
* Rolling session narrative table.
*
* Stores a compact prose summary of what has happened in each CLEO session,
* updated incrementally by the Dialectic Evaluator's `appendNarrativeDelta()`.
*
* PSYCHE reference: `upstream psyche-lineage · deriver/deriver.py`
* (session state derivation — PSYCHE maintains a rolling representation of
* what a session "is about" to inform future retrieval and sigil generation).
*
* @task T1089
* @epic T1082
*/
var sessionNarrative = sqliteTable("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)
});
/** Valid status values for brain_backfill_runs.status. */
var BRAIN_BACKFILL_RUN_STATUSES = [
	"staged",
	"approved",
	"rolled-back"
];
/**
* Valid item types for the deriver queue.
* - `observation`  — derive an inductive synthesis from a set of observations
* - `session`      — summarize a session into session_narrative
* - `narrative`    — update an existing narrative with new observations
* - `embedding`    — compute/backfill embeddings for an observation
*/
var DERIVER_QUEUE_ITEM_TYPES = [
	"observation",
	"session",
	"narrative",
	"embedding"
];
/**
* Valid status values for deriver_queue.status.
* - `pending`     — waiting to be claimed by a worker
* - `in_progress` — claimed by a worker, being processed
* - `done`        — successfully processed
* - `failed`      — permanently failed (moved to DLQ semantics)
*/
var DERIVER_QUEUE_STATUSES = [
	"pending",
	"in_progress",
	"done",
	"failed"
];
/**
* Durable background derivation work queue.
*
* Implements a SQLite-WAL-backed producer/consumer queue using the
* "status column + ORDER BY created_at" pattern (analogous to PostgreSQL
* `FOR UPDATE SKIP LOCKED`). Workers claim items via exclusive transactions
* and complete/fail them atomically.
*
* Stale items (claimed_at older than threshold) are re-queued to `pending`
* during maintenance passes.
*
* @task T1145
* @epic T1145
*/
var deriverQueue = sqliteTable("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"),
	nextAttemptAt: text("next_attempt_at")
}, (table) => [
	index("idx_deriver_queue_status_priority").on(table.status, table.priority, table.createdAt, table.nextAttemptAt),
	index("idx_deriver_queue_item").on(table.itemType, table.itemId),
	index("idx_deriver_queue_claimed_at").on(table.claimedAt)
]);
/**
* Hierarchical Random Projection Tree nodes for consolidated memory.
*
* Each row represents a node in the RPTree. Leaf nodes contain groups of
* semantically-similar observations (leaf_ids). Internal nodes group leaves.
* Trees are rebuilt each dream cycle (full truncate + repopulate).
*
* brain_observations.tree_id references the leaf node containing that
* observation after the last dream cycle.
*
* @task T1146
* @epic T1146
*/
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)]);
/**
* Shadow-write staging table for the T1147 BRAIN noise sweep.
*
* One row per candidate entry to sweep. Anchored to a `brain_backfill_runs`
* row (`sweep_run_id`) of kind `noise-sweep-2440`. The workflow is:
*
* 1. W7-3 detector populates `brain_observations_staging` + a `brain_backfill_runs`
*    row (`status: 'staged'`).
* 2. Autonomous 100-entry stratified validation writes sample JSON.
* 3. `cleo memory sweep --approve <runId>` calls W7-4 executor, which opens
*    a cutover tx: applies actions to live tables, updates `brain_backfill_runs`
*    to `approved`, removes `pending` candidates.
* 4. Reject: `brain_backfill_runs` → `rolled-back`; candidates discarded.
*
* `action` values:
* - `purge`       — set `invalid_at = now()`, `provenance_class = 'noise-purged'`
* - `keep`        — set `provenance_class = 'swept-clean'` (no structural change)
* - `reclassify`  — adjust `quality_score` and mark `swept-clean`
* - `promote`     — raise tier + `swept-clean`
*
* History: renamed from `brain_v2_candidate` (T1402) — the prior name read
* like a schema version, but the intent was "staging rows awaiting validation."
*
* @task T1147
* @epic T1075
*/
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").notNull(),
	newQualityScore: real("new_quality_score"),
	newInvalidAt: text("new_invalid_at"),
	newProvenanceClass: text("new_provenance_class"),
	validationStatus: text("validation_status").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)
]);
/** Valid action values for brain_observations_staging.action. */
var BRAIN_OBSERVATIONS_STAGING_ACTIONS = [
	"purge",
	"keep",
	"reclassify",
	"promote"
];
/** Valid validation_status values for brain_observations_staging. */
var BRAIN_OBSERVATIONS_STAGING_STATUSES = [
	"pending",
	"applied",
	"skipped"
];

export { BRAIN_PATTERN_TYPES as A, BRAIN_ATTENTION_STATUSES as B, BRAIN_STICKY_PRIORITIES as C, DERIVER_QUEUE_STATUSES as D, BRAIN_STICKY_COLORS as E, BRAIN_STICKY_STATUSES as F, BRAIN_SOURCE_CONFIDENCE as G, BRAIN_COGNITIVE_TYPES as H, BRAIN_MEMORY_TIERS as I, memory_schema_exports as J, brainPageEdges as a, brainPageNodes as b, brainObservations as c, brainDecisions as d, brainPatterns as e, brainLearnings as f, brainMemoryLinks as g, brainStickyNotes as h, brainAttention as i, jsonbText as j, jsonb as k, BRAIN_ATTENTION_SCOPE_KINDS as l, makeSchemaMetaTable as m, BRAIN_BACKFILL_RUN_STATUSES as n, BRAIN_DECISION_CATEGORIES as o, BRAIN_OUTCOME_TYPES as p, BRAIN_CONFIDENCE_LEVELS as q, BRAIN_DECISION_TYPES as r, stickyTags as s, DERIVER_QUEUE_ITEM_TYPES as t, BRAIN_LINK_TYPES as u, BRAIN_MEMORY_TYPES as v, BRAIN_OBSERVATION_TYPES as w, BRAIN_EDGE_TYPES as x, BRAIN_NODE_TYPES as y, BRAIN_IMPACT_LEVELS as z };
//# sourceMappingURL=memory-schema-Bi7cChwo.js.map
