import{s as e}from"./DrKWWDpL.js";import{t}from"./DYP3EJMY.js";import{i as n}from"./CX8DOZuw2.js";import{t as r}from"./DTkg6Mnx.js";import{f as i,g as a,i as o,l as s,m as c,n as l,u,v as d}from"./DeO5NWhN.js";import{t as f}from"./2PQNgpBd.js";import{d as p}from"./B_DA9RKE2.js";var m=e(t(),1),h=`1.0.0`,g=null,_=null,v=null,y=null,b=null,x=`nexus_global`;function S(e){return o(`project`,e)}function C(){let e=n(),t=o(`global`);if(!t.startsWith(e))throw Error(`BUG: getNexusRegistryDbPath() resolved to "${t}" which is NOT under getCleoHome() ("${e}"). The nexus registry/identity tables are global-only per ADR-036/ADR-090 §2.2. This indicates a code path that bypasses canonical path resolution — fix the caller, do not suppress this error.`);return t}function w(e){let t=C(),n=t.replace(/'/g,`''`),r=e.prepare(`PRAGMA database_list`).all().find(e=>e.name===x);if(r){if(r.file===t)return;try{e.exec(`DETACH DATABASE ${x}`)}catch{return}}e.exec(`ATTACH DATABASE '${n}' AS ${x}`)}function T(){return u(`drizzle-nexus`)}var E=`nexus.db`,D=new Set;function O(){return(0,m.join)(n(),`nexus`,E)}function k(){let e;try{e=O()}catch{return!1}if(!(0,m.existsSync)(e)||D.has(e))return!1;D.add(e);let t=S();return r(`nexus-sqlite`).warn({nestedPath:e,canonicalPath:t,migrationCommand:`node scripts/migrate-nested-nexus.mjs`,adr:`ADR-086`,task:`T10321`},`Detected nested-nexus structural bug — canonical consolidated cleo.db is in use; nested duplicates at <cleoHome>/nexus/ are migration debris. Run the migration script to remove them.`),!0}function A(e,t){return!!e.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`).get(t)}function j(e,t,n){return!!e.prepare(`SELECT name FROM sqlite_master WHERE type=? AND name=?`).get(t,n)}function M(e){A(e,`nexus_nodes`)&&(j(e,`table`,`nexus_symbols_fts`)||e.exec(`
      CREATE VIRTUAL TABLE nexus_symbols_fts USING fts5(
        node_id UNINDEXED,
        label,
        file_path,
        tokenize = 'unicode61 remove_diacritics 1'
      )
    `),e.exec(`DROP TRIGGER IF EXISTS nexus_nodes_fts_ai`),e.exec(`
    CREATE TRIGGER nexus_nodes_fts_ai
    AFTER INSERT ON nexus_nodes
    BEGIN
      INSERT INTO nexus_symbols_fts(rowid, node_id, label, file_path)
      VALUES (new.rowid, new.id, new.label, new.file_path);
    END
  `),e.exec(`DROP TRIGGER IF EXISTS nexus_nodes_fts_ad`),e.exec(`
    CREATE TRIGGER nexus_nodes_fts_ad
    AFTER DELETE ON nexus_nodes
    BEGIN
      DELETE FROM nexus_symbols_fts WHERE rowid = old.rowid;
    END
  `),e.exec(`DROP TRIGGER IF EXISTS nexus_nodes_fts_au`),e.exec(`
    CREATE TRIGGER nexus_nodes_fts_au
    AFTER UPDATE ON nexus_nodes
    BEGIN
      DELETE FROM nexus_symbols_fts WHERE rowid = old.rowid;
      INSERT INTO nexus_symbols_fts(rowid, node_id, label, file_path)
      VALUES (new.rowid, new.id, new.label, new.file_path);
    END
  `),e.exec(`
    INSERT INTO nexus_symbols_fts(rowid, node_id, label, file_path)
    SELECT rowid, id, label, file_path
    FROM nexus_nodes
    WHERE rowid NOT IN (SELECT rowid FROM nexus_symbols_fts)
  `))}function N(e){if(!A(e,`nexus_relations`)||(e.exec(`
    CREATE TABLE IF NOT EXISTS nexus_relation_weights (
      relation_id       TEXT PRIMARY KEY NOT NULL,
      weight            REAL DEFAULT 0.0 NOT NULL,
      last_accessed_at  TEXT,
      co_accessed_count INTEGER DEFAULT 0 NOT NULL
    )
  `),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relation_weights_last_accessed ON nexus_relation_weights (last_accessed_at)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relation_weights_weight ON nexus_relation_weights (weight)`),!e.prepare(`PRAGMA table_info(nexus_relations)`).all().some(e=>e.name===`weight`)))return;e.exec(`
    INSERT OR IGNORE INTO nexus_relation_weights (relation_id, weight, last_accessed_at, co_accessed_count)
    SELECT id, COALESCE(weight, 0.0), last_accessed_at, COALESCE(co_accessed_count, 0)
      FROM nexus_relations
     WHERE COALESCE(weight, 0.0) > 0.0
        OR last_accessed_at IS NOT NULL
        OR COALESCE(co_accessed_count, 0) > 0
  `);let t=e.prepare(`PRAGMA foreign_keys`).get()?.foreign_keys===1;e.exec(`PRAGMA foreign_keys=OFF`);try{e.exec(`DROP INDEX IF EXISTS idx_nexus_relations_last_accessed`),e.exec(`
      CREATE TABLE nexus_relations__narrow (
        id text PRIMARY KEY,
        project_id text NOT NULL,
        source_id text NOT NULL,
        target_id text NOT NULL,
        type text NOT NULL,
        confidence real NOT NULL,
        reason text,
        step integer,
        indexed_at text DEFAULT (datetime('now')) NOT NULL,
        CHECK ("type" IN ('contains', 'defines', 'imports', 'accesses', 'calls', 'extends', 'implements', 'method_overrides', 'method_implements', 'has_method', 'has_property', 'member_of', 'step_in_process', 'handles_route', 'fetches', 'handles_tool', 'entry_point_of', 'wraps', 'queries', 'documents', 'applies_to', 'co_changed', 'co_cited_in_task')),
        CHECK ("indexed_at" IS NULL OR "indexed_at" GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*')
      )
    `),e.exec(`
      INSERT INTO nexus_relations__narrow
        (id, project_id, source_id, target_id, type, confidence, reason, step, indexed_at)
      SELECT id, project_id, source_id, target_id, type, confidence, reason, step, indexed_at
        FROM nexus_relations
    `),e.exec(`DROP TABLE nexus_relations`),e.exec(`ALTER TABLE nexus_relations__narrow RENAME TO nexus_relations`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relations_project ON nexus_relations (project_id)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relations_source ON nexus_relations (source_id)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relations_target ON nexus_relations (target_id)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relations_type ON nexus_relations (type)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relations_project_type ON nexus_relations (project_id, type)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relations_source_type ON nexus_relations (source_id, type)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relations_target_type ON nexus_relations (target_id, type)`),e.exec(`CREATE INDEX IF NOT EXISTS idx_nexus_relations_confidence ON nexus_relations (confidence)`)}finally{e.exec(`PRAGMA foreign_keys=${t?`ON`:`OFF`}`)}}function P(e,t){let n=T();if(A(e,`nexus_nodes`)&&v){let e=v.replace(/\.db$/,`-pre-cleo.db.bak`);if(!(0,m.existsSync)(e))try{(0,m.copyFileSync)(v,e)}catch{}}a(e,n,`_nexus_meta`,`nexus`,s(`drizzle-nexus`));let r;for(let i=1;i<=5;i++)try{c(t,n,e,`_nexus_meta`,`nexus`),r=void 0;break}catch(e){if(!d(e)||i===5)throw e;r=e;let t=Math.min(100*2**(i-1)*(1+Math.random()*.5),2e3);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.round(t))}if(r)throw r;N(e),i(e,`nexus_nodes`,[{name:`is_external`,ddl:`integer DEFAULT 0`}],`nexus`),M(e)}async function F(){let e=S(),t=C();if(g&&v!==e&&L(),g&&y!==t&&L(),g&&(_===null||!_.isOpen)&&L(),g){if(_)try{w(_)}catch{L()}if(g)return g}if(b)return b;b=(async()=>{v=e,y=t,k(),await l(`global`);let n=(await l(`project`)).db.$client??null;if(!n)throw Error(`T11648: openDualScopeDb returned a handle without $client — cannot extract DatabaseSync for the nexus-schema drizzle wrapping.`);_=n,w(n);let r=f({client:n,schema:p});return P(n,r),n.prepare(`INSERT OR IGNORE INTO nexus_schema_meta (key, value) VALUES ('schemaVersion', '${h}')`).run(),g=r,r})();try{return await b}finally{b=null}}function I(){_=null,g=null,v=null,y=null,b=null}function L(){_=null,g=null,v=null,y=null,b=null}function R(){return _}export{F as a,C as c,O as i,L as l,I as n,S as o,k as r,R as s,h as t,T as u};