@crewx/sdk 0.9.0-rc.72 → 0.9.0-rc.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,15 @@
1
- 'use strict';var yn=require('fs'),ye=require('path'),hr=require('os'),drizzleOrm=require('drizzle-orm'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var yn__namespace=/*#__PURE__*/_interopNamespace(yn);var ye__namespace=/*#__PURE__*/_interopNamespace(ye);var hr__default=/*#__PURE__*/_interopDefault(hr);var Be=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var N=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:ye.join(hr__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return yn.existsSync(e??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(e,t,n){super(t),this.name="RepositoryError",this.code=e,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};var Ht=r=>{try{return yn__namespace.statSync(`${r}-wal`).size}catch{return 0}},Wt=32*1024*1024;function k(r){let e=Be("better-sqlite3"),{drizzle:t}=Be("drizzle-orm/better-sqlite3"),n=new e(r);return n.exec("PRAGMA journal_mode = WAL"),n.exec(`PRAGMA journal_size_limit = ${Wt}`),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:t(n),runRaw:(o,s=[])=>n.prepare(o).run(...s),close:()=>n.close()}}function wr(r,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=Be("better-sqlite3"),n=Ht(r),o;try{o=new t(r),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),a=Ht(r);return {busy:s[0]?.busy===1,walBytesBefore:n,walBytesAfter:a}}finally{o?.close();}}var Kt=new Set,kr={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT"};function gt(r,e){return (r.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function yr(r,e){if(e>0||!gt(r,"tasks"))return;let t=r.all("PRAGMA table_info(tasks)"),n=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(kr))n.has(o)||r.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var br={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"}};function Rr(r,e,t){if(!gt(r,"__drizzle_migrations")||!gt(r,"tasks"))return;let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(yn.readFileSync(ye__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=br[a.tag];if(!c)continue;let u=ye__namespace.default.join(e,`${a.tag}.sql`);if(!yn.existsSync(u))continue;let l=yn.readFileSync(u,"utf-8"),p=crypto.createHash("sha256").update(l).digest("hex");if(o.has(p))continue;let _=r.all("PRAGMA table_info(tasks)"),g=new Set(_.map(m=>m.name));for(let[m,P]of Object.entries(c))g.has(m)||(r.run(`ALTER TABLE tasks ADD COLUMN ${m} ${P}`),g.add(m));}}function Er(r,e,t){let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(yn.readFileSync(ye__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=ye__namespace.default.join(e,`${a.tag}.sql`);if(!yn.existsSync(c))continue;let u=yn.readFileSync(c,"utf-8"),l=crypto.createHash("sha256").update(u).digest("hex");if(o.has(l))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,_=[],g;for(;(g=p.exec(u))!==null;)_.push({table:g[1],column:g[2]});if(_.length===0||!u.split(/-->\s*statement-breakpoint/).map(w=>w.trim()).filter(Boolean).every(w=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(w)))continue;_.every(({table:w,column:$})=>r.all(`PRAGMA table_info("${w}")`).some(W=>W.name===$))&&r.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${a.when})`);}}function qe(r){let{migrate:e}=Be("drizzle-orm/better-sqlite3/migrator"),{sql:t}=Be("drizzle-orm"),n=[ye__namespace.default.join(__dirname,"../migrations"),ye__namespace.default.join(__dirname,"migrations"),ye__namespace.default.join(__dirname,"../../../../drizzle/migrations"),ye__namespace.default.join(process.cwd(),"drizzle/migrations")],o=n.find(l=>yn.existsSync(ye__namespace.default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
1
+ 'use strict';var Qn=require('fs'),Re=require('path'),Qr=require('os'),crypto=require('crypto'),drizzleOrm=require('drizzle-orm'),sqliteCore=require('drizzle-orm/sqlite-core');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Qn__namespace=/*#__PURE__*/_interopNamespace(Qn);var Re__namespace=/*#__PURE__*/_interopNamespace(Re);var Qr__default=/*#__PURE__*/_interopDefault(Qr);var We=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var v=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:Re.join(Qr__default.default.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return Qn.existsSync(e??this.resolveDbPath())}};var d=class extends Error{code;cause;constructor(e,t,n){super(t),this.name="RepositoryError",this.code=e,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};var hn=r=>{try{return Qn__namespace.statSync(`${r}-wal`).size}catch{return 0}},kn=32*1024*1024;function y(r){let e=We("better-sqlite3"),{drizzle:t}=We("drizzle-orm/better-sqlite3"),n=new e(r);return n.exec("PRAGMA journal_mode = WAL"),n.exec(`PRAGMA journal_size_limit = ${kn}`),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),n.exec("PRAGMA analysis_limit = 400"),n.exec("PRAGMA optimize"),{db:t(n),runRaw:(o,s=[])=>n.prepare(o).run(...s),close:()=>n.close()}}function Zr(r,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=We("better-sqlite3"),n=hn(r),o;try{o=new t(r),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),a=hn(r);return {busy:s[0]?.busy===1,walBytesBefore:n,walBytesAfter:a}}finally{o?.close();}}var yn=new Set,eo={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT"};function It(r,e){return (r.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function to(r,e){if(e>0||!It(r,"tasks"))return;let t=r.all("PRAGMA table_info(tasks)"),n=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(eo))n.has(o)||r.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var no={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"}};function ro(r,e,t){if(!It(r,"__drizzle_migrations")||!It(r,"tasks"))return;let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(Qn.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=no[a.tag];if(!c)continue;let l=Re__namespace.default.join(e,`${a.tag}.sql`);if(!Qn.existsSync(l))continue;let u=Qn.readFileSync(l,"utf-8"),p=crypto.createHash("sha256").update(u).digest("hex");if(o.has(p))continue;let _=r.all("PRAGMA table_info(tasks)"),g=new Set(_.map(h=>h.name));for(let[h,j]of Object.entries(c))g.has(h)||(r.run(`ALTER TABLE tasks ADD COLUMN ${h} ${j}`),g.add(h));}}function oo(r,e,t){let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(Qn.readFileSync(Re__namespace.default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=Re__namespace.default.join(e,`${a.tag}.sql`);if(!Qn.existsSync(c))continue;let l=Qn.readFileSync(c,"utf-8"),u=crypto.createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,_=[],g;for(;(g=p.exec(l))!==null;)_.push({table:g[1],column:g[2]});if(_.length===0||!l.split(/-->\s*statement-breakpoint/).map(k=>k.trim()).filter(Boolean).every(k=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(k)))continue;_.every(({table:k,column:$})=>r.all(`PRAGMA table_info("${k}")`).some(K=>K.name===$))&&r.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${a.when})`);}}function Ge(r){let{migrate:e}=We("drizzle-orm/better-sqlite3/migrator"),{sql:t}=We("drizzle-orm"),n=[Re__namespace.default.join(__dirname,"../migrations"),Re__namespace.default.join(__dirname,"migrations"),Re__namespace.default.join(__dirname,"../../../../drizzle/migrations"),Re__namespace.default.join(process.cwd(),"drizzle/migrations")],o=n.find(u=>Qn.existsSync(Re__namespace.default.join(u,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
2
2
  ${n.join(`
3
- `)}`);let s=r.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;s?.cnt&&(a=r.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),yr(r,a),s?.cnt&&(Er(r,o,t),Rr(r,o,t)),e(r,{migrationsFolder:o});let u=(r.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(u>0){let l=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${l} (${u} migration${u>1?"s":""} applied).`);}}function C(r,e){Kt.has(e)||(qe(r),Kt.add(e));}var h=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var i=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},r=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${r.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(r.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(r.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(r.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(r.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(r.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(r.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(r.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(r.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(r.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(r.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(r.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(r.workspace_id,r.started_at)}));var ue=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>i.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},r=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(r.task_id,r.seq)}));var f=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},r=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(r.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(r.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(r.workspace_id,r.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(r.title)}));var Ee=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Ee.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},r=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(r.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(r.parent_span_id)}));var pe=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},r=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(r.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(r.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(r.timestamp)}));var ne=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},r=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(r.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(r.thread_id,r.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(r.thread_id,r.seq)}));var Me=sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},r=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(r.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(r.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(r.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(r.partition_key)}));var U=sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},r=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(r.provider,r.account_ref,r.limit_window,r.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(r.limit_window,r.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(r.provider,r.limit_window,r.bucket_start)}));var V=sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},r=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(r.workspace_id,r.month)}));var R=sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},r=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(r.workspace_id,drizzleOrm.sql`${r.created_at} DESC`)})),j=sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},r=>({pk:sqliteCore.primaryKey({columns:[r.notification_id,r.user_id]})}));var T=sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},r=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(r.workspace_id,r.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(r.workspace_id,r.created_at)}));sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},r=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${r.id}) BETWEEN 5 AND 128 AND ${r.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${r.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${r.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${r.definition_hash}) = 64 AND ${r.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${r.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${r.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${r.domain_ref_json}) AND json_type(${r.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${r.state_json}) AND json_type(${r.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${r.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${r.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${r.granted_capabilities_json}) AND json_type(${r.granted_capabilities_json}) = 'array'`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${r.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${r.updated_at} >= ${r.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(r.workspace_id,r.thread_id)}));sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},r=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${r.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${r.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${r.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${r.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${r.actor_json}) AND json_type(${r.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${r.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${r.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${r.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${r.after_revision} IS NULL OR ${r.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${r.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${r.outcome} IS NULL OR ${r.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${r.input_json}) AND json_type(${r.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${r.result_json} IS NULL OR (json_valid(${r.result_json}) AND json_type(${r.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${r.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${r.settled_at} IS NULL OR ${r.settled_at} >= ${r.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
3
+ `)}`);let s=r.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),a=0;s?.cnt&&(a=r.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),to(r,a),s?.cnt&&(oo(r,o,t),ro(r,o,t)),e(r,{migrationsFolder:o});let l=(r.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-a;if(l>0){let u=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${u} (${l} migration${l>1?"s":""} applied).`);}}function N(r,e){yn.has(e)||(Ge(r),yn.add(e));}var w=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()});var i=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),rendered_prompt:sqliteCore.text("rendered_prompt"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0)},r=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${r.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(r.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(r.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(r.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(r.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(r.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(r.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(r.pid),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(r.thread_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(r.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(r.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(r.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(r.workspace_id,r.started_at)}));var fe=sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>i.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},r=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(r.task_id,r.seq)}));var go="json_extract(metadata, '$.threadTitle.state')",mo="json_extract(metadata, '$.threadTitle.priority')",f=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>w.id,{onDelete:"set null"}),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},r=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(r.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(r.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(r.workspace_id,r.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(r.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(r.workspace_id,drizzleOrm.sql.raw(go)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(r.workspace_id,drizzleOrm.sql.raw(mo))}));var Se=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>Se.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},r=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(r.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(r.parent_span_id)}));var ge=sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},r=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(r.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(r.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(r.timestamp)}));var de=sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>f.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},r=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(r.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(r.thread_id,r.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(r.thread_id,r.seq)}));var Ke=sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},r=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(r.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(r.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(r.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(r.partition_key)}));var z=sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},r=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(r.provider,r.account_ref,r.limit_window,r.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(r.limit_window,r.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(r.provider,r.limit_window,r.bucket_start)}));var Z=sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},r=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(r.workspace_id,r.month)}));var T=sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},r=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(r.workspace_id,drizzleOrm.sql`${r.created_at} DESC`)})),B=sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},r=>({pk:sqliteCore.primaryKey({columns:[r.notification_id,r.user_id]})}));var C=sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},r=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(r.workspace_id,r.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(r.workspace_id,r.created_at)}));sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},r=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${r.id}) BETWEEN 5 AND 128 AND ${r.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${r.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${r.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${r.definition_hash}) = 64 AND ${r.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${r.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${r.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${r.domain_ref_json}) AND json_type(${r.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${r.state_json}) AND json_type(${r.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${r.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${r.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${r.granted_capabilities_json}) AND json_type(${r.granted_capabilities_json}) = 'array'`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${r.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${r.updated_at} >= ${r.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(r.workspace_id,r.thread_id)}));sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},r=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${r.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${r.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${r.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${r.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${r.actor_json}) AND json_type(${r.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${r.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${r.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${r.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${r.after_revision} IS NULL OR ${r.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${r.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${r.outcome} IS NULL OR ${r.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${r.input_json}) AND json_type(${r.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${r.result_json} IS NULL OR (json_valid(${r.result_json}) AND json_type(${r.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${r.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${r.settled_at} IS NULL OR ${r.settled_at} >= ${r.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
4
4
  (${r.status} = 'requested' AND ${r.after_revision} IS NULL AND ${r.outcome} IS NULL AND ${r.settled_at} IS NULL)
5
5
  OR
6
6
  (${r.status} = 'settled' AND ${r.after_revision} IS NOT NULL AND ${r.outcome} IS NOT NULL AND ${r.settled_at} IS NOT NULL)
7
- )`),instanceRequestUnique:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(r.instance_id,r.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(r.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(r.requested_at)}));var v=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},r=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${r.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${r.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${r.stages_json}) AND json_type(${r.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${r.stage_index} >= 1`)})),Q=sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>v.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},r=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${r.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${r.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${r.evidence_json}) AND json_type(${r.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(r.project_id,r.position)})),ce=sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>v.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},r=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${r.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${r.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${r.payload_json}) AND json_type(${r.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(r.project_id,r.seq)}));function kt(r){let e=ye__namespace.resolve(r);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,n)=>`${n.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function sn(r){let e=kt(r);return crypto.createHash("sha256").update(e).digest("hex")}function at(r){return r.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Rt=class extends N{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?ye.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{qe(n.db);}catch(o){throw n.close(),o}return n}resolveSlug(e,t,n){let o=at(ye.basename(n)),a=`${at(ye.basename(ye.dirname(n)))}-${o}`,c=[o,a];try{let u=l=>e.select({id:h.id}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.slug,l),drizzleOrm.ne(h.id,t))).limit(1).all().length>0;for(let l of c)if(!u(l))return l;for(let l=2;l<1e3;l+=1){let p=`${a}-${l}`;if(!u(p))return p}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:h.id,slug:h.slug}).from(h).all(),n=0;for(let o of t)if(o.slug.includes("/")){let s=at(o.slug.replace(/\//g,"-"));e.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,o.id)).run(),n+=1;}return {updated:n,checked:t.length}}catch(t){throw new d("DB_ERROR","Failed to normalize legacy slugs",t)}finally{e.close();}}ensureRow(e,t){let{id:n,slug:o,name:s,workspacePath:a}=t,c=new Date().toISOString();e.insert(h).values({id:n,slug:o,name:s,workspace_path:a,is_active:1,created_at:c,updated_at:c}).onConflictDoNothing().run(),e.update(h).set({workspace_path:a,updated_at:c}).where(drizzleOrm.and(drizzleOrm.eq(h.id,n),drizzleOrm.isNull(h.workspace_path))).run();}registerWorkspace(e){let t=kt(e),n=this.openHandle(true);try{let o=sn(t),s=ye.basename(t),a=this.resolveSlug(n.db,o,t);return this.ensureRow(n.db,{id:o,slug:a,name:s,workspacePath:t}),{id:o,slug:a}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to register workspace",o)}finally{n.close();}}listProjects(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let n=e.isActive!==void 0?drizzleOrm.eq(h.is_active,e.isActive?1:0):void 0,o=t.db.select({count:drizzleOrm.sql`count(*)`}).from(h).where(n).get();return {rows:t.db.select().from(h).where(n).orderBy(drizzleOrm.desc(h.updated_at)).limit(e.limit).offset(e.offset).all(),total:o?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{t.close();}}findAgentsByProject(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${e} AND agent_id IS NOT NULL ORDER BY agent_id`).map(o=>o.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{t.close();}}findThreadsByProject(e,t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let o=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
7
+ )`),instanceRequestUnique:sqliteCore.uniqueIndex("ui_action_receipts_instance_request_uq").on(r.instance_id,r.request_id),instanceIdIdx:sqliteCore.index("ui_action_receipts_instance_id_idx").on(r.instance_id),requestedAtIdx:sqliteCore.index("ui_action_receipts_requested_at_idx").on(r.requested_at)}));var D=sqliteCore.sqliteTable("projects",{id:sqliteCore.text("id").primaryKey().notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),name:sqliteCore.text("name").notNull(),outcome:sqliteCore.text("outcome").notNull(),due_date:sqliteCore.text("due_date"),scene:sqliteCore.text("scene").notNull().default("planning"),stages_json:sqliteCore.text("stages_json").notNull(),stage_index:sqliteCore.integer("stage_index").notNull(),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),accepted_at:sqliteCore.text("accepted_at"),archived_at:sqliteCore.text("archived_at")},r=>({idCheck:sqliteCore.check("projects_id_ck",drizzleOrm.sql`${r.id} GLOB 'prj_*'`),sceneCheck:sqliteCore.check("projects_scene_ck",drizzleOrm.sql`${r.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:sqliteCore.check("projects_stages_json_ck",drizzleOrm.sql`json_valid(${r.stages_json}) AND json_type(${r.stages_json}) = 'array'`),stageIndexCheck:sqliteCore.check("projects_stage_index_ck",drizzleOrm.sql`${r.stage_index} >= 1`)})),ne=sqliteCore.sqliteTable("project_criteria",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>D.id,{onDelete:"cascade"}),position:sqliteCore.integer("position").notNull(),statement:sqliteCore.text("statement").notNull(),verify_status:sqliteCore.text("verify_status").notNull().default("pending"),verified_at:sqliteCore.text("verified_at"),evidence_json:sqliteCore.text("evidence_json").notNull().default("[]"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},r=>({idCheck:sqliteCore.check("project_criteria_id_ck",drizzleOrm.sql`${r.id} GLOB 'pjc_*'`),verifyStatusCheck:sqliteCore.check("project_criteria_verify_status_ck",drizzleOrm.sql`${r.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:sqliteCore.check("project_criteria_evidence_json_ck",drizzleOrm.sql`json_valid(${r.evidence_json}) AND json_type(${r.evidence_json}) = 'array'`),projectPositionUnique:sqliteCore.uniqueIndex("project_criteria_project_position_uq").on(r.project_id,r.position)})),_e=sqliteCore.sqliteTable("project_events",{id:sqliteCore.text("id").primaryKey().notNull(),project_id:sqliteCore.text("project_id").notNull().references(()=>D.id,{onDelete:"restrict"}),seq:sqliteCore.integer("seq").notNull(),actor_type:sqliteCore.text("actor_type").notNull(),actor_id:sqliteCore.text("actor_id"),type:sqliteCore.text("type").notNull(),title:sqliteCore.text("title").notNull(),summary:sqliteCore.text("summary"),payload_json:sqliteCore.text("payload_json").notNull().default("{}"),created_at:sqliteCore.text("created_at").notNull()},r=>({idCheck:sqliteCore.check("project_events_id_ck",drizzleOrm.sql`${r.id} GLOB 'pje_*'`),actorTypeCheck:sqliteCore.check("project_events_actor_type_ck",drizzleOrm.sql`${r.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:sqliteCore.check("project_events_payload_json_ck",drizzleOrm.sql`json_valid(${r.payload_json}) AND json_type(${r.payload_json}) = 'object'`),projectSeqUnique:sqliteCore.uniqueIndex("project_events_project_seq_uq").on(r.project_id,r.seq)}));var yt=["THREAD_STATE","THREAD_PRIORITY"],bt=["gray","blue","violet","green","amber","orange","red","pink"],m=sqliteCore.sqliteTable("common_codes",{code_group:sqliteCore.text("code_group").notNull(),code:sqliteCore.text("code").notNull(),code_name:sqliteCore.text("code_name"),color:sqliteCore.text("color").notNull().default("gray"),sort_order:sqliteCore.integer("sort_order").notNull(),workspace_id:sqliteCore.text("workspace_id"),is_builtin:sqliteCore.integer("is_builtin").notNull().default(0),is_archived:sqliteCore.integer("is_archived").notNull().default(0),metadata:sqliteCore.text("metadata"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},r=>({pk:sqliteCore.primaryKey({columns:[r.code_group,r.code]}),metadataCheck:sqliteCore.check("common_codes_metadata_ck",drizzleOrm.sql`${r.metadata} IS NULL OR (json_valid(${r.metadata}) AND json_type(${r.metadata}) = 'object')`),builtinCheck:sqliteCore.check("common_codes_builtin_ck",drizzleOrm.sql`${r.is_builtin} IN (0, 1)`),archivedCheck:sqliteCore.check("common_codes_archived_ck",drizzleOrm.sql`${r.is_archived} IN (0, 1)`),idxCommonCodesSelection:sqliteCore.index("idx_common_codes_group_archived_order").on(r.code_group,r.is_archived,r.sort_order)}));var U=class extends d{reason;constructor(e,t="VALIDATION",n=e,o){super(t,n,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Ln="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Xo(){let r=crypto.randomBytes(16),e="";for(let t of r)e+=Ln[t%Ln.length];return e.slice(0,12)}function Ye(){return `c_${Xo()}`}function Qo(r){return typeof r=="string"&&yt.includes(r)}function Zo(r){return typeof r=="string"&&bt.includes(r)}function ot(r){if(!Qo(r))throw new U("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${r}`)}function Pn(r){if(!Zo(r))throw new U("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${r}`)}function jn(r){let e=typeof r=="string"?r.trim():"",t=[...e].length;if(t<1||t>20)throw new U("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function st(r){if(typeof r!="string"||r.trim().length===0)throw new U("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Ut(r){if(typeof r!="string"||r.trim().length===0)throw new U("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function Je(r,e){return drizzleOrm.and(drizzleOrm.eq(m.code_group,r),drizzleOrm.or(drizzleOrm.isNull(m.workspace_id),drizzleOrm.eq(m.workspace_id,e)))}var Ft=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");e&&Qn.mkdirSync(Re.dirname(t),{recursive:true});let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}listSelectable(e,t){if(ot(e),st(t),!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(m).where(drizzleOrm.and(Je(e,t),drizzleOrm.eq(m.is_archived,0))).orderBy(drizzleOrm.asc(m.sort_order),drizzleOrm.asc(m.code)).all()}catch(o){throw new d("DB_ERROR","Failed to list selectable common codes",o)}finally{n.close();}}listForHistory(e,t){if(ot(e),st(t),!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(m).where(Je(e,t)).orderBy(drizzleOrm.asc(m.sort_order),drizzleOrm.asc(m.code)).all()}catch(o){throw new d("DB_ERROR","Failed to list common-code history",o)}finally{n.close();}}resolve(e,t){if(ot(e),Ut(t),!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select().from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,e),drizzleOrm.eq(m.code,t))).limit(1).get()??null}catch(o){throw new d("DB_ERROR","Failed to resolve common code",o)}finally{n.close();}}createThreadState(e){st(e.workspaceId);let t=jn(e.name);Pn(e.color);let n=this.openHandle(true);try{return n.db.transaction(o=>{if(o.select({code:m.code}).from(m).where(drizzleOrm.and(Je("THREAD_STATE",e.workspaceId),drizzleOrm.eq(m.is_archived,0),drizzleOrm.eq(m.code_name,t))).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`);let a=o.select({maxSortOrder:drizzleOrm.sql`max(${m.sort_order})`}).from(m).where(Je("THREAD_STATE",e.workspaceId)).get(),c=new Date().toISOString(),l=Ye();for(;o.select({code:m.code}).from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,"THREAD_STATE"),drizzleOrm.eq(m.code,l))).limit(1).get();)l=Ye();o.insert(m).values({code_group:"THREAD_STATE",code:l,code_name:t,color:e.color,sort_order:(a?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:c,updated_at:c}).run();let u=o.select().from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,"THREAD_STATE"),drizzleOrm.eq(m.code,l))).limit(1).get();if(!u)throw new d("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to create thread state common code",o)}finally{n.close();}}updateDisplay(e){if(ot(e.group),Ut(e.code),st(e.workspaceId),e.name===void 0&&e.color===void 0)throw new U("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let t=e.name===void 0||e.name===null?e.name:jn(e.name);e.color!==void 0&&Pn(e.color);let n=this.openHandle(true);try{return n.db.transaction(o=>{let s=o.select().from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,e.group),drizzleOrm.eq(m.code,e.code))).limit(1).get();if(!s)throw new U("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e.group}/${e.code}`);if(this.assertOwnership(s,e.workspaceId),t===null&&s.is_builtin!==1)throw new U("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof t=="string"&&s.is_archived===0){let l=drizzleOrm.and(Je(e.group,e.workspaceId),drizzleOrm.eq(m.is_archived,0));if(o.select({code:m.code}).from(m).where(drizzleOrm.and(l,drizzleOrm.eq(m.code_name,t),drizzleOrm.sql`${m.code} <> ${e.code}`)).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`)}let a={updated_at:new Date().toISOString()};e.name!==void 0&&(a.code_name=t??null),e.color!==void 0&&(a.color=e.color),o.update(m).set(a).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,e.group),drizzleOrm.eq(m.code,e.code))).run();let c=o.select().from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,e.group),drizzleOrm.eq(m.code,e.code))).limit(1).get();if(!c)throw new d("DB_ERROR","Updated common code could not be read back");return c},{behavior:"immediate"})}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update common-code display values",o)}finally{n.close();}}archive(e,t,n,o=true){if(ot(e),Ut(t),st(n),typeof o!="boolean")throw new U("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(a=>{let c=a.select().from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,e),drizzleOrm.eq(m.code,t))).limit(1).get();if(!c)throw new U("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${t}`);if(c.is_builtin===1)throw new U("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(c,n),!o&&c.code_name!==null&&a.select({code:m.code}).from(m).where(drizzleOrm.and(Je(e,n),drizzleOrm.eq(m.is_archived,0),drizzleOrm.eq(m.code_name,c.code_name),drizzleOrm.ne(m.code,t))).limit(1).get())throw new U("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${c.code_name}`);a.update(m).set({is_archived:o?1:0,updated_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,e),drizzleOrm.eq(m.code,t))).run();let l=a.select().from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,e),drizzleOrm.eq(m.code,t))).limit(1).get();if(!l)throw new d("DB_ERROR","Archived common code could not be read back");return l},{behavior:"immediate"})}catch(a){throw a instanceof d?a:new d("DB_ERROR","Failed to archive common code",a)}finally{s.close();}}assertOwnership(e,t){if(e.workspace_id!==null&&e.workspace_id!==t)throw new U("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function Ht(r){let e=Re__namespace.resolve(r);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,n)=>`${n.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function Mn(r){let e=Ht(r);return crypto.createHash("sha256").update(e).digest("hex")}function Et(r){return r.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Gt=class extends v{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?Re.join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{Ge(n.db);}catch(o){throw n.close(),o}return n}resolveSlug(e,t,n){let o=Et(Re.basename(n)),a=`${Et(Re.basename(Re.dirname(n)))}-${o}`,c=[o,a];try{let l=u=>e.select({id:w.id}).from(w).where(drizzleOrm.and(drizzleOrm.eq(w.slug,u),drizzleOrm.ne(w.id,t))).limit(1).all().length>0;for(let u of c)if(!l(u))return u;for(let u=2;u<1e3;u+=1){let p=`${a}-${u}`;if(!l(p))return p}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:w.id,slug:w.slug}).from(w).all(),n=0;for(let o of t)if(o.slug.includes("/")){let s=Et(o.slug.replace(/\//g,"-"));e.db.update(w).set({slug:s,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(w.id,o.id)).run(),n+=1;}return {updated:n,checked:t.length}}catch(t){throw new d("DB_ERROR","Failed to normalize legacy slugs",t)}finally{e.close();}}ensureRow(e,t){let{id:n,slug:o,name:s,workspacePath:a}=t,c=new Date().toISOString();e.insert(w).values({id:n,slug:o,name:s,workspace_path:a,is_active:1,created_at:c,updated_at:c}).onConflictDoNothing().run(),e.update(w).set({workspace_path:a,updated_at:c}).where(drizzleOrm.and(drizzleOrm.eq(w.id,n),drizzleOrm.isNull(w.workspace_path))).run();}registerWorkspace(e){let t=Ht(e),n=this.openHandle(true);try{let o=Mn(t),s=Re.basename(t),a=this.resolveSlug(n.db,o,t);return this.ensureRow(n.db,{id:o,slug:a,name:s,workspacePath:t}),{id:o,slug:a}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to register workspace",o)}finally{n.close();}}listProjects(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let n=e.isActive!==void 0?drizzleOrm.eq(w.is_active,e.isActive?1:0):void 0,o=t.db.select({count:drizzleOrm.sql`count(*)`}).from(w).where(n).get();return {rows:t.db.select().from(w).where(n).orderBy(drizzleOrm.desc(w.updated_at)).limit(e.limit).offset(e.offset).all(),total:o?.count??0}}catch(n){throw new d("DB_ERROR","Failed to list projects",n)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(w).where(drizzleOrm.eq(w.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace",n)}finally{t.close();}}findAgentsByProject(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(drizzleOrm.sql`SELECT DISTINCT agent_id FROM tasks WHERE workspace_id = ${e} AND agent_id IS NOT NULL ORDER BY agent_id`).map(o=>o.agent_id)}catch(n){throw new d("DB_ERROR","Failed to find agents by project",n)}finally{t.close();}}findThreadsByProject(e,t){if(!this.dbExists())return {rows:[],total:0};let n=this.openHandle(false);try{let o=n.db.get(drizzleOrm.sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:n.db.all(drizzleOrm.sql`SELECT t.*,
8
8
  (SELECT agent_id FROM tasks tk WHERE tk.thread_id = t.id AND tk.agent_id IS NOT NULL ORDER BY tk.started_at ASC LIMIT 1) AS agent_id
9
9
  FROM threads t
10
10
  WHERE t.workspace_id = ${e}
11
11
  ORDER BY t.updated_at DESC
12
- LIMIT ${t.limit} OFFSET ${t.offset}`),total:o?.count??0}}catch(o){throw new d("DB_ERROR","Failed to find threads by project",o)}finally{n.close();}}findBySlug(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(h).where(drizzleOrm.eq(h.slug,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{t.close();}}slugExists(e,t){if(!this.dbExists())return false;let n=this.openHandle(false);try{let o=t?drizzleOrm.and(drizzleOrm.eq(h.slug,e),drizzleOrm.ne(h.id,t)):drizzleOrm.eq(h.slug,e);return !!n.db.select({id:h.id}).from(h).where(o).limit(1).get()}catch(o){throw new d("DB_ERROR","Failed to check slug",o)}finally{n.close();}}insert(e,t,n,o){let s=this.openHandle(true);try{let a=new Date().toISOString();s.db.insert(h).values({id:e,slug:t,name:n,workspace_path:o,is_active:1,created_at:a,updated_at:a}).run();let c=s.db.select().from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get();if(!c)throw new d("DB_ERROR","Insert did not return a row");return c}catch(a){throw a instanceof d?a:new d("DB_ERROR","Failed to insert workspace",a)}finally{s.close();}}update(e,t,n){let o=this.openHandle(true);try{o.runRaw(`UPDATE workspaces SET ${t.join(", ")} WHERE id = ?`,n);let s=o.db.select().from(h).where(drizzleOrm.eq(h.id,e)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${e} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{o.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:h.id,workspace_path:h.workspace_path}).from(h).where(drizzleOrm.and(drizzleOrm.eq(h.is_active,1),drizzleOrm.isNotNull(h.workspace_path))).all(),n=0;for(let o of t){let s=o.workspace_path;yn.existsSync(ye.join(s,"crewx.yaml"))||yn.existsSync(ye.join(s,"crewx.yml"))||(e.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(h.id,o.id)).run(),n+=1);}return {softDeleted:n,checked:t.length}}catch(t){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",t)}finally{e.close();}}delete(e){let t=this.openHandle(true);try{t.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${e}`),t.db.delete(h).where(drizzleOrm.eq(h.id,e)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{t.close();}}};var ln="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ao(r){let e=crypto.randomBytes(r*2),t="";for(let n=0;n<e.length&&t.length<r;n++){let o=e[n];o<248&&(t+=ln[o%62]);}for(;t.length<r;)t+=ln[crypto.randomBytes(1)[0]%62];return t}function Ce(r){return `${r}_${ao(8)}`}var St=["outcome_plan","contract_check","feature_link","use_verify","result_review"],fo=new Set(St),mn=Object.freeze(St.map(r=>({key:r,labelOverride:null}))),mo=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),ho=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),wo=new Set(["pending","verifying","passed","failed"]),ko=new Set(["user","project_manager","system"]),yo=new Set(["task","wi","url"]),bo=/^\d{4}-\d{2}-\d{2}$/;function O(r){throw new d("VALIDATION",r)}function re(r){throw new d("NOT_FOUND",r)}function q(r,e){(typeof r!="string"||r.trim().length===0)&&O(`${e} is required`);}function Ro(r){if(r==null)return;bo.test(r)||O("dueDate must use YYYY-MM-DD");let e=new Date(`${r}T00:00:00.000Z`);(Number.isNaN(e.getTime())||e.toISOString().slice(0,10)!==r)&&O("dueDate must be a valid calendar date");}function hn(r){let e=r??mn;(!Array.isArray(e)||e.length===0)&&O("stages must contain at least one stage");let t=new Set;return e.map(n=>{(!n||typeof n!="object"||Array.isArray(n))&&O("stage must be an object");let o=n;return q(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&O("stage.labelOverride must be a string or null"),o.labelOverride!==null&&q(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&O("stage.key is required"),!fo.has(o.key)&&o.labelOverride===null&&O(`custom stage requires a labelOverride: ${o.key}`),t.has(o.key)&&O(`duplicate stage key: ${o.key}`),t.add(o.key),{key:o.key,labelOverride:o.labelOverride}})}function Eo(r){Array.isArray(r)||O("criteria must be an array");for(let e of r)q(e,"criterion.statement");}function Ue(r={}){let e=r.actorType??"system";ko.has(e)||O(`invalid actorType: ${String(e)}`);let t=r.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&O(`actorId is required for ${e}`),{actorType:e,actorId:t}}function wn(r,e){let t=r??{};if((t===null||typeof t!="object"||Array.isArray(t))&&O("event payload must be a JSON object"),e==="accepted")for(let n of ["remainingRisks","nextPlan","lessons","evidenceRefs"])(!Object.prototype.hasOwnProperty.call(t,n)||t[n]===void 0)&&O(`accepted payload requires ${n}`);try{return JSON.stringify(t)}catch(n){throw new d("VALIDATION","event payload must be JSON serializable",n)}}function So(r){return Array.isArray(r)||O("evidence must be an array"),r.map(e=>((!e||typeof e!="object")&&O("evidence item must be an object"),yo.has(e.kind)||O(`invalid evidence kind: ${String(e.kind)}`),q(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&O("evidence.label must be a string"),e.label===void 0?{kind:e.kind,ref:e.ref}:{kind:e.kind,ref:e.ref,label:e.label}))}function fn(r){let e;try{e=JSON.parse(r);}catch(t){throw new d("DB_ERROR","Project stages JSON is invalid",t)}try{if(!Array.isArray(e))throw new d("DB_ERROR","Project stages JSON is invalid");return hn(e)}catch(t){throw new d("DB_ERROR","Project stages JSON is invalid",t)}}function kn(r){return q(r.projectId,"projectId"),q(r.title,"title"),mo.has(r.type)||O(`invalid project event type: ${String(r.type)}`),{...Ue(r),payloadJson:wn(r.payload,r.type)}}function $e(r,e,t){let n=kn(e);r.select({id:v.id}).from(v).where(drizzleOrm.eq(v.id,e.projectId)).get()||re(`Project ${e.projectId} not found`);let s=r.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${ce.seq}), 0)`}).from(ce).where(drizzleOrm.eq(ce.project_id,e.projectId)).get()?.maxSeq??0,a=Ce("pje");r.insert(ce).values({id:a,project_id:e.projectId,seq:s+1,actor_type:n.actorType,actor_id:n.actorId,type:e.type,title:e.title,summary:e.summary??null,payload_json:n.payloadJson,created_at:t}).run();let c=r.select().from(ce).where(drizzleOrm.eq(ce.id,a)).get();if(!c)throw new d("DB_ERROR","Event insert did not return a row");return c}var Et=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}getDetailFromHandle(e,t){let n=e.db.select().from(v).where(drizzleOrm.eq(v.id,t)).get();if(!n)return;let o=e.db.select().from(Q).where(drizzleOrm.eq(Q.project_id,t)).orderBy(drizzleOrm.asc(Q.position)).all();return {...n,stages:fn(n.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||re(`Project ${e} not found`),t}createProject(e){q(e.workspaceId,"workspaceId"),q(e.name,"name"),q(e.outcome,"outcome"),Ro(e.dueDate);let t=hn(e.stages);Eo(e.criteria);let n=Ce("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(a=>{a.insert(v).values({id:n,workspace_id:e.workspaceId,name:e.name,outcome:e.outcome,due_date:e.dueDate??null,scene:"planning",stages_json:JSON.stringify(t),stage_index:1,created_at:o,updated_at:o,accepted_at:null,archived_at:null}).run(),e.criteria.forEach((c,u)=>{a.insert(Q).values({id:Ce("pjc"),project_id:n,position:u+1,statement:c,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),$e(a,{projectId:n,actorType:"system",type:"created",title:"Project created",payload:{}},o);});}catch(a){throw a instanceof d?a:new d("DB_ERROR","Failed to create project",a)}finally{s.close();}return this.getDetailOrThrow(n)}getProject(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return this.getDetailFromHandle(t,e)}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to get project",n)}finally{t.close();}}listProjectsByWorkspace(e,t={}){if(q(e,"workspaceId"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=t.includeArchived?drizzleOrm.eq(v.workspace_id,e):drizzleOrm.and(drizzleOrm.eq(v.workspace_id,e),drizzleOrm.isNull(v.archived_at));return n.db.select({id:v.id}).from(v).where(o).orderBy(drizzleOrm.desc(v.updated_at),drizzleOrm.desc(v.created_at)).all().map(a=>this.getDetailFromHandle(n,a.id)).filter(a=>a!==void 0)}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to list projects",o)}finally{n.close();}}archiveProject(e){q(e,"projectId");let t=this.openHandle(true);try{t.db.update(v).set({archived_at:new Date().toISOString()}).where(drizzleOrm.eq(v.id,e)).run().changes===0&&re(`Project ${e} not found`);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to archive project",n)}finally{t.close();}return this.getDetailOrThrow(e)}setScene(e,t,n={}){q(e,"projectId"),ho.has(t)||O(`invalid project scene: ${String(t)}`);let o=Ue(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let u=c.select().from(v).where(drizzleOrm.eq(v.id,e)).get();u||re(`Project ${e} not found`),c.update(v).set({scene:t,updated_at:s}).where(drizzleOrm.eq(v.id,e)).run(),$e(c,{projectId:e,...o,type:"scene_changed",title:"Project scene changed",payload:{before:u.scene,after:t}},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to set project scene",c)}finally{a.close();}return this.getDetailOrThrow(e)}setStageIndex(e,t,n={}){q(e,"projectId"),Number.isInteger(t)||O("stage index must be an integer");let o=Ue(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let u=c.select().from(v).where(drizzleOrm.eq(v.id,e)).get();u||re(`Project ${e} not found`);let l=fn(u.stages_json);(t<1||t>l.length)&&O("stage index is outside the project stages"),c.update(v).set({stage_index:t,updated_at:s}).where(drizzleOrm.eq(v.id,e)).run(),$e(c,{projectId:e,...o,type:"stage_advanced",title:"Project stage advanced",payload:{before:u.stage_index,after:t}},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to set project stage",c)}finally{a.close();}return this.getDetailOrThrow(e)}setCriterionVerify(e,t,n,o={}){let s=typeof e=="string"?{projectId:typeof n=="string"?e:void 0,criterionId:typeof n=="string"?t:e,verifyStatus:typeof n=="string"?n:t,...typeof n=="string"?o:n}:e,a=s.verifyStatus??s.status;(!a||!wo.has(a))&&O(`invalid criterion status: ${String(a)}`),q(s.criterionId,"criterionId");let c=Ue(s),u=new Date().toISOString(),l=this.openHandle(true),p;try{l.db.transaction(g=>{let m=g.select().from(Q).where(drizzleOrm.eq(Q.id,s.criterionId)).get();m||re(`Criterion ${s.criterionId} not found`),p=m.project_id,s.projectId&&s.projectId!==m.project_id&&re(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(Q).set({verify_status:a,verified_at:a==="passed"?u:null,updated_at:u}).where(drizzleOrm.eq(Q.id,s.criterionId)).run(),$e(g,{projectId:m.project_id,...c,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:s.criterionId,status:a}},u);});}catch(g){throw g instanceof d?g:new d("DB_ERROR","Failed to set criterion verification",g)}finally{l.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||re(`Criterion ${s.criterionId} not found`),_}setCriterionEvidence(e,t,n,o={}){let s=typeof e=="string"?{projectId:Array.isArray(n)?e:void 0,criterionId:Array.isArray(n)?t:e,evidence:Array.isArray(n)?n:t,...Array.isArray(n)?o:n}:e;q(s.criterionId,"criterionId");let a=So(s.evidence),c=Ue(s),u=new Date().toISOString(),l=this.openHandle(true),p;try{l.db.transaction(g=>{let m=g.select().from(Q).where(drizzleOrm.eq(Q.id,s.criterionId)).get();m||re(`Criterion ${s.criterionId} not found`),p=m.project_id,s.projectId&&s.projectId!==m.project_id&&re(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(Q).set({evidence_json:JSON.stringify(a),updated_at:u}).where(drizzleOrm.eq(Q.id,s.criterionId)).run(),$e(g,{projectId:m.project_id,...c,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:s.criterionId,evidence:a}},u);});}catch(g){throw g instanceof d?g:new d("DB_ERROR","Failed to set criterion evidence",g)}finally{l.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||re(`Criterion ${s.criterionId} not found`),_}appendEvent(e,t){let n=typeof e=="string"?{...t,projectId:e}:e;kn(n);let o=new Date().toISOString(),s=this.openHandle(true),a;try{s.db.transaction(c=>{a=$e(c,n,o);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to append project event",c)}finally{s.close();}if(!a)throw new d("DB_ERROR","Event append did not return a row");return a}listEvents(e,t={}){if(q(e,"projectId"),t.afterSeq!==void 0&&(!Number.isInteger(t.afterSeq)||t.afterSeq<0)&&O("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&O("limit must be a positive integer"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=[drizzleOrm.eq(ce.project_id,e)];t.afterSeq!==void 0&&o.push(drizzleOrm.gt(ce.seq,t.afterSeq));let s=n.db.select().from(ce).where(drizzleOrm.and(...o)).orderBy(drizzleOrm.asc(ce.seq));return t.limit!==void 0&&(s=s.limit(t.limit)),s.all()}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to list project events",o)}finally{n.close();}}acceptProject(e,t){q(e,"projectId");let n=Ue(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};wn(o,"accepted");let s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{c.select({id:v.id}).from(v).where(drizzleOrm.eq(v.id,e)).get()||re(`Project ${e} not found`),c.update(v).set({scene:"accepted",accepted_at:s,updated_at:s}).where(drizzleOrm.eq(v.id,e)).run(),$e(c,{projectId:e,...n,type:"accepted",title:"Project accepted",payload:o},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to accept project",c)}finally{a.close();}return this.getDetailOrThrow(e)}};var Rn=[h,i,f,Ee,pe,ne,Me];function xo(){return ye__namespace.default.join(hr__default.default.homedir(),".crewx","crewx.db")}function No(r){if(!yn__namespace.default.existsSync(r))return null;let e=Math.floor(Date.now()/1e3),t=`${r}.bak-${e}`;return yn__namespace.default.copyFileSync(r,t),t}function En(r){let e=r.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(e.map(t=>t.name))}function Do(r){return r==null||typeof r=="object"&&"queryChunks"in r?null:typeof r=="number"?String(r):typeof r=="boolean"?r?"1":"0":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:String(r)}function Ao(r){let e=r.getSQLType(),t=`"${r.name}" ${e}`,n=Do(r.default);return n!==null&&(t+=` DEFAULT ${n}`),r.notNull&&(t+=" NOT NULL"),t}function Io(r,e){let t=e?.dbPath??xo(),n=e?.force??false,o=e?.dryRun??false,s=o?null:No(t);if(n&&!o)try{r.run("DELETE FROM __drizzle_migrations");}catch{}let a=En(r);if(!o)try{qe(r);}catch(_){let g=_ instanceof Error?`${_.message} ${_.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw _}let c,u;o?(c=Rn.map(g=>sqliteCore.getTableConfig(g).name).filter(g=>!a.has(g)),u=a):(u=En(r),c=[...u].filter(_=>!a.has(_)));let l=[],p=[];for(let _ of Rn){let g=sqliteCore.getTableConfig(_),m=g.name;if(!u.has(m))continue;let P=r.all(`PRAGMA table_info("${m}")`),w=new Set(P.map(S=>S.name)),$=new Set(g.columns.map(S=>S.name));for(let S of g.columns)if(!w.has(S.name)){if(!o){let W=Ao(S);r.run(`ALTER TABLE "${m}" ADD COLUMN ${W}`);}l.push({table:m,column:S.name});}for(let S of P)$.has(S.name)||p.push(`${m}.${S.name} exists in DB but not in schema (untouched)`);}return {created:c,altered:l,warnings:p,backupPath:s}}function Sn(r){let e=r.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let t=e.lastIndexOf("/");return t>=0&&(e=e.slice(t+1)),e=e.replace(/-\d{8}$/,""),e}function Dn(r,e){let t=e===void 0?"":` at index ${e}`;if(!r||typeof r!="object")throw new d("VALIDATION",`Task log entry${t} must be an object`);if(typeof r.timestamp!="string"||typeof r.level!="string"||typeof r.message!="string")throw new d("VALIDATION",`Task log entry${t} must contain string timestamp, level, and message fields`);return {timestamp:r.timestamp,level:r.level,message:r.message}}function xn(r,e){if(e===null||e.trim()==="")return [];let t;try{t=JSON.parse(e);}catch(n){throw new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n)}if(!Array.isArray(t))throw new d("DB_ERROR",`Malformed legacy task logs: ${r} (expected an array)`);try{return t.map((n,o)=>Dn(n,o))}catch(n){throw n instanceof d?new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n):n}}function An(r){if(r.log_storage!=="blob"&&r.log_storage!=="events")throw new d("DB_ERROR",`Invalid task log storage for task: ${r.id}`);if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new d("DB_ERROR",`Invalid task log sequence for task: ${r.id}`);if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new d("DB_ERROR",`Invalid task log revision for task: ${r.id}`);return r.log_storage}function Nn(r){return {taskId:r.id,source:An(r),revision:r.log_revision,lastSeq:r.last_log_seq}}function qo(r){if(!Number.isInteger(r)||r<0)throw new d("VALIDATION","Task log tail limit must be a non-negative integer")}var Ve=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}findStateRow(e,t){return e.db.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()}findStateRowInTransaction(e,t){return e.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()}requireStateRowInTransaction(e,t){let n=this.findStateRowInTransaction(e,t);if(!n)throw new d("NOT_FOUND",`Task not found: ${t}`);return n}appendLog(e,t){return this.appendLogs(e,[t])}appendLogs(e,t){let n=t.map((s,a)=>Dn(s,a));if(n.length===0){let s=this.getLogState(e);if(!s)throw new d("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(a=>{let c=this.requireStateRowInTransaction(a,e),u=An(c);if(u==="blob"){let g=xn(e,c.logs);if(a.update(i).set({logs:JSON.stringify([...g,...n]),log_revision:drizzleOrm.sql`${i.log_revision} + 1`}).where(drizzleOrm.eq(i.id,e)).run().changes!==1)throw new d("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:u,revision:c.log_revision+1,lastSeq:c.last_log_seq}}let l=c.last_log_seq+1,p=c.last_log_seq+n.length;if(a.insert(ue).values(n.map((g,m)=>({task_id:e,seq:l+m,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(i).set({last_log_seq:p,log_revision:drizzleOrm.sql`${i.log_revision} + 1`}).where(drizzleOrm.eq(i.id,e)).run().changes!==1)throw new d("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:u,revision:c.log_revision+1,lastSeq:p}},{behavior:"immediate"})}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let t=this.openHandle(false);try{let n=this.findStateRow(t,e);return n?Nn(n):void 0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to read task log state",n)}finally{t.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,t){return qo(t),this.readLogsInternal(e,t)}readTail(e,t){return this.readLogsTail(e,t)}readLogsInternal(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let a=Nn(s);if(a.source==="blob"){let p=xn(e,s.logs);return {...a,entries:t===void 0?p:p.slice(Math.max(0,p.length-t))}}let c=o.select({seq:ue.seq,timestamp:ue.timestamp,level:ue.level,message:ue.message}).from(ue).where(drizzleOrm.eq(ue.task_id,e)).orderBy(t===void 0?drizzleOrm.asc(ue.seq):drizzleOrm.desc(ue.seq)),l=(t===void 0?c.all():c.limit(t).all()).map(({timestamp:p,level:_,message:g})=>({timestamp:p,level:_,message:g}));return t!==void 0&&l.reverse(),{...a,entries:l}},{behavior:"deferred"})}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to read task logs",o)}finally{n.close();}}};var vt=40,ve="2026-05-09",Wo="0.8.9-rc.13",xe=10,Ne=parseInt(Wo.split("rc.")[1]);function In(){let r=drizzleOrm.sql`
12
+ LIMIT ${t.limit} OFFSET ${t.offset}`),total:o?.count??0}}catch(o){throw new d("DB_ERROR","Failed to find threads by project",o)}finally{n.close();}}findBySlug(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(w).where(drizzleOrm.eq(w.slug,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find workspace by slug",n)}finally{t.close();}}slugExists(e,t){if(!this.dbExists())return false;let n=this.openHandle(false);try{let o=t?drizzleOrm.and(drizzleOrm.eq(w.slug,e),drizzleOrm.ne(w.id,t)):drizzleOrm.eq(w.slug,e);return !!n.db.select({id:w.id}).from(w).where(o).limit(1).get()}catch(o){throw new d("DB_ERROR","Failed to check slug",o)}finally{n.close();}}insert(e,t,n,o){let s=this.openHandle(true);try{let a=new Date().toISOString();s.db.insert(w).values({id:e,slug:t,name:n,workspace_path:o,is_active:1,created_at:a,updated_at:a}).run();let c=s.db.select().from(w).where(drizzleOrm.eq(w.id,e)).limit(1).get();if(!c)throw new d("DB_ERROR","Insert did not return a row");return c}catch(a){throw a instanceof d?a:new d("DB_ERROR","Failed to insert workspace",a)}finally{s.close();}}update(e,t,n){let o=this.openHandle(true);try{o.runRaw(`UPDATE workspaces SET ${t.join(", ")} WHERE id = ?`,n);let s=o.db.select().from(w).where(drizzleOrm.eq(w.id,e)).limit(1).get();if(!s)throw new d("NOT_FOUND",`Workspace ${e} not found`);return s}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update workspace",s)}finally{o.close();}}cleanupOrphanWorkspaces(){if(!this.dbExists())return {softDeleted:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:w.id,workspace_path:w.workspace_path}).from(w).where(drizzleOrm.and(drizzleOrm.eq(w.is_active,1),drizzleOrm.isNotNull(w.workspace_path))).all(),n=0;for(let o of t){let s=o.workspace_path;Qn.existsSync(Re.join(s,"crewx.yaml"))||Qn.existsSync(Re.join(s,"crewx.yml"))||(e.db.update(w).set({is_active:0,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(w.id,o.id)).run(),n+=1);}return {softDeleted:n,checked:t.length}}catch(t){throw new d("DB_ERROR","Failed to cleanup orphan workspaces",t)}finally{e.close();}}delete(e){let t=this.openHandle(true);try{t.db.run(drizzleOrm.sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${e}`),t.db.delete(w).where(drizzleOrm.eq(w.id,e)).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to delete workspace",n)}finally{t.close();}}};var Fn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ss(r){let e=crypto.randomBytes(r*2),t="";for(let n=0;n<e.length&&t.length<r;n++){let o=e[n];o<248&&(t+=Fn[o%62]);}for(;t.length<r;)t+=Fn[crypto.randomBytes(1)[0]%62];return t}function je(r){return `${r}_${ss(8)}`}var Kt=["outcome_plan","contract_check","feature_link","use_verify","result_review"],ps=new Set(Kt),Kn=Object.freeze(Kt.map(r=>({key:r,labelOverride:null}))),_s=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),fs=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),gs=new Set(["pending","verifying","passed","failed"]),ms=new Set(["user","project_manager","system"]),hs=new Set(["task","wi","url"]),ws=/^\d{4}-\d{2}-\d{2}$/;function L(r){throw new d("VALIDATION",r)}function ce(r){throw new d("NOT_FOUND",r)}function F(r,e){(typeof r!="string"||r.trim().length===0)&&L(`${e} is required`);}function ks(r){if(r==null)return;ws.test(r)||L("dueDate must use YYYY-MM-DD");let e=new Date(`${r}T00:00:00.000Z`);(Number.isNaN(e.getTime())||e.toISOString().slice(0,10)!==r)&&L("dueDate must be a valid calendar date");}function Jn(r){let e=r??Kn;(!Array.isArray(e)||e.length===0)&&L("stages must contain at least one stage");let t=new Set;return e.map(n=>{(!n||typeof n!="object"||Array.isArray(n))&&L("stage must be an object");let o=n;return F(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&L("stage.labelOverride must be a string or null"),o.labelOverride!==null&&F(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&L("stage.key is required"),!ps.has(o.key)&&o.labelOverride===null&&L(`custom stage requires a labelOverride: ${o.key}`),t.has(o.key)&&L(`duplicate stage key: ${o.key}`),t.add(o.key),{key:o.key,labelOverride:o.labelOverride}})}function ys(r){Array.isArray(r)||L("criteria must be an array");for(let e of r)F(e,"criterion.statement");}function Xe(r={}){let e=r.actorType??"system";ms.has(e)||L(`invalid actorType: ${String(e)}`);let t=r.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&L(`actorId is required for ${e}`),{actorType:e,actorId:t}}function Yn(r,e){let t=r??{};if((t===null||typeof t!="object"||Array.isArray(t))&&L("event payload must be a JSON object"),e==="accepted")for(let n of ["remainingRisks","nextPlan","lessons","evidenceRefs"])(!Object.prototype.hasOwnProperty.call(t,n)||t[n]===void 0)&&L(`accepted payload requires ${n}`);try{return JSON.stringify(t)}catch(n){throw new d("VALIDATION","event payload must be JSON serializable",n)}}function bs(r){return Array.isArray(r)||L("evidence must be an array"),r.map(e=>((!e||typeof e!="object")&&L("evidence item must be an object"),hs.has(e.kind)||L(`invalid evidence kind: ${String(e.kind)}`),F(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&L("evidence.label must be a string"),e.label===void 0?{kind:e.kind,ref:e.ref}:{kind:e.kind,ref:e.ref,label:e.label}))}function Vn(r){let e;try{e=JSON.parse(r);}catch(t){throw new d("DB_ERROR","Project stages JSON is invalid",t)}try{if(!Array.isArray(e))throw new d("DB_ERROR","Project stages JSON is invalid");return Jn(e)}catch(t){throw new d("DB_ERROR","Project stages JSON is invalid",t)}}function Xn(r){return F(r.projectId,"projectId"),F(r.title,"title"),_s.has(r.type)||L(`invalid project event type: ${String(r.type)}`),{...Xe(r),payloadJson:Yn(r.payload,r.type)}}function Fe(r,e,t){let n=Xn(e);r.select({id:D.id}).from(D).where(drizzleOrm.eq(D.id,e.projectId)).get()||ce(`Project ${e.projectId} not found`);let s=r.select({maxSeq:drizzleOrm.sql`COALESCE(MAX(${_e.seq}), 0)`}).from(_e).where(drizzleOrm.eq(_e.project_id,e.projectId)).get()?.maxSeq??0,a=je("pje");r.insert(_e).values({id:a,project_id:e.projectId,seq:s+1,actor_type:n.actorType,actor_id:n.actorId,type:e.type,title:e.title,summary:e.summary??null,payload_json:n.payloadJson,created_at:t}).run();let c=r.select().from(_e).where(drizzleOrm.eq(_e.id,a)).get();if(!c)throw new d("DB_ERROR","Event insert did not return a row");return c}var Vt=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}getDetailFromHandle(e,t){let n=e.db.select().from(D).where(drizzleOrm.eq(D.id,t)).get();if(!n)return;let o=e.db.select().from(ne).where(drizzleOrm.eq(ne.project_id,t)).orderBy(drizzleOrm.asc(ne.position)).all();return {...n,stages:Vn(n.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||ce(`Project ${e} not found`),t}createProject(e){F(e.workspaceId,"workspaceId"),F(e.name,"name"),F(e.outcome,"outcome"),ks(e.dueDate);let t=Jn(e.stages);ys(e.criteria);let n=je("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(a=>{a.insert(D).values({id:n,workspace_id:e.workspaceId,name:e.name,outcome:e.outcome,due_date:e.dueDate??null,scene:"planning",stages_json:JSON.stringify(t),stage_index:1,created_at:o,updated_at:o,accepted_at:null,archived_at:null}).run(),e.criteria.forEach((c,l)=>{a.insert(ne).values({id:je("pjc"),project_id:n,position:l+1,statement:c,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),Fe(a,{projectId:n,actorType:"system",type:"created",title:"Project created",payload:{}},o);});}catch(a){throw a instanceof d?a:new d("DB_ERROR","Failed to create project",a)}finally{s.close();}return this.getDetailOrThrow(n)}getProject(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return this.getDetailFromHandle(t,e)}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to get project",n)}finally{t.close();}}listProjectsByWorkspace(e,t={}){if(F(e,"workspaceId"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=t.includeArchived?drizzleOrm.eq(D.workspace_id,e):drizzleOrm.and(drizzleOrm.eq(D.workspace_id,e),drizzleOrm.isNull(D.archived_at));return n.db.select({id:D.id}).from(D).where(o).orderBy(drizzleOrm.desc(D.updated_at),drizzleOrm.desc(D.created_at)).all().map(a=>this.getDetailFromHandle(n,a.id)).filter(a=>a!==void 0)}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to list projects",o)}finally{n.close();}}archiveProject(e){F(e,"projectId");let t=this.openHandle(true);try{t.db.update(D).set({archived_at:new Date().toISOString()}).where(drizzleOrm.eq(D.id,e)).run().changes===0&&ce(`Project ${e} not found`);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to archive project",n)}finally{t.close();}return this.getDetailOrThrow(e)}setScene(e,t,n={}){F(e,"projectId"),fs.has(t)||L(`invalid project scene: ${String(t)}`);let o=Xe(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let l=c.select().from(D).where(drizzleOrm.eq(D.id,e)).get();l||ce(`Project ${e} not found`),c.update(D).set({scene:t,updated_at:s}).where(drizzleOrm.eq(D.id,e)).run(),Fe(c,{projectId:e,...o,type:"scene_changed",title:"Project scene changed",payload:{before:l.scene,after:t}},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to set project scene",c)}finally{a.close();}return this.getDetailOrThrow(e)}setStageIndex(e,t,n={}){F(e,"projectId"),Number.isInteger(t)||L("stage index must be an integer");let o=Xe(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let l=c.select().from(D).where(drizzleOrm.eq(D.id,e)).get();l||ce(`Project ${e} not found`);let u=Vn(l.stages_json);(t<1||t>u.length)&&L("stage index is outside the project stages"),c.update(D).set({stage_index:t,updated_at:s}).where(drizzleOrm.eq(D.id,e)).run(),Fe(c,{projectId:e,...o,type:"stage_advanced",title:"Project stage advanced",payload:{before:l.stage_index,after:t}},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to set project stage",c)}finally{a.close();}return this.getDetailOrThrow(e)}setCriterionVerify(e,t,n,o={}){let s=typeof e=="string"?{projectId:typeof n=="string"?e:void 0,criterionId:typeof n=="string"?t:e,verifyStatus:typeof n=="string"?n:t,...typeof n=="string"?o:n}:e,a=s.verifyStatus??s.status;(!a||!gs.has(a))&&L(`invalid criterion status: ${String(a)}`),F(s.criterionId,"criterionId");let c=Xe(s),l=new Date().toISOString(),u=this.openHandle(true),p;try{u.db.transaction(g=>{let h=g.select().from(ne).where(drizzleOrm.eq(ne.id,s.criterionId)).get();h||ce(`Criterion ${s.criterionId} not found`),p=h.project_id,s.projectId&&s.projectId!==h.project_id&&ce(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(ne).set({verify_status:a,verified_at:a==="passed"?l:null,updated_at:l}).where(drizzleOrm.eq(ne.id,s.criterionId)).run(),Fe(g,{projectId:h.project_id,...c,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:s.criterionId,status:a}},l);});}catch(g){throw g instanceof d?g:new d("DB_ERROR","Failed to set criterion verification",g)}finally{u.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||ce(`Criterion ${s.criterionId} not found`),_}setCriterionEvidence(e,t,n,o={}){let s=typeof e=="string"?{projectId:Array.isArray(n)?e:void 0,criterionId:Array.isArray(n)?t:e,evidence:Array.isArray(n)?n:t,...Array.isArray(n)?o:n}:e;F(s.criterionId,"criterionId");let a=bs(s.evidence),c=Xe(s),l=new Date().toISOString(),u=this.openHandle(true),p;try{u.db.transaction(g=>{let h=g.select().from(ne).where(drizzleOrm.eq(ne.id,s.criterionId)).get();h||ce(`Criterion ${s.criterionId} not found`),p=h.project_id,s.projectId&&s.projectId!==h.project_id&&ce(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(ne).set({evidence_json:JSON.stringify(a),updated_at:l}).where(drizzleOrm.eq(ne.id,s.criterionId)).run(),Fe(g,{projectId:h.project_id,...c,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:s.criterionId,evidence:a}},l);});}catch(g){throw g instanceof d?g:new d("DB_ERROR","Failed to set criterion evidence",g)}finally{u.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||ce(`Criterion ${s.criterionId} not found`),_}appendEvent(e,t){let n=typeof e=="string"?{...t,projectId:e}:e;Xn(n);let o=new Date().toISOString(),s=this.openHandle(true),a;try{s.db.transaction(c=>{a=Fe(c,n,o);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to append project event",c)}finally{s.close();}if(!a)throw new d("DB_ERROR","Event append did not return a row");return a}listEvents(e,t={}){if(F(e,"projectId"),t.afterSeq!==void 0&&(!Number.isInteger(t.afterSeq)||t.afterSeq<0)&&L("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&L("limit must be a positive integer"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=[drizzleOrm.eq(_e.project_id,e)];t.afterSeq!==void 0&&o.push(drizzleOrm.gt(_e.seq,t.afterSeq));let s=n.db.select().from(_e).where(drizzleOrm.and(...o)).orderBy(drizzleOrm.asc(_e.seq));return t.limit!==void 0&&(s=s.limit(t.limit)),s.all()}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to list project events",o)}finally{n.close();}}acceptProject(e,t){F(e,"projectId");let n=Xe(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};Yn(o,"accepted");let s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{c.select({id:D.id}).from(D).where(drizzleOrm.eq(D.id,e)).get()||ce(`Project ${e} not found`),c.update(D).set({scene:"accepted",accepted_at:s,updated_at:s}).where(drizzleOrm.eq(D.id,e)).run(),Fe(c,{projectId:e,...n,type:"accepted",title:"Project accepted",payload:o},s);});}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to accept project",c)}finally{a.close();}return this.getDetailOrThrow(e)}};var er=[w,i,f,Se,ge,de,Ke];function Ts(){return Re__namespace.default.join(Qr__default.default.homedir(),".crewx","crewx.db")}function Ss(r){if(!Qn__namespace.default.existsSync(r))return null;let e=Math.floor(Date.now()/1e3),t=`${r}.bak-${e}`;return Qn__namespace.default.copyFileSync(r,t),t}function tr(r){let e=r.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(e.map(t=>t.name))}function Cs(r){return r==null||typeof r=="object"&&"queryChunks"in r?null:typeof r=="number"?String(r):typeof r=="boolean"?r?"1":"0":typeof r=="string"?`'${r.replace(/'/g,"''")}'`:String(r)}function vs(r){let e=r.getSQLType(),t=`"${r.name}" ${e}`,n=Cs(r.default);return n!==null&&(t+=` DEFAULT ${n}`),r.notNull&&(t+=" NOT NULL"),t}function Ds(r,e){let t=e?.dbPath??Ts(),n=e?.force??false,o=e?.dryRun??false,s=o?null:Ss(t);if(n&&!o)try{r.run("DELETE FROM __drizzle_migrations");}catch{}let a=tr(r);if(!o)try{Ge(r);}catch(_){let g=_ instanceof Error?`${_.message} ${_.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw _}let c,l;o?(c=er.map(g=>sqliteCore.getTableConfig(g).name).filter(g=>!a.has(g)),l=a):(l=tr(r),c=[...l].filter(_=>!a.has(_)));let u=[],p=[];for(let _ of er){let g=sqliteCore.getTableConfig(_),h=g.name;if(!l.has(h))continue;let j=r.all(`PRAGMA table_info("${h}")`),k=new Set(j.map(S=>S.name)),$=new Set(g.columns.map(S=>S.name));for(let S of g.columns)if(!k.has(S.name)){if(!o){let K=vs(S);r.run(`ALTER TABLE "${h}" ADD COLUMN ${K}`);}u.push({table:h,column:S.name});}for(let S of j)$.has(S.name)||p.push(`${h}.${S.name} exists in DB but not in schema (untouched)`);}return {created:c,altered:u,warnings:p,backupPath:s}}function nr(r){let e=r.toLowerCase().trim();e=e.replace(/\[[^\]]*\]$/g,"");let t=e.lastIndexOf("/");return t>=0&&(e=e.slice(t+1)),e=e.replace(/-\d{8}$/,""),e}function ar(r,e){let t=e===void 0?"":` at index ${e}`;if(!r||typeof r!="object")throw new d("VALIDATION",`Task log entry${t} must be an object`);if(typeof r.timestamp!="string"||typeof r.level!="string"||typeof r.message!="string")throw new d("VALIDATION",`Task log entry${t} must contain string timestamp, level, and message fields`);return {timestamp:r.timestamp,level:r.level,message:r.message}}function sr(r,e){if(e===null||e.trim()==="")return [];let t;try{t=JSON.parse(e);}catch(n){throw new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n)}if(!Array.isArray(t))throw new d("DB_ERROR",`Malformed legacy task logs: ${r} (expected an array)`);try{return t.map((n,o)=>ar(n,o))}catch(n){throw n instanceof d?new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n):n}}function dr(r){if(r.log_storage!=="blob"&&r.log_storage!=="events")throw new d("DB_ERROR",`Invalid task log storage for task: ${r.id}`);if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new d("DB_ERROR",`Invalid task log sequence for task: ${r.id}`);if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new d("DB_ERROR",`Invalid task log revision for task: ${r.id}`);return r.log_storage}function ir(r){return {taskId:r.id,source:dr(r),revision:r.log_revision,lastSeq:r.last_log_seq}}function js(r){if(!Number.isInteger(r)||r<0)throw new d("VALIDATION","Task log tail limit must be a non-negative integer")}var dt=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}findStateRow(e,t){return e.db.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()}findStateRowInTransaction(e,t){return e.select({id:i.id,log_storage:i.log_storage,last_log_seq:i.last_log_seq,log_revision:i.log_revision,logs:i.logs}).from(i).where(drizzleOrm.eq(i.id,t)).limit(1).get()}requireStateRowInTransaction(e,t){let n=this.findStateRowInTransaction(e,t);if(!n)throw new d("NOT_FOUND",`Task not found: ${t}`);return n}appendLog(e,t){return this.appendLogs(e,[t])}appendLogs(e,t){let n=t.map((s,a)=>ar(s,a));if(n.length===0){let s=this.getLogState(e);if(!s)throw new d("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(a=>{let c=this.requireStateRowInTransaction(a,e),l=dr(c);if(l==="blob"){let g=sr(e,c.logs);if(a.update(i).set({logs:JSON.stringify([...g,...n]),log_revision:drizzleOrm.sql`${i.log_revision} + 1`}).where(drizzleOrm.eq(i.id,e)).run().changes!==1)throw new d("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:c.log_revision+1,lastSeq:c.last_log_seq}}let u=c.last_log_seq+1,p=c.last_log_seq+n.length;if(a.insert(fe).values(n.map((g,h)=>({task_id:e,seq:u+h,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),a.update(i).set({last_log_seq:p,log_revision:drizzleOrm.sql`${i.log_revision} + 1`}).where(drizzleOrm.eq(i.id,e)).run().changes!==1)throw new d("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:c.log_revision+1,lastSeq:p}},{behavior:"immediate"})}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let t=this.openHandle(false);try{let n=this.findStateRow(t,e);return n?ir(n):void 0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to read task log state",n)}finally{t.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,t){return js(t),this.readLogsInternal(e,t)}readTail(e,t){return this.readLogsTail(e,t)}readLogsInternal(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let a=ir(s);if(a.source==="blob"){let p=sr(e,s.logs);return {...a,entries:t===void 0?p:p.slice(Math.max(0,p.length-t))}}let c=o.select({seq:fe.seq,timestamp:fe.timestamp,level:fe.level,message:fe.message}).from(fe).where(drizzleOrm.eq(fe.task_id,e)).orderBy(t===void 0?drizzleOrm.asc(fe.seq):drizzleOrm.desc(fe.seq)),u=(t===void 0?c.all():c.limit(t).all()).map(({timestamp:p,level:_,message:g})=>({timestamp:p,level:_,message:g}));return t!==void 0&&u.reverse(),{...a,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to read task logs",o)}finally{n.close();}}};var Yt=40,Oe="2026-05-09",Fs="0.8.9-rc.13",Ne=10,Ae=parseInt(Fs.split("rc.")[1]);function cr(){let r=drizzleOrm.sql`
13
13
  CASE
14
14
  WHEN ${i.model} LIKE 'claude-%' OR ${i.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
15
15
  WHEN ${i.model} LIKE 'gpt-%' OR ${i.model} LIKE 'codex-%' THEN 'codex'
@@ -38,7 +38,7 @@ ${n.join(`
38
38
  WHEN trim(${o}) = '' THEN 'unknown'
39
39
  ELSE ${o}
40
40
  END
41
- `}var Ko=new Set(["workflow","mcp"]),Cn=600*1e3,xt=class extends N{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Ve({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}startTask(e){let t=this.openHandle(true);try{let n={id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},o=s=>{t.db.insert(i).values(s).onConflictDoUpdate({target:i.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${i.pid})`},setWhere:drizzleOrm.eq(i.status,"running")}).run();};try{o(n);}catch(s){let a=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage/i.test(a)||!/no such column|no column named/i.test(a))throw s;t.runRaw(`INSERT INTO tasks (
41
+ `}var Hs=new Set(["workflow","mcp"]),lr=600*1e3,Xt=class extends v{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new dt({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}startTask(e){let t=this.openHandle(true);try{let n={id:e.id,agent_id:e.agentId,prompt:e.prompt,mode:e.mode,status:e.status,started_at:e.startedAt,pid:e.pid??null,parent_task_id:e.parentTaskId??null,caller_agent_id:e.callerAgentId??null,trace_id:e.traceId??null,command:e.command??null,metadata:e.metadata??null,workspace_id:e.workspaceId??null,project_id:e.projectId??null,platform:e.platform??"cli",crewx_version:e.crewxVersion??null,thread_id:e.threadId??null,model:e.model??null,rendered_prompt:e.renderedPrompt??null,coding_agent_command:e.codingAgentCommand??null,log_storage:"events"},o=s=>{t.db.insert(i).values(s).onConflictDoUpdate({target:i.id,set:{pid:drizzleOrm.sql`COALESCE(excluded.pid, ${i.pid})`},setWhere:drizzleOrm.eq(i.status,"running")}).run();};try{o(n);}catch(s){let a=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage/i.test(a)||!/no such column|no column named/i.test(a))throw s;t.runRaw(`INSERT INTO tasks (
42
42
  id, agent_id, prompt, mode, status, started_at, pid,
43
43
  parent_task_id, caller_agent_id, trace_id, command, metadata,
44
44
  workspace_id, project_id, platform, crewx_version, thread_id,
@@ -48,7 +48,7 @@ ${n.join(`
48
48
  WHERE tasks.status = 'running'`,[n.id,n.agent_id,n.prompt,n.mode,n.status,n.started_at,n.pid,n.parent_task_id,n.caller_agent_id,n.trace_id,n.command,n.metadata,n.workspace_id,n.project_id,n.platform,n.crewx_version,n.thread_id,n.model,n.rendered_prompt,n.coding_agent_command]);}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to start task",n)}finally{t.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.project_id,e)).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to list tasks by project",n)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{let n=e.runEpoch??null;t.runRaw(`UPDATE tasks SET status=?, result=?, error=?, completed_at=?, duration_ms=?,
49
49
  exit_code=?, input_tokens=?, output_tokens=?, cached_input_tokens=?, cost_usd=?,
50
50
  model=COALESCE(?, model)
51
- WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{t.close();}}appendLog(e,t){this.taskLogRepository.appendLog(e,t);}appendLogs(e,t){this.taskLogRepository.appendLogs(e,t);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,t){return this.taskLogRepository.readLogsTail(e,t)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(t){throw new d("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(t){throw new d("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let n=t.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,e)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return t.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:i.id,pid:i.pid,platform:i.platform,run_epoch:i.run_epoch}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=Date.now(),o=new Set,s=0;for(let a of t){if(a.pid){let l=!1;try{process.kill(a.pid,0),l=!0;}catch{}l||(e.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,a.id),drizzleOrm.eq(i.status,"running"))).run(),s++);continue}if(Ko.has(a.platform??"cli"))continue;let c=`${a.id}:${a.run_epoch??0}`;o.add(c);let u=this.pidNullObservedSince.get(c);if(u===void 0){this.pidNullObservedSince.set(c,n);continue}n-u>=Cn&&(e.db.update(i).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,a.id),drizzleOrm.eq(i.status,"running"))).run(),s++,this.pidNullObservedSince.delete(c));}for(let a of Array.from(this.pidNullObservedSince.keys()))o.has(a)||this.pidNullObservedSince.delete(a);return s}finally{e.close();}}reapRunningWorkflowTasks(e=Cn){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=new Date(Date.now()-e).toISOString();return t.db.update(i).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.platform,"workflow"),drizzleOrm.isNull(i.pid),drizzleOrm.lt(i.started_at,n),drizzleOrm.or(drizzleOrm.isNull(i.metadata),drizzleOrm.and(drizzleOrm.notLike(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{t.close();}}findTaskStatus(e,t){let n=this.resolveDbPaths();for(let o of n){if(!yn.existsSync(o))continue;let s=k(o);try{let a=t?drizzleOrm.eq(i.workspace_id,t):void 0,c=a?drizzleOrm.and(drizzleOrm.eq(i.id,e),a):drizzleOrm.eq(i.id,e),u=s.db.select().from(i).where(c).limit(1).get()??void 0;if(!u){let l=drizzleOrm.or(drizzleOrm.eq(i.thread_id,e),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${e}%`))),p=a?drizzleOrm.and(l,a):l;u=s.db.select().from(i).where(p).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(u)return u}catch(a){throw new d("DB_ERROR","Failed to find task status",a)}finally{s.close();}}}findChildTasks(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!yn.existsSync(a))continue;let c=k(a);try{let u=t?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,e),drizzleOrm.eq(i.workspace_id,t)):drizzleOrm.eq(i.parent_task_id,e),l=c.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(u){throw new d("DB_ERROR","Failed to find child tasks",u)}finally{c.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?drizzleOrm.sql`
51
+ WHERE id=? AND status='running' AND COALESCE(run_epoch, 0) = COALESCE(?, 0)`,[e.status,e.result??null,e.error??null,e.completedAt,e.durationMs??null,e.exitCode??null,e.inputTokens??0,e.outputTokens??0,e.cachedInputTokens??0,e.costUsd??0,e.model??null,e.id,n]);}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to finish task",n)}finally{t.close();}}appendLog(e,t){this.taskLogRepository.appendLog(e,t);}appendLogs(e,t){this.taskLogRepository.appendLogs(e,t);}readLogs(e){return this.taskLogRepository.readLogs(e)}readLogsTail(e,t){return this.taskLogRepository.readLogsTail(e,t)}getLogState(e){return this.taskLogRepository.getLogState(e)}getRunningTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(i).where(drizzleOrm.eq(i.status,"running")).orderBy(drizzleOrm.desc(i.started_at)).all()}catch(t){throw new d("DB_ERROR","Failed to get running tasks",t)}finally{e.close();}}getAllTasks(){if(!this.dbExists())return [];let e=this.openHandle(false);try{return e.db.select().from(i).orderBy(drizzleOrm.desc(i.started_at)).limit(100).all()}catch(t){throw new d("DB_ERROR","Failed to get all tasks",t)}finally{e.close();}}getTask(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(i).where(drizzleOrm.eq(i.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to get task",n)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let n=t.db.select({id:i.id,status:i.status,pid:i.pid}).from(i).where(drizzleOrm.eq(i.id,e)).limit(1).get();if(!n||n.status!=="running")return {killed:!1};if(n.pid)try{process.kill(n.pid,"SIGTERM");}catch{}return t.db.update(i).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.status,"running"))).run(),{killed:!0,pid:n.pid??void 0}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to kill task",n)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:i.id,pid:i.pid,platform:i.platform,run_epoch:i.run_epoch}).from(i).where(drizzleOrm.eq(i.status,"running")).all(),n=Date.now(),o=new Set,s=0;for(let a of t){if(a.pid){let u=!1;try{process.kill(a.pid,0),u=!0;}catch{}u||(e.db.update(i).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,a.id),drizzleOrm.eq(i.status,"running"))).run(),s++);continue}if(Hs.has(a.platform??"cli"))continue;let c=`${a.id}:${a.run_epoch??0}`;o.add(c);let l=this.pidNullObservedSince.get(c);if(l===void 0){this.pidNullObservedSince.set(c,n);continue}n-l>=lr&&(e.db.update(i).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.id,a.id),drizzleOrm.eq(i.status,"running"))).run(),s++,this.pidNullObservedSince.delete(c));}for(let a of Array.from(this.pidNullObservedSince.keys()))o.has(a)||this.pidNullObservedSince.delete(a);return s}finally{e.close();}}reapRunningWorkflowTasks(e=lr){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let n=new Date(Date.now()-e).toISOString();return t.db.update(i).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(drizzleOrm.and(drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.platform,"workflow"),drizzleOrm.isNull(i.pid),drizzleOrm.lt(i.started_at,n),drizzleOrm.or(drizzleOrm.isNull(i.metadata),drizzleOrm.and(drizzleOrm.notLike(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{t.close();}}findTaskStatus(e,t){let n=this.resolveDbPaths();for(let o of n){if(!Qn.existsSync(o))continue;let s=y(o);try{let a=t?drizzleOrm.eq(i.workspace_id,t):void 0,c=a?drizzleOrm.and(drizzleOrm.eq(i.id,e),a):drizzleOrm.eq(i.id,e),l=s.db.select().from(i).where(c).limit(1).get()??void 0;if(!l){let u=a?drizzleOrm.and(drizzleOrm.eq(i.thread_id,e),a):drizzleOrm.eq(i.thread_id,e);l=s.db.select().from(i).where(u).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??void 0;}if(l)return l}catch(a){throw new d("DB_ERROR","Failed to find task status",a)}finally{s.close();}}}findChildTasks(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!Qn.existsSync(a))continue;let c=y(a);try{let l=t?drizzleOrm.and(drizzleOrm.eq(i.parent_task_id,e),drizzleOrm.eq(i.workspace_id,t)):drizzleOrm.eq(i.parent_task_id,e),u=c.db.select().from(i).where(l).orderBy(drizzleOrm.asc(i.started_at)).all();for(let p of u)o.has(p.id)||(o.add(p.id),s.push(p));}catch(l){throw new d("DB_ERROR","Failed to find child tasks",l)}finally{c.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?drizzleOrm.sql`
52
52
  SELECT
53
53
  COALESCE(workspace_id, 'unknown') AS workspace_id,
54
54
  COALESCE(SUM(input_tokens), 0) AS input_tokens,
@@ -69,7 +69,7 @@ ${n.join(`
69
69
  FROM tasks
70
70
  GROUP BY workspace_id
71
71
  ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
72
- `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{t.close();}}getThreadTokenUsage(e,t){let n=this.resolveDbPaths(),o=new Set,s=0,a=0,c=0;for(let u of n){if(!yn.existsSync(u))continue;let l=k(u);try{let p=drizzleOrm.or(drizzleOrm.eq(i.thread_id,e),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${e}%`))),_=t?drizzleOrm.and(p,drizzleOrm.eq(i.workspace_id,t)):p,g=l.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(_).all();for(let m of g)o.has(m.id)||(o.add(m.id),s+=m.input_tokens??0,a+=m.output_tokens??0,c+=m.cost_usd??0);}catch(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{l.close();}}return {inputTokens:s,outputTokens:a,costUsd:c}}findTasksByThread(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!yn.existsSync(a))continue;let c=k(a);try{let u=drizzleOrm.or(drizzleOrm.eq(i.thread_id,e),drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.like(i.command,`%--thread=${e}%`))),l=t?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,t)):u,p=c.db.select().from(i).where(l).orderBy(drizzleOrm.asc(i.started_at)).all();for(let _ of p)o.has(_.id)||(o.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find tasks by thread",u)}finally{c.close();}}return s}parseWorkflowCardMetadata(e){if(!e)return {};try{let t=JSON.parse(e);return {kind:typeof t.kind=="string"?t.kind:void 0,workflowRunId:typeof t.workflowRunId=="string"?t.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let t of this.resolveDbPaths()){if(!yn.existsSync(t))continue;let n=k(t);try{e.push(...n.db.select({id:i.id,agent_id:i.agent_id,thread_id:i.thread_id,workspace_id:i.workspace_id,platform:i.platform,status:i.status,error:i.error,completed_at:i.completed_at,duration_ms:i.duration_ms,started_at:i.started_at,metadata:i.metadata}).from(i).where(drizzleOrm.and(drizzleOrm.eq(i.platform,"workflow"),drizzleOrm.or(drizzleOrm.like(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(i.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(drizzleOrm.desc(i.started_at)).all());}catch(o){throw new d("DB_ERROR","Failed to find workflow parent tasks",o)}finally{n.close();}}return e}batchFetchWorkflowCards(e,t){let n=new Map;if(e.length===0)return n;let o=new Set(e),s=new Map,a=t?drizzleOrm.eq(i.workspace_id,t):void 0,c=(u,l)=>{if(!u)return;let p=s.get(u);if(p&&l.started_at<=p)return;let _=this.parseWorkflowCardMetadata(l.metadata);_.kind!=="workflow_card"&&_.kind!=="workflow_ui_instance"||(s.set(u,l.started_at),n.set(u,{taskId:l.id,workflowRunId:_.workflowRunId,raw:l.result??void 0}));};for(let u of this.resolveDbPaths()){if(!yn.existsSync(u))continue;let l=k(u);try{let p=drizzleOrm.and(drizzleOrm.inArray(i.thread_id,e),drizzleOrm.or(drizzleOrm.like(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(i.metadata,'%"kind":"workflow_ui_instance"%'))),_=l.db.select({id:i.id,thread_id:i.thread_id,metadata:i.metadata,result:i.result,started_at:i.started_at}).from(i).where(a?drizzleOrm.and(p,a):p).all();for(let P of _)c(P.thread_id,P);let g=drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.or(drizzleOrm.like(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(i.metadata,'%"kind":"workflow_ui_instance"%'))),m=l.db.select({id:i.id,command:i.command,metadata:i.metadata,result:i.result,started_at:i.started_at}).from(i).where(a?drizzleOrm.and(g,a):g).all();for(let P of m){let w=this.extractThreadIdFromCommand(P.command);!w||!o.has(w)||c(w,P);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{l.close();}}return n}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let n=[];e.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&n.push(drizzleOrm.inArray(i.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&n.push(drizzleOrm.inArray(i.status,s));let a=e.q??e.search;a&&n.push(drizzleOrm.like(i.prompt,`%${a}%`)),e.from&&n.push(drizzleOrm.gte(i.started_at,e.from)),e.to&&n.push(drizzleOrm.lt(i.started_at,e.to));let c=n.length>0?drizzleOrm.and(...n):void 0,u=t.db.select({count:drizzleOrm.sql`count(*)`}).from(i).where(c).get(),l=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at);return {rows:t.db.select().from(i).where(c).orderBy(l).limit(e.limit).offset(e.offset).all(),total:u?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{t.close();}}getAgentUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(n?drizzleOrm.sql`
72
+ `)}catch(n){throw new d("DB_ERROR","Failed to get workspace usage summary",n)}finally{t.close();}}getThreadTokenUsage(e,t){let n=this.resolveDbPaths(),o=new Set,s=0,a=0,c=0;for(let l of n){if(!Qn.existsSync(l))continue;let u=y(l);try{let p=drizzleOrm.eq(i.thread_id,e),_=t?drizzleOrm.and(p,drizzleOrm.eq(i.workspace_id,t)):p,g=u.db.select({id:i.id,input_tokens:i.input_tokens,output_tokens:i.output_tokens,cost_usd:i.cost_usd}).from(i).where(_).all();for(let h of g)o.has(h.id)||(o.add(h.id),s+=h.input_tokens??0,a+=h.output_tokens??0,c+=h.cost_usd??0);}catch(p){throw new d("DB_ERROR","Failed to get thread token usage",p)}finally{u.close();}}return {inputTokens:s,outputTokens:a,costUsd:c}}findTasksByThread(e,t,n){let o=this.resolveDbPaths(),s=new Set,a=[],c=n?.projection==="activity-log";for(let l of o){if(!Qn.existsSync(l))continue;let u=y(l);try{let p=drizzleOrm.eq(i.thread_id,e),_=t?drizzleOrm.and(p,drizzleOrm.eq(i.workspace_id,t)):p,g=c?u.db.select({id:i.id,thread_id:i.thread_id,agent_id:i.agent_id,parent_task_id:i.parent_task_id,started_at:i.started_at,completed_at:i.completed_at}).from(i).where(_).orderBy(drizzleOrm.asc(i.started_at)).all():u.db.select().from(i).where(_).orderBy(drizzleOrm.asc(i.started_at)).all();for(let h of g)s.has(h.id)||(s.add(h.id),a.push(h));}catch(p){throw new d("DB_ERROR","Failed to find tasks by thread",p)}finally{u.close();}}return a}parseWorkflowCardMetadata(e){if(!e)return {};try{let t=JSON.parse(e);return {kind:typeof t.kind=="string"?t.kind:void 0,workflowRunId:typeof t.workflowRunId=="string"?t.workflowRunId:void 0}}catch{return {}}}extractThreadIdFromCommand(e){return e?/--thread=(\S+)/.exec(e)?.[1]??null:null}findRunningWorkflowParentTasks(){if(!this.dbExists())return [];let e=[];for(let t of this.resolveDbPaths()){if(!Qn.existsSync(t))continue;let n=y(t);try{e.push(...n.db.select({id:i.id,agent_id:i.agent_id,thread_id:i.thread_id,workspace_id:i.workspace_id,platform:i.platform,status:i.status,error:i.error,completed_at:i.completed_at,duration_ms:i.duration_ms,started_at:i.started_at,metadata:i.metadata}).from(i).where(drizzleOrm.and(drizzleOrm.eq(i.platform,"workflow"),drizzleOrm.or(drizzleOrm.like(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(i.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(drizzleOrm.desc(i.started_at)).all());}catch(o){throw new d("DB_ERROR","Failed to find workflow parent tasks",o)}finally{n.close();}}return e}batchFetchWorkflowCards(e,t){let n=new Map;if(e.length===0)return n;let o=new Set(e),s=new Map,a=t?drizzleOrm.eq(i.workspace_id,t):void 0,c=(l,u)=>{if(!l)return;let p=s.get(l);if(p&&u.started_at<=p)return;let _=this.parseWorkflowCardMetadata(u.metadata);_.kind!=="workflow_card"&&_.kind!=="workflow_ui_instance"||(s.set(l,u.started_at),n.set(l,{taskId:u.id,workflowRunId:_.workflowRunId,raw:u.result??void 0}));};for(let l of this.resolveDbPaths()){if(!Qn.existsSync(l))continue;let u=y(l);try{let p=drizzleOrm.and(drizzleOrm.inArray(i.thread_id,e),drizzleOrm.or(drizzleOrm.like(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(i.metadata,'%"kind":"workflow_ui_instance"%'))),_=u.db.select({id:i.id,thread_id:i.thread_id,metadata:i.metadata,result:i.result,started_at:i.started_at}).from(i).where(a?drizzleOrm.and(p,a):p).all();for(let j of _)c(j.thread_id,j);let g=drizzleOrm.and(drizzleOrm.isNull(i.thread_id),drizzleOrm.or(drizzleOrm.like(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.like(i.metadata,'%"kind":"workflow_ui_instance"%'))),h=u.db.select({id:i.id,command:i.command,metadata:i.metadata,result:i.result,started_at:i.started_at}).from(i).where(a?drizzleOrm.and(g,a):g).all();for(let j of h){let k=this.extractThreadIdFromCommand(j.command);!k||!o.has(k)||c(k,j);}}catch(p){throw new d("DB_ERROR","Failed to batch fetch workflow cards",p)}finally{u.close();}}return n}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let n=[];e.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&n.push(drizzleOrm.inArray(i.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&n.push(drizzleOrm.inArray(i.status,s));let a=e.q??e.search;a&&n.push(drizzleOrm.like(i.prompt,`%${a}%`)),e.from&&n.push(drizzleOrm.gte(i.started_at,e.from)),e.to&&n.push(drizzleOrm.lt(i.started_at,e.to));let c=n.length>0?drizzleOrm.and(...n):void 0,l=t.db.select({count:drizzleOrm.sql`count(*)`}).from(i).where(c).get(),u=(e.sortDir??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at);return {rows:t.db.select().from(i).where(c).orderBy(u).limit(e.limit).offset(e.offset).all(),total:l?.count??0}}catch(n){throw new d("DB_ERROR","Failed to find all tasks",n)}finally{t.close();}}getAgentUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(n?drizzleOrm.sql`
73
73
  SELECT
74
74
  t.agent_id,
75
75
  t.workspace_id,
@@ -77,11 +77,11 @@ ${n.join(`
77
77
  COALESCE(SUM(
78
78
  COALESCE(t.input_tokens, 0)
79
79
  + CASE
80
- WHEN t.started_at >= ${ve}
80
+ WHEN t.started_at >= ${Oe}
81
81
  AND (
82
82
  t.crewx_version IS NULL
83
83
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
84
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${xe}) AS INTEGER) < ${Ne})
84
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ne}) AS INTEGER) < ${Ae})
85
85
  )
86
86
  THEN COALESCE(t.cached_input_tokens, 0)
87
87
  ELSE 0
@@ -100,11 +100,11 @@ ${n.join(`
100
100
  COALESCE(SUM(
101
101
  COALESCE(t.input_tokens, 0)
102
102
  + CASE
103
- WHEN t.started_at >= ${ve}
103
+ WHEN t.started_at >= ${Oe}
104
104
  AND (
105
105
  t.crewx_version IS NULL
106
106
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
107
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${xe}) AS INTEGER) < ${Ne})
107
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ne}) AS INTEGER) < ${Ae})
108
108
  )
109
109
  THEN COALESCE(t.cached_input_tokens, 0)
110
110
  ELSE 0
@@ -120,11 +120,11 @@ ${n.join(`
120
120
  COALESCE(SUM(
121
121
  COALESCE(t.input_tokens, 0)
122
122
  + CASE
123
- WHEN t.started_at >= ${ve}
123
+ WHEN t.started_at >= ${Oe}
124
124
  AND (
125
125
  t.crewx_version IS NULL
126
126
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
127
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${xe}) AS INTEGER) < ${Ne})
127
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ne}) AS INTEGER) < ${Ae})
128
128
  )
129
129
  THEN COALESCE(t.cached_input_tokens, 0)
130
130
  ELSE 0
@@ -142,11 +142,11 @@ ${n.join(`
142
142
  COALESCE(SUM(
143
143
  COALESCE(t.input_tokens, 0)
144
144
  + CASE
145
- WHEN t.started_at >= ${ve}
145
+ WHEN t.started_at >= ${Oe}
146
146
  AND (
147
147
  t.crewx_version IS NULL
148
148
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
149
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${xe}) AS INTEGER) < ${Ne})
149
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ne}) AS INTEGER) < ${Ae})
150
150
  )
151
151
  THEN COALESCE(t.cached_input_tokens, 0)
152
152
  ELSE 0
@@ -161,11 +161,11 @@ ${n.join(`
161
161
  COALESCE(SUM(
162
162
  COALESCE(t.input_tokens, 0)
163
163
  + CASE
164
- WHEN t.started_at >= ${ve}
164
+ WHEN t.started_at >= ${Oe}
165
165
  AND (
166
166
  t.crewx_version IS NULL
167
167
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
168
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${xe}) AS INTEGER) < ${Ne})
168
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ne}) AS INTEGER) < ${Ae})
169
169
  )
170
170
  THEN COALESCE(t.cached_input_tokens, 0)
171
171
  ELSE 0
@@ -188,11 +188,11 @@ ${n.join(`
188
188
  COALESCE(SUM(
189
189
  COALESCE(t.input_tokens, 0)
190
190
  + CASE
191
- WHEN t.started_at >= ${ve}
191
+ WHEN t.started_at >= ${Oe}
192
192
  AND (
193
193
  t.crewx_version IS NULL
194
194
  OR (t.crewx_version LIKE '0.8.%' AND t.crewx_version NOT LIKE '0.8.9%')
195
- OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${xe}) AS INTEGER) < ${Ne})
195
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ne}) AS INTEGER) < ${Ae})
196
196
  )
197
197
  THEN COALESCE(t.cached_input_tokens, 0)
198
198
  ELSE 0
@@ -207,14 +207,14 @@ ${n.join(`
207
207
  AND t.started_at < ${t}
208
208
  GROUP BY date(t.started_at), t.agent_id
209
209
  ORDER BY date(t.started_at) ASC
210
- `).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.workspace_id,t))).limit(1).get()??void 0}catch(o){throw new d("DB_ERROR","Failed to find task for stop",o)}finally{n.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let t=this.openHandle(false);try{return t.db.select({id:i.id,thread_id:i.thread_id,status:i.status,result:i.result,error:i.error,started_at:i.started_at,completed_at:i.completed_at,metadata:i.metadata}).from(i).where(drizzleOrm.and(drizzleOrm.eq(i.agent_id,e.agentId),drizzleOrm.eq(i.workspace_id,e.workspaceId),drizzleOrm.sql`${i.metadata} IS NOT NULL AND json_valid(${i.metadata}) AND json_extract(${i.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??null}catch(n){throw new d("DB_ERROR","Failed to find latest task by metadata",n)}finally{t.close();}}markTaskFailed(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString(),a=n?drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.status,"running"));o.db.update(i).set({status:"failed",error:t,completed_at:s}).where(a).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{o.close();}}findTasksByPromptHint(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!yn.existsSync(a))continue;let c=k(a);try{let u=t?drizzleOrm.and(drizzleOrm.like(i.prompt,`%${e}%`),drizzleOrm.eq(i.workspace_id,t)):drizzleOrm.like(i.prompt,`%${e}%`),l=c.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let p of l)o.has(p.id)||(o.add(p.id),s.push(p));}catch(u){throw new d("DB_ERROR","Failed to find tasks by prompt hint",u)}finally{c.close();}}return s}getProviderUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=In(),a=drizzleOrm.sql`
210
+ `).map(a=>({date:a.date,agentId:a.agent_id,inputTokens:a.input_tokens,outputTokens:a.output_tokens,cachedInputTokens:a.cached_input_tokens,costUsd:a.cost_usd,totalTokens:a.input_tokens+a.output_tokens}))}catch(s){throw new d("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(i).where(drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.workspace_id,t))).limit(1).get()??void 0}catch(o){throw new d("DB_ERROR","Failed to find task for stop",o)}finally{n.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let t=this.openHandle(false);try{return t.db.select({id:i.id,thread_id:i.thread_id,status:i.status,result:i.result,error:i.error,started_at:i.started_at,completed_at:i.completed_at,metadata:i.metadata}).from(i).where(drizzleOrm.and(drizzleOrm.eq(i.agent_id,e.agentId),drizzleOrm.eq(i.workspace_id,e.workspaceId),drizzleOrm.sql`${i.metadata} IS NOT NULL AND json_valid(${i.metadata}) AND json_extract(${i.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(drizzleOrm.desc(i.started_at)).limit(1).get()??null}catch(n){throw new d("DB_ERROR","Failed to find latest task by metadata",n)}finally{t.close();}}markTaskFailed(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString(),a=n?drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.status,"running"),drizzleOrm.eq(i.workspace_id,n)):drizzleOrm.and(drizzleOrm.eq(i.id,e),drizzleOrm.eq(i.status,"running"));o.db.update(i).set({status:"failed",error:t,completed_at:s}).where(a).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to mark task failed",s)}finally{o.close();}}findTasksByPromptHint(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!Qn.existsSync(a))continue;let c=y(a);try{let l=t?drizzleOrm.and(drizzleOrm.like(i.prompt,`%${e}%`),drizzleOrm.eq(i.workspace_id,t)):drizzleOrm.like(i.prompt,`%${e}%`),u=c.db.select().from(i).where(l).orderBy(drizzleOrm.asc(i.started_at)).all();for(let p of u)o.has(p.id)||(o.add(p.id),s.push(p));}catch(l){throw new d("DB_ERROR","Failed to find tasks by prompt hint",l)}finally{c.close();}}return s}getProviderUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=cr(),a=drizzleOrm.sql`
211
211
  COALESCE(${i.input_tokens}, 0)
212
212
  + CASE
213
- WHEN ${i.started_at} >= ${ve}
213
+ WHEN ${i.started_at} >= ${Oe}
214
214
  AND (
215
215
  ${i.crewx_version} IS NULL
216
216
  OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
217
- OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${xe}) AS INTEGER) < ${Ne})
217
+ OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ne}) AS INTEGER) < ${Ae})
218
218
  )
219
219
  THEN COALESCE(${i.cached_input_tokens}, 0)
220
220
  ELSE 0
@@ -233,19 +233,19 @@ ${n.join(`
233
233
  ${c}
234
234
  GROUP BY ${s}
235
235
  ORDER BY (COALESCE(SUM(${a}), 0) + COALESCE(SUM(${i.output_tokens}), 0)) DESC
236
- `).map(l=>({provider:l.provider,totalTasks:l.total_tasks,inputTokens:l.input_tokens,outputTokens:l.output_tokens,cachedInputTokens:l.cached_input_tokens,costUsd:l.cost_usd,totalTokens:l.input_tokens+l.output_tokens,activeDurationMs:l.active_duration_ms??0,lastActiveAt:l.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=In(),a=drizzleOrm.sql`
236
+ `).map(u=>({provider:u.provider,totalTasks:u.total_tasks,inputTokens:u.input_tokens,outputTokens:u.output_tokens,cachedInputTokens:u.cached_input_tokens,costUsd:u.cost_usd,totalTokens:u.input_tokens+u.output_tokens,activeDurationMs:u.active_duration_ms??0,lastActiveAt:u.last_active_at??null}))}catch(s){throw new d("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=cr(),a=drizzleOrm.sql`
237
237
  COALESCE(${i.input_tokens}, 0)
238
238
  + CASE
239
- WHEN ${i.started_at} >= ${ve}
239
+ WHEN ${i.started_at} >= ${Oe}
240
240
  AND (
241
241
  ${i.crewx_version} IS NULL
242
242
  OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
243
- OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${xe}) AS INTEGER) < ${Ne})
243
+ OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ne}) AS INTEGER) < ${Ae})
244
244
  )
245
245
  THEN COALESCE(${i.cached_input_tokens}, 0)
246
246
  ELSE 0
247
247
  END
248
- `,c=n?drizzleOrm.sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:drizzleOrm.sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`,u=o.db.all(drizzleOrm.sql`
248
+ `,c=n?drizzleOrm.sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:drizzleOrm.sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`,l=o.db.all(drizzleOrm.sql`
249
249
  SELECT
250
250
  ${i.model} AS model,
251
251
  ${s} AS provider,
@@ -259,7 +259,7 @@ ${n.join(`
259
259
  FROM ${i}
260
260
  ${c}
261
261
  GROUP BY ${i.model}, ${s}
262
- `),l=new Map;for(let p of u){let _=Sn(p.model??""),g=JSON.stringify([p.provider,_]),m=l.get(g);m?(m.totalTasks+=p.total_tasks,m.inputTokens+=p.input_tokens,m.outputTokens+=p.output_tokens,m.cachedInputTokens+=p.cached_input_tokens,m.costUsd+=p.cost_usd,m.totalTokens+=p.input_tokens+p.output_tokens,m.activeDurationMs+=p.active_duration_ms??0,p.last_active_at&&(!m.lastActiveAt||p.last_active_at>m.lastActiveAt)&&(m.lastActiveAt=p.last_active_at)):l.set(g,{model:_,provider:p.provider,totalTasks:p.total_tasks,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null});}return Array.from(l.values()).sort((p,_)=>_.costUsd-p.costUsd)}catch(s){throw new d("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=n?drizzleOrm.sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:drizzleOrm.sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`;return o.db.all(drizzleOrm.sql`
262
+ `),u=new Map;for(let p of l){let _=nr(p.model??""),g=JSON.stringify([p.provider,_]),h=u.get(g);h?(h.totalTasks+=p.total_tasks,h.inputTokens+=p.input_tokens,h.outputTokens+=p.output_tokens,h.cachedInputTokens+=p.cached_input_tokens,h.costUsd+=p.cost_usd,h.totalTokens+=p.input_tokens+p.output_tokens,h.activeDurationMs+=p.active_duration_ms??0,p.last_active_at&&(!h.lastActiveAt||p.last_active_at>h.lastActiveAt)&&(h.lastActiveAt=p.last_active_at)):u.set(g,{model:_,provider:p.provider,totalTasks:p.total_tasks,inputTokens:p.input_tokens,outputTokens:p.output_tokens,cachedInputTokens:p.cached_input_tokens,costUsd:p.cost_usd,totalTokens:p.input_tokens+p.output_tokens,activeDurationMs:p.active_duration_ms??0,lastActiveAt:p.last_active_at??null});}return Array.from(u.values()).sort((p,_)=>_.costUsd-p.costUsd)}catch(s){throw new d("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=n?drizzleOrm.sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:drizzleOrm.sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`;return o.db.all(drizzleOrm.sql`
263
263
  SELECT
264
264
  ${i.thread_id} AS thread_id,
265
265
  ${i.agent_id} AS agent_id,
@@ -273,11 +273,11 @@ ${n.join(`
273
273
  `).map(c=>({threadId:c.thread_id,agentId:c.agent_id,startedAt:c.started_at,status:c.status,error:c.error,exitCode:c.exit_code}))}catch(s){throw new d("DB_ERROR","Failed to get tasks for report",s)}finally{o.close();}}getDelegationMatrix(e,t,n){if(!this.dbExists())return {edges:[],truncated:false};let o=this.openHandle(false);try{let s=drizzleOrm.sql`
274
274
  COALESCE(${i.input_tokens}, 0)
275
275
  + CASE
276
- WHEN ${i.started_at} >= ${ve}
276
+ WHEN ${i.started_at} >= ${Oe}
277
277
  AND (
278
278
  ${i.crewx_version} IS NULL
279
279
  OR (${i.crewx_version} LIKE '0.8.%' AND ${i.crewx_version} NOT LIKE '0.8.9%')
280
- OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${xe}) AS INTEGER) < ${Ne})
280
+ OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ne}) AS INTEGER) < ${Ae})
281
281
  )
282
282
  THEN COALESCE(${i.cached_input_tokens}, 0)
283
283
  ELSE 0
@@ -293,27 +293,27 @@ ${n.join(`
293
293
  ${a}
294
294
  GROUP BY ${i.caller_agent_id}, ${i.agent_id}
295
295
  ORDER BY task_count DESC, ${i.caller_agent_id} ASC, ${i.agent_id} ASC
296
- LIMIT ${vt+1}
297
- `),u=c.length>vt;return {edges:c.slice(0,vt).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:u}}catch(s){throw new d("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=[];e.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&n.push(drizzleOrm.inArray(i.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&n.push(drizzleOrm.inArray(i.status,e.statuses)),e.from&&n.push(drizzleOrm.gte(i.started_at,e.from)),e.to&&n.push(drizzleOrm.lt(i.started_at,e.to));let o=n.length>0?drizzleOrm.and(...n):void 0,s=(e.order??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at),a={id:i.id,agent_id:i.agent_id,status:i.status,prompt:i.prompt,started_at:i.started_at,completed_at:i.completed_at,thread_id:i.thread_id};return e.limit?t.db.select(a).from(i).where(o).orderBy(s).limit(e.limit).all():t.db.select(a).from(i).where(o).orderBy(s).all()}catch(n){throw new d("DB_ERROR","Failed to find task evidence",n)}finally{t.close();}}findThreadChains(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[drizzleOrm.isNotNull(i.thread_id),drizzleOrm.isNull(i.parent_task_id),drizzleOrm.isNull(i.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(i.platform),drizzleOrm.ne(i.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(i.metadata),drizzleOrm.and(drizzleOrm.notLike(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))),drizzleOrm.or(drizzleOrm.isNull(i.metadata),drizzleOrm.notLike(i.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(drizzleOrm.eq(i.workspace_id,e.workspaceId)),e.from&&s.push(drizzleOrm.gte(i.started_at,e.from)),e.to&&s.push(drizzleOrm.lt(i.started_at,e.to));let a=t.db.select({id:i.id,agent_id:i.agent_id,status:i.status,prompt:i.prompt,started_at:i.started_at,completed_at:i.completed_at,thread_id:i.thread_id}).from(i).where(drizzleOrm.and(...s)).orderBy(drizzleOrm.asc(i.started_at),drizzleOrm.asc(i.id)).all(),c=new Map;for(let l of a){if(!l.thread_id)continue;let p={id:l.id,agentId:l.agent_id,status:l.status,prompt:l.prompt,startedAt:l.started_at,completedAt:l.completed_at},_=c.get(l.thread_id);_?_.push(p):c.set(l.thread_id,[p]);}let u=[];for(let[l,p]of c){let _=p.filter(g=>g.agentId===e.targetAgentId).length;_<2||u.push({threadId:l,targetAgentTurnCount:_,turns:p});}return u.sort((l,p)=>{let _=l.turns[l.turns.length-1].startedAt,g=p.turns[p.turns.length-1].startedAt;return _<g?1:_>g?-1:0}),u.slice(0,n).map(l=>({threadId:l.threadId,targetAgentTurnCount:l.targetAgentTurnCount,turns:l.turns.slice(-o)}))}catch(n){throw new d("DB_ERROR","Failed to find thread chains",n)}finally{t.close();}}};var $n=["success","failed","completed"],_t=10*1024*1024*1024,jn=256,es=new Set($n),z=class extends Error{constructor(t,n,o="metadata"){super(n);this.taskId=t;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function Bn(r){return r||(process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:ye.join(hr.homedir(),".crewx","crewx.db"))}function ts(){return Be("better-sqlite3")}function qn(r,e){let t=r===":memory:";if(!t&&!yn.existsSync(r))throw new Error(`Database not found: ${r}`);let n=new(ts())(r,{readonly:e,fileMustExist:!t,timeout:5e3});return n.pragma("foreign_keys = ON"),n.pragma("busy_timeout = 5000"),n}function He(r,e,t=[]){return r.prepare(e).all(...t)}function Fe(r,e,t=[]){return r.prepare(e).get(...t)}function ns(r,e,t=[]){return r.prepare(e).run(...t)}function rs(r,e,t=[]){return r.prepare(e).iterate(...t)}function os(r){return typeof r=="string"&&r.length>0?r:"<unknown>"}function Mn(r){return typeof r=="string"&&es.has(r)}function On(r,e){r.set(e,(r.get(e)??0)+1);}function Ln(r){return Object.fromEntries([...r.entries()].sort(([e],[t])=>e.localeCompare(t)))}function ss(r){let e=new Set(He(r,"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('tasks', 'task_log_events')").map(a=>a.name)),t=["tasks","task_log_events"].filter(a=>!e.has(a));if(t.length>0)throw new Error(`Database schema is missing required table(s): ${t.join(", ")}`);let n=new Set(He(r,"PRAGMA table_info('tasks')").map(a=>a.name)),s=["id","status","logs","log_storage","last_log_seq","log_revision"].filter(a=>!n.has(a));if(s.length>0)throw new Error(`Database schema is missing required tasks column(s): ${s.join(", ")}`)}function Un(r,e){if(e==null)return {entries:[]};if(typeof e!="string")throw new z(r,"Malformed task logs: tasks.logs must be JSON text or null","malformed");if(e.trim()==="")return {entries:[]};let t;try{t=JSON.parse(e);}catch(o){let s=o instanceof Error?o.message:String(o);throw new z(r,`Malformed JSON in tasks.logs (${s})`,"malformed")}if(!Array.isArray(t))throw new z(r,"Malformed task logs: expected a JSON array","malformed");let n=[];for(let[o,s]of t.entries()){if(s===null||typeof s!="object"||typeof s.timestamp!="string"||typeof s.level!="string"||typeof s.message!="string")throw new z(r,`Malformed task logs: entry ${o} must contain string timestamp, level, and message fields`,"malformed");let a=s;n.push({timestamp:a.timestamp,level:a.level,message:a.message});}return {entries:n}}function At(r,e){if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new z(r.id,"Invalid last_log_seq metadata","metadata");if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new z(r.id,"Invalid log_revision metadata","metadata");if(e==="blob"&&r.last_log_seq!==0)throw new z(r.id,"Blob source must have last_log_seq=0","metadata")}function is(r){let e=He(r,`SELECT task_id, COUNT(*) AS event_count
298
- FROM task_log_events GROUP BY task_id`);return new Map(e.map(t=>[t.task_id,t.event_count]))}function as(r){let e=is(r),t=new Map,n=[],o=[],s=[],a=new Map,c=new Map,u=0,l=0,p=0,_=0,g=0,m=0;for(let P of rs(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
299
- FROM tasks ORDER BY id`)){let w=P,$=os(w.status);if(On(a,$),t.set(w.id,{id:w.id,status:w.status,log_storage:w.log_storage,last_log_seq:w.last_log_seq,log_revision:w.log_revision}),u+=1,w.log_storage==="events"){_+=1;try{At(w,"events");}catch(we){s.push(It(we,w.id));}w.logs!==null&&s.push({taskId:w.id,reason:"Event source still has a non-null tasks.logs blob",kind:"mixed-source"});continue}if(w.log_storage!=="blob"){s.push({taskId:w.id,reason:`Unknown log_storage value: ${w.log_storage}`,kind:"invalid-source"});continue}l+=1;let S=Mn(w.status);S||(p+=1,On(c,$)),typeof w.logs=="string"?m+=Buffer.byteLength(w.logs,"utf8"):Buffer.isBuffer(w.logs)&&(m+=w.logs.byteLength);let W=e.get(w.id)??0;W>0&&s.push({taskId:w.id,reason:`Blob source already has ${W} task_log_events row(s)`,kind:"mixed-source"});let Ae;try{Ae=Un(w.id,w.logs),g+=Ae.entries.length,At(w,"blob");}catch(we){let ke=It(we,w.id);s.push(ke),ke.kind==="malformed"&&o.push(ke);continue}W>0||S&&n.push(w.id);}return {taskCount:u,candidateTaskCount:l,eligibleTaskCount:n.length,eventSourceTasks:_,statusCounts:Ln(a),deferredTaskCount:p,deferredStatusCounts:Ln(c),entryCount:g,sourceBytes:m,candidateIds:n,malformedRows:o,failures:s,tasks:t}}function It(r,e){return r instanceof z?{taskId:r.taskId,reason:r.message,kind:r.kind}:{taskId:e,reason:r instanceof Error?r.message:String(r),kind:"metadata"}}function ds(r){return Fe(r,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function cs(r){return Fe(r,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function ls(r){if(r===":memory:")return 0;let e=t=>{try{return yn.statSync(t).size}catch{return 0}};return e(r)+e(`${r}-wal`)}function us(r,e){return ls(r)+e*jn}function Fn(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=e+_t}function Pn(r){let e=ye.dirname(ye.resolve(r));for(;!yn.existsSync(e);){let t=ye.dirname(e);if(t===e)break;e=t;}return e}function Hn(r,e,t){let n=[...new Set([Pn(r),...t?[Pn(t)]:[]])],o=[],s=Number.POSITIVE_INFINITY;for(let u of n)try{let l=yn.statfsSync(u);s=Math.min(s,l.bavail*l.bsize);}catch(l){s=0,o.push(`Unable to inspect free space for ${u}: ${l instanceof Error?l.message:String(l)}`);}let a=us(r,e),c=a+_t;return {estimatedFreeSpaceBytes:a,requiredFreeSpaceBytes:c,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:_t,freeSpaceGatePassed:Fn(Number.isFinite(s)?Math.floor(s):0,a),warnings:o}}function zn(r){return new Set(r.map(e=>e.taskId)).size}function Wn(r){try{let e=r.pragma("wal_checkpoint(TRUNCATE)"),t=Array.isArray(e)?e[0]:e,n=t!==null&&typeof t=="object"&&"busy"in t?Number(t.busy):0;return n>0?`WAL checkpoint(TRUNCATE) busy (${n}); continuing without failing migration`:void 0}catch(e){return `WAL checkpoint(TRUNCATE) warning; continuing without failing migration: ${e instanceof Error?e.message:String(e)}`}}function ut(r,e,t,n,o=Hn(e,t.entryCount)){let s=n.failures??t.failures,a=n.malformedRows??t.malformedRows,{ok:c,...u}=n;return {mode:r,ok:c,dbPath:e,activeTaskCount:n.activeTaskCount??0,taskCount:t.taskCount,candidateTaskCount:t.candidateTaskCount,eligibleTaskCount:t.eligibleTaskCount,statusCounts:t.statusCounts,deferredTaskCount:t.deferredTaskCount,deferredStatusCounts:t.deferredStatusCounts,entryCount:t.entryCount,sourceBytes:t.sourceBytes,estimatedFreeSpaceBytes:o.estimatedFreeSpaceBytes,requiredFreeSpaceBytes:o.requiredFreeSpaceBytes,availableFreeSpaceBytes:o.availableFreeSpaceBytes,minimumFreeSpaceReserveBytes:o.minimumFreeSpaceReserveBytes,freeSpaceGatePassed:o.freeSpaceGatePassed,migratedTasks:n.migratedTasks??0,migratedEntries:n.migratedEntries??0,skippedTasks:n.skippedTasks??t.eventSourceTasks,failedTasks:n.failedTasks??zn(s),malformedRows:a,failures:s,logicalSourceBytesRemoved:n.logicalSourceBytesRemoved??0,warnings:n.warnings??o.warnings,remainingTaskCount:n.remainingTaskCount??t.candidateTaskCount,...u}}function ps(r,e){return r.length!==e.length?false:r.every((t,n)=>{let o=e[n];return t.seq===n+1&&t.timestamp===o.timestamp&&t.level===o.level&&t.message===o.message})}function _s(r,e){return r.transaction(()=>{let n=Fe(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
300
- FROM tasks WHERE id = ?`,[e]);if(!n)throw new z(e,"Task disappeared before migration","metadata");if(n.log_storage==="events")return {status:"skipped",entryCount:0,sourceBytes:0};if(n.log_storage!=="blob")throw new z(e,`Unknown log_storage value: ${n.log_storage}`,"invalid-source");if(!Mn(n.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=n.logs,s=Un(e,o);At(n,"blob");let a=Fe(r,"SELECT COUNT(*) AS count FROM task_log_events WHERE task_id = ?",[e])?.count??0;if(a!==0)throw new z(e,`Blob source already has ${a} task_log_events row(s)`,"mixed-source");let c=r.prepare(`INSERT INTO task_log_events (task_id, seq, timestamp, level, message)
301
- VALUES (?, ?, ?, ?, ?)`);for(let[_,g]of s.entries.entries())c.run(e,_+1,g.timestamp,g.level,g.message);let u=He(r,`SELECT seq, timestamp, level, message
302
- FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!ps(u,s.entries))throw new z(e,"Event parity check failed before source clear","metadata");if(ns(r,`UPDATE tasks
296
+ LIMIT ${Yt+1}
297
+ `),l=c.length>Yt;return {edges:c.slice(0,Yt).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:l}}catch(s){throw new d("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=[];e.workspaceId&&n.push(drizzleOrm.eq(i.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&n.push(drizzleOrm.inArray(i.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&n.push(drizzleOrm.inArray(i.status,e.statuses)),e.from&&n.push(drizzleOrm.gte(i.started_at,e.from)),e.to&&n.push(drizzleOrm.lt(i.started_at,e.to));let o=n.length>0?drizzleOrm.and(...n):void 0,s=(e.order??"DESC")==="ASC"?drizzleOrm.asc(i.started_at):drizzleOrm.desc(i.started_at),a={id:i.id,agent_id:i.agent_id,status:i.status,prompt:i.prompt,started_at:i.started_at,completed_at:i.completed_at,thread_id:i.thread_id};return e.limit?t.db.select(a).from(i).where(o).orderBy(s).limit(e.limit).all():t.db.select(a).from(i).where(o).orderBy(s).all()}catch(n){throw new d("DB_ERROR","Failed to find task evidence",n)}finally{t.close();}}findThreadChains(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[drizzleOrm.isNotNull(i.thread_id),drizzleOrm.isNull(i.parent_task_id),drizzleOrm.isNull(i.caller_agent_id),drizzleOrm.or(drizzleOrm.isNull(i.platform),drizzleOrm.ne(i.platform,"workflow")),drizzleOrm.or(drizzleOrm.isNull(i.metadata),drizzleOrm.and(drizzleOrm.notLike(i.metadata,'%"kind":"workflow_card"%'),drizzleOrm.notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))),drizzleOrm.or(drizzleOrm.isNull(i.metadata),drizzleOrm.notLike(i.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(drizzleOrm.eq(i.workspace_id,e.workspaceId)),e.from&&s.push(drizzleOrm.gte(i.started_at,e.from)),e.to&&s.push(drizzleOrm.lt(i.started_at,e.to));let a=t.db.select({id:i.id,agent_id:i.agent_id,status:i.status,prompt:i.prompt,started_at:i.started_at,completed_at:i.completed_at,thread_id:i.thread_id}).from(i).where(drizzleOrm.and(...s)).orderBy(drizzleOrm.asc(i.started_at),drizzleOrm.asc(i.id)).all(),c=new Map;for(let u of a){if(!u.thread_id)continue;let p={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},_=c.get(u.thread_id);_?_.push(p):c.set(u.thread_id,[p]);}let l=[];for(let[u,p]of c){let _=p.filter(g=>g.agentId===e.targetAgentId).length;_<2||l.push({threadId:u,targetAgentTurnCount:_,turns:p});}return l.sort((u,p)=>{let _=u.turns[u.turns.length-1].startedAt,g=p.turns[p.turns.length-1].startedAt;return _<g?1:_>g?-1:0}),l.slice(0,n).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(n){throw new d("DB_ERROR","Failed to find thread chains",n)}finally{t.close();}}};var fr=["success","failed","completed"],Ot=10*1024*1024*1024,gr=256,Xs=new Set(fr),V=class extends Error{constructor(t,n,o="metadata"){super(n);this.taskId=t;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function mr(r){return r||(process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:Re.join(Qr.homedir(),".crewx","crewx.db"))}function Qs(){return We("better-sqlite3")}function hr(r,e){let t=r===":memory:";if(!t&&!Qn.existsSync(r))throw new Error(`Database not found: ${r}`);let n=new(Qs())(r,{readonly:e,fileMustExist:!t,timeout:5e3});return n.pragma("foreign_keys = ON"),n.pragma("busy_timeout = 5000"),n}function Ze(r,e,t=[]){return r.prepare(e).all(...t)}function Qe(r,e,t=[]){return r.prepare(e).get(...t)}function Zs(r,e,t=[]){return r.prepare(e).run(...t)}function ei(r,e,t=[]){return r.prepare(e).iterate(...t)}function ti(r){return typeof r=="string"&&r.length>0?r:"<unknown>"}function wr(r){return typeof r=="string"&&Xs.has(r)}function ur(r,e){r.set(e,(r.get(e)??0)+1);}function pr(r){return Object.fromEntries([...r.entries()].sort(([e],[t])=>e.localeCompare(t)))}function ni(r){let e=new Set(Ze(r,"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('tasks', 'task_log_events')").map(a=>a.name)),t=["tasks","task_log_events"].filter(a=>!e.has(a));if(t.length>0)throw new Error(`Database schema is missing required table(s): ${t.join(", ")}`);let n=new Set(Ze(r,"PRAGMA table_info('tasks')").map(a=>a.name)),s=["id","status","logs","log_storage","last_log_seq","log_revision"].filter(a=>!n.has(a));if(s.length>0)throw new Error(`Database schema is missing required tasks column(s): ${s.join(", ")}`)}function kr(r,e){if(e==null)return {entries:[]};if(typeof e!="string")throw new V(r,"Malformed task logs: tasks.logs must be JSON text or null","malformed");if(e.trim()==="")return {entries:[]};let t;try{t=JSON.parse(e);}catch(o){let s=o instanceof Error?o.message:String(o);throw new V(r,`Malformed JSON in tasks.logs (${s})`,"malformed")}if(!Array.isArray(t))throw new V(r,"Malformed task logs: expected a JSON array","malformed");let n=[];for(let[o,s]of t.entries()){if(s===null||typeof s!="object"||typeof s.timestamp!="string"||typeof s.level!="string"||typeof s.message!="string")throw new V(r,`Malformed task logs: entry ${o} must contain string timestamp, level, and message fields`,"malformed");let a=s;n.push({timestamp:a.timestamp,level:a.level,message:a.message});}return {entries:n}}function en(r,e){if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new V(r.id,"Invalid last_log_seq metadata","metadata");if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new V(r.id,"Invalid log_revision metadata","metadata");if(e==="blob"&&r.last_log_seq!==0)throw new V(r.id,"Blob source must have last_log_seq=0","metadata")}function ri(r){let e=Ze(r,`SELECT task_id, COUNT(*) AS event_count
298
+ FROM task_log_events GROUP BY task_id`);return new Map(e.map(t=>[t.task_id,t.event_count]))}function oi(r){let e=ri(r),t=new Map,n=[],o=[],s=[],a=new Map,c=new Map,l=0,u=0,p=0,_=0,g=0,h=0;for(let j of ei(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
299
+ FROM tasks ORDER BY id`)){let k=j,$=ti(k.status);if(ur(a,$),t.set(k.id,{id:k.id,status:k.status,log_storage:k.log_storage,last_log_seq:k.last_log_seq,log_revision:k.log_revision}),l+=1,k.log_storage==="events"){_+=1;try{en(k,"events");}catch(ye){s.push(tn(ye,k.id));}k.logs!==null&&s.push({taskId:k.id,reason:"Event source still has a non-null tasks.logs blob",kind:"mixed-source"});continue}if(k.log_storage!=="blob"){s.push({taskId:k.id,reason:`Unknown log_storage value: ${k.log_storage}`,kind:"invalid-source"});continue}u+=1;let S=wr(k.status);S||(p+=1,ur(c,$)),typeof k.logs=="string"?h+=Buffer.byteLength(k.logs,"utf8"):Buffer.isBuffer(k.logs)&&(h+=k.logs.byteLength);let K=e.get(k.id)??0;K>0&&s.push({taskId:k.id,reason:`Blob source already has ${K} task_log_events row(s)`,kind:"mixed-source"});let Ie;try{Ie=kr(k.id,k.logs),g+=Ie.entries.length,en(k,"blob");}catch(ye){let be=tn(ye,k.id);s.push(be),be.kind==="malformed"&&o.push(be);continue}K>0||S&&n.push(k.id);}return {taskCount:l,candidateTaskCount:u,eligibleTaskCount:n.length,eventSourceTasks:_,statusCounts:pr(a),deferredTaskCount:p,deferredStatusCounts:pr(c),entryCount:g,sourceBytes:h,candidateIds:n,malformedRows:o,failures:s,tasks:t}}function tn(r,e){return r instanceof V?{taskId:r.taskId,reason:r.message,kind:r.kind}:{taskId:e,reason:r instanceof Error?r.message:String(r),kind:"metadata"}}function si(r){return Qe(r,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function ii(r){return Qe(r,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function ai(r){if(r===":memory:")return 0;let e=t=>{try{return Qn.statSync(t).size}catch{return 0}};return e(r)+e(`${r}-wal`)}function di(r,e){return ai(r)+e*gr}function yr(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=e+Ot}function _r(r){let e=Re.dirname(Re.resolve(r));for(;!Qn.existsSync(e);){let t=Re.dirname(e);if(t===e)break;e=t;}return e}function br(r,e,t){let n=[...new Set([_r(r),...t?[_r(t)]:[]])],o=[],s=Number.POSITIVE_INFINITY;for(let l of n)try{let u=Qn.statfsSync(l);s=Math.min(s,u.bavail*u.bsize);}catch(u){s=0,o.push(`Unable to inspect free space for ${l}: ${u instanceof Error?u.message:String(u)}`);}let a=di(r,e),c=a+Ot;return {estimatedFreeSpaceBytes:a,requiredFreeSpaceBytes:c,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:Ot,freeSpaceGatePassed:yr(Number.isFinite(s)?Math.floor(s):0,a),warnings:o}}function Rr(r){return new Set(r.map(e=>e.taskId)).size}function Er(r){try{let e=r.pragma("wal_checkpoint(TRUNCATE)"),t=Array.isArray(e)?e[0]:e,n=t!==null&&typeof t=="object"&&"busy"in t?Number(t.busy):0;return n>0?`WAL checkpoint(TRUNCATE) busy (${n}); continuing without failing migration`:void 0}catch(e){return `WAL checkpoint(TRUNCATE) warning; continuing without failing migration: ${e instanceof Error?e.message:String(e)}`}}function vt(r,e,t,n,o=br(e,t.entryCount)){let s=n.failures??t.failures,a=n.malformedRows??t.malformedRows,{ok:c,...l}=n;return {mode:r,ok:c,dbPath:e,activeTaskCount:n.activeTaskCount??0,taskCount:t.taskCount,candidateTaskCount:t.candidateTaskCount,eligibleTaskCount:t.eligibleTaskCount,statusCounts:t.statusCounts,deferredTaskCount:t.deferredTaskCount,deferredStatusCounts:t.deferredStatusCounts,entryCount:t.entryCount,sourceBytes:t.sourceBytes,estimatedFreeSpaceBytes:o.estimatedFreeSpaceBytes,requiredFreeSpaceBytes:o.requiredFreeSpaceBytes,availableFreeSpaceBytes:o.availableFreeSpaceBytes,minimumFreeSpaceReserveBytes:o.minimumFreeSpaceReserveBytes,freeSpaceGatePassed:o.freeSpaceGatePassed,migratedTasks:n.migratedTasks??0,migratedEntries:n.migratedEntries??0,skippedTasks:n.skippedTasks??t.eventSourceTasks,failedTasks:n.failedTasks??Rr(s),malformedRows:a,failures:s,logicalSourceBytesRemoved:n.logicalSourceBytesRemoved??0,warnings:n.warnings??o.warnings,remainingTaskCount:n.remainingTaskCount??t.candidateTaskCount,...l}}function ci(r,e){return r.length!==e.length?false:r.every((t,n)=>{let o=e[n];return t.seq===n+1&&t.timestamp===o.timestamp&&t.level===o.level&&t.message===o.message})}function li(r,e){return r.transaction(()=>{let n=Qe(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
300
+ FROM tasks WHERE id = ?`,[e]);if(!n)throw new V(e,"Task disappeared before migration","metadata");if(n.log_storage==="events")return {status:"skipped",entryCount:0,sourceBytes:0};if(n.log_storage!=="blob")throw new V(e,`Unknown log_storage value: ${n.log_storage}`,"invalid-source");if(!wr(n.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=n.logs,s=kr(e,o);en(n,"blob");let a=Qe(r,"SELECT COUNT(*) AS count FROM task_log_events WHERE task_id = ?",[e])?.count??0;if(a!==0)throw new V(e,`Blob source already has ${a} task_log_events row(s)`,"mixed-source");let c=r.prepare(`INSERT INTO task_log_events (task_id, seq, timestamp, level, message)
301
+ VALUES (?, ?, ?, ?, ?)`);for(let[_,g]of s.entries.entries())c.run(e,_+1,g.timestamp,g.level,g.message);let l=Ze(r,`SELECT seq, timestamp, level, message
302
+ FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!ci(l,s.entries))throw new V(e,"Event parity check failed before source clear","metadata");if(Zs(r,`UPDATE tasks
303
303
  SET log_storage = 'events', last_log_seq = ?, log_revision = log_revision + 1, logs = NULL
304
- WHERE id = ? AND log_storage = 'blob' AND logs IS ?`,[s.entries.length,e,o]).changes!==1)throw new z(e,"Task changed while migration was in progress","metadata");let p=Fe(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
305
- FROM tasks WHERE id = ?`,[e]);if(!p||p.log_storage!=="events"||p.logs!==null||p.last_log_seq!==s.entries.length||p.log_revision!==n.log_revision+1)throw new z(e,"Final task metadata parity check failed","metadata");return {status:"migrated",entryCount:s.entries.length,sourceBytes:typeof o=="string"?Buffer.byteLength(o,"utf8"):Buffer.isBuffer(o)?o.byteLength:0}}).immediate()}function Kn(r){let e=new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14),t=crypto.randomBytes(6).toString("hex");return `${r}.task-log-backup-${e}-${t}.sqlite`}async function gs(r,e,t){let n=t??Kn(e);if(ye.resolve(n)===ye.resolve(e))throw new Error("Backup path must be different from the source database");if(yn.existsSync(n))throw new Error(`Refusing to overwrite existing backup: ${n}`);if(yn.mkdirSync(ye.dirname(n),{recursive:true}),await r.backup(n),!yn.existsSync(n))throw new Error(`SQLite backup was not created: ${n}`);let o=qn(n,true);try{let s=o.pragma("integrity_check",{simple:!0});if(s!=="ok")throw new Error(`Backup integrity check failed: ${s}`)}finally{o.close();}return n}function fs(r){let e=He(r,`SELECT task_id AS taskId,
304
+ WHERE id = ? AND log_storage = 'blob' AND logs IS ?`,[s.entries.length,e,o]).changes!==1)throw new V(e,"Task changed while migration was in progress","metadata");let p=Qe(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
305
+ FROM tasks WHERE id = ?`,[e]);if(!p||p.log_storage!=="events"||p.logs!==null||p.last_log_seq!==s.entries.length||p.log_revision!==n.log_revision+1)throw new V(e,"Final task metadata parity check failed","metadata");return {status:"migrated",entryCount:s.entries.length,sourceBytes:typeof o=="string"?Buffer.byteLength(o,"utf8"):Buffer.isBuffer(o)?o.byteLength:0}}).immediate()}function Tr(r){let e=new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14),t=crypto.randomBytes(6).toString("hex");return `${r}.task-log-backup-${e}-${t}.sqlite`}async function ui(r,e,t){let n=t??Tr(e);if(Re.resolve(n)===Re.resolve(e))throw new Error("Backup path must be different from the source database");if(Qn.existsSync(n))throw new Error(`Refusing to overwrite existing backup: ${n}`);if(Qn.mkdirSync(Re.dirname(n),{recursive:true}),await r.backup(n),!Qn.existsSync(n))throw new Error(`SQLite backup was not created: ${n}`);let o=hr(n,true);try{let s=o.pragma("integrity_check",{simple:!0});if(s!=="ok")throw new Error(`Backup integrity check failed: ${s}`)}finally{o.close();}return n}function pi(r){let e=Ze(r,`SELECT task_id AS taskId,
306
306
  COUNT(*) AS eventCount,
307
307
  COUNT(DISTINCT seq) AS distinctSeqCount,
308
308
  MIN(seq) AS minSeq,
309
309
  MAX(seq) AS maxSeq
310
- FROM task_log_events GROUP BY task_id`),t=e.reduce((n,o)=>n+o.eventCount,0);return {rows:e,eventCount:t}}function De(r,e,t,n={}){return {taskId:r,kind:e,reason:t,...n}}function ms(r,e,t){let n=[];for(let _ of t.failures)_.kind==="malformed"?n.push(De(_.taskId,"malformed-blob",_.reason)):_.kind==="mixed-source"?n.push(De(_.taskId,"mixed-source",_.reason)):n.push(De(_.taskId,"source-invariant",_.reason));let o=fs(r),s=new Map(o.rows.map(_=>[_.taskId,_]));for(let _ of o.rows){let g=t.tasks.get(_.taskId);if(!g){n.push(De(null,"orphan-event",`Event rows reference missing task ${_.taskId}`,{actual:_.eventCount}));continue}(_.minSeq===null||_.minSeq<1||_.distinctSeqCount!==_.maxSeq)&&n.push(De(g.id,"seq-gap","Task event sequence has a gap or invalid starting sequence",{expected:_.maxSeq??0,actual:_.distinctSeqCount})),g.log_storage==="events"&&g.last_log_seq!==_.eventCount&&n.push(De(g.id,"count-mismatch","last_log_seq does not match task_log_events row count",{expected:g.last_log_seq??0,actual:_.eventCount}));}for(let _ of t.tasks.values())_.log_storage==="events"&&!s.has(_.id)&&_.last_log_seq!==0&&n.push(De(_.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:_.last_log_seq??0,actual:0}));for(let _ of He(r,`SELECT task_id AS taskId, seq, COUNT(*) AS duplicateCount
311
- FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))n.push(De(_.taskId,"duplicate-seq",`Duplicate task event sequence ${_.seq}`,{actual:_.duplicateCount,seq:_.seq}));let a=Fe(r,`SELECT COUNT(*) AS count FROM task_log_events
312
- WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;a>0&&n.push(De(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:a}));let c=new Set(n.flatMap(_=>_.taskId?[_.taskId]:[])),u=n.map(_=>({taskId:_.taskId??"(orphan)",reason:_.reason,kind:_.kind==="malformed-blob"?"malformed":_.kind==="mixed-source"?"mixed-source":"metadata"})),l=u.filter(_=>_.kind==="malformed"),p={checkedTasks:t.taskCount,eventSourceTasks:t.eventSourceTasks,blobSourceTasks:t.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:n.filter(_=>_.kind==="orphan-event").length,failedTasks:c.size,issues:n};return ut("verify",e,t,{ok:n.length===0,migratedTasks:t.eventSourceTasks,migratedEntries:o.eventCount,skippedTasks:t.candidateTaskCount,failedTasks:c.size,malformedRows:l,failures:u,remainingTaskCount:t.candidateTaskCount,verification:p})}function hs(r){if(r.mode!=="apply"&&r.batchTasks!==void 0)throw new Error("--batch-tasks is only valid with --apply");if(r.batchTasks!==void 0&&(!Number.isInteger(r.batchTasks)||r.batchTasks<1))throw new Error("--batch-tasks must be a positive integer")}async function ws(r){hs(r);let e=Bn(r.dbPath),t=qn(e,r.mode!=="apply");try{ss(t);let n=as(t),o=ds(t);if(r.mode==="verify")return {...ms(t,e,n),activeTaskCount:o};if(r.mode==="dry-run")return ut("dry-run",e,n,{ok:n.failures.length===0,activeTaskCount:o,skippedTasks:n.eventSourceTasks,remainingTaskCount:n.candidateTaskCount});let s=r.backupPath??Kn(e),a=Hn(e,n.entryCount,s);if(!a.freeSpaceGatePassed)return ut("apply",e,n,{ok:!1,activeTaskCount:o,blockedReason:`Apply blocked: available free space (${a.availableFreeSpaceBytes} bytes) is below the required ${a.requiredFreeSpaceBytes} bytes (including a ${a.minimumFreeSpaceReserveBytes} byte reserve)`,skippedTasks:n.eventSourceTasks,remainingTaskCount:n.candidateTaskCount},a);let c=await gs(t,e,s),u=[...n.failures],l=r.batchTasks===void 0?n.candidateIds:n.candidateIds.slice(0,r.batchTasks),p=r.batchTasks??Math.max(l.length,1),_=0,g=0,m=0,P=[...a.warnings];for(let[w,$]of l.entries()){try{let S=_s(t,$);S.status==="migrated"&&(_+=1,g+=S.entryCount,m+=S.sourceBytes);}catch(S){u.push(It(S,$));}if((w+1)%p===0||w===l.length-1){let S=Wn(t);S&&P.push(S);}}return ut("apply",e,n,{ok:u.length===0,activeTaskCount:o,backupPath:c,backupMethod:"sqlite-online-backup",migratedTasks:_,migratedEntries:g,logicalSourceBytesRemoved:m,failedTasks:zn(u),failures:u,malformedRows:n.malformedRows,remainingTaskCount:cs(t),skippedTasks:n.eventSourceTasks,warnings:P},a)}finally{t.close();}}function ks(r){return ye.basename(r)}var Ct=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}validateWorkspaceId(e,t){return e.db.select({id:h.id}).from(h).where(drizzleOrm.eq(h.id,t)).limit(1).get()?t:null}topLevelTaskPredicateSql(e="child"){return drizzleOrm.sql.raw(`NOT EXISTS (
310
+ FROM task_log_events GROUP BY task_id`),t=e.reduce((n,o)=>n+o.eventCount,0);return {rows:e,eventCount:t}}function xe(r,e,t,n={}){return {taskId:r,kind:e,reason:t,...n}}function _i(r,e,t){let n=[];for(let _ of t.failures)_.kind==="malformed"?n.push(xe(_.taskId,"malformed-blob",_.reason)):_.kind==="mixed-source"?n.push(xe(_.taskId,"mixed-source",_.reason)):n.push(xe(_.taskId,"source-invariant",_.reason));let o=pi(r),s=new Map(o.rows.map(_=>[_.taskId,_]));for(let _ of o.rows){let g=t.tasks.get(_.taskId);if(!g){n.push(xe(null,"orphan-event",`Event rows reference missing task ${_.taskId}`,{actual:_.eventCount}));continue}(_.minSeq===null||_.minSeq<1||_.distinctSeqCount!==_.maxSeq)&&n.push(xe(g.id,"seq-gap","Task event sequence has a gap or invalid starting sequence",{expected:_.maxSeq??0,actual:_.distinctSeqCount})),g.log_storage==="events"&&g.last_log_seq!==_.eventCount&&n.push(xe(g.id,"count-mismatch","last_log_seq does not match task_log_events row count",{expected:g.last_log_seq??0,actual:_.eventCount}));}for(let _ of t.tasks.values())_.log_storage==="events"&&!s.has(_.id)&&_.last_log_seq!==0&&n.push(xe(_.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:_.last_log_seq??0,actual:0}));for(let _ of Ze(r,`SELECT task_id AS taskId, seq, COUNT(*) AS duplicateCount
311
+ FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))n.push(xe(_.taskId,"duplicate-seq",`Duplicate task event sequence ${_.seq}`,{actual:_.duplicateCount,seq:_.seq}));let a=Qe(r,`SELECT COUNT(*) AS count FROM task_log_events
312
+ WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;a>0&&n.push(xe(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:a}));let c=new Set(n.flatMap(_=>_.taskId?[_.taskId]:[])),l=n.map(_=>({taskId:_.taskId??"(orphan)",reason:_.reason,kind:_.kind==="malformed-blob"?"malformed":_.kind==="mixed-source"?"mixed-source":"metadata"})),u=l.filter(_=>_.kind==="malformed"),p={checkedTasks:t.taskCount,eventSourceTasks:t.eventSourceTasks,blobSourceTasks:t.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:n.filter(_=>_.kind==="orphan-event").length,failedTasks:c.size,issues:n};return vt("verify",e,t,{ok:n.length===0,migratedTasks:t.eventSourceTasks,migratedEntries:o.eventCount,skippedTasks:t.candidateTaskCount,failedTasks:c.size,malformedRows:u,failures:l,remainingTaskCount:t.candidateTaskCount,verification:p})}function fi(r){if(r.mode!=="apply"&&r.batchTasks!==void 0)throw new Error("--batch-tasks is only valid with --apply");if(r.batchTasks!==void 0&&(!Number.isInteger(r.batchTasks)||r.batchTasks<1))throw new Error("--batch-tasks must be a positive integer")}async function gi(r){fi(r);let e=mr(r.dbPath),t=hr(e,r.mode!=="apply");try{ni(t);let n=oi(t),o=si(t);if(r.mode==="verify")return {..._i(t,e,n),activeTaskCount:o};if(r.mode==="dry-run")return vt("dry-run",e,n,{ok:n.failures.length===0,activeTaskCount:o,skippedTasks:n.eventSourceTasks,remainingTaskCount:n.candidateTaskCount});let s=r.backupPath??Tr(e),a=br(e,n.entryCount,s);if(!a.freeSpaceGatePassed)return vt("apply",e,n,{ok:!1,activeTaskCount:o,blockedReason:`Apply blocked: available free space (${a.availableFreeSpaceBytes} bytes) is below the required ${a.requiredFreeSpaceBytes} bytes (including a ${a.minimumFreeSpaceReserveBytes} byte reserve)`,skippedTasks:n.eventSourceTasks,remainingTaskCount:n.candidateTaskCount},a);let c=await ui(t,e,s),l=[...n.failures],u=r.batchTasks===void 0?n.candidateIds:n.candidateIds.slice(0,r.batchTasks),p=r.batchTasks??Math.max(u.length,1),_=0,g=0,h=0,j=[...a.warnings];for(let[k,$]of u.entries()){try{let S=li(t,$);S.status==="migrated"&&(_+=1,g+=S.entryCount,h+=S.sourceBytes);}catch(S){l.push(tn(S,$));}if((k+1)%p===0||k===u.length-1){let S=Er(t);S&&j.push(S);}}return vt("apply",e,n,{ok:l.length===0,activeTaskCount:o,backupPath:c,backupMethod:"sqlite-online-backup",migratedTasks:_,migratedEntries:g,logicalSourceBytesRemoved:h,failedTasks:Rr(l),failures:l,malformedRows:n.malformedRows,remainingTaskCount:ii(t),skippedTasks:n.eventSourceTasks,warnings:j},a)}finally{t.close();}}function mi(r){return Re.basename(r)}var ze=class extends d{reason;constructor(e,t=e){super("VALIDATION",t),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function ut(r){if(!r)return {};try{let e=JSON.parse(r);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function bi(r){let t=ut(r).threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {priority:null,state:null};let n=t;return {priority:typeof n.priority=="string"?n.priority:null,state:typeof n.state=="string"?n.state:null}}var nn=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}validateWorkspaceId(e,t){return e.db.select({id:w.id}).from(w).where(drizzleOrm.eq(w.id,t)).limit(1).get()?t:null}topLevelTaskPredicateSql(e="child"){return drizzleOrm.sql.raw(`NOT EXISTS (
313
313
  SELECT 1 FROM tasks parent
314
314
  WHERE parent.id = ${e}.parent_task_id
315
315
  AND parent.thread_id = ${e}.thread_id
316
- )`)}findAllThreads(e){let t=this.resolveDbPaths(),n=new Set,o=[];for(let s of t){if(!yn.existsSync(s))continue;let a=k(s);try{let c=e?drizzleOrm.eq(f.workspace_id,e):void 0,u=a.db.select().from(f).where(c).orderBy(drizzleOrm.desc(f.updated_at)).all();for(let l of u)n.has(l.id)||(n.add(l.id),o.push(l));}catch(c){throw new d("DB_ERROR","Failed to find all threads",c)}finally{a.close();}}return o}findThreadsByIdsOrTitles(e,t){if(e.length===0)return [];let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!yn.existsSync(a))continue;let c=k(a);try{let u=drizzleOrm.or(drizzleOrm.inArray(f.id,e),drizzleOrm.inArray(f.title,e)),l=t?drizzleOrm.and(u,drizzleOrm.eq(f.workspace_id,t)):u,p=c.db.select().from(f).where(l).orderBy(drizzleOrm.desc(f.updated_at)).all();for(let _ of p)o.has(_.id)||(o.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find threads by ids or titles",u)}finally{c.close();}}return s}findThreadById(e,t){let n=this.resolveDbPaths();for(let o of n){if(!yn.existsSync(o))continue;let s=k(o);try{let a=drizzleOrm.eq(f.id,e),c=t?drizzleOrm.and(a,drizzleOrm.eq(f.workspace_id,t)):a,u=s.db.select().from(f).where(c).limit(1).get()??void 0;if(u)return u}catch(a){throw new d("DB_ERROR","Failed to find thread by id",a)}finally{s.close();}}}threadExists(e,t){let n=this.resolveDbPaths();for(let o of n){if(!yn.existsSync(o))continue;let s=k(o);try{let a=drizzleOrm.eq(f.id,e),c=t?drizzleOrm.and(a,drizzleOrm.eq(f.workspace_id,t)):a;if(s.db.select({id:f.id}).from(f).where(c).limit(1).get())return !0}catch(a){throw new d("DB_ERROR","Failed to check thread existence",a)}finally{s.close();}}return false}aggregateTaskStats(e,t){let n=this.resolveDbPaths(),o=0,s=0,a=0,c=0,u=0,l=new Set;for(let p of n){if(!yn.existsSync(p))continue;let _=k(p);try{let g=_.db.get(drizzleOrm.sql`
316
+ )`)}findAllThreads(e){let t=this.resolveDbPaths(),n=new Set,o=[];for(let s of t){if(!Qn.existsSync(s))continue;let a=y(s);try{let c=e?drizzleOrm.eq(f.workspace_id,e):void 0,l=a.db.select().from(f).where(c).orderBy(drizzleOrm.desc(f.updated_at)).all();for(let u of l)n.has(u.id)||(n.add(u.id),o.push(u));}catch(c){throw new d("DB_ERROR","Failed to find all threads",c)}finally{a.close();}}return o}findThreadsByIdsOrTitles(e,t){if(e.length===0)return [];let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!Qn.existsSync(a))continue;let c=y(a);try{let l=drizzleOrm.or(drizzleOrm.inArray(f.id,e),drizzleOrm.inArray(f.title,e)),u=t?drizzleOrm.and(l,drizzleOrm.eq(f.workspace_id,t)):l,p=c.db.select().from(f).where(u).orderBy(drizzleOrm.desc(f.updated_at)).all();for(let _ of p)o.has(_.id)||(o.add(_.id),s.push(_));}catch(l){throw new d("DB_ERROR","Failed to find threads by ids or titles",l)}finally{c.close();}}return s}findThreadById(e,t){let n=this.resolveDbPaths();for(let o of n){if(!Qn.existsSync(o))continue;let s=y(o);try{let a=drizzleOrm.eq(f.id,e),c=t?drizzleOrm.and(a,drizzleOrm.eq(f.workspace_id,t)):a,l=s.db.select().from(f).where(c).limit(1).get()??void 0;if(l)return l}catch(a){throw new d("DB_ERROR","Failed to find thread by id",a)}finally{s.close();}}}threadExists(e,t){let n=this.resolveDbPaths();for(let o of n){if(!Qn.existsSync(o))continue;let s=y(o);try{let a=drizzleOrm.eq(f.id,e),c=t?drizzleOrm.and(a,drizzleOrm.eq(f.workspace_id,t)):a;if(s.db.select({id:f.id}).from(f).where(c).limit(1).get())return !0}catch(a){throw new d("DB_ERROR","Failed to check thread existence",a)}finally{s.close();}}return false}aggregateTaskStats(e,t){let n=this.resolveDbPaths(),o=0,s=0,a=0,c=0,l=0,u=new Set;for(let p of n){if(!Qn.existsSync(p))continue;let _=y(p);try{let g=_.db.get(drizzleOrm.sql`
317
317
  SELECT
318
318
  count(*) AS cnt,
319
319
  COALESCE(SUM(child.input_tokens), 0) AS total_input,
@@ -324,13 +324,13 @@ ${n.join(`
324
324
  WHERE child.thread_id = ${e}
325
325
  AND ${this.topLevelTaskPredicateSql()}
326
326
  ${t?drizzleOrm.sql`AND child.workspace_id = ${t}`:drizzleOrm.sql``}
327
- `);g&&(o+=g.cnt,s+=g.total_input,a+=g.total_output,c+=g.total_cached,u+=g.total_cost);let m=_.db.all(drizzleOrm.sql`
327
+ `);g&&(o+=g.cnt,s+=g.total_input,a+=g.total_output,c+=g.total_cached,l+=g.total_cost);let h=_.db.all(drizzleOrm.sql`
328
328
  SELECT DISTINCT child.agent_id FROM tasks child
329
329
  WHERE child.thread_id = ${e}
330
330
  AND child.agent_id IS NOT NULL AND child.agent_id != ''
331
331
  AND ${this.topLevelTaskPredicateSql()}
332
332
  ${t?drizzleOrm.sql`AND child.workspace_id = ${t}`:drizzleOrm.sql``}
333
- `);for(let P of m)l.add(P.agent_id);}catch(g){throw new d("DB_ERROR","Failed to aggregate task stats",g)}finally{_.close();}}return {taskCount:o,inputTokens:s,outputTokens:a,cachedInputTokens:c,costUsd:u,agentIds:Array.from(l)}}findTopLevelTasks(e,t,n){let o=this.resolveDbPaths(),s=new Set,a=[];for(let c of o){if(!yn.existsSync(c))continue;let u=k(c);try{let l;n!==void 0?l=u.db.all(drizzleOrm.sql`
333
+ `);for(let j of h)u.add(j.agent_id);}catch(g){throw new d("DB_ERROR","Failed to aggregate task stats",g)}finally{_.close();}}return {taskCount:o,inputTokens:s,outputTokens:a,cachedInputTokens:c,costUsd:l,agentIds:Array.from(u)}}findTopLevelTasks(e,t,n){let o=this.resolveDbPaths(),s=new Set,a=[];for(let c of o){if(!Qn.existsSync(c))continue;let l=y(c);try{let u;n!==void 0?u=l.db.all(drizzleOrm.sql`
334
334
  SELECT * FROM (
335
335
  SELECT child.*,
336
336
  ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
@@ -341,13 +341,13 @@ ${n.join(`
341
341
  ) ranked
342
342
  WHERE rn <= ${n}
343
343
  ORDER BY started_at ASC
344
- `):l=u.db.all(drizzleOrm.sql`
344
+ `):u=l.db.all(drizzleOrm.sql`
345
345
  SELECT child.* FROM tasks child
346
346
  WHERE child.thread_id = ${e}
347
347
  AND ${this.topLevelTaskPredicateSql()}
348
348
  ${t?drizzleOrm.sql`AND child.workspace_id = ${t}`:drizzleOrm.sql``}
349
349
  ORDER BY child.started_at ASC
350
- `);for(let p of l)s.has(p.id)||(s.add(p.id),a.push(p));}catch(l){throw new d("DB_ERROR","Failed to find top-level tasks",l)}finally{u.close();}}if(n!==void 0&&o.length>1){let c=new Map;for(let u of a){let l=u.agent_id??"";c.has(l)||c.set(l,[]),c.get(l).push(u);}a=[];for(let u of c.values())u.sort((l,p)=>(p.started_at??"").localeCompare(l.started_at??"")),a.push(...u.slice(0,n));a.sort((u,l)=>(u.started_at??"").localeCompare(l.started_at??""));}return a}findAllTasks(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!yn.existsSync(a))continue;let c=k(a);try{let u=drizzleOrm.eq(i.thread_id,e),l=t?drizzleOrm.and(u,drizzleOrm.eq(i.workspace_id,t)):u,p=c.db.select().from(i).where(l).orderBy(drizzleOrm.asc(i.started_at)).all();for(let _ of p)o.has(_.id)||(o.add(_.id),s.push(_));}catch(u){throw new d("DB_ERROR","Failed to find all tasks for thread",u)}finally{c.close();}}return s}findTaskById(e,t,n){let o=this.resolveDbPaths();for(let s of o){if(!yn.existsSync(s))continue;let a=k(s);try{let c=drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.thread_id,e)),u=n?drizzleOrm.and(c,drizzleOrm.eq(i.workspace_id,n)):c,l=a.db.select().from(i).where(u).limit(1).get();if(!l)continue;let p=a.db.select().from(i).where(drizzleOrm.eq(i.parent_task_id,l.id)).orderBy(drizzleOrm.asc(i.started_at)).all();return {task:l,children:p}}catch(c){throw new d("DB_ERROR","Failed to find task by id",c)}finally{a.close();}}}batchFetchTasksQuery(e,t){return drizzleOrm.sql`
350
+ `);for(let p of u)s.has(p.id)||(s.add(p.id),a.push(p));}catch(u){throw new d("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}if(n!==void 0&&o.length>1){let c=new Map;for(let l of a){let u=l.agent_id??"";c.has(u)||c.set(u,[]),c.get(u).push(l);}a=[];for(let l of c.values())l.sort((u,p)=>(p.started_at??"").localeCompare(u.started_at??"")),a.push(...l.slice(0,n));a.sort((l,u)=>(l.started_at??"").localeCompare(u.started_at??""));}return a}findAllTasks(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let a of n){if(!Qn.existsSync(a))continue;let c=y(a);try{let l=drizzleOrm.eq(i.thread_id,e),u=t?drizzleOrm.and(l,drizzleOrm.eq(i.workspace_id,t)):l,p=c.db.select().from(i).where(u).orderBy(drizzleOrm.asc(i.started_at)).all();for(let _ of p)o.has(_.id)||(o.add(_.id),s.push(_));}catch(l){throw new d("DB_ERROR","Failed to find all tasks for thread",l)}finally{c.close();}}return s}findTaskById(e,t,n){let o=this.resolveDbPaths();for(let s of o){if(!Qn.existsSync(s))continue;let a=y(s);try{let c=drizzleOrm.and(drizzleOrm.eq(i.id,t),drizzleOrm.eq(i.thread_id,e)),l=n?drizzleOrm.and(c,drizzleOrm.eq(i.workspace_id,n)):c,u=a.db.select().from(i).where(l).limit(1).get();if(!u)continue;let p=a.db.select().from(i).where(drizzleOrm.eq(i.parent_task_id,u.id)).orderBy(drizzleOrm.asc(i.started_at)).all();return {task:u,children:p}}catch(c){throw new d("DB_ERROR","Failed to find task by id",c)}finally{a.close();}}}batchFetchTasksQuery(e,t){return drizzleOrm.sql`
351
351
  SELECT child.id, child.thread_id, child.agent_id, child.status,
352
352
  child.parent_task_id, child.started_at, child.completed_at,
353
353
  child.duration_ms, child.input_tokens, child.output_tokens,
@@ -357,7 +357,7 @@ ${n.join(`
357
357
  AND ${this.topLevelTaskPredicateSql()}
358
358
  ${t?drizzleOrm.sql`AND child.workspace_id = ${t}`:drizzleOrm.sql``}
359
359
  ORDER BY child.started_at ASC
360
- `}batchFetchTasks(e,t){let n=new Map;if(e.length===0)return n;let o=this.resolveDbPaths();for(let s of o){if(!yn.existsSync(s))continue;let a=k(s);try{let c=a.db.all(this.batchFetchTasksQuery(e,t));for(let u of c){let l=u.thread_id;n.has(l)||n.set(l,[]),n.get(l).push(u);}}catch(c){throw new d("DB_ERROR","Failed to batch fetch tasks",c)}finally{a.close();}}return n}explainBatchFetchTasksPlan(e,t){let n=this.resolveDbPaths();for(let o of n){if(!yn.existsSync(o))continue;let s=k(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,t)}`).map(c=>c.detail)}finally{s.close();}}return []}updateThreadTitle(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=drizzleOrm.eq(f.id,e),a=n?drizzleOrm.and(s,drizzleOrm.eq(f.workspace_id,n)):s;if(!o.db.select({id:f.id}).from(f).where(a).limit(1).get())return;o.db.update(f).set({title:t,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(f.id,e)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,t){let n=this.openHandle(true);try{let o=t.workspaceId?this.validateWorkspaceId(n,t.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:f.id,message_count:f.message_count}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get()){let c={updated_at:s};t.title!==void 0&&(c.title=t.title),t.titleLocked!==void 0&&(c.title_locked=t.titleLocked?1:0),n.db.update(f).set(c).where(drizzleOrm.eq(f.id,e)).run();}else n.db.insert(f).values({id:e,platform:t.platform,workspace_id:o,title:t.title??null,title_locked:t.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to upsert thread",o)}finally{n.close();}}ensureThread(e,t,n){let o=this.openHandle(true);try{let s=n?this.validateWorkspaceId(o,n):null,a=o.db.select({id:f.id,platform:f.platform,workspace_id:f.workspace_id}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get();if(a){s&&!a.workspace_id&&o.db.update(f).set({workspace_id:s}).where(drizzleOrm.eq(f.id,e)).run();return}let c=new Date().toISOString();o.db.insert(f).values({id:e,platform:t,workspace_id:s,message_count:0,created_at:c,updated_at:c}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{o.close();}}saveUserMessage(e,t,n){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(c=>{let l=c.select({message_count:f.message_count}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get()?.message_count===0;return c.run(drizzleOrm.sql`
360
+ `}batchFetchTasks(e,t){let n=new Map;if(e.length===0)return n;let o=this.resolveDbPaths();for(let s of o){if(!Qn.existsSync(s))continue;let a=y(s);try{let c=a.db.all(this.batchFetchTasksQuery(e,t));for(let l of c){let u=l.thread_id;n.has(u)||n.set(u,[]),n.get(u).push(l);}}catch(c){throw new d("DB_ERROR","Failed to batch fetch tasks",c)}finally{a.close();}}return n}explainBatchFetchTasksPlan(e,t){let n=this.resolveDbPaths();for(let o of n){if(!Qn.existsSync(o))continue;let s=y(o);try{return s.db.all(drizzleOrm.sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,t)}`).map(c=>c.detail)}finally{s.close();}}return []}updateThreadTitle(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=drizzleOrm.eq(f.id,e),a=n?drizzleOrm.and(s,drizzleOrm.eq(f.workspace_id,n)):s;if(!o.db.select({id:f.id}).from(f).where(a).limit(1).get())return;o.db.update(f).set({title:t,title_locked:1,updated_at:new Date().toISOString()}).where(drizzleOrm.eq(f.id,e)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,t){let n=this.openHandle(true);try{let o=t.workspaceId?this.validateWorkspaceId(n,t.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:f.id,message_count:f.message_count}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get()){let c={updated_at:s};t.title!==void 0&&(c.title=t.title),t.titleLocked!==void 0&&(c.title_locked=t.titleLocked?1:0),n.db.update(f).set(c).where(drizzleOrm.eq(f.id,e)).run();}else n.db.insert(f).values({id:e,platform:t.platform,workspace_id:o,title:t.title??null,title_locked:t.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to upsert thread",o)}finally{n.close();}}ensureThread(e,t,n){let o=this.openHandle(true);try{let s=n?this.validateWorkspaceId(o,n):null,a=o.db.select({id:f.id,platform:f.platform,workspace_id:f.workspace_id}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get();if(a){s&&!a.workspace_id&&o.db.update(f).set({workspace_id:s}).where(drizzleOrm.eq(f.id,e)).run();return}let c=new Date().toISOString();o.db.insert(f).values({id:e,platform:t,workspace_id:s,message_count:0,created_at:c,updated_at:c}).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to ensure thread",s)}finally{o.close();}}saveUserMessage(e,t,n){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(c=>{let u=c.select({message_count:f.message_count}).from(f).where(drizzleOrm.eq(f.id,e)).limit(1).get()?.message_count===0;return c.run(drizzleOrm.sql`
361
361
  UPDATE threads
362
362
  SET first_message = COALESCE(first_message, ${t}),
363
363
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${t}, 1, 60) ELSE title END,
@@ -365,4 +365,4 @@ ${n.join(`
365
365
  message_count = message_count + 1,
366
366
  updated_at = ${s}
367
367
  WHERE id = ${e}
368
- `),l},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(f).set({last_message:t,updated_at:s}).where(drizzleOrm.eq(f.id,e)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,t){if(!this.dbExists())return;let n=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};t.title!==void 0&&(o.title=t.title,o.title_locked=1),t.titleLocked!==void 0&&(o.title_locked=t.titleLocked?1:0),n.db.update(f).set(o).where(drizzleOrm.eq(f.id,e)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update thread",o)}finally{n.close();}}togglePin(e,t){let n=this.openHandle(true);try{let o=t?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.id,e),s=n.db.select({pinned:f.pinned,metadata:f.metadata}).from(f).where(o).get();if(!s)return null;let a=s.pinned?0:1,c=s.metadata?JSON.parse(s.metadata):{};if(a){let u=t?drizzleOrm.and(drizzleOrm.eq(f.pinned,1),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.pinned,1),l=n.db.select({metadata:f.metadata}).from(f).where(u).all(),p=null;for(let _ of l){let g=_.metadata?JSON.parse(_.metadata):{};typeof g.pinOrder=="number"&&(p===null||g.pinOrder<p)&&(p=g.pinOrder);}c.pinOrder=p===null?0:p-1;}else delete c.pinOrder;return n.db.update(f).set({pinned:a,metadata:Object.keys(c).length>0?JSON.stringify(c):null}).where(o).run(),{pinned:!!a}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to toggle pin",o)}finally{n.close();}}reorderPins(e,t){let n=this.openHandle(true);try{for(let o=0;o<e.length;o++){let s=t?drizzleOrm.and(drizzleOrm.eq(f.id,e[o]),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.id,e[o]),a=n.db.select({metadata:f.metadata}).from(f).where(s).get();if(!a)continue;let c=a.metadata?JSON.parse(a.metadata):{};c.pinOrder=o+1,n.db.update(f).set({metadata:JSON.stringify(c)}).where(s).run();}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to reorder pins",o)}finally{n.close();}}toggleStar(e,t){let n=this.openHandle(true);try{let o=t?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.id,e),s=n.db.select({starred:f.starred}).from(f).where(o).get();if(!s)return null;let a=s.starred?0:1;return n.db.update(f).set({starred:a}).where(o).run(),{starred:!!a}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to toggle star",o)}finally{n.close();}}resolveOverdriveForRequest(e,t,n,o){let a=this.openHandle(true);try{let c=t?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.id,e);return a.db.transaction(l=>{let p=l.select({metadata:f.metadata}).from(f).where(c).get();if(!p)return null;let _=p.metadata?JSON.parse(p.metadata):{},g=_.overdrive??{},m=o?.defaultTurns??g.defaultTurns??3,P=o?.updatedBy??"ui",w=new Date().toISOString(),$,S,W,Ae;switch(n){case "enable-count":{let we=o?.turns??m,ke=o?.consumeCurrent?Math.max(we-1,0):we;$=ke>0?"count":"off",S=ke,W=!0,Ae="count";break}case "enable-latch":{$="latch",S=0,W=!0,Ae="latch";break}case "disable":{$="off",S=0,W=!1;break}default:{let we=g.state??"off",ke=typeof g.remaining=="number"?g.remaining:0;if(we==="count"&&ke>0){let Ft=ke-1;Ft<=0?($="off",S=0):($="count",S=Ft),W=!0,Ae="count";}else we==="latch"?($="latch",S=0,W=!0,Ae="latch"):($="off",S=0,W=!1);break}}return _.overdrive={state:$,remaining:S,defaultTurns:m,updatedAt:w,updatedBy:P},l.update(f).set({metadata:JSON.stringify(_),updated_at:w}).where(c).run(),{applied:W,appliedMode:Ae,state:$,remaining:S}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var Ot=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Ee).values(e).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Ee).where(drizzleOrm.eq(Ee.task_id,e)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(Ee).where(drizzleOrm.eq(Ee.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{t.close();}}};var Lt=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(pe).values(e).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(pe).where(drizzleOrm.eq(pe.task_id,e)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{t.close();}}aggregateByName(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select({toolName:pe.tool_name,count:drizzleOrm.sql`count(*)`}).from(pe).where(drizzleOrm.eq(pe.task_id,e)).groupBy(pe.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{t.close();}}};var Pt=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}ensureThreadExists(e,t){if(!e.db.select({id:f.id}).from(f).where(drizzleOrm.eq(f.id,t)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${t}`)}findByThreadId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return this.ensureThreadExists(t,e),t.db.select().from(ne).where(drizzleOrm.eq(ne.thread_id,e)).orderBy(drizzleOrm.asc(ne.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{t.close();}}findById(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(ne).where(drizzleOrm.and(drizzleOrm.eq(ne.id,t),drizzleOrm.eq(ne.thread_id,e))).limit(1).get()??void 0}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to find box by id",o)}finally{n.close();}}insert(e){let t=this.openHandle(true);try{this.ensureThreadExists(t,e.threadId);try{t.db.insert(ne).values({id:e.id,thread_id:e.threadId,seq:e.seq,first_task_id:e.first_task_id,mid_task_id:e.mid_task_id,last_task_id:e.last_task_id,task_count:e.task_count,summary:e.summary??null,source_tokens:e.source_tokens,summary_tokens:e.summary_tokens??null,created_at:e.created_at}).run();}catch(o){throw o instanceof Error&&/UNIQUE constraint failed/i.test(o.message)?new d("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let n=t.db.select().from(ne).where(drizzleOrm.eq(ne.id,e.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{t.close();}}};var $t=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}bulkInsert(e){if(e.length===0)return;let t=this.openHandle(true);try{let n=new Date().toISOString();t.db.transaction(o=>{for(let s of e)o.insert(Me).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{t.close();}}findRecent(e=100){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Me).orderBy(drizzleOrm.desc(Me.timestamp)).limit(e).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{t.close();}}};function rr(r){return new Date(Math.floor(r/3e5)*3e5).toISOString()}var jt=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}upsert(e){let t=this.openHandle(true);try{let n=rr(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(U).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:n,captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,source:e.source,metadata:e.metadata??null}).onConflictDoUpdate({target:[U.provider,U.account_ref,U.limit_window,U.bucket_start],set:{captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,metadata:e.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{t.close();}}getTrends(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=t.db.select({provider:U.provider,bucket_start:U.bucket_start,used_percent:U.used_percent,remaining_percent:U.remaining_percent,resets_at:U.resets_at}).from(U).where(drizzleOrm.and(drizzleOrm.eq(U.limit_window,e.window),drizzleOrm.gte(U.bucket_start,e.fromIso),drizzleOrm.lte(U.bucket_start,e.toIso))).orderBy(drizzleOrm.asc(U.bucket_start)).all(),o=new Map;for(let s of n)o.has(s.provider)||o.set(s.provider,[]),o.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(o.entries()).map(([s,a])=>({provider:s,points:a}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{t.close();}}};var Bt=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}publish(e){let t=this.openHandle(true);try{t.db.insert(V).values({id:e.id,workspace_id:e.workspaceId,month:e.month,generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}).onConflictDoUpdate({target:[V.workspace_id,V.month],set:{generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}}).run();let n=t.db.select().from(V).where(drizzleOrm.and(drizzleOrm.eq(V.workspace_id,e.workspaceId),drizzleOrm.eq(V.month,e.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{t.close();}}findByMonth(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(V).where(drizzleOrm.and(drizzleOrm.eq(V.workspace_id,e),drizzleOrm.eq(V.month,t))).limit(1).get()??void 0}catch(o){throw new d("DB_ERROR","Failed to find usage report",o)}finally{n.close();}}listByWorkspace(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(V).where(drizzleOrm.eq(V.workspace_id,e)).orderBy(drizzleOrm.desc(V.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{t.close();}}};var lr=500,ur=50,qt=class extends N{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??lr;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}create(e){let t=this.openHandle(true);try{let n=Ce("ntf"),o=new Date().toISOString();return t.db.insert(R).values({id:n,workspace_id:e.workspaceId,agent_id:e.agentId??null,task_id:e.taskId??null,thread_id:e.threadId??null,source:e.source??"agent",level:e.level??"info",title:e.title,body:e.body??null,target_user_id:e.targetUserId??null,created_at:o,metadata:e.metadata??null}).run(),this.enforceCap(t,e.workspaceId),{id:n}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create notification",n)}finally{t.close();}}enforceCap(e,t){let s=(e.db.select({count:drizzleOrm.sql`count(*)`}).from(R).where(drizzleOrm.eq(R.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let c=e.db.select({id:R.id}).from(R).innerJoin(j,drizzleOrm.eq(j.notification_id,R.id)).where(drizzleOrm.eq(R.workspace_id,t)).groupBy(R.id).orderBy(drizzleOrm.asc(R.created_at)).limit(s).all().map(u=>u.id);c.length!==0&&(e.db.delete(j).where(drizzleOrm.inArray(j.notification_id,c)).run(),e.db.delete(R).where(drizzleOrm.inArray(R.id,c)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??ur,n=this.openHandle(false);try{return n.db.select({id:R.id,workspace_id:R.workspace_id,agent_id:R.agent_id,task_id:R.task_id,thread_id:R.thread_id,source:R.source,level:R.level,title:R.title,body:R.body,target_user_id:R.target_user_id,created_at:R.created_at,metadata:R.metadata,read_at:j.read_at}).from(R).leftJoin(j,drizzleOrm.and(drizzleOrm.eq(j.notification_id,R.id),drizzleOrm.eq(j.user_id,e.userId))).where(drizzleOrm.eq(R.workspace_id,e.workspaceId)).orderBy(drizzleOrm.desc(R.created_at)).limit(t).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new d("DB_ERROR","Failed to list notifications",o)}finally{n.close();}}unreadCount(e){if(!this.dbExists())return 0;let t=this.openHandle(false);try{return t.db.select({count:drizzleOrm.sql`count(*)`}).from(R).leftJoin(j,drizzleOrm.and(drizzleOrm.eq(j.notification_id,R.id),drizzleOrm.eq(j.user_id,e.userId))).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,e.workspaceId),drizzleOrm.isNull(j.notification_id))).get()?.count??0}catch(n){throw new d("DB_ERROR","Failed to count unread notifications",n)}finally{t.close();}}markRead(e){let t=this.openHandle(true);try{if(!t.db.select({id:R.id}).from(R).where(drizzleOrm.and(drizzleOrm.eq(R.id,e.notificationId),drizzleOrm.eq(R.workspace_id,e.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return t.db.insert(j).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark notification read",n)}finally{t.close();}}markAllRead(e){let t=this.openHandle(true);try{let n=t.db.select({id:R.id}).from(R).leftJoin(j,drizzleOrm.and(drizzleOrm.eq(j.notification_id,R.id),drizzleOrm.eq(j.user_id,e.userId))).where(drizzleOrm.and(drizzleOrm.eq(R.workspace_id,e.workspaceId),drizzleOrm.isNull(j.notification_id))).all();if(n.length===0)return 0;let o=new Date().toISOString();return t.db.transaction(s=>{for(let a of n)s.insert(j).values({notification_id:a.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),n.length}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark all notifications read",n)}finally{t.close();}}};var gr=50,Ut=class extends N{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=ye.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=ye.dirname(t);yn.existsSync(o)||yn.mkdirSync(o,{recursive:true});}else if(!yn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{C(n.db,t);}catch(o){throw n.close(),o}return n}create(e){let t=this.openHandle(true);try{let n=new Date().toISOString(),o=[],s=e.map(a=>{let c=Ce("sug");return o.push(c),{id:c,workspace_id:a.workspaceId,agent_id:a.agentId,task_id:a.taskId??null,type:a.type,status:a.status??"pending",payload:a.payload,applied_commit_sha:a.appliedCommitSha??null,created_at:n,updated_at:n}});return s.length>0&&t.db.insert(T).values(s).run(),{ids:o}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create agent suggestions",n)}finally{t.close();}}findLatestSet(e,t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let o=n.db.select({task_id:T.task_id}).from(T).where(drizzleOrm.and(drizzleOrm.eq(T.workspace_id,e),drizzleOrm.eq(T.agent_id,t))).orderBy(drizzleOrm.desc(T.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?drizzleOrm.isNull(T.task_id):drizzleOrm.eq(T.task_id,o.task_id);return n.db.select().from(T).where(drizzleOrm.and(drizzleOrm.eq(T.workspace_id,e),drizzleOrm.eq(T.agent_id,t),s)).orderBy(drizzleOrm.asc(T.created_at)).all()}catch(o){throw new d("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{n.close();}}findSetByTaskId(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(T).where(drizzleOrm.and(drizzleOrm.eq(T.workspace_id,e),drizzleOrm.eq(T.agent_id,t),drizzleOrm.eq(T.task_id,n))).orderBy(drizzleOrm.asc(T.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,t,n){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(T).where(drizzleOrm.and(drizzleOrm.eq(T.workspace_id,e),drizzleOrm.eq(T.agent_id,t),drizzleOrm.eq(T.id,n))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,t,n){let o=this.openHandle(true);try{let s={status:t,updated_at:new Date().toISOString()};return n!==void 0&&(s.applied_commit_sha=n),o.db.update(T).set(s).where(drizzleOrm.eq(T.id,e)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,t,n=gr){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(T).where(drizzleOrm.and(drizzleOrm.eq(T.workspace_id,e),drizzleOrm.eq(T.agent_id,t))).orderBy(drizzleOrm.desc(T.created_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,t,n=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(T).where(drizzleOrm.and(drizzleOrm.eq(T.workspace_id,e),drizzleOrm.eq(T.agent_id,t),drizzleOrm.eq(T.status,"dismissed"))).orderBy(drizzleOrm.desc(T.updated_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};exports.AgentSuggestionRepository=Ut;exports.BaseSqliteRepository=N;exports.CREWX_JOURNAL_SIZE_LIMIT_BYTES=Wt;exports.DEFAULT_AGENT_SUGGESTION_LIST_LIMIT=gr;exports.DEFAULT_NOTIFICATION_CAP=lr;exports.DEFAULT_NOTIFICATION_LIST_LIMIT=ur;exports.DEFAULT_PROJECT_STAGES=mn;exports.DEFAULT_PROJECT_STAGE_KEYS=St;exports.NotificationRepository=qt;exports.ProjectRepository=Et;exports.RepositoryError=d;exports.RequestLogRepository=$t;exports.SpanRepository=Ot;exports.TASK_LOG_MIGRATION_EVENT_ROW_BYTES=jn;exports.TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES=_t;exports.TASK_LOG_MIGRATION_TERMINAL_STATUSES=$n;exports.TaskLogRepository=Ve;exports.TaskRepository=xt;exports.ThreadBoxRepository=Pt;exports.ThreadRepository=Ct;exports.ToolCallRepository=Lt;exports.UsageLimitSnapshotRepository=jt;exports.UsageReportRepository=Bt;exports.WorkspaceRepository=Rt;exports.calcBucketStart=rr;exports.hasSufficientTaskLogMigrationFreeSpace=Fn;exports.openDrizzleDb=k;exports.pushSchema=Io;exports.reclaimTemporaryJournal=wr;exports.resolveTaskLogMigrationDbPath=Bn;exports.runMigrations=qe;exports.runMigrationsOnce=C;exports.runTaskLogMigration=ws;exports.taskLogBackupName=ks;exports.tasks=i;exports.tryCheckpointTaskLogWal=Wn;
368
+ `),u},{behavior:"immediate"})}}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(f).set({last_message:t,updated_at:s}).where(drizzleOrm.eq(f.id,e)).run();}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,t){if(!this.dbExists())return;let n=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};t.title!==void 0&&(o.title=t.title,o.title_locked=1),t.titleLocked!==void 0&&(o.title_locked=t.titleLocked?1:0),n.db.update(f).set(o).where(drizzleOrm.eq(f.id,e)).run();}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to update thread",o)}finally{n.close();}}patchThreadTitleMetadata(e,t,n){let o=t;if(!o||typeof o!="object"||Array.isArray(o))return new ze("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new ze("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let a=o;if(a.priority===void 0&&a.state===void 0)return new ze("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let l of [a.priority,a.state])if(l!=null&&(typeof l!="string"||l.length===0))return new ze("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let c=this.openHandle(true);try{let l=n?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,n)):drizzleOrm.eq(f.id,e);return c.db.transaction(u=>{let p=u.select({metadata:f.metadata}).from(f).where(l).get();if(!p)return null;let _=ut(p.metadata),g=_.threadTitle,h=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};a.priority===null?delete h.priority:a.priority!==void 0&&(h.priority=a.priority),a.state===null?delete h.state:a.state!==void 0&&(h.state=a.state),Object.keys(h).length>0?_.threadTitle=h:delete _.threadTitle;let j=Object.keys(_).length>0?JSON.stringify(_):null,k=new Date().toISOString();u.update(f).set({metadata:j,updated_at:k}).where(l).run();let $=u.select({metadata:f.metadata}).from(f).where(l).get();if(!$)throw new d("DB_ERROR","Thread-title metadata update could not be read back");let S=bi($.metadata);return {threadId:e,priority:S.priority,state:S.state}},{behavior:"immediate"})}catch(l){throw l instanceof d?l:new d("DB_ERROR","Failed to patch thread-title metadata",l)}finally{c.close();}}togglePin(e,t){let n=this.openHandle(true);try{let o=t?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.id,e);return n.db.transaction(s=>{let a=s.select({pinned:f.pinned,metadata:f.metadata}).from(f).where(o).get();if(!a)return null;let c=a.pinned?0:1,l=ut(a.metadata);if(c){let u=t?drizzleOrm.and(drizzleOrm.eq(f.pinned,1),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.pinned,1),p=s.select({metadata:f.metadata}).from(f).where(u).all(),_=null;for(let g of p){let h=ut(g.metadata);typeof h.pinOrder=="number"&&(_===null||h.pinOrder<_)&&(_=h.pinOrder);}l.pinOrder=_===null?0:_-1;}else delete l.pinOrder;return s.update(f).set({pinned:c,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!c}},{behavior:"immediate"})}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to toggle pin",o)}finally{n.close();}}reorderPins(e,t){let n=this.openHandle(true);try{n.db.transaction(o=>{for(let s=0;s<e.length;s++){let a=t?drizzleOrm.and(drizzleOrm.eq(f.id,e[s]),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.id,e[s]),c=o.select({metadata:f.metadata}).from(f).where(a).get();if(!c)continue;let l=ut(c.metadata);l.pinOrder=s+1,o.update(f).set({metadata:JSON.stringify(l)}).where(a).run();}},{behavior:"immediate"});}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to reorder pins",o)}finally{n.close();}}toggleStar(e,t){let n=this.openHandle(true);try{let o=t?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.id,e),s=n.db.select({starred:f.starred}).from(f).where(o).get();if(!s)return null;let a=s.starred?0:1;return n.db.update(f).set({starred:a}).where(o).run(),{starred:!!a}}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to toggle star",o)}finally{n.close();}}resolveOverdriveForRequest(e,t,n,o){let a=this.openHandle(true);try{let c=t?drizzleOrm.and(drizzleOrm.eq(f.id,e),drizzleOrm.eq(f.workspace_id,t)):drizzleOrm.eq(f.id,e);return a.db.transaction(u=>{let p=u.select({metadata:f.metadata}).from(f).where(c).get();if(!p)return null;let _=p.metadata?JSON.parse(p.metadata):{},g=_.overdrive??{},h=o?.defaultTurns??g.defaultTurns??3,j=o?.updatedBy??"ui",k=new Date().toISOString(),$,S,K,Ie;switch(n){case "enable-count":{let ye=o?.turns??h,be=o?.consumeCurrent?Math.max(ye-1,0):ye;$=be>0?"count":"off",S=be,K=!0,Ie="count";break}case "enable-latch":{$="latch",S=0,K=!0,Ie="latch";break}case "disable":{$="off",S=0,K=!1;break}default:{let ye=g.state??"off",be=typeof g.remaining=="number"?g.remaining:0;if(ye==="count"&&be>0){let mn=be-1;mn<=0?($="off",S=0):($="count",S=mn),K=!0,Ie="count";}else ye==="latch"?($="latch",S=0,K=!0,Ie="latch"):($="off",S=0,K=!1);break}}return _.overdrive={state:$,remaining:S,defaultTurns:h,updatedAt:k,updatedBy:j},u.update(f).set({metadata:JSON.stringify(_),updated_at:k}).where(c).run(),{applied:K,appliedMode:Ie,state:$,remaining:S}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var et="THREAD_STATE",xt="custom:";function Ci(r){return r.dbPath?r.dbPath:r.dbRoot?Re.join(r.dbRoot,".crewx","crewx.db"):process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:Re.join(Qr.homedir(),".crewx","crewx.db")}function sn(r){if(!r)return null;try{let e=JSON.parse(r);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function Or(r){let t=sn(r)?.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t.state;return typeof n=="string"&&n.startsWith(xt)?n:null}function rn(r){let e=[...r].length;return e>=1&&e<=20}function vi(r){let e=r.select({id:f.id,workspace_id:f.workspace_id,metadata:f.metadata}).from(f).all(),t=[];for(let n of e){let o=Or(n.metadata);o!==null&&t.push({id:n.id,workspace_id:n.workspace_id,metadata:n.metadata,label:o.slice(xt.length)});}return t}function Di(r){return r===null?drizzleOrm.isNull(m.workspace_id):drizzleOrm.eq(m.workspace_id,r)}function Oi(r){return r===null?drizzleOrm.isNull(m.workspace_id):drizzleOrm.or(drizzleOrm.isNull(m.workspace_id),drizzleOrm.eq(m.workspace_id,r))}function Ni(r,e,t){let n=r.select().from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,et),drizzleOrm.eq(m.code_name,e),Di(t),drizzleOrm.eq(m.is_builtin,0))).limit(1).get();if(n)return {code:n.code,created:false};let o=r.select({maxSortOrder:drizzleOrm.sql`max(${m.sort_order})`}).from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,et),Oi(t))).get(),s=Ye();for(;r.select({code:m.code}).from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,et),drizzleOrm.eq(m.code,s))).limit(1).get();)s=Ye();let a=new Date().toISOString();return r.insert(m).values({code_group:et,code:s,code_name:e,color:"gray",sort_order:(o?.maxSortOrder??-1)+1,workspace_id:t,is_builtin:0,is_archived:0,metadata:null,created_at:a,updated_at:a}).run(),{code:s,created:true}}function Ai(r,e,t,n){let o=r.select({id:f.id,workspace_id:f.workspace_id,metadata:f.metadata}).from(f).all(),s=`${xt}${e}`,a=0,c=new Date().toISOString();for(let l of o){if(n!==null&&l.workspace_id!==n||Or(l.metadata)!==s)continue;let u=sn(l.metadata)??{},p=u.threadTitle,_=p&&typeof p=="object"&&!Array.isArray(p)?{...p}:{};_.state=t,u.threadTitle=_,r.update(f).set({metadata:JSON.stringify(u),updated_at:c}).where(drizzleOrm.eq(f.id,l.id)).run(),a+=1;}return a}function on(r,e,t){return r.transaction(n=>{let o=Ni(n,e,t),s=Ai(n,e,o.code,t);return {...o,migratedRows:s}},{behavior:"immediate"})}function xi(r,e){return r.select({code:m.code}).from(m).where(drizzleOrm.and(drizzleOrm.eq(m.code_group,et),drizzleOrm.eq(m.code_name,e),drizzleOrm.isNull(m.workspace_id),drizzleOrm.eq(m.is_builtin,0))).limit(1).get()?.code??null}function Ii(r){let e=new Set(r.select({code:m.code}).from(m).where(drizzleOrm.eq(m.code_group,et)).all().map(s=>s.code)),t=r.select({metadata:f.metadata}).from(f).all(),n=0,o=0;for(let s of t){let c=sn(s.metadata)?.threadTitle;if(!c||typeof c!="object"||Array.isArray(c))continue;let l=c.state;typeof l=="string"&&(l.startsWith(xt)&&(n+=1),e.has(l)||(o+=1));}return {remainingCustomReferences:n,orphanReferences:o}}function Nr(r={}){let e=Ci(r);if(!Qn.existsSync(e))return {migratedRows:0,createdCodes:0,remainingCustomReferences:0,orphanReferences:0};let t=y(e);try{N(t.db,e);let n=vi(t.db),o=new Set;for(let p of r.configuredLabels??[])typeof p=="string"&&o.add(p);let s=new Set(o),a=new Map;for(let p of n)if(rn(p.label))if(p.workspace_id===null)s.add(p.label);else {let _=a.get(p.workspace_id)??new Set;_.add(p.label),a.set(p.workspace_id,_);}let c=0,l=0,u=new Map;for(let p of [...s].sort()){if(!rn(p))continue;let _=on(t.db,p,null);u.set(p,_.code),c+=_.migratedRows,_.created&&(l+=1);}for(let p of [...a.keys()].sort())for(let _ of [...a.get(p)].sort()){if(!rn(_)||u.has(_))continue;if(xi(t.db,_)){let h=on(t.db,_,null);u.set(_,h.code),c+=h.migratedRows,h.created&&(l+=1);continue}let g=on(t.db,_,p);c+=g.migratedRows,g.created&&(l+=1);}return {migratedRows:c,createdCodes:l,...Ii(t.db)}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to migrate legacy thread-title common codes",n)}finally{t.close();}}var Li=Nr;var an=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Se).values(e).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert span",n)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Se).where(drizzleOrm.eq(Se.task_id,e)).all()}catch(n){throw new d("DB_ERROR","Failed to find spans by task id",n)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(Se).where(drizzleOrm.eq(Se.id,e)).limit(1).get()??void 0}catch(n){throw new d("DB_ERROR","Failed to find span by id",n)}finally{t.close();}}};var dn=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(ge).values(e).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert tool call",n)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(ge).where(drizzleOrm.eq(ge.task_id,e)).all()}catch(n){throw new d("DB_ERROR","Failed to find tool calls by task id",n)}finally{t.close();}}aggregateByName(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select({toolName:ge.tool_name,count:drizzleOrm.sql`count(*)`}).from(ge).where(drizzleOrm.eq(ge.task_id,e)).groupBy(ge.tool_name).all().map(n=>({toolName:n.toolName,count:n.count}))}catch(n){throw new d("DB_ERROR","Failed to aggregate tool calls by name",n)}finally{t.close();}}};var cn=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}ensureThreadExists(e,t){if(!e.db.select({id:f.id}).from(f).where(drizzleOrm.eq(f.id,t)).limit(1).get())throw new d("NOT_FOUND",`Thread not found: ${t}`)}findByThreadId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return this.ensureThreadExists(t,e),t.db.select().from(de).where(drizzleOrm.eq(de.thread_id,e)).orderBy(drizzleOrm.asc(de.seq)).all()}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to find boxes by thread id",n)}finally{t.close();}}findById(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(de).where(drizzleOrm.and(drizzleOrm.eq(de.id,t),drizzleOrm.eq(de.thread_id,e))).limit(1).get()??void 0}catch(o){throw o instanceof d?o:new d("DB_ERROR","Failed to find box by id",o)}finally{n.close();}}insert(e){let t=this.openHandle(true);try{this.ensureThreadExists(t,e.threadId);try{t.db.insert(de).values({id:e.id,thread_id:e.threadId,seq:e.seq,first_task_id:e.first_task_id,mid_task_id:e.mid_task_id,last_task_id:e.last_task_id,task_count:e.task_count,summary:e.summary??null,source_tokens:e.source_tokens,summary_tokens:e.summary_tokens??null,created_at:e.created_at}).run();}catch(o){throw o instanceof Error&&/UNIQUE constraint failed/i.test(o.message)?new d("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let n=t.db.select().from(de).where(drizzleOrm.eq(de.id,e.id)).limit(1).get();if(!n)throw new d("DB_ERROR","Insert did not return a row");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to insert thread box",n)}finally{t.close();}}};var ln=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}bulkInsert(e){if(e.length===0)return;let t=this.openHandle(true);try{let n=new Date().toISOString();t.db.transaction(o=>{for(let s of e)o.insert(Ke).values({id:crypto.randomUUID(),path:s.path,method:s.method,status_code:s.statusCode,duration_ms:s.durationMs,ip:s.ip??null,request_headers:s.requestHeaders??null,response_headers:s.responseHeaders??null,request_body:s.requestBody??null,response_body:s.responseBody??null,query:s.query??null,user_id:s.userId??null,project_id:s.projectId??null,partition_key:s.partitionKey??"default",timestamp:n,metadata:s.metadata??null}).run();});}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to bulk insert request logs",n)}finally{t.close();}}findRecent(e=100){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Ke).orderBy(drizzleOrm.desc(Ke.timestamp)).limit(e).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{t.close();}}};function Mr(r){return new Date(Math.floor(r/3e5)*3e5).toISOString()}var un=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}upsert(e){let t=this.openHandle(true);try{let n=Mr(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(z).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:n,captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,source:e.source,metadata:e.metadata??null}).onConflictDoUpdate({target:[z.provider,z.account_ref,z.limit_window,z.bucket_start],set:{captured_at:e.capturedAt,used_percent:e.usedPercent,remaining_percent:e.remainingPercent,resets_at:e.resetsAt??null,metadata:e.metadata??null}}).run();}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to upsert usage limit snapshot",n)}finally{t.close();}}getTrends(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let n=t.db.select({provider:z.provider,bucket_start:z.bucket_start,used_percent:z.used_percent,remaining_percent:z.remaining_percent,resets_at:z.resets_at}).from(z).where(drizzleOrm.and(drizzleOrm.eq(z.limit_window,e.window),drizzleOrm.gte(z.bucket_start,e.fromIso),drizzleOrm.lte(z.bucket_start,e.toIso))).orderBy(drizzleOrm.asc(z.bucket_start)).all(),o=new Map;for(let s of n)o.has(s.provider)||o.set(s.provider,[]),o.get(s.provider).push({bucketStart:s.bucket_start,usedPercent:s.used_percent,remainingPercent:s.remaining_percent,resetsAt:s.resets_at??null});return Array.from(o.entries()).map(([s,a])=>({provider:s,points:a}))}catch(n){throw new d("DB_ERROR","Failed to get usage limit trends",n)}finally{t.close();}}};var pn=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}publish(e){let t=this.openHandle(true);try{t.db.insert(Z).values({id:e.id,workspace_id:e.workspaceId,month:e.month,generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}).onConflictDoUpdate({target:[Z.workspace_id,Z.month],set:{generated_at:e.generatedAt,source_range:e.sourceRange,tier:e.tier,total_tokens:e.totalTokens,total_cost_usd:e.totalCostUsd,payload:e.payload}}).run();let n=t.db.select().from(Z).where(drizzleOrm.and(drizzleOrm.eq(Z.workspace_id,e.workspaceId),drizzleOrm.eq(Z.month,e.month))).limit(1).get();if(!n)throw new d("DB_ERROR","Failed to read back published usage report");return n}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to publish usage report",n)}finally{t.close();}}findByMonth(e,t){if(!this.dbExists())return;let n=this.openHandle(false);try{return n.db.select().from(Z).where(drizzleOrm.and(drizzleOrm.eq(Z.workspace_id,e),drizzleOrm.eq(Z.month,t))).limit(1).get()??void 0}catch(o){throw new d("DB_ERROR","Failed to find usage report",o)}finally{n.close();}}listByWorkspace(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Z).where(drizzleOrm.eq(Z.workspace_id,e)).orderBy(drizzleOrm.desc(Z.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{t.close();}}};var Wr=500,Gr=50,_n=class extends v{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??Wr;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}create(e){let t=this.openHandle(true);try{let n=je("ntf"),o=new Date().toISOString();return t.db.insert(T).values({id:n,workspace_id:e.workspaceId,agent_id:e.agentId??null,task_id:e.taskId??null,thread_id:e.threadId??null,source:e.source??"agent",level:e.level??"info",title:e.title,body:e.body??null,target_user_id:e.targetUserId??null,created_at:o,metadata:e.metadata??null}).run(),this.enforceCap(t,e.workspaceId),{id:n}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create notification",n)}finally{t.close();}}enforceCap(e,t){let s=(e.db.select({count:drizzleOrm.sql`count(*)`}).from(T).where(drizzleOrm.eq(T.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let c=e.db.select({id:T.id}).from(T).innerJoin(B,drizzleOrm.eq(B.notification_id,T.id)).where(drizzleOrm.eq(T.workspace_id,t)).groupBy(T.id).orderBy(drizzleOrm.asc(T.created_at)).limit(s).all().map(l=>l.id);c.length!==0&&(e.db.delete(B).where(drizzleOrm.inArray(B.notification_id,c)).run(),e.db.delete(T).where(drizzleOrm.inArray(T.id,c)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??Gr,n=this.openHandle(false);try{return n.db.select({id:T.id,workspace_id:T.workspace_id,agent_id:T.agent_id,task_id:T.task_id,thread_id:T.thread_id,source:T.source,level:T.level,title:T.title,body:T.body,target_user_id:T.target_user_id,created_at:T.created_at,metadata:T.metadata,read_at:B.read_at}).from(T).leftJoin(B,drizzleOrm.and(drizzleOrm.eq(B.notification_id,T.id),drizzleOrm.eq(B.user_id,e.userId))).where(drizzleOrm.eq(T.workspace_id,e.workspaceId)).orderBy(drizzleOrm.desc(T.created_at)).limit(t).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new d("DB_ERROR","Failed to list notifications",o)}finally{n.close();}}unreadCount(e){if(!this.dbExists())return 0;let t=this.openHandle(false);try{return t.db.select({count:drizzleOrm.sql`count(*)`}).from(T).leftJoin(B,drizzleOrm.and(drizzleOrm.eq(B.notification_id,T.id),drizzleOrm.eq(B.user_id,e.userId))).where(drizzleOrm.and(drizzleOrm.eq(T.workspace_id,e.workspaceId),drizzleOrm.isNull(B.notification_id))).get()?.count??0}catch(n){throw new d("DB_ERROR","Failed to count unread notifications",n)}finally{t.close();}}markRead(e){let t=this.openHandle(true);try{if(!t.db.select({id:T.id}).from(T).where(drizzleOrm.and(drizzleOrm.eq(T.id,e.notificationId),drizzleOrm.eq(T.workspace_id,e.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return t.db.insert(B).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark notification read",n)}finally{t.close();}}markAllRead(e){let t=this.openHandle(true);try{let n=t.db.select({id:T.id}).from(T).leftJoin(B,drizzleOrm.and(drizzleOrm.eq(B.notification_id,T.id),drizzleOrm.eq(B.user_id,e.userId))).where(drizzleOrm.and(drizzleOrm.eq(T.workspace_id,e.workspaceId),drizzleOrm.isNull(B.notification_id))).all();if(n.length===0)return 0;let o=new Date().toISOString();return t.db.transaction(s=>{for(let a of n)s.insert(B).values({notification_id:a.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),n.length}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to mark all notifications read",n)}finally{t.close();}}};var Jr=50,gn=class extends v{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=Re.join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=Re.dirname(t);Qn.existsSync(o)||Qn.mkdirSync(o,{recursive:true});}else if(!Qn.existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{N(n.db,t);}catch(o){throw n.close(),o}return n}create(e){let t=this.openHandle(true);try{let n=new Date().toISOString(),o=[],s=e.map(a=>{let c=je("sug");return o.push(c),{id:c,workspace_id:a.workspaceId,agent_id:a.agentId,task_id:a.taskId??null,type:a.type,status:a.status??"pending",payload:a.payload,applied_commit_sha:a.appliedCommitSha??null,created_at:n,updated_at:n}});return s.length>0&&t.db.insert(C).values(s).run(),{ids:o}}catch(n){throw n instanceof d?n:new d("DB_ERROR","Failed to create agent suggestions",n)}finally{t.close();}}findLatestSet(e,t){if(!this.dbExists())return [];let n=this.openHandle(false);try{let o=n.db.select({task_id:C.task_id}).from(C).where(drizzleOrm.and(drizzleOrm.eq(C.workspace_id,e),drizzleOrm.eq(C.agent_id,t))).orderBy(drizzleOrm.desc(C.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?drizzleOrm.isNull(C.task_id):drizzleOrm.eq(C.task_id,o.task_id);return n.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.workspace_id,e),drizzleOrm.eq(C.agent_id,t),s)).orderBy(drizzleOrm.asc(C.created_at)).all()}catch(o){throw new d("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{n.close();}}findSetByTaskId(e,t,n){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.workspace_id,e),drizzleOrm.eq(C.agent_id,t),drizzleOrm.eq(C.task_id,n))).orderBy(drizzleOrm.asc(C.created_at)).all()}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,t,n){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.workspace_id,e),drizzleOrm.eq(C.agent_id,t),drizzleOrm.eq(C.id,n))).get()??null}catch(s){throw new d("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,t,n){let o=this.openHandle(true);try{let s={status:t,updated_at:new Date().toISOString()};return n!==void 0&&(s.applied_commit_sha=n),o.db.update(C).set(s).where(drizzleOrm.eq(C.id,e)).run().changes>0}catch(s){throw s instanceof d?s:new d("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,t,n=Jr){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.workspace_id,e),drizzleOrm.eq(C.agent_id,t))).orderBy(drizzleOrm.desc(C.created_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,t,n=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(C).where(drizzleOrm.and(drizzleOrm.eq(C.workspace_id,e),drizzleOrm.eq(C.agent_id,t),drizzleOrm.eq(C.status,"dismissed"))).orderBy(drizzleOrm.desc(C.updated_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};exports.AgentSuggestionRepository=gn;exports.BaseSqliteRepository=v;exports.COMMON_CODE_COLORS=bt;exports.COMMON_CODE_GROUPS=yt;exports.CREWX_JOURNAL_SIZE_LIMIT_BYTES=kn;exports.CommonCodeRepository=Ft;exports.CommonCodeRepositoryError=U;exports.DEFAULT_AGENT_SUGGESTION_LIST_LIMIT=Jr;exports.DEFAULT_NOTIFICATION_CAP=Wr;exports.DEFAULT_NOTIFICATION_LIST_LIMIT=Gr;exports.DEFAULT_PROJECT_STAGES=Kn;exports.DEFAULT_PROJECT_STAGE_KEYS=Kt;exports.NotificationRepository=_n;exports.ProjectRepository=Vt;exports.RepositoryError=d;exports.RequestLogRepository=ln;exports.SpanRepository=an;exports.TASK_LOG_MIGRATION_EVENT_ROW_BYTES=gr;exports.TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES=Ot;exports.TASK_LOG_MIGRATION_TERMINAL_STATUSES=fr;exports.TaskLogRepository=dt;exports.TaskRepository=Xt;exports.ThreadBoxRepository=cn;exports.ThreadRepository=nn;exports.ThreadTitleMetadataPatchError=ze;exports.ToolCallRepository=dn;exports.UsageLimitSnapshotRepository=un;exports.UsageReportRepository=pn;exports.WorkspaceRepository=Gt;exports.calcBucketStart=Mr;exports.generateCommonCodeId=Ye;exports.hasSufficientTaskLogMigrationFreeSpace=yr;exports.migrateLegacyThreadTitleCommonCodes=Nr;exports.migrateThreadTitleCommonCodes=Li;exports.openDrizzleDb=y;exports.pushSchema=Ds;exports.reclaimTemporaryJournal=Zr;exports.resolveTaskLogMigrationDbPath=mr;exports.runMigrations=Ge;exports.runMigrationsOnce=N;exports.runTaskLogMigration=gi;exports.taskLogBackupName=mi;exports.tasks=i;exports.tryCheckpointTaskLogWal=Er;