const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./DMBpTXzO2.js","./DgZn9uJn.js","./CbGRcr-D.js","./CWxOfblT.js","./CVwAhlPZ.js","./DIQmuJJZ.js","./DrKWWDpL.js","./D7w7HllH.js","./DB5ifLM-.js","./DYP3EJMY.js","./CvaH7m0y.js","./B8PRMiR2.js","./C25QgxZW2.js","./DlZwu-Y7.js","./D-eE9s2f.js","./O2P-f9sv.js","./A9BaqypU2.js","./B5XQZRTz.js","./Dw1eNzkF.js","./BHBwigkz2.js","./DcdSJ5IZ2.js","./LgUi1QRR2.js","./DOqzs8kl2.js","./BYJC6_MM.js","./DTkg6Mnx.js","./CX8DOZuw2.js","./DsQIgu-4.js","./CxlOpib82.js","./D1Pv_C30.js","./dZi01wQz2.js","./CDeeGj-v2.js","./Y4KFZbvl.js","./kwfd020K.js","./BDDiPmhF.js","./Di4pSlYe.js","./BGCA7rZq.js","./Czb-RtcG.js"])))=>i.map(i=>d[i]);
import{s as e}from"./DrKWWDpL.js";import{n as t,t as n}from"./DsQIgu-4.js";import{t as r}from"./DYP3EJMY.js";import{i,l as a}from"./CX8DOZuw2.js";import{t as o}from"./DTkg6Mnx.js";import"./Czb-RtcG.js";import{t as s}from"./CudpqN6Z.js";import{t as c}from"./C0nwgWmB.js";import{c as l,i as u,o as d,t as f}from"./DgZn9uJn.js";var p=4,m=100,h=50;function g(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`sqlite_busy`)||t.includes(`database is locked`)}async function ee(e,t={}){let n=Math.max(1,t.maxAttempts??p),r=t.baseDelayMs??m,i=t.jitterMs??h,a=t.onRetry,o;for(let t=1;t<=n;t++)try{return await e()}catch(e){if(!g(e))throw e;if(o=e,t===n)break;let s=r*2**(t-1),c=(Math.random()*2-1)*i,l=Math.max(0,s+c);a&&a(t,l,e),await te(l)}let s=Error(`E_WRITE_CONTENTION: SQLITE_BUSY persisted after ${n} attempts. Retry the operation after a brief delay. Underlying error: ${o instanceof Error?o.message:String(o)}`);throw s.code=`E_WRITE_CONTENTION`,s.cause=o,s}function te(e){return new Promise(t=>setTimeout(t,e))}var _=e(r(),1),v=5,y=100,ne=2e3;function b(e){return e.replace(/--[^\n]*/g,``).replace(/\/\*[\s\S]*?\*\//g,``)}function x(e){let t=/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/i,n=/DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[`"]?(\w+)[`"]?/i,r=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+RENAME\s+TO\s+[`"]?(\w+)[`"]?/i,i=new Map,a=[...e].sort((e,t)=>e.folderMillis-t.folderMillis);for(let e of a){let a=Array.isArray(e.sql)?e.sql:[e.sql??``];for(let e of a){let a=b(e);for(let e of a.split(`;`)){let a=t.exec(e);if(a){i.set(a[1],!0);continue}let o=r.exec(e);if(o){i.set(o[2],!0);continue}let s=n.exec(e);s&&i.set(s[1],!1)}}}let o=new Set;for(let[e,t]of i)t||o.add(e);return o}var re=`20260531000001`,S=14;function ie(e){let t=(0,_.dirname)(e);for(let e of[`drizzle-cleo-project`,`drizzle-cleo-global`]){let n=(0,_.join)(t,e);if((0,_.existsSync)(n))try{let e=s({migrationsFolder:n}).find(e=>/-consolidation-cleo-/.test(e.name??``));if(e?.name)return e.name.slice(0,S)}catch{}}return re}function ae(e,t){let n=(e??``).slice(0,S);return n.length<S?!0:n<=t}function C(e,t){return!!e.prepare(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`).get(t)}function oe(e){let t=e.replace(/\.db$/,`-pre-cleo.db.bak`);if(!(0,_.existsSync)(t))try{(0,_.copyFileSync)(e,t)}catch{}}function w(e,t,n,r){let i=e.prepare(`PRAGMA table_info("__drizzle_migrations")`).all(),a=new Set(i.map(e=>e.name));a.has(`name`)||e.exec(`ALTER TABLE "__drizzle_migrations" ADD COLUMN "name" text`),a.has(`applied_at`)||e.exec(`ALTER TABLE "__drizzle_migrations" ADD COLUMN "applied_at" TEXT`),e.exec(`INSERT OR IGNORE INTO "__drizzle_migrations" ("hash", "created_at", "name") VALUES ('${t}', ${n}, '${r}')`)}function se(e,t,n,r=new Set,i=re){let a=b((Array.isArray(t.sql)?t.sql:[t.sql??``]).join(`
`)),s=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+COLUMN\s+[`"]?(\w+)[`"]?/gi,c=/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/gi,l=/CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/gi,u=/CREATE\s+TRIGGER\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/gi,d=[];for(let e of a.matchAll(s))d.push({table:e[1],column:e[2]});let f=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+RENAME\s+TO\s+[`"]?(\w+)[`"]?/gi,p=new Map;for(let e of a.matchAll(f))p.set(e[1],e[2]);let m=!0,h=[];for(let e of a.matchAll(c)){let t=e[1];p.has(t)?h.push(p.get(t)):(m=!1,h.push(t))}let g=m&&h.length>0&&d.length===0,ee=p.size>0,te=/CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?\s+ON\s+[`"]?(\w+)[`"]?/gi,_=new Map;for(let e of a.matchAll(te))_.set(e[1],e[2]);let v=[];if(!g&&!ee)for(let e of a.matchAll(l)){let t=e[1];r.has(_.get(t)??``)||v.push(t)}let y=[];for(let e of a.matchAll(u))y.push(e[1]);if(d.length+h.length+v.length+y.length===0)return ae(t.name,i)?(w(e,t.hash,t.folderMillis,t.name??``),o(n).debug({migration:t.name},`Zero-DDL pre-consolidation migration ${t.name} stamped applied (subsumed; not re-run).`),!0):!1;let ne=d.every(({table:t,column:n})=>C(e,t)?e.prepare(`PRAGMA table_info(${t})`).all().some(e=>e.name===n):!1),x=h.every(t=>C(e,t)||r.has(t)),S=v.every(t=>e.prepare(`SELECT name FROM sqlite_master WHERE type='index' AND name=?`).all(t).length>0),ie=y.every(t=>e.prepare(`SELECT name FROM sqlite_master WHERE type='trigger' AND name=?`).all(t).length>0);return ne&&x&&S&&ie?(w(e,t.hash,t.folderMillis,t.name??``),o(n).debug({migration:t.name,alters:d.length,tables:h.length,indexes:v.length,isRebuildOnly:g},`Migration ${t.name} DDL already present in schema — marked applied.`),!0):!1}function ce(e){try{return new Set(s({migrationsFolder:e}).map(e=>e.hash))}catch{return new Set}}function le(e){if(C(e,`__drizzle_migrations`))try{e.exec(`DELETE FROM "__drizzle_migrations" WHERE id NOT IN (SELECT MIN(id) FROM "__drizzle_migrations" GROUP BY hash)`),e.exec(`CREATE UNIQUE INDEX IF NOT EXISTS "idx_drizzle_migrations_hash" ON "__drizzle_migrations" ("hash")`)}catch{}}function T(e,t,n,r,i=[]){let a=x(s({migrationsFolder:t})),c=ie(t);if(C(e,n)&&!C(e,`__drizzle_migrations`)){let n=s({migrationsFolder:t})[0];n&&(e.exec(`
        CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (
          id INTEGER PRIMARY KEY,
          hash text NOT NULL,
          created_at numeric,
          name text,
          applied_at TEXT
        )
      `),w(e,n.hash,n.folderMillis,n.name??``))}if(le(e),C(e,`__drizzle_migrations`)&&C(e,n)){let n=s({migrationsFolder:t}),l=new Set(n.map(e=>e.hash)),u=new Set(l);for(let e of i)if(e!==t)for(let t of ce(e))u.add(t);let d=e.prepare(`SELECT id, hash FROM "__drizzle_migrations"`).all(),f=d.filter(e=>!u.has(e.hash));if(f.length>0){let t=new Set(d.map(e=>e.hash)),i=n.every(e=>t.has(e.hash)),s=o(r);if(i)s.debug({extra:f.length},`Migration journal has ${f.length} entries for migrations not known to this install (DB is ahead). Skipping reconciliation.`);else{s.warn({orphaned:f.length},`Detected ${f.length} true-orphan journal entries from a previous CLEO lineage. Reconciling via DDL probe.`);let t=e.prepare(`DELETE FROM "__drizzle_migrations" WHERE id = ?`);for(let e of f)t.run(e.id);let i=new Set(e.prepare(`SELECT hash FROM "__drizzle_migrations"`).all().map(e=>e.hash));for(let t of n)i.has(t.hash)||se(e,t,r,a,c)}}}if(C(e,`__drizzle_migrations`)&&C(e,n)){let n=s({migrationsFolder:t}),i=e.prepare(`SELECT hash FROM "__drizzle_migrations"`).all(),l=new Set(i.map(e=>e.hash));for(let t of n){if(l.has(t.hash))continue;let n=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+COLUMN\s+[`"]?(\w+)[`"]?\s*(.*?)(?:;|$)/gi,i=[],s=(Array.isArray(t.sql)?t.sql:[t.sql??``]).join(`
`);for(let e of s.matchAll(n))i.push({table:e[1],column:e[2],ddl:(e[3]||``).trim()});if(i.length===0){if(b(s).trim()===``){o(r).debug({migration:t.name},`Migration ${t.name} is a comment-only baseline marker — marking applied on existing DB.`),w(e,t.hash,t.folderMillis,t.name??``);continue}let n=/ALTER\s+TABLE\s+[`"]?\w+[`"]?\s+RENAME\s+TO\s+[`"]?\w+[`"]?/i,i=/CREATE\s+TABLE/i;n.test(s)&&i.test(s)||i.test(s)||/CREATE\s+TRIGGER/i.test(s),se(e,t,r,a,c);continue}let u=[],d=[];for(let t of i){if(!C(e,t.table)){d.push(t);continue}e.prepare(`PRAGMA table_info(${t.table})`).all().some(e=>e.name===t.column)?u.push(t):d.push(t)}if(d.length===0){o(r).warn({migration:t.name,columns:i},`Detected partially-applied migration ${t.name} — columns exist but journal entry missing. Auto-reconciling.`),w(e,t.hash,t.folderMillis,t.name??``);continue}if(u.length>0&&d.length>0){let n=o(r);n.warn({migration:t.name,existingColumns:u.map(e=>`${e.table}.${e.column}`),missingColumns:d.map(e=>`${e.table}.${e.column}`)},`T920: Detected partial migration ${t.name} — some ALTER columns exist, some missing. Adding missing columns and marking applied.`);for(let{table:r,column:i,ddl:a}of d)if(C(e,r))try{e.exec(`ALTER TABLE ${r} ADD COLUMN ${i}${a?` ${a}`:``}`),n.warn({migration:t.name,table:r,column:i},`T920: Added missing column ${r}.${i} to complete partial migration.`)}catch{n.warn({migration:t.name,table:r,column:i},`T920: Could not add missing column ${r}.${i} — will let Drizzle migrate() handle it.`)}w(e,t.hash,t.folderMillis,t.name??``)}}}if(C(e,`__drizzle_migrations`)&&C(e,n)){if(!e.prepare(`PRAGMA table_info("__drizzle_migrations")`).all().some(e=>e.name===`name`))return;let n=s({migrationsFolder:t}),i=new Map(n.map(e=>[e.hash,e.name??``])),a=e.prepare(`SELECT id, hash FROM "__drizzle_migrations" WHERE name IS NULL`).all();for(let t of a){let n=i.get(t.hash);n&&(o(r).debug({id:t.id,hash:t.hash,name:n},`Backfilling missing name on journal entry id=${t.id} (Drizzle v1 beta legacy compat).`),e.exec(`UPDATE "__drizzle_migrations" SET "name" = '${n}' WHERE id = ${t.id}`))}}}function ue(e,t){e.exec(`
    CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (
      id INTEGER PRIMARY KEY,
      hash text NOT NULL,
      created_at numeric,
      name text,
      applied_at TEXT
    )
  `);let n=he(s({migrationsFolder:t})),r=new Set(e.prepare(`SELECT hash FROM "__drizzle_migrations"`).all().map(e=>e.hash)),i=x(n),a=/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"]?(\w+)[`"]?/gi,o=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+RENAME\s+TO\s+[`"]?(\w+)[`"]?/gi,c=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+COLUMN\s+[`"]?(\w+)[`"]?/gi,l=(t,n)=>C(e,t)?e.prepare(`PRAGMA table_info("${t}")`).all().some(e=>e.name===n):!1,u=0,d=0;for(let t of n){if(r.has(t.hash))continue;let n=b(t.sql.join(`
`)),s=new Map,f=[];for(let e of n.matchAll(o))s.set(e[1],e[2]),f.push(e[2]);let p=new Set(f);for(let e of n.matchAll(a)){let t=e[1];p.add(s.get(t)??t)}let m=[];for(let e of n.matchAll(c))m.push({table:e[1],column:e[2]});let h=p.size>0&&[...p].every(t=>C(e,t)||i.has(t)),g=p.size===0&&m.length>0&&m.every(({table:e,column:t})=>l(e,t));if(h||g){for(let n of t.sql){let t=b(n).trim();/^CREATE\s+(?:UNIQUE\s+)?INDEX\s+IF\s+NOT\s+EXISTS/i.test(t)&&!/CREATE\s+TABLE|ALTER\s+TABLE/i.test(t)&&e.exec(n)}w(e,t.hash,t.folderMillis,t.name??``),r.add(t.hash),u++;continue}for(let n of t.sql)e.exec(n);w(e,t.hash,t.folderMillis,t.name??``),r.add(t.hash),d++}return{marked:u,applied:d}}function de(e){let t=[],n=e;for(let e=0;n instanceof Error&&e<16;e++)t.push(n.message),n=n.cause;return t.join(`
`)}function fe(e){return e instanceof Error?/duplicate column name/i.test(de(e)):!1}function pe(e){return e instanceof Error?/table .+ already exists/i.test(de(e)):!1}function me(e){return e.trim()===``?!1:e.replace(/--[^\n]*/g,``).replace(/\/\*[\s\S]*?\*\//g,``).trim()!==``}function he(e){return e.map(e=>({...e,sql:e.sql.filter(me)}))}function E(e,t){let n=he(s(t)),r=e;r.dialect.migrate(n,r.session,t)}function D(e,t,n,r,i){let a=!1,s=!1;for(let c=1;c<=v;c++)try{E(e,{migrationsFolder:t});return}catch(e){if(fe(e)&&!a&&n!==void 0&&r!==void 0&&i!==void 0){a=!0,T(n,t,r,i);continue}if(pe(e)&&!s&&n!==void 0&&r!==void 0&&i!==void 0){s=!0,o(i).warn({message:e.message},`[T9174] Migration "table already exists" — reconciling journal and retrying`),T(n,t,r,i);continue}if(!g(e)||c===v)throw e;let l=Math.min(y*2**(c-1)*(1+Math.random()*.5),ne);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.round(l))}}function ge(e,t,n,r,i=`legacy-upgrade`){if(!C(e,t)||n.length===0)return;let a=e.prepare(`PRAGMA table_info(${t})`).all(),s=new Set(a.map(e=>e.name));for(let a of n)if(!s.has(a.name)){let n=o(r),s=`Adding missing column ${t}.${a.name} via ALTER TABLE`,c={column:a.name,context:i};i===`fresh`?n.error(c,`${s} — MIGRATION DEFECT (fresh DB should not need repair)`):n.warn(c,s),e.exec(`ALTER TABLE ${t} ADD COLUMN ${a.name} ${a.ddl}`)}}function _e(e){return(0,_.dirname)((0,_.dirname)(e))}var ve=[`drizzle-tasks`,`drizzle-cleo-project`,`drizzle-nexus`,`drizzle-brain`,`drizzle-conduit`,`drizzle-cleo-global`,`drizzle-agent-registry`,`drizzle-skills`,`drizzle-telemetry`];function O(e){return ve.filter(t=>t!==e).map(e=>k(e))}function k(e){try{return(0,_.join)(_e((0,_.fileURLToPath)(import.meta.resolve(`@cleocode/core`,import.meta.url))),`migrations`,e)}catch{}let t=(0,_.createRequire)(import.meta.url);try{return(0,_.join)(_e(t.resolve(`@cleocode/core`)),`migrations`,e)}catch(t){throw Error(`resolveCorePackageMigrationsFolder("${e}"): cannot locate @cleocode/core from "${import.meta.url}". Ensure @cleocode/core is installed (workspace or npm). Original error: ${t.message}`)}}var A=`_writer_leases`,j=`_writer_queue`,ye=`ux_writer_leases_active`;u(A,{id:l(`id`).primaryKey(),scope:d(`scope`).notNull(),lane:d(`lane`).notNull(),holderId:d(`holder_id`).notNull(),holderPid:l(`holder_pid`).notNull(),epoch:l(`epoch`).notNull(),acquiredAt:l(`acquired_at`).notNull(),heartbeatAt:l(`heartbeat_at`).notNull(),ttlMs:l(`ttl_ms`).notNull(),reentrancyDepth:l(`reentrancy_depth`).notNull().default(1),active:l(`active`).notNull().default(1)}),u(j,{ticket:l(`ticket`).primaryKey({autoIncrement:!0}),scope:d(`scope`).notNull(),lane:d(`lane`).notNull(),holderId:d(`holder_id`).notNull(),priority:l(`priority`).notNull().default(100),enqueuedAt:l(`enqueued_at`).notNull(),deadlineAt:l(`deadline_at`).notNull()},e=>[f(`ix_writer_queue_order`).on(e.scope,e.lane,e.priority,e.ticket)]);function M(e){if(!e.prepare(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = ?`).get(`ux_writer_leases_active`))throw Error(`E_WRITER_LEASE_INDEX_MISSING: partial-unique active-row index "${ye}" is absent from this cleo.db. The lease baseline migration (drizzle-cleo-{project,global}/…_t11891-writer-leases) did not run, so the single-active-writer invariant (AC1) is unenforced.`)}var be=100,N=3e4,P=25,F=null;function I(){return F===null&&(F=o(`writer-lease`)),F}var L=null,xe=!1;function Se(){if(L!==null)return L;let e={}.CLEO_WRITER_LEASE_MODE;switch(e){case`supervisor`:case`local`:case`off`:case`require`:L=e;break;default:L=`local`;break}return L}function R(){let e=Se();return e===`supervisor`?(xe||(xe=!0,I().info(`CLEO_WRITER_LEASE_MODE=supervisor but no IPC client is wired (ST-2); demoting to local-mode arbitration for the process lifetime.`)),`local`):e}var z=async(e,t)=>{let n;return n=t!==void 0&&t!==G(e)?e===`project`?await $(`project`,t):await $(`global`,t):e===`project`?await Q(`project`):await Q(`global`),{native:n.db.$client,dbPath:n.dbPath??t??G(e)}},Ce=G,B=new Map,V=new Map;function H(e,t,n){return`${e}::${t}::${n}`}function we(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}function Te(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function Ee(e){return`pid-${process.pid}:${e}:${(0,_.randomUUID)().slice(0,8)}`}var De=class{scope;lane;epoch;holderId;dbPath;nativeDb;ttlMs;heartbeatTimer=null;released=!1;constructor(e){this.scope=e.scope,this.lane=e.lane,this.epoch=e.epoch,this.holderId=e.holderId,this.dbPath=e.dbPath,this.nativeDb=e.nativeDb,this.ttlMs=e.ttlMs,this.startHeartbeat()}startHeartbeat(){let e=Math.max(1,Math.floor(this.ttlMs/3));this.heartbeatTimer=setInterval(()=>this.heartbeat(),e),this.heartbeatTimer.unref?.()}heartbeat(){if(!this.released)try{this.nativeDb.prepare(`UPDATE ${A} SET heartbeat_at = ? WHERE scope = ? AND lane = ? AND holder_id = ? AND epoch = ? AND active = 1`).run(Date.now(),this.scope,this.lane,this.holderId,this.epoch)}catch(e){this.released=!0,this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null),I().debug({scope:this.scope,lane:this.lane,err:e instanceof Error?e.message:e},`writer-lease heartbeat failed (native handle likely closed); stopping heartbeat`)}}releaseRow(){if(!this.released){this.released=!0,this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null);try{this.nativeDb.prepare(`UPDATE ${A} SET active = 0, reentrancy_depth = 0 WHERE scope = ? AND lane = ? AND holder_id = ? AND epoch = ? AND active = 1`).run(this.scope,this.lane,this.holderId,this.epoch)}catch(e){I().debug({scope:this.scope,lane:this.lane,err:e instanceof Error?e.message:e},`writer-lease releaseRow failed (native handle likely closed); row freed by close/TTL`)}}}async release(){await Ie(this.scope,this.dbPath,this.lane)}},Oe=class extends Error{codeName=`E_LEASE_UNAVAILABLE`;constructor(e,t,n){super(`E_LEASE_UNAVAILABLE: could not acquire ${e}/${t} writer lease (mode=require): ${n}`),this.name=`LeaseUnavailableError`}},ke=class extends Error{codeName=`E_WRITER_LEASE_REQUIRED`;constructor(e,t){super(`E_WRITER_LEASE_REQUIRED: cannot open the ${e}/${t} writer handle without a held writer lease (AC4) — wrap the write in withWriterLease/acquireWriterLease, or set CLEO_WRITER_LEASE_MODE=off to bypass.`),this.name=`WriterLeaseRequiredError`}};function Ae(e,t){let n=B.get(H(e,Ce(e),t));return n!==void 0&&n.refcount>0}function je(e,t){if(R()!==`off`&&!Ae(e,t))throw new ke(e,t)}function Me(e,t,n,r,i){let a=Date.now();e.exec(`BEGIN IMMEDIATE TRANSACTION`);try{let o=e.prepare(`SELECT id, holder_id, holder_pid, epoch, heartbeat_at, ttl_ms, reentrancy_depth FROM ${A} WHERE scope = ? AND lane = ? AND active = 1`).get(t,n);if(o===void 0){let o=e.prepare(`SELECT COALESCE(MAX(epoch), 0) + 1 AS e FROM _writer_leases WHERE scope = ? AND lane = ?`).get(t,n)?.e??1;return e.prepare(`INSERT INTO ${A} (scope, lane, holder_id, holder_pid, epoch, acquired_at, heartbeat_at, ttl_ms, reentrancy_depth, active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 1)`).run(t,n,r,process.pid,o,a,a,i),e.exec(`COMMIT`),o}if(o.holder_id===r)return e.prepare(`UPDATE ${A} SET reentrancy_depth = reentrancy_depth + 1, heartbeat_at = ? WHERE id = ?`).run(a,o.id),e.exec(`COMMIT`),o.epoch;if(a-o.heartbeat_at>o.ttl_ms&&!Te(o.holder_pid)){let t=o.epoch+1;return e.prepare(`UPDATE ${A} SET holder_id = ?, holder_pid = ?, epoch = ?, acquired_at = ?, heartbeat_at = ?, ttl_ms = ?, reentrancy_depth = 1 WHERE id = ? AND epoch = ?`).run(r,process.pid,t,a,a,i,o.id,o.epoch),e.exec(`COMMIT`),t}return e.exec(`ROLLBACK`),null}catch(t){try{e.exec(`ROLLBACK`)}catch{}throw t}}function Ne(e,t,n,r,i,a){let o=Date.now();e.prepare(`SELECT ticket FROM _writer_queue WHERE scope = ? AND lane = ? AND holder_id = ?`).get(t,n,r)||e.prepare(`INSERT INTO ${j} (scope, lane, holder_id, priority, enqueued_at, deadline_at) VALUES (?, ?, ?, ?, ?, ?)`).run(t,n,r,i,o,o+a)}function U(e,t,n,r){e.prepare(`DELETE FROM ${j} WHERE scope = ? AND lane = ? AND holder_id = ?`).run(t,n,r)}async function Pe(e,t,n){let r=R(),i=n?.reentrant??!0;if(r===`off`)return Le(e,t);let a=n?.dbPath??Ce(e),o=H(e,a,t);if(i){let n=B.get(o);if(n){n.refcount+=1;let{native:r}=await z(e,a);return r.prepare(`UPDATE ${A} SET reentrancy_depth = reentrancy_depth + 1 WHERE scope = ? AND lane = ? AND holder_id = ? AND epoch = ? AND active = 1`).run(e,t,n.handle.holderId,n.handle.epoch),n.handle}let r=V.get(o);if(r){let n=await r,i=B.get(o);if(i&&i.handle===n){i.refcount+=1;let{native:n}=await z(e,a);return n.prepare(`UPDATE ${A} SET reentrancy_depth = reentrancy_depth + 1 WHERE scope = ? AND lane = ? AND holder_id = ? AND epoch = ? AND active = 1`).run(e,t,i.handle.holderId,i.handle.epoch),i.handle}}}let s=Fe(e,a,t,r,o,n);i&&V.set(o,s);try{return await s}finally{i&&V.get(o)===s&&V.delete(o)}}async function Fe(e,t,n,r,i,a){let{native:o}=await z(e,t);M(o);let s=Ee(n),c=a?.ttlMs??3e4,l=a?.priority??be,u=Math.min(N,Math.max(1,c)),d=Date.now()+u,f=!1;for(;;){let a=Me(o,e,n,s,c);if(a!==null){f&&U(o,e,n,s);let r=new De({scope:e,lane:n,epoch:a,holderId:s,dbPath:t,nativeDb:o,ttlMs:c});return B.set(i,{handle:r,refcount:1}),r}if(f||=(Ne(o,e,n,s,l,c),!0),Date.now()>=d){if(f&&U(o,e,n,s),r===`require`)throw new Oe(e,n,`live holder did not release within deadline`);return I().warn({scope:e,lane:n},`writer-lease acquire deadline exceeded; proceeding under busy_timeout fallback (degraded)`),Le(e,n)}await we(P)}}async function Ie(e,t,n){let r=H(e,t,n),i=B.get(r);if(i){if(--i.refcount,i.refcount>0){let{native:r}=await z(e,t);r.prepare(`UPDATE ${A} SET reentrancy_depth = reentrancy_depth - 1 WHERE scope = ? AND lane = ? AND holder_id = ? AND epoch = ? AND active = 1`).run(e,n,i.handle.holderId,i.handle.epoch);return}B.delete(r),i.handle.releaseRow()}}function Le(e,t){return{scope:e,lane:t,epoch:0,async release(){},heartbeat(){}}}async function Re(e,t,n,r){let i=await Pe(e,t,r);try{return await n(i)}finally{await i.release()}}var ze=[`CREATE TABLE IF NOT EXISTS "__drizzle_migrations" (
     id INTEGER PRIMARY KEY,
     hash text NOT NULL,
     created_at numeric,
     name text,
     applied_at TEXT
   )`,`CREATE TABLE IF NOT EXISTS ${A} (
     id INTEGER PRIMARY KEY,
     scope TEXT NOT NULL,
     lane TEXT NOT NULL,
     holder_id TEXT NOT NULL,
     holder_pid INTEGER NOT NULL,
     epoch INTEGER NOT NULL,
     acquired_at INTEGER NOT NULL,
     heartbeat_at INTEGER NOT NULL,
     ttl_ms INTEGER NOT NULL,
     reentrancy_depth INTEGER NOT NULL DEFAULT 1,
     active INTEGER NOT NULL DEFAULT 1
   )`,`CREATE UNIQUE INDEX IF NOT EXISTS ${ye} ON ${A} (scope, lane) WHERE active = 1`,`CREATE TABLE IF NOT EXISTS ${j} (
     ticket INTEGER PRIMARY KEY AUTOINCREMENT,
     scope TEXT NOT NULL,
     lane TEXT NOT NULL,
     holder_id TEXT NOT NULL,
     priority INTEGER NOT NULL DEFAULT 100,
     enqueued_at INTEGER NOT NULL,
     deadline_at INTEGER NOT NULL
   )`,`CREATE INDEX IF NOT EXISTS ix_writer_queue_order ON ${j} (scope, lane, priority ASC, ticket ASC)`];function Be(e){for(let t of ze)e.exec(t)}async function Ve(e,t,n,r){r?.dbPath;let i=R();if(i===`off`)return n();Be(t),M(t);let a=`tasks`,o=Ee(a),s=r?.ttlMs??6e4,c=r?.priority??0,l=Math.min(N,Math.max(1,s)),u=Date.now()+l,d=!1,f=null;for(;;){if(f=Me(t,e,a,o,s),f!==null){d&&U(t,e,a,o);break}if(d||=(Ne(t,e,a,o,c,s),!0),Date.now()>=u){if(d&&U(t,e,a,o),i===`require`)throw new Oe(e,a,`cold-open: live holder did not release within deadline`);return I().warn({scope:e},`cold-open writer-lease acquire deadline exceeded; proceeding under busy_timeout fallback (degraded)`),n()}await we(P)}try{return await n()}finally{t.prepare(`UPDATE ${A} SET active = 0, reentrancy_depth = 0 WHERE scope = ? AND lane = ? AND holder_id = ? AND epoch = ? AND active = 1`).run(e,a,o,f)}}t();var W=new Map;function He(e,t){return`${e}::${t}`}function G(e,t){return e===`project`?(0,_.join)(a(t),`cleo.db`):(0,_.join)(i(),`cleo.db`)}function K(e){return e===`project`?`drizzle-cleo-project`:`drizzle-cleo-global`}var Ue=(0,_.createRequire)(import.meta.url),q=null;function We(){return q===null&&(q=Ue(`drizzle-orm/node-sqlite`).drizzle),q}var J=null;function Ge(){return J===null&&(J=Ue(`node:sqlite`).DatabaseSync),J}var Y=null,X=null;async function Ke(){return Y===null&&(Y=await n(()=>import(`./DMBpTXzO2.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]),import.meta.url)),Y}async function qe(){return X===null&&(X=await n(()=>import(`./A9BaqypU2.js`),__vite__mapDeps([16,1,2,3,4,17,6,18,5,7,8,9,19,12,13,14,15]),import.meta.url)),X}function Z(e){return e===`project`?`tasks_tasks`:`nexus_project_registry`}function Je(){return{}.CLEO_SENTIENT_DAEMON===`1`||{}.CLEO_DB_FULL_MEM===`1`?{}:{mmapSizeBytes:0,cacheSizeKb:8e3}}async function Q(e,t){let n=G(e,t);return $(e===`project`?`project`:`global`,n,t)}async function Ye(e,t,n){n.debug({scope:e,dbPath:t},`opening DEDICATED (non-cached) dual-scope cleo.db (T11782 FIX D)`);let r=(0,_.dirname)(t);(0,_.existsSync)(r)||(0,_.mkdirSync)(r,{recursive:!0});let i=new(Ge())(t,{allowExtension:!0});c(i,Je());let a=e===`project`?await Ke():await qe(),o=We()({client:i,schema:a}),s=k(K(e));return T(i,s,Z(e),`dual-scope-db[${e}]`,O(K(e))),D(o,s,i,Z(e),`dual-scope-db[${e}]`),n.debug({scope:e,dbPath:t},`DEDICATED dual-scope cleo.db ready (T11782 FIX D)`),{db:o,scope:e,dbPath:t,close(){try{i.close()}catch{}}}}async function $(e,t,r,i){let a=i?.dedicated===!0,s=He(e,t);if(!a){let e=W.get(s);if(e)return e.initPromise?e.initPromise:e.handle}let l=o(`dual-scope-db`);if(a)return Ye(e,t,l);let u=(async()=>{l.debug({scope:e,dbPath:t},`opening dual-scope cleo.db`);let i=(0,_.dirname)(t);(0,_.existsSync)(i)||(0,_.mkdirSync)(i,{recursive:!0});let a=new(Ge())(t,{allowExtension:!0});c(a,Je());let o=e===`project`?await Ke():await qe(),u=We()({client:a,schema:o}),d=k(K(e)),f=await Ve(e,a,async()=>{T(a,d,Z(e),`dual-scope-db[${e}]`,O(K(e))),D(u,d,a,Z(e),`dual-scope-db[${e}]`),l.debug({scope:e,dbPath:t},`dual-scope cleo.db ready`);let n={db:u,scope:e,dbPath:t,close(){W.delete(s);try{a.close()}catch{}}},r=W.get(s);return r&&(r.initPromise=null,r.handle=n),n},{dbPath:t});if(r!==void 0&&t===G(e,r)){let i=null,o=!1;try{let{governor:e}=await n(async()=>{let{governor:e}=await import(`./DcdSJ5IZ2.js`);return{governor:e}},__vite__mapDeps([20,21,6,22,9,23,24,5,7,8,25,26,27,28]),import.meta.url),t=await e.tryAcquire(`db-heavy`);t.deferred?o=!0:i=t.release}catch{}if(o)return l.debug({scope:e,dbPath:t},`exodus-on-open skipped this open — db-heavy deferred under memory pressure (re-runs idempotently on a calmer open)`),f;try{let{maybeRunExodusOnOpen:i}=await n(async()=>{let{maybeRunExodusOnOpen:e}=await import(`./dZi01wQz2.js`);return{maybeRunExodusOnOpen:e}},__vite__mapDeps([29,6,26,24,9,30,25,22,5,7,8,27,31,32,33,23,34]),import.meta.url),o=await i(e,t,a,r);if(o.outcome===`migrated`||o.outcome===`aborted`){let r=e===`project`?await $(`project`,t):await $(`global`,t);if(o.outcome===`aborted`){let i={scope:e,dbPath:t,reason:o.reason,at:Date.now()};l.warn({scope:e,reason:o.reason},`exodus-on-open aborted; consolidated cleo.db left empty, legacy kept as source — mutating callers must check handle.exodusAbort / call assertWriteDurable (T11828)`);let{emitExodusAbort:a}=await n(async()=>{let{emitExodusAbort:e}=await import(`./BGCA7rZq.js`);return{emitExodusAbort:e}},__vite__mapDeps([35,36,6,9]),import.meta.url);return a(i),{...r,exodusAbort:i}}let{clearExodusAborts:i}=await n(async()=>{let{clearExodusAborts:e}=await import(`./BGCA7rZq.js`);return{clearExodusAborts:e}},__vite__mapDeps([35,36,6,9]),import.meta.url);return i(e),r}}catch(n){return l.warn({err:n,scope:e},`exodus-on-open hook failed (non-fatal); re-opening consolidated handle`),$(e===`project`?`project`:`global`,t)}finally{i&&await i().catch(()=>{})}}return f})();return W.set(s,{handle:null,nativeDb:null,initPromise:u}),u.catch(()=>{let e=W.get(s);e&&e.initPromise===u&&W.delete(s)}),u}function Xe(e){for(let[t,n]of W)if(!(e!==void 0&&n.handle?.scope!==e)){if(n.handle)try{n.handle.close()}catch{}W.delete(t)}e===void 0&&(Y=null,X=null)}export{C as _,Pe as a,Re as c,oe as d,ge as f,T as g,ue as h,G as i,O as l,D as m,Q as n,je as o,E as p,$ as r,Se as s,Xe as t,k as u,g as v,ee as y};