@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
- import*as be from'path';import be__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as bn from'fs';import bn__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import Rr,{homedir}from'os';import {sql,and,eq,ne,isNull,desc,isNotNull,asc,gt as gt$1,lt,or as or$1,notLike,like,inArray,gte,lte}from'drizzle-orm';import {randomUUID,createHash,randomBytes}from'crypto';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var qe=(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 wr=()=>fileURLToPath(import.meta.url),kr=()=>be__default.dirname(wr()),y=kr();var D=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(Rr.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return 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 zt=r=>{try{return bn.statSync(`${r}-wal`).size}catch{return 0}},Kt=32*1024*1024;function k(r){let e=qe("better-sqlite3"),{drizzle:t}=qe("drizzle-orm/better-sqlite3"),n=new e(r);return n.exec("PRAGMA journal_mode = WAL"),n.exec(`PRAGMA journal_size_limit = ${Kt}`),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 Er(r,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=qe("better-sqlite3"),n=zt(r),o;try{o=new t(r),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),a=zt(r);return {busy:s[0]?.busy===1,walBytesBefore:n,walBytesAfter:a}}finally{o?.close();}}var Gt=new Set,Sr={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 ft(r,e){return (r.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function Tr(r,e){if(e>0||!ft(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(Sr))n.has(o)||r.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var vr={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"}};function xr(r,e,t){if(!ft(r,"__drizzle_migrations")||!ft(r,"tasks"))return;let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(readFileSync(be__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=vr[a.tag];if(!c)continue;let u=be__default.join(e,`${a.tag}.sql`);if(!existsSync(u))continue;let l=readFileSync(u,"utf-8"),p=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,$]of Object.entries(c))g.has(m)||(r.run(`ALTER TABLE tasks ADD COLUMN ${m} ${$}`),g.add(m));}}function Nr(r,e,t){let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(readFileSync(be__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=be__default.join(e,`${a.tag}.sql`);if(!existsSync(c))continue;let u=readFileSync(c,"utf-8"),l=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:j})=>r.all(`PRAGMA table_info("${w}")`).some(K=>K.name===j))&&r.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${l}, ${a.when})`);}}function Me(r){let{migrate:e}=qe("drizzle-orm/better-sqlite3/migrator"),{sql:t}=qe("drizzle-orm"),n=[be__default.join(y,"../migrations"),be__default.join(y,"migrations"),be__default.join(y,"../../../../drizzle/migrations"),be__default.join(process.cwd(),"drizzle/migrations")],o=n.find(l=>existsSync(be__default.join(l,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
1
+ import*as Ee from'path';import Ee__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as Zn from'fs';import Zn__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import ro,{homedir}from'os';import {randomUUID,createHash,randomBytes}from'crypto';import {sql,and,eq,asc,ne,isNull,desc,isNotNull,gt,lt,or,notLike,like,inArray,gte,lte}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var Ge=(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 Zr=()=>fileURLToPath(import.meta.url),eo=()=>Ee__default.dirname(Zr()),b=eo();var D=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(ro.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return 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 wn=r=>{try{return Zn.statSync(`${r}-wal`).size}catch{return 0}},yn=32*1024*1024;function y(r){let e=Ge("better-sqlite3"),{drizzle:t}=Ge("drizzle-orm/better-sqlite3"),n=new e(r);return n.exec("PRAGMA journal_mode = WAL"),n.exec(`PRAGMA journal_size_limit = ${yn}`),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 oo(r,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=Ge("better-sqlite3"),n=wn(r),o;try{o=new t(r),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),a=wn(r);return {busy:s[0]?.busy===1,walBytesBefore:n,walBytesAfter:a}}finally{o?.close();}}var bn=new Set,so={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 Lt(r,e){return (r.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function io(r,e){if(e>0||!Lt(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(so))n.has(o)||r.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var ao={"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 co(r,e,t){if(!Lt(r,"__drizzle_migrations")||!Lt(r,"tasks"))return;let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(readFileSync(Ee__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=ao[a.tag];if(!c)continue;let l=Ee__default.join(e,`${a.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),p=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,$]of Object.entries(c))g.has(h)||(r.run(`ALTER TABLE tasks ADD COLUMN ${h} ${$}`),g.add(h));}}function lo(r,e,t){let n=r.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(n.map(a=>a.hash)),s=JSON.parse(readFileSync(Ee__default.join(e,"meta/_journal.json"),"utf-8"));for(let a of s.entries){let c=Ee__default.join(e,`${a.tag}.sql`);if(!existsSync(c))continue;let l=readFileSync(c,"utf-8"),u=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:M})=>r.all(`PRAGMA table_info("${k}")`).some(J=>J.name===M))&&r.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${a.when})`);}}function Ve(r){let{migrate:e}=Ge("drizzle-orm/better-sqlite3/migrator"),{sql:t}=Ge("drizzle-orm"),n=[Ee__default.join(b,"../migrations"),Ee__default.join(b,"migrations"),Ee__default.join(b,"../../../../drizzle/migrations"),Ee__default.join(process.cwd(),"drizzle/migrations")],o=n.find(u=>existsSync(Ee__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),Tr(r,a),s?.cnt&&(Nr(r,o,t),xr(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 O(r,e){Gt.has(e)||(Me(r),Gt.add(e));}var h=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},r=>({log_storage_check:check("tasks_log_storage_ck",sql`${r.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(r.agent_id),idx_tasks_status:index("idx_tasks_status").on(r.status),idx_tasks_started_at:index("idx_tasks_started_at").on(r.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(r.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(r.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(r.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(r.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(r.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(r.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(r.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(r.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(r.workspace_id,r.started_at)}));var pe=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>i.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},r=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(r.task_id,r.seq)}));var f=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>h.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},r=>({idx_threads_updated_at:index("idx_threads_updated_at").on(r.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(r.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(r.workspace_id,r.updated_at),idx_threads_title:index("idx_threads_title").on(r.title)}));var Se=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Se.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},r=>({idx_spans_task_id:index("idx_spans_task_id").on(r.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(r.parent_span_id)}));var _e=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},r=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(r.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(r.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(r.timestamp)}));var re=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>f.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},r=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(r.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(r.thread_id,r.seq),uniq_thread_boxes_thread_seq:unique().on(r.thread_id,r.seq)}));var Ue=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},r=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(r.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(r.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(r.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(r.partition_key)}));var F=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},r=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(r.provider,r.account_ref,r.limit_window,r.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(r.limit_window,r.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(r.provider,r.limit_window,r.bucket_start)}));var Y=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},r=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(r.workspace_id,r.month)}));var E=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},r=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(r.workspace_id,sql`${r.created_at} DESC`)})),B=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},r=>({pk:primaryKey({columns:[r.notification_id,r.user_id]})}));var v=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},r=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(r.workspace_id,r.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(r.workspace_id,r.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},r=>({idCheck:check("ui_instances_id_ck",sql`length(${r.id}) BETWEEN 5 AND 128 AND ${r.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${r.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${r.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${r.definition_hash}) = 64 AND ${r.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${r.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${r.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${r.domain_ref_json}) AND json_type(${r.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${r.state_json}) AND json_type(${r.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${r.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${r.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${r.granted_capabilities_json}) AND json_type(${r.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${r.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${r.updated_at} >= ${r.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(r.workspace_id,r.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},r=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${r.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${r.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${r.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${r.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${r.actor_json}) AND json_type(${r.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${r.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${r.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${r.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${r.after_revision} IS NULL OR ${r.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${r.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${r.outcome} IS NULL OR ${r.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${r.input_json}) AND json_type(${r.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${r.result_json} IS NULL OR (json_valid(${r.result_json}) AND json_type(${r.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${r.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${r.settled_at} IS NULL OR ${r.settled_at} >= ${r.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",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),io(r,a),s?.cnt&&(lo(r,o,t),co(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 A(r,e){bn.has(e)||(Ve(r),bn.add(e));}var w=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});var i=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0)},r=>({log_storage_check:check("tasks_log_storage_ck",sql`${r.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(r.agent_id),idx_tasks_status:index("idx_tasks_status").on(r.status),idx_tasks_started_at:index("idx_tasks_started_at").on(r.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(r.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(r.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(r.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(r.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(r.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(r.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(r.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(r.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(r.workspace_id,r.started_at)}));var ge=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>i.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},r=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(r.task_id,r.seq)}));var yo="json_extract(metadata, '$.threadTitle.state')",bo="json_extract(metadata, '$.threadTitle.priority')",f=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>w.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},r=>({idx_threads_updated_at:index("idx_threads_updated_at").on(r.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(r.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(r.workspace_id,r.updated_at),idx_threads_title:index("idx_threads_title").on(r.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(r.workspace_id,sql.raw(yo)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(r.workspace_id,sql.raw(bo))}));var Ce=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Ce.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},r=>({idx_spans_task_id:index("idx_spans_task_id").on(r.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(r.parent_span_id)}));var me=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>i.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},r=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(r.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(r.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(r.timestamp)}));var ce=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>f.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},r=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(r.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(r.thread_id,r.seq),uniq_thread_boxes_thread_seq:unique().on(r.thread_id,r.seq)}));var Je=sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},r=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(r.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(r.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(r.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(r.partition_key)}));var W=sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},r=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(r.provider,r.account_ref,r.limit_window,r.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(r.limit_window,r.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(r.provider,r.limit_window,r.bucket_start)}));var ee=sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},r=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(r.workspace_id,r.month)}));var S=sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},r=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(r.workspace_id,sql`${r.created_at} DESC`)})),q=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},r=>({pk:primaryKey({columns:[r.notification_id,r.user_id]})}));var v=sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},r=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(r.workspace_id,r.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(r.workspace_id,r.created_at)}));sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},r=>({idCheck:check("ui_instances_id_ck",sql`length(${r.id}) BETWEEN 5 AND 128 AND ${r.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${r.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${r.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${r.definition_hash}) = 64 AND ${r.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${r.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${r.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${r.domain_ref_json}) AND json_type(${r.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${r.state_json}) AND json_type(${r.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${r.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${r.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${r.granted_capabilities_json}) AND json_type(${r.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${r.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${r.updated_at} >= ${r.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(r.workspace_id,r.thread_id)}));sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},r=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${r.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${r.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${r.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${r.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${r.actor_json}) AND json_type(${r.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${r.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${r.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${r.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${r.after_revision} IS NULL OR ${r.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${r.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${r.outcome} IS NULL OR ${r.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${r.input_json}) AND json_type(${r.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${r.result_json} IS NULL OR (json_valid(${r.result_json}) AND json_type(${r.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${r.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${r.settled_at} IS NULL OR ${r.settled_at} >= ${r.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",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:uniqueIndex("ui_action_receipts_instance_request_uq").on(r.instance_id,r.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(r.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(r.requested_at)}));var x=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},r=>({idCheck:check("projects_id_ck",sql`${r.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${r.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${r.stages_json}) AND json_type(${r.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${r.stage_index} >= 1`)})),Z=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>x.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},r=>({idCheck:check("project_criteria_id_ck",sql`${r.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${r.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${r.evidence_json}) AND json_type(${r.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(r.project_id,r.position)})),le=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>x.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},r=>({idCheck:check("project_events_id_ck",sql`${r.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${r.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${r.payload_json}) AND json_type(${r.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(r.project_id,r.seq)}));function yt(r){let e=be.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 an(r){let e=yt(r);return createHash("sha256").update(e).digest("hex")}function dt(r){return r.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Et=class extends D{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{Me(n.db);}catch(o){throw n.close(),o}return n}resolveSlug(e,t,n){let o=dt(basename(n)),a=`${dt(basename(dirname(n)))}-${o}`,c=[o,a];try{let u=l=>e.select({id:h.id}).from(h).where(and(eq(h.slug,l),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=dt(o.slug.replace(/\//g,"-"));e.db.update(h).set({slug:s,updated_at:new Date().toISOString()}).where(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(and(eq(h.id,n),isNull(h.workspace_path))).run();}registerWorkspace(e){let t=yt(e),n=this.openHandle(true);try{let o=an(t),s=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?eq(h.is_active,e.isActive?1:0):void 0,o=t.db.select({count:sql`count(*)`}).from(h).where(n).get();return {rows:t.db.select().from(h).where(n).orderBy(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(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(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(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:n.db.all(sql`SELECT t.*,
7
+ )`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(r.instance_id,r.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(r.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(r.requested_at)}));var O=sqliteTable("projects",{id:text("id").primaryKey().notNull(),workspace_id:text("workspace_id").notNull(),name:text("name").notNull(),outcome:text("outcome").notNull(),due_date:text("due_date"),scene:text("scene").notNull().default("planning"),stages_json:text("stages_json").notNull(),stage_index:integer("stage_index").notNull(),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),accepted_at:text("accepted_at"),archived_at:text("archived_at")},r=>({idCheck:check("projects_id_ck",sql`${r.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${r.scene} IN ('planning', 'plan_review', 'running', 'human_wait', 'limit_wait', 'failed_stop', 'analyzing_feedback', 'replanned', 'awaiting_review', 'accepted')`),stagesJsonCheck:check("projects_stages_json_ck",sql`json_valid(${r.stages_json}) AND json_type(${r.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${r.stage_index} >= 1`)})),re=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>O.id,{onDelete:"cascade"}),position:integer("position").notNull(),statement:text("statement").notNull(),verify_status:text("verify_status").notNull().default("pending"),verified_at:text("verified_at"),evidence_json:text("evidence_json").notNull().default("[]"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},r=>({idCheck:check("project_criteria_id_ck",sql`${r.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${r.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${r.evidence_json}) AND json_type(${r.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(r.project_id,r.position)})),fe=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>O.id,{onDelete:"restrict"}),seq:integer("seq").notNull(),actor_type:text("actor_type").notNull(),actor_id:text("actor_id"),type:text("type").notNull(),title:text("title").notNull(),summary:text("summary"),payload_json:text("payload_json").notNull().default("{}"),created_at:text("created_at").notNull()},r=>({idCheck:check("project_events_id_ck",sql`${r.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${r.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${r.payload_json}) AND json_type(${r.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(r.project_id,r.seq)}));var bt=["THREAD_STATE","THREAD_PRIORITY"],Rt=["gray","blue","violet","green","amber","orange","red","pink"],m=sqliteTable("common_codes",{code_group:text("code_group").notNull(),code:text("code").notNull(),code_name:text("code_name"),color:text("color").notNull().default("gray"),sort_order:integer("sort_order").notNull(),workspace_id:text("workspace_id"),is_builtin:integer("is_builtin").notNull().default(0),is_archived:integer("is_archived").notNull().default(0),metadata:text("metadata"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},r=>({pk:primaryKey({columns:[r.code_group,r.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${r.metadata} IS NULL OR (json_valid(${r.metadata}) AND json_type(${r.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${r.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${r.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(r.code_group,r.is_archived,r.sort_order)}));var F=class extends d{reason;constructor(e,t="VALIDATION",n=e,o){super(t,n,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Pn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ns(){let r=randomBytes(16),e="";for(let t of r)e+=Pn[t%Pn.length];return e.slice(0,12)}function Xe(){return `c_${ns()}`}function rs(r){return typeof r=="string"&&bt.includes(r)}function os(r){return typeof r=="string"&&Rt.includes(r)}function st(r){if(!rs(r))throw new F("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${r}`)}function jn(r){if(!os(r))throw new F("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${r}`)}function $n(r){let e=typeof r=="string"?r.trim():"",t=[...e].length;if(t<1||t>20)throw new F("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function it(r){if(typeof r!="string"||r.trim().length===0)throw new F("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function Ft(r){if(typeof r!="string"||r.trim().length===0)throw new F("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function Ye(r,e){return and(eq(m.code_group,r),or(isNull(m.workspace_id),eq(m.workspace_id,e)))}var Ht=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new d("NOT_FOUND","Database not found");e&&mkdirSync(dirname(t),{recursive:true});let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}listSelectable(e,t){if(st(e),it(t),!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(m).where(and(Ye(e,t),eq(m.is_archived,0))).orderBy(asc(m.sort_order),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(st(e),it(t),!this.dbExists())return [];let n=this.openHandle(false);try{return n.db.select().from(m).where(Ye(e,t)).orderBy(asc(m.sort_order),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(st(e),Ft(t),!this.dbExists())return null;let n=this.openHandle(false);try{return n.db.select().from(m).where(and(eq(m.code_group,e),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){it(e.workspaceId);let t=$n(e.name);jn(e.color);let n=this.openHandle(true);try{return n.db.transaction(o=>{if(o.select({code:m.code}).from(m).where(and(Ye("THREAD_STATE",e.workspaceId),eq(m.is_archived,0),eq(m.code_name,t))).limit(1).get())throw new F("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`);let a=o.select({maxSortOrder:sql`max(${m.sort_order})`}).from(m).where(Ye("THREAD_STATE",e.workspaceId)).get(),c=new Date().toISOString(),l=Xe();for(;o.select({code:m.code}).from(m).where(and(eq(m.code_group,"THREAD_STATE"),eq(m.code,l))).limit(1).get();)l=Xe();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(and(eq(m.code_group,"THREAD_STATE"),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(st(e.group),Ft(e.code),it(e.workspaceId),e.name===void 0&&e.color===void 0)throw new F("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let t=e.name===void 0||e.name===null?e.name:$n(e.name);e.color!==void 0&&jn(e.color);let n=this.openHandle(true);try{return n.db.transaction(o=>{let s=o.select().from(m).where(and(eq(m.code_group,e.group),eq(m.code,e.code))).limit(1).get();if(!s)throw new F("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 F("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof t=="string"&&s.is_archived===0){let l=and(Ye(e.group,e.workspaceId),eq(m.is_archived,0));if(o.select({code:m.code}).from(m).where(and(l,eq(m.code_name,t),sql`${m.code} <> ${e.code}`)).limit(1).get())throw new F("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(and(eq(m.code_group,e.group),eq(m.code,e.code))).run();let c=o.select().from(m).where(and(eq(m.code_group,e.group),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(st(e),Ft(t),it(n),typeof o!="boolean")throw new F("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(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get();if(!c)throw new F("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${t}`);if(c.is_builtin===1)throw new F("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(and(Ye(e,n),eq(m.is_archived,0),eq(m.code_name,c.code_name),ne(m.code,t))).limit(1).get())throw new F("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(and(eq(m.code_group,e),eq(m.code,t))).run();let l=a.select().from(m).where(and(eq(m.code_group,e),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 F("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function zt(r){let e=Ee.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 Bn(r){let e=zt(r);return createHash("sha256").update(e).digest("hex")}function Tt(r){return r.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Vt=class extends D{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{Ve(n.db);}catch(o){throw n.close(),o}return n}resolveSlug(e,t,n){let o=Tt(basename(n)),a=`${Tt(basename(dirname(n)))}-${o}`,c=[o,a];try{let l=u=>e.select({id:w.id}).from(w).where(and(eq(w.slug,u),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=Tt(o.slug.replace(/\//g,"-"));e.db.update(w).set({slug:s,updated_at:new Date().toISOString()}).where(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(and(eq(w.id,n),isNull(w.workspace_path))).run();}registerWorkspace(e){let t=zt(e),n=this.openHandle(true);try{let o=Bn(t),s=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?eq(w.is_active,e.isActive?1:0):void 0,o=t.db.select({count:sql`count(*)`}).from(w).where(n).get();return {rows:t.db.select().from(w).where(n).orderBy(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(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(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(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:n.db.all(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(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?and(eq(h.slug,e),ne(h.id,t)):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(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(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(and(eq(h.is_active,1),isNotNull(h.workspace_path))).all(),n=0;for(let o of t){let s=o.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(e.db.update(h).set({is_active:0,updated_at:new Date().toISOString()}).where(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(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${e}`),t.db.delete(h).where(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 un="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function _o(r){let e=randomBytes(r*2),t="";for(let n=0;n<e.length&&t.length<r;n++){let o=e[n];o<248&&(t+=un[o%62]);}for(;t.length<r;)t+=un[randomBytes(1)[0]%62];return t}function Oe(r){return `${r}_${_o(8)}`}var Tt=["outcome_plan","contract_check","feature_link","use_verify","result_review"],yo=new Set(Tt),hn=Object.freeze(Tt.map(r=>({key:r,labelOverride:null}))),bo=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),Ro=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),Eo=new Set(["pending","verifying","passed","failed"]),So=new Set(["user","project_manager","system"]),To=new Set(["task","wi","url"]),vo=/^\d{4}-\d{2}-\d{2}$/;function L(r){throw new d("VALIDATION",r)}function oe(r){throw new d("NOT_FOUND",r)}function M(r,e){(typeof r!="string"||r.trim().length===0)&&L(`${e} is required`);}function xo(r){if(r==null)return;vo.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 wn(r){let e=r??hn;(!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 M(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&L("stage.labelOverride must be a string or null"),o.labelOverride!==null&&M(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&L("stage.key is required"),!yo.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 No(r){Array.isArray(r)||L("criteria must be an array");for(let e of r)M(e,"criterion.statement");}function Fe(r={}){let e=r.actorType??"system";So.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 kn(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 Do(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"),To.has(e.kind)||L(`invalid evidence kind: ${String(e.kind)}`),M(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 mn(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 wn(e)}catch(t){throw new d("DB_ERROR","Project stages JSON is invalid",t)}}function yn(r){return M(r.projectId,"projectId"),M(r.title,"title"),bo.has(r.type)||L(`invalid project event type: ${String(r.type)}`),{...Fe(r),payloadJson:kn(r.payload,r.type)}}function je(r,e,t){let n=yn(e);r.select({id:x.id}).from(x).where(eq(x.id,e.projectId)).get()||oe(`Project ${e.projectId} not found`);let s=r.select({maxSeq:sql`COALESCE(MAX(${le.seq}), 0)`}).from(le).where(eq(le.project_id,e.projectId)).get()?.maxSeq??0,a=Oe("pje");r.insert(le).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(le).where(eq(le.id,a)).get();if(!c)throw new d("DB_ERROR","Event insert did not return a row");return c}var St=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new d("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let n=k(t);if(e)try{O(n.db,t);}catch(o){throw n.close(),o}return n}getDetailFromHandle(e,t){let n=e.db.select().from(x).where(eq(x.id,t)).get();if(!n)return;let o=e.db.select().from(Z).where(eq(Z.project_id,t)).orderBy(asc(Z.position)).all();return {...n,stages:mn(n.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||oe(`Project ${e} not found`),t}createProject(e){M(e.workspaceId,"workspaceId"),M(e.name,"name"),M(e.outcome,"outcome"),xo(e.dueDate);let t=wn(e.stages);No(e.criteria);let n=Oe("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(a=>{a.insert(x).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(Z).values({id:Oe("pjc"),project_id:n,position:u+1,statement:c,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),je(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(M(e,"workspaceId"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=t.includeArchived?eq(x.workspace_id,e):and(eq(x.workspace_id,e),isNull(x.archived_at));return n.db.select({id:x.id}).from(x).where(o).orderBy(desc(x.updated_at),desc(x.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){M(e,"projectId");let t=this.openHandle(true);try{t.db.update(x).set({archived_at:new Date().toISOString()}).where(eq(x.id,e)).run().changes===0&&oe(`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={}){M(e,"projectId"),Ro.has(t)||L(`invalid project scene: ${String(t)}`);let o=Fe(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let u=c.select().from(x).where(eq(x.id,e)).get();u||oe(`Project ${e} not found`),c.update(x).set({scene:t,updated_at:s}).where(eq(x.id,e)).run(),je(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={}){M(e,"projectId"),Number.isInteger(t)||L("stage index must be an integer");let o=Fe(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let u=c.select().from(x).where(eq(x.id,e)).get();u||oe(`Project ${e} not found`);let l=mn(u.stages_json);(t<1||t>l.length)&&L("stage index is outside the project stages"),c.update(x).set({stage_index:t,updated_at:s}).where(eq(x.id,e)).run(),je(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||!Eo.has(a))&&L(`invalid criterion status: ${String(a)}`),M(s.criterionId,"criterionId");let c=Fe(s),u=new Date().toISOString(),l=this.openHandle(true),p;try{l.db.transaction(g=>{let m=g.select().from(Z).where(eq(Z.id,s.criterionId)).get();m||oe(`Criterion ${s.criterionId} not found`),p=m.project_id,s.projectId&&s.projectId!==m.project_id&&oe(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(Z).set({verify_status:a,verified_at:a==="passed"?u:null,updated_at:u}).where(eq(Z.id,s.criterionId)).run(),je(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 _||oe(`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;M(s.criterionId,"criterionId");let a=Do(s.evidence),c=Fe(s),u=new Date().toISOString(),l=this.openHandle(true),p;try{l.db.transaction(g=>{let m=g.select().from(Z).where(eq(Z.id,s.criterionId)).get();m||oe(`Criterion ${s.criterionId} not found`),p=m.project_id,s.projectId&&s.projectId!==m.project_id&&oe(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(Z).set({evidence_json:JSON.stringify(a),updated_at:u}).where(eq(Z.id,s.criterionId)).run(),je(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 _||oe(`Criterion ${s.criterionId} not found`),_}appendEvent(e,t){let n=typeof e=="string"?{...t,projectId:e}:e;yn(n);let o=new Date().toISOString(),s=this.openHandle(true),a;try{s.db.transaction(c=>{a=je(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(M(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=[eq(le.project_id,e)];t.afterSeq!==void 0&&o.push(gt$1(le.seq,t.afterSeq));let s=n.db.select().from(le).where(and(...o)).orderBy(asc(le.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){M(e,"projectId");let n=Fe(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};kn(o,"accepted");let s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{c.select({id:x.id}).from(x).where(eq(x.id,e)).get()||oe(`Project ${e} not found`),c.update(x).set({scene:"accepted",accepted_at:s,updated_at:s}).where(eq(x.id,e)).run(),je(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 En=[h,i,f,Se,_e,re,Ue];function Co(){return be__default.join(Rr.homedir(),".crewx","crewx.db")}function Oo(r){if(!bn__default.existsSync(r))return null;let e=Math.floor(Date.now()/1e3),t=`${r}.bak-${e}`;return bn__default.copyFileSync(r,t),t}function Sn(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 Lo(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 Po(r){let e=r.getSQLType(),t=`"${r.name}" ${e}`,n=Lo(r.default);return n!==null&&(t+=` DEFAULT ${n}`),r.notNull&&(t+=" NOT NULL"),t}function $o(r,e){let t=e?.dbPath??Co(),n=e?.force??false,o=e?.dryRun??false,s=o?null:Oo(t);if(n&&!o)try{r.run("DELETE FROM __drizzle_migrations");}catch{}let a=Sn(r);if(!o)try{Me(r);}catch(_){let g=_ instanceof Error?`${_.message} ${_.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw _}let c,u;o?(c=En.map(g=>getTableConfig(g).name).filter(g=>!a.has(g)),u=a):(u=Sn(r),c=[...u].filter(_=>!a.has(_)));let l=[],p=[];for(let _ of En){let g=getTableConfig(_),m=g.name;if(!u.has(m))continue;let $=r.all(`PRAGMA table_info("${m}")`),w=new Set($.map(T=>T.name)),j=new Set(g.columns.map(T=>T.name));for(let T of g.columns)if(!w.has(T.name)){if(!o){let K=Po(T);r.run(`ALTER TABLE "${m}" ADD COLUMN ${K}`);}l.push({table:m,column:T.name});}for(let T of $)j.has(T.name)||p.push(`${m}.${T.name} exists in DB but not in schema (untouched)`);}return {created:c,altered:l,warnings:p,backupPath:s}}function Tn(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 An(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 Nn(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)=>An(n,o))}catch(n){throw n instanceof d?new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n):n}}function In(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 Dn(r){return {taskId:r.id,source:In(r),revision:r.log_revision,lastSeq:r.last_log_seq}}function zo(r){if(!Number.isInteger(r)||r<0)throw new d("VALIDATION","Task log tail limit must be a non-negative integer")}var Ye=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(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(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(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)=>An(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=In(c);if(u==="blob"){let g=Nn(e,c.logs);if(a.update(i).set({logs:JSON.stringify([...g,...n]),log_revision:sql`${i.log_revision} + 1`}).where(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(pe).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:sql`${i.log_revision} + 1`}).where(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?Dn(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 zo(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=Dn(s);if(a.source==="blob"){let p=Nn(e,s.logs);return {...a,entries:t===void 0?p:p.slice(Math.max(0,p.length-t))}}let c=o.select({seq:pe.seq,timestamp:pe.timestamp,level:pe.level,message:pe.message}).from(pe).where(eq(pe.task_id,e)).orderBy(t===void 0?asc(pe.seq):desc(pe.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 xt=40,xe="2026-05-09",Yo="0.8.9-rc.13",Ne=10,De=parseInt(Yo.split("rc.")[1]);function Cn(){let r=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(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?and(eq(w.slug,e),ne(w.id,t)):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(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(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(and(eq(w.is_active,1),isNotNull(w.workspace_path))).all(),n=0;for(let o of t){let s=o.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(e.db.update(w).set({is_active:0,updated_at:new Date().toISOString()}).where(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(sql`UPDATE threads SET workspace_id = NULL WHERE workspace_id = ${e}`),t.db.delete(w).where(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 Hn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ls(r){let e=randomBytes(r*2),t="";for(let n=0;n<e.length&&t.length<r;n++){let o=e[n];o<248&&(t+=Hn[o%62]);}for(;t.length<r;)t+=Hn[randomBytes(1)[0]%62];return t}function $e(r){return `${r}_${ls(8)}`}var Jt=["outcome_plan","contract_check","feature_link","use_verify","result_review"],hs=new Set(Jt),Jn=Object.freeze(Jt.map(r=>({key:r,labelOverride:null}))),ws=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),ks=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),ys=new Set(["pending","verifying","passed","failed"]),bs=new Set(["user","project_manager","system"]),Rs=new Set(["task","wi","url"]),Es=/^\d{4}-\d{2}-\d{2}$/;function P(r){throw new d("VALIDATION",r)}function le(r){throw new d("NOT_FOUND",r)}function H(r,e){(typeof r!="string"||r.trim().length===0)&&P(`${e} is required`);}function Ts(r){if(r==null)return;Es.test(r)||P("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)&&P("dueDate must be a valid calendar date");}function Yn(r){let e=r??Jn;(!Array.isArray(e)||e.length===0)&&P("stages must contain at least one stage");let t=new Set;return e.map(n=>{(!n||typeof n!="object"||Array.isArray(n))&&P("stage must be an object");let o=n;return H(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&P("stage.labelOverride must be a string or null"),o.labelOverride!==null&&H(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&P("stage.key is required"),!hs.has(o.key)&&o.labelOverride===null&&P(`custom stage requires a labelOverride: ${o.key}`),t.has(o.key)&&P(`duplicate stage key: ${o.key}`),t.add(o.key),{key:o.key,labelOverride:o.labelOverride}})}function Ss(r){Array.isArray(r)||P("criteria must be an array");for(let e of r)H(e,"criterion.statement");}function Qe(r={}){let e=r.actorType??"system";bs.has(e)||P(`invalid actorType: ${String(e)}`);let t=r.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&P(`actorId is required for ${e}`),{actorType:e,actorId:t}}function Xn(r,e){let t=r??{};if((t===null||typeof t!="object"||Array.isArray(t))&&P("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)&&P(`accepted payload requires ${n}`);try{return JSON.stringify(t)}catch(n){throw new d("VALIDATION","event payload must be JSON serializable",n)}}function Cs(r){return Array.isArray(r)||P("evidence must be an array"),r.map(e=>((!e||typeof e!="object")&&P("evidence item must be an object"),Rs.has(e.kind)||P(`invalid evidence kind: ${String(e.kind)}`),H(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&P("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 Kn(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 Yn(e)}catch(t){throw new d("DB_ERROR","Project stages JSON is invalid",t)}}function Qn(r){return H(r.projectId,"projectId"),H(r.title,"title"),ws.has(r.type)||P(`invalid project event type: ${String(r.type)}`),{...Qe(r),payloadJson:Xn(r.payload,r.type)}}function He(r,e,t){let n=Qn(e);r.select({id:O.id}).from(O).where(eq(O.id,e.projectId)).get()||le(`Project ${e.projectId} not found`);let s=r.select({maxSeq:sql`COALESCE(MAX(${fe.seq}), 0)`}).from(fe).where(eq(fe.project_id,e.projectId)).get()?.maxSeq??0,a=$e("pje");r.insert(fe).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(fe).where(eq(fe.id,a)).get();if(!c)throw new d("DB_ERROR","Event insert did not return a row");return c}var Kt=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new d("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}getDetailFromHandle(e,t){let n=e.db.select().from(O).where(eq(O.id,t)).get();if(!n)return;let o=e.db.select().from(re).where(eq(re.project_id,t)).orderBy(asc(re.position)).all();return {...n,stages:Kn(n.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||le(`Project ${e} not found`),t}createProject(e){H(e.workspaceId,"workspaceId"),H(e.name,"name"),H(e.outcome,"outcome"),Ts(e.dueDate);let t=Yn(e.stages);Ss(e.criteria);let n=$e("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(a=>{a.insert(O).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(re).values({id:$e("pjc"),project_id:n,position:l+1,statement:c,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),He(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(H(e,"workspaceId"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=t.includeArchived?eq(O.workspace_id,e):and(eq(O.workspace_id,e),isNull(O.archived_at));return n.db.select({id:O.id}).from(O).where(o).orderBy(desc(O.updated_at),desc(O.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){H(e,"projectId");let t=this.openHandle(true);try{t.db.update(O).set({archived_at:new Date().toISOString()}).where(eq(O.id,e)).run().changes===0&&le(`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={}){H(e,"projectId"),ks.has(t)||P(`invalid project scene: ${String(t)}`);let o=Qe(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let l=c.select().from(O).where(eq(O.id,e)).get();l||le(`Project ${e} not found`),c.update(O).set({scene:t,updated_at:s}).where(eq(O.id,e)).run(),He(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={}){H(e,"projectId"),Number.isInteger(t)||P("stage index must be an integer");let o=Qe(n),s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{let l=c.select().from(O).where(eq(O.id,e)).get();l||le(`Project ${e} not found`);let u=Kn(l.stages_json);(t<1||t>u.length)&&P("stage index is outside the project stages"),c.update(O).set({stage_index:t,updated_at:s}).where(eq(O.id,e)).run(),He(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||!ys.has(a))&&P(`invalid criterion status: ${String(a)}`),H(s.criterionId,"criterionId");let c=Qe(s),l=new Date().toISOString(),u=this.openHandle(true),p;try{u.db.transaction(g=>{let h=g.select().from(re).where(eq(re.id,s.criterionId)).get();h||le(`Criterion ${s.criterionId} not found`),p=h.project_id,s.projectId&&s.projectId!==h.project_id&&le(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(re).set({verify_status:a,verified_at:a==="passed"?l:null,updated_at:l}).where(eq(re.id,s.criterionId)).run(),He(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 _||le(`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;H(s.criterionId,"criterionId");let a=Cs(s.evidence),c=Qe(s),l=new Date().toISOString(),u=this.openHandle(true),p;try{u.db.transaction(g=>{let h=g.select().from(re).where(eq(re.id,s.criterionId)).get();h||le(`Criterion ${s.criterionId} not found`),p=h.project_id,s.projectId&&s.projectId!==h.project_id&&le(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(re).set({evidence_json:JSON.stringify(a),updated_at:l}).where(eq(re.id,s.criterionId)).run(),He(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 _||le(`Criterion ${s.criterionId} not found`),_}appendEvent(e,t){let n=typeof e=="string"?{...t,projectId:e}:e;Qn(n);let o=new Date().toISOString(),s=this.openHandle(true),a;try{s.db.transaction(c=>{a=He(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(H(e,"projectId"),t.afterSeq!==void 0&&(!Number.isInteger(t.afterSeq)||t.afterSeq<0)&&P("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&P("limit must be a positive integer"),!this.dbExists())return [];let n=this.openHandle(false);try{let o=[eq(fe.project_id,e)];t.afterSeq!==void 0&&o.push(gt(fe.seq,t.afterSeq));let s=n.db.select().from(fe).where(and(...o)).orderBy(asc(fe.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){H(e,"projectId");let n=Qe(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};Xn(o,"accepted");let s=new Date().toISOString(),a=this.openHandle(true);try{a.db.transaction(c=>{c.select({id:O.id}).from(O).where(eq(O.id,e)).get()||le(`Project ${e} not found`),c.update(O).set({scene:"accepted",accepted_at:s,updated_at:s}).where(eq(O.id,e)).run(),He(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 tr=[w,i,f,Ce,me,ce,Je];function Os(){return Ee__default.join(ro.homedir(),".crewx","crewx.db")}function Ns(r){if(!Zn__default.existsSync(r))return null;let e=Math.floor(Date.now()/1e3),t=`${r}.bak-${e}`;return Zn__default.copyFileSync(r,t),t}function nr(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 As(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 xs(r){let e=r.getSQLType(),t=`"${r.name}" ${e}`,n=As(r.default);return n!==null&&(t+=` DEFAULT ${n}`),r.notNull&&(t+=" NOT NULL"),t}function Is(r,e){let t=e?.dbPath??Os(),n=e?.force??false,o=e?.dryRun??false,s=o?null:Ns(t);if(n&&!o)try{r.run("DELETE FROM __drizzle_migrations");}catch{}let a=nr(r);if(!o)try{Ve(r);}catch(_){let g=_ instanceof Error?`${_.message} ${_.cause?.message??""}`:"";if(!n||!g.includes("duplicate column"))throw _}let c,l;o?(c=tr.map(g=>getTableConfig(g).name).filter(g=>!a.has(g)),l=a):(l=nr(r),c=[...l].filter(_=>!a.has(_)));let u=[],p=[];for(let _ of tr){let g=getTableConfig(_),h=g.name;if(!l.has(h))continue;let $=r.all(`PRAGMA table_info("${h}")`),k=new Set($.map(C=>C.name)),M=new Set(g.columns.map(C=>C.name));for(let C of g.columns)if(!k.has(C.name)){if(!o){let J=xs(C);r.run(`ALTER TABLE "${h}" ADD COLUMN ${J}`);}u.push({table:h,column:C.name});}for(let C of $)M.has(C.name)||p.push(`${h}.${C.name} exists in DB but not in schema (untouched)`);}return {created:c,altered:u,warnings:p,backupPath:s}}function rr(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 dr(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 ir(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)=>dr(n,o))}catch(n){throw n instanceof d?new d("DB_ERROR",`Malformed legacy task logs: ${r}`,n):n}}function cr(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 ar(r){return {taskId:r.id,source:cr(r),revision:r.log_revision,lastSeq:r.last_log_seq}}function Us(r){if(!Number.isInteger(r)||r<0)throw new d("VALIDATION","Task log tail limit must be a non-negative integer")}var ct=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(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(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(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)=>dr(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=cr(c);if(l==="blob"){let g=ir(e,c.logs);if(a.update(i).set({logs:JSON.stringify([...g,...n]),log_revision:sql`${i.log_revision} + 1`}).where(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(ge).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:sql`${i.log_revision} + 1`}).where(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?ar(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 Us(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=ar(s);if(a.source==="blob"){let p=ir(e,s.logs);return {...a,entries:t===void 0?p:p.slice(Math.max(0,p.length-t))}}let c=o.select({seq:ge.seq,timestamp:ge.timestamp,level:ge.level,message:ge.message}).from(ge).where(eq(ge.task_id,e)).orderBy(t===void 0?asc(ge.seq):desc(ge.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 Xt=40,Ne="2026-05-09",Vs="0.8.9-rc.13",Ae=10,xe=parseInt(Vs.split("rc.")[1]);function lr(){let r=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 Xo=new Set(["workflow","mcp"]),On=600*1e3,Nt=class extends D{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new Ye({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(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:sql`COALESCE(excluded.pid, ${i.pid})`},setWhere: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 Ks=new Set(["workflow","mcp"]),ur=600*1e3,Qt=class extends D{dbPath;taskLogRepository;pidNullObservedSince=new Map;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.taskLogRepository=new ct({dbPath:this.dbPath});}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(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:sql`COALESCE(excluded.pid, ${i.pid})`},setWhere: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(eq(i.project_id,e)).orderBy(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(eq(i.status,"running")).orderBy(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(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(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(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(and(eq(i.id,e),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(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(and(eq(i.id,a.id),eq(i.status,"running"))).run(),s++);continue}if(Xo.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>=On&&(e.db.update(i).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(i.id,a.id),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=On){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(and(eq(i.status,"running"),eq(i.platform,"workflow"),isNull(i.pid),lt(i.started_at,n),or$1(isNull(i.metadata),and(notLike(i.metadata,'%"kind":"workflow_card"%'),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(!existsSync(o))continue;let s=k(o);try{let a=t?eq(i.workspace_id,t):void 0,c=a?and(eq(i.id,e),a):eq(i.id,e),u=s.db.select().from(i).where(c).limit(1).get()??void 0;if(!u){let l=or$1(eq(i.thread_id,e),and(isNull(i.thread_id),like(i.command,`%--thread=${e}%`))),p=a?and(l,a):l;u=s.db.select().from(i).where(p).orderBy(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(!existsSync(a))continue;let c=k(a);try{let u=t?and(eq(i.parent_task_id,e),eq(i.workspace_id,t)):eq(i.parent_task_id,e),l=c.db.select().from(i).where(u).orderBy(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?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(eq(i.status,"running")).orderBy(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(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(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(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(and(eq(i.id,e),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(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(and(eq(i.id,a.id),eq(i.status,"running"))).run(),s++);continue}if(Ks.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>=ur&&(e.db.update(i).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(i.id,a.id),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=ur){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(and(eq(i.status,"running"),eq(i.platform,"workflow"),isNull(i.pid),lt(i.started_at,n),or(isNull(i.metadata),and(notLike(i.metadata,'%"kind":"workflow_card"%'),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(!existsSync(o))continue;let s=y(o);try{let a=t?eq(i.workspace_id,t):void 0,c=a?and(eq(i.id,e),a):eq(i.id,e),l=s.db.select().from(i).where(c).limit(1).get()??void 0;if(!l){let u=a?and(eq(i.thread_id,e),a):eq(i.thread_id,e);l=s.db.select().from(i).where(u).orderBy(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(!existsSync(a))continue;let c=y(a);try{let l=t?and(eq(i.parent_task_id,e),eq(i.workspace_id,t)):eq(i.parent_task_id,e),u=c.db.select().from(i).where(l).orderBy(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?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(!existsSync(u))continue;let l=k(u);try{let p=or$1(eq(i.thread_id,e),and(isNull(i.thread_id),like(i.command,`%--thread=${e}%`))),_=t?and(p,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(!existsSync(a))continue;let c=k(a);try{let u=or$1(eq(i.thread_id,e),and(isNull(i.thread_id),like(i.command,`%--thread=${e}%`))),l=t?and(u,eq(i.workspace_id,t)):u,p=c.db.select().from(i).where(l).orderBy(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(!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(and(eq(i.platform,"workflow"),or$1(like(i.metadata,'%"kind":"workflow_card"%'),like(i.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(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?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(!existsSync(u))continue;let l=k(u);try{let p=and(inArray(i.thread_id,e),or$1(like(i.metadata,'%"kind":"workflow_card"%'),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?and(p,a):p).all();for(let $ of _)c($.thread_id,$);let g=and(isNull(i.thread_id),or$1(like(i.metadata,'%"kind":"workflow_card"%'),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?and(g,a):g).all();for(let $ of m){let w=this.extractThreadIdFromCommand($.command);!w||!o.has(w)||c(w,$);}}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(eq(i.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&n.push(inArray(i.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&n.push(inArray(i.status,s));let a=e.q??e.search;a&&n.push(like(i.prompt,`%${a}%`)),e.from&&n.push(gte(i.started_at,e.from)),e.to&&n.push(lt(i.started_at,e.to));let c=n.length>0?and(...n):void 0,u=t.db.select({count:sql`count(*)`}).from(i).where(c).get(),l=(e.sortDir??"DESC")==="ASC"?asc(i.started_at):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?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(!existsSync(l))continue;let u=y(l);try{let p=eq(i.thread_id,e),_=t?and(p,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(!existsSync(l))continue;let u=y(l);try{let p=eq(i.thread_id,e),_=t?and(p,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(asc(i.started_at)).all():u.db.select().from(i).where(_).orderBy(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(!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(and(eq(i.platform,"workflow"),or(like(i.metadata,'%"kind":"workflow_card"%'),like(i.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(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?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(!existsSync(l))continue;let u=y(l);try{let p=and(inArray(i.thread_id,e),or(like(i.metadata,'%"kind":"workflow_card"%'),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?and(p,a):p).all();for(let $ of _)c($.thread_id,$);let g=and(isNull(i.thread_id),or(like(i.metadata,'%"kind":"workflow_card"%'),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?and(g,a):g).all();for(let $ of h){let k=this.extractThreadIdFromCommand($.command);!k||!o.has(k)||c(k,$);}}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(eq(i.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&n.push(inArray(i.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&n.push(inArray(i.status,s));let a=e.q??e.search;a&&n.push(like(i.prompt,`%${a}%`)),e.from&&n.push(gte(i.started_at,e.from)),e.to&&n.push(lt(i.started_at,e.to));let c=n.length>0?and(...n):void 0,l=t.db.select({count:sql`count(*)`}).from(i).where(c).get(),u=(e.sortDir??"DESC")==="ASC"?asc(i.started_at):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?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 >= ${xe}
80
+ WHEN t.started_at >= ${Ne}
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, ${Ne}) AS INTEGER) < ${De})
84
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ae}) AS INTEGER) < ${xe})
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 >= ${xe}
103
+ WHEN t.started_at >= ${Ne}
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, ${Ne}) AS INTEGER) < ${De})
107
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ae}) AS INTEGER) < ${xe})
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 >= ${xe}
123
+ WHEN t.started_at >= ${Ne}
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, ${Ne}) AS INTEGER) < ${De})
127
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ae}) AS INTEGER) < ${xe})
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 >= ${xe}
145
+ WHEN t.started_at >= ${Ne}
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, ${Ne}) AS INTEGER) < ${De})
149
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ae}) AS INTEGER) < ${xe})
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 >= ${xe}
164
+ WHEN t.started_at >= ${Ne}
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, ${Ne}) AS INTEGER) < ${De})
168
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ae}) AS INTEGER) < ${xe})
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 >= ${xe}
191
+ WHEN t.started_at >= ${Ne}
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, ${Ne}) AS INTEGER) < ${De})
195
+ OR (t.crewx_version LIKE '0.8.9-rc.%' AND CAST(SUBSTR(t.crewx_version, ${Ae}) AS INTEGER) < ${xe})
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(and(eq(i.id,e),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(and(eq(i.agent_id,e.agentId),eq(i.workspace_id,e.workspaceId),sql`${i.metadata} IS NOT NULL AND json_valid(${i.metadata}) AND json_extract(${i.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(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?and(eq(i.id,e),eq(i.status,"running"),eq(i.workspace_id,n)):and(eq(i.id,e),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(!existsSync(a))continue;let c=k(a);try{let u=t?and(like(i.prompt,`%${e}%`),eq(i.workspace_id,t)):like(i.prompt,`%${e}%`),l=c.db.select().from(i).where(u).orderBy(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=Cn(),a=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(and(eq(i.id,e),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(and(eq(i.agent_id,e.agentId),eq(i.workspace_id,e.workspaceId),sql`${i.metadata} IS NOT NULL AND json_valid(${i.metadata}) AND json_extract(${i.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(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?and(eq(i.id,e),eq(i.status,"running"),eq(i.workspace_id,n)):and(eq(i.id,e),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(!existsSync(a))continue;let c=y(a);try{let l=t?and(like(i.prompt,`%${e}%`),eq(i.workspace_id,t)):like(i.prompt,`%${e}%`),u=c.db.select().from(i).where(l).orderBy(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=lr(),a=sql`
211
211
  COALESCE(${i.input_tokens}, 0)
212
212
  + CASE
213
- WHEN ${i.started_at} >= ${xe}
213
+ WHEN ${i.started_at} >= ${Ne}
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}, ${Ne}) AS INTEGER) < ${De})
217
+ OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ae}) AS INTEGER) < ${xe})
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=Cn(),a=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=lr(),a=sql`
237
237
  COALESCE(${i.input_tokens}, 0)
238
238
  + CASE
239
- WHEN ${i.started_at} >= ${xe}
239
+ WHEN ${i.started_at} >= ${Ne}
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}, ${Ne}) AS INTEGER) < ${De})
243
+ OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ae}) AS INTEGER) < ${xe})
244
244
  )
245
245
  THEN COALESCE(${i.cached_input_tokens}, 0)
246
246
  ELSE 0
247
247
  END
248
- `,c=n?sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`,u=o.db.all(sql`
248
+ `,c=n?sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:sql`WHERE ${i.status} IN ('completed', 'success') AND ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`,l=o.db.all(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 _=Tn(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?sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`;return o.db.all(sql`
262
+ `),u=new Map;for(let p of l){let _=rr(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?sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t} AND ${i.workspace_id} = ${n}`:sql`WHERE ${i.started_at} >= ${e} AND ${i.started_at} < ${t}`;return o.db.all(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=sql`
274
274
  COALESCE(${i.input_tokens}, 0)
275
275
  + CASE
276
- WHEN ${i.started_at} >= ${xe}
276
+ WHEN ${i.started_at} >= ${Ne}
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}, ${Ne}) AS INTEGER) < ${De})
280
+ OR (${i.crewx_version} LIKE '0.8.9-rc.%' AND CAST(SUBSTR(${i.crewx_version}, ${Ae}) AS INTEGER) < ${xe})
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 ${xt+1}
297
- `),u=c.length>xt;return {edges:c.slice(0,xt).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(eq(i.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&n.push(inArray(i.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&n.push(inArray(i.status,e.statuses)),e.from&&n.push(gte(i.started_at,e.from)),e.to&&n.push(lt(i.started_at,e.to));let o=n.length>0?and(...n):void 0,s=(e.order??"DESC")==="ASC"?asc(i.started_at):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=[isNotNull(i.thread_id),isNull(i.parent_task_id),isNull(i.caller_agent_id),or$1(isNull(i.platform),ne(i.platform,"workflow")),or$1(isNull(i.metadata),and(notLike(i.metadata,'%"kind":"workflow_card"%'),notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))),or$1(isNull(i.metadata),notLike(i.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(i.workspace_id,e.workspaceId)),e.from&&s.push(gte(i.started_at,e.from)),e.to&&s.push(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(and(...s)).orderBy(asc(i.started_at),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 jn=["success","failed","completed"],gt=10*1024*1024*1024,Bn=256,ss=new Set(jn),W=class extends Error{constructor(t,n,o="metadata"){super(n);this.taskId=t;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function qn(r){return r||(process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(homedir(),".crewx","crewx.db"))}function is(){return qe("better-sqlite3")}function Mn(r,e){let t=r===":memory:";if(!t&&!existsSync(r))throw new Error(`Database not found: ${r}`);let n=new(is())(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 He(r,e,t=[]){return r.prepare(e).get(...t)}function as(r,e,t=[]){return r.prepare(e).run(...t)}function ds(r,e,t=[]){return r.prepare(e).iterate(...t)}function cs(r){return typeof r=="string"&&r.length>0?r:"<unknown>"}function Un(r){return typeof r=="string"&&ss.has(r)}function Ln(r,e){r.set(e,(r.get(e)??0)+1);}function Pn(r){return Object.fromEntries([...r.entries()].sort(([e],[t])=>e.localeCompare(t)))}function ls(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 Fn(r,e){if(e==null)return {entries:[]};if(typeof e!="string")throw new W(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 W(r,`Malformed JSON in tasks.logs (${s})`,"malformed")}if(!Array.isArray(t))throw new W(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 W(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 It(r,e){if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new W(r.id,"Invalid last_log_seq metadata","metadata");if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new W(r.id,"Invalid log_revision metadata","metadata");if(e==="blob"&&r.last_log_seq!==0)throw new W(r.id,"Blob source must have last_log_seq=0","metadata")}function us(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 ps(r){let e=us(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 $ of ds(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
299
- FROM tasks ORDER BY id`)){let w=$,j=cs(w.status);if(Ln(a,j),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{It(w,"events");}catch(ke){s.push(Ct(ke,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 T=Un(w.status);T||(p+=1,Ln(c,j)),typeof w.logs=="string"?m+=Buffer.byteLength(w.logs,"utf8"):Buffer.isBuffer(w.logs)&&(m+=w.logs.byteLength);let K=e.get(w.id)??0;K>0&&s.push({taskId:w.id,reason:`Blob source already has ${K} task_log_events row(s)`,kind:"mixed-source"});let Ie;try{Ie=Fn(w.id,w.logs),g+=Ie.entries.length,It(w,"blob");}catch(ke){let ye=Ct(ke,w.id);s.push(ye),ye.kind==="malformed"&&o.push(ye);continue}K>0||T&&n.push(w.id);}return {taskCount:u,candidateTaskCount:l,eligibleTaskCount:n.length,eventSourceTasks:_,statusCounts:Pn(a),deferredTaskCount:p,deferredStatusCounts:Pn(c),entryCount:g,sourceBytes:m,candidateIds:n,malformedRows:o,failures:s,tasks:t}}function Ct(r,e){return r instanceof W?{taskId:r.taskId,reason:r.message,kind:r.kind}:{taskId:e,reason:r instanceof Error?r.message:String(r),kind:"metadata"}}function _s(r){return He(r,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function gs(r){return He(r,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function fs(r){if(r===":memory:")return 0;let e=t=>{try{return statSync(t).size}catch{return 0}};return e(r)+e(`${r}-wal`)}function ms(r,e){return fs(r)+e*Bn}function Hn(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=e+gt}function $n(r){let e=dirname(resolve(r));for(;!existsSync(e);){let t=dirname(e);if(t===e)break;e=t;}return e}function zn(r,e,t){let n=[...new Set([$n(r),...t?[$n(t)]:[]])],o=[],s=Number.POSITIVE_INFINITY;for(let u of n)try{let l=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=ms(r,e),c=a+gt;return {estimatedFreeSpaceBytes:a,requiredFreeSpaceBytes:c,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:gt,freeSpaceGatePassed:Hn(Number.isFinite(s)?Math.floor(s):0,a),warnings:o}}function Wn(r){return new Set(r.map(e=>e.taskId)).size}function Kn(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 pt(r,e,t,n,o=zn(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??Wn(s),malformedRows:a,failures:s,logicalSourceBytesRemoved:n.logicalSourceBytesRemoved??0,warnings:n.warnings??o.warnings,remainingTaskCount:n.remainingTaskCount??t.candidateTaskCount,...u}}function hs(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 ws(r,e){return r.transaction(()=>{let n=He(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
300
- FROM tasks WHERE id = ?`,[e]);if(!n)throw new W(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 W(e,`Unknown log_storage value: ${n.log_storage}`,"invalid-source");if(!Un(n.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=n.logs,s=Fn(e,o);It(n,"blob");let a=He(r,"SELECT COUNT(*) AS count FROM task_log_events WHERE task_id = ?",[e])?.count??0;if(a!==0)throw new W(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=ze(r,`SELECT seq, timestamp, level, message
302
- FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!hs(u,s.entries))throw new W(e,"Event parity check failed before source clear","metadata");if(as(r,`UPDATE tasks
296
+ LIMIT ${Xt+1}
297
+ `),l=c.length>Xt;return {edges:c.slice(0,Xt).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(eq(i.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&n.push(inArray(i.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&n.push(inArray(i.status,e.statuses)),e.from&&n.push(gte(i.started_at,e.from)),e.to&&n.push(lt(i.started_at,e.to));let o=n.length>0?and(...n):void 0,s=(e.order??"DESC")==="ASC"?asc(i.started_at):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=[isNotNull(i.thread_id),isNull(i.parent_task_id),isNull(i.caller_agent_id),or(isNull(i.platform),ne(i.platform,"workflow")),or(isNull(i.metadata),and(notLike(i.metadata,'%"kind":"workflow_card"%'),notLike(i.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(i.metadata),notLike(i.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(i.workspace_id,e.workspaceId)),e.from&&s.push(gte(i.started_at,e.from)),e.to&&s.push(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(and(...s)).orderBy(asc(i.started_at),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 gr=["success","failed","completed"],Nt=10*1024*1024*1024,mr=256,ni=new Set(gr),K=class extends Error{constructor(t,n,o="metadata"){super(n);this.taskId=t;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function hr(r){return r||(process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(homedir(),".crewx","crewx.db"))}function ri(){return Ge("better-sqlite3")}function wr(r,e){let t=r===":memory:";if(!t&&!existsSync(r))throw new Error(`Database not found: ${r}`);let n=new(ri())(r,{readonly:e,fileMustExist:!t,timeout:5e3});return n.pragma("foreign_keys = ON"),n.pragma("busy_timeout = 5000"),n}function et(r,e,t=[]){return r.prepare(e).all(...t)}function Ze(r,e,t=[]){return r.prepare(e).get(...t)}function oi(r,e,t=[]){return r.prepare(e).run(...t)}function si(r,e,t=[]){return r.prepare(e).iterate(...t)}function ii(r){return typeof r=="string"&&r.length>0?r:"<unknown>"}function kr(r){return typeof r=="string"&&ni.has(r)}function pr(r,e){r.set(e,(r.get(e)??0)+1);}function _r(r){return Object.fromEntries([...r.entries()].sort(([e],[t])=>e.localeCompare(t)))}function ai(r){let e=new Set(et(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(et(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 yr(r,e){if(e==null)return {entries:[]};if(typeof e!="string")throw new K(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 K(r,`Malformed JSON in tasks.logs (${s})`,"malformed")}if(!Array.isArray(t))throw new K(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 K(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 tn(r,e){if(!Number.isInteger(r.last_log_seq)||r.last_log_seq<0)throw new K(r.id,"Invalid last_log_seq metadata","metadata");if(!Number.isInteger(r.log_revision)||r.log_revision<0)throw new K(r.id,"Invalid log_revision metadata","metadata");if(e==="blob"&&r.last_log_seq!==0)throw new K(r.id,"Blob source must have last_log_seq=0","metadata")}function di(r){let e=et(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 ci(r){let e=di(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 $ of si(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
299
+ FROM tasks ORDER BY id`)){let k=$,M=ii(k.status);if(pr(a,M),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{tn(k,"events");}catch(be){s.push(nn(be,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 C=kr(k.status);C||(p+=1,pr(c,M)),typeof k.logs=="string"?h+=Buffer.byteLength(k.logs,"utf8"):Buffer.isBuffer(k.logs)&&(h+=k.logs.byteLength);let J=e.get(k.id)??0;J>0&&s.push({taskId:k.id,reason:`Blob source already has ${J} task_log_events row(s)`,kind:"mixed-source"});let Le;try{Le=yr(k.id,k.logs),g+=Le.entries.length,tn(k,"blob");}catch(be){let Re=nn(be,k.id);s.push(Re),Re.kind==="malformed"&&o.push(Re);continue}J>0||C&&n.push(k.id);}return {taskCount:l,candidateTaskCount:u,eligibleTaskCount:n.length,eventSourceTasks:_,statusCounts:_r(a),deferredTaskCount:p,deferredStatusCounts:_r(c),entryCount:g,sourceBytes:h,candidateIds:n,malformedRows:o,failures:s,tasks:t}}function nn(r,e){return r instanceof K?{taskId:r.taskId,reason:r.message,kind:r.kind}:{taskId:e,reason:r instanceof Error?r.message:String(r),kind:"metadata"}}function li(r){return Ze(r,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function ui(r){return Ze(r,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function pi(r){if(r===":memory:")return 0;let e=t=>{try{return statSync(t).size}catch{return 0}};return e(r)+e(`${r}-wal`)}function _i(r,e){return pi(r)+e*mr}function br(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=e+Nt}function fr(r){let e=dirname(resolve(r));for(;!existsSync(e);){let t=dirname(e);if(t===e)break;e=t;}return e}function Rr(r,e,t){let n=[...new Set([fr(r),...t?[fr(t)]:[]])],o=[],s=Number.POSITIVE_INFINITY;for(let l of n)try{let u=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=_i(r,e),c=a+Nt;return {estimatedFreeSpaceBytes:a,requiredFreeSpaceBytes:c,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:Nt,freeSpaceGatePassed:br(Number.isFinite(s)?Math.floor(s):0,a),warnings:o}}function Er(r){return new Set(r.map(e=>e.taskId)).size}function Tr(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 Dt(r,e,t,n,o=Rr(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??Er(s),malformedRows:a,failures:s,logicalSourceBytesRemoved:n.logicalSourceBytesRemoved??0,warnings:n.warnings??o.warnings,remainingTaskCount:n.remainingTaskCount??t.candidateTaskCount,...l}}function fi(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 gi(r,e){return r.transaction(()=>{let n=Ze(r,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
300
+ FROM tasks WHERE id = ?`,[e]);if(!n)throw new K(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 K(e,`Unknown log_storage value: ${n.log_storage}`,"invalid-source");if(!kr(n.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=n.logs,s=yr(e,o);tn(n,"blob");let a=Ze(r,"SELECT COUNT(*) AS count FROM task_log_events WHERE task_id = ?",[e])?.count??0;if(a!==0)throw new K(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=et(r,`SELECT seq, timestamp, level, message
302
+ FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!fi(l,s.entries))throw new K(e,"Event parity check failed before source clear","metadata");if(oi(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 W(e,"Task changed while migration was in progress","metadata");let p=He(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 W(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 Gn(r){let e=new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14),t=randomBytes(6).toString("hex");return `${r}.task-log-backup-${e}-${t}.sqlite`}async function ks(r,e,t){let n=t??Gn(e);if(resolve(n)===resolve(e))throw new Error("Backup path must be different from the source database");if(existsSync(n))throw new Error(`Refusing to overwrite existing backup: ${n}`);if(mkdirSync(dirname(n),{recursive:true}),await r.backup(n),!existsSync(n))throw new Error(`SQLite backup was not created: ${n}`);let o=Mn(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 ys(r){let e=ze(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 K(e,"Task changed while migration was in progress","metadata");let p=Ze(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 K(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 Sr(r){let e=new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14),t=randomBytes(6).toString("hex");return `${r}.task-log-backup-${e}-${t}.sqlite`}async function mi(r,e,t){let n=t??Sr(e);if(resolve(n)===resolve(e))throw new Error("Backup path must be different from the source database");if(existsSync(n))throw new Error(`Refusing to overwrite existing backup: ${n}`);if(mkdirSync(dirname(n),{recursive:true}),await r.backup(n),!existsSync(n))throw new Error(`SQLite backup was not created: ${n}`);let o=wr(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 hi(r){let e=et(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 Ae(r,e,t,n={}){return {taskId:r,kind:e,reason:t,...n}}function bs(r,e,t){let n=[];for(let _ of t.failures)_.kind==="malformed"?n.push(Ae(_.taskId,"malformed-blob",_.reason)):_.kind==="mixed-source"?n.push(Ae(_.taskId,"mixed-source",_.reason)):n.push(Ae(_.taskId,"source-invariant",_.reason));let o=ys(r),s=new Map(o.rows.map(_=>[_.taskId,_]));for(let _ of o.rows){let g=t.tasks.get(_.taskId);if(!g){n.push(Ae(null,"orphan-event",`Event rows reference missing task ${_.taskId}`,{actual:_.eventCount}));continue}(_.minSeq===null||_.minSeq<1||_.distinctSeqCount!==_.maxSeq)&&n.push(Ae(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(Ae(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(Ae(_.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(Ae(_.taskId,"duplicate-seq",`Duplicate task event sequence ${_.seq}`,{actual:_.duplicateCount,seq:_.seq}));let a=He(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(Ae(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 pt("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 Rs(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 Es(r){Rs(r);let e=qn(r.dbPath),t=Mn(e,r.mode!=="apply");try{ls(t);let n=ps(t),o=_s(t);if(r.mode==="verify")return {...bs(t,e,n),activeTaskCount:o};if(r.mode==="dry-run")return pt("dry-run",e,n,{ok:n.failures.length===0,activeTaskCount:o,skippedTasks:n.eventSourceTasks,remainingTaskCount:n.candidateTaskCount});let s=r.backupPath??Gn(e),a=zn(e,n.entryCount,s);if(!a.freeSpaceGatePassed)return pt("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 ks(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,$=[...a.warnings];for(let[w,j]of l.entries()){try{let T=ws(t,j);T.status==="migrated"&&(_+=1,g+=T.entryCount,m+=T.sourceBytes);}catch(T){u.push(Ct(T,j));}if((w+1)%p===0||w===l.length-1){let T=Kn(t);T&&$.push(T);}}return pt("apply",e,n,{ok:u.length===0,activeTaskCount:o,backupPath:c,backupMethod:"sqlite-online-backup",migratedTasks:_,migratedEntries:g,logicalSourceBytesRemoved:m,failedTasks:Wn(u),failures:u,malformedRows:n.malformedRows,remainingTaskCount:gs(t),skippedTasks:n.eventSourceTasks,warnings:$},a)}finally{t.close();}}function Ss(r){return basename(r)}var Ot=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(n.db,t);}catch(o){throw n.close(),o}return n}validateWorkspaceId(e,t){return e.db.select({id:h.id}).from(h).where(eq(h.id,t)).limit(1).get()?t:null}topLevelTaskPredicateSql(e="child"){return 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 Ie(r,e,t,n={}){return {taskId:r,kind:e,reason:t,...n}}function wi(r,e,t){let n=[];for(let _ of t.failures)_.kind==="malformed"?n.push(Ie(_.taskId,"malformed-blob",_.reason)):_.kind==="mixed-source"?n.push(Ie(_.taskId,"mixed-source",_.reason)):n.push(Ie(_.taskId,"source-invariant",_.reason));let o=hi(r),s=new Map(o.rows.map(_=>[_.taskId,_]));for(let _ of o.rows){let g=t.tasks.get(_.taskId);if(!g){n.push(Ie(null,"orphan-event",`Event rows reference missing task ${_.taskId}`,{actual:_.eventCount}));continue}(_.minSeq===null||_.minSeq<1||_.distinctSeqCount!==_.maxSeq)&&n.push(Ie(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(Ie(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(Ie(_.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:_.last_log_seq??0,actual:0}));for(let _ of et(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(Ie(_.taskId,"duplicate-seq",`Duplicate task event sequence ${_.seq}`,{actual:_.duplicateCount,seq:_.seq}));let a=Ze(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(Ie(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 Dt("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 ki(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 yi(r){ki(r);let e=hr(r.dbPath),t=wr(e,r.mode!=="apply");try{ai(t);let n=ci(t),o=li(t);if(r.mode==="verify")return {...wi(t,e,n),activeTaskCount:o};if(r.mode==="dry-run")return Dt("dry-run",e,n,{ok:n.failures.length===0,activeTaskCount:o,skippedTasks:n.eventSourceTasks,remainingTaskCount:n.candidateTaskCount});let s=r.backupPath??Sr(e),a=Rr(e,n.entryCount,s);if(!a.freeSpaceGatePassed)return Dt("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 mi(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,$=[...a.warnings];for(let[k,M]of u.entries()){try{let C=gi(t,M);C.status==="migrated"&&(_+=1,g+=C.entryCount,h+=C.sourceBytes);}catch(C){l.push(nn(C,M));}if((k+1)%p===0||k===u.length-1){let C=Tr(t);C&&$.push(C);}}return Dt("apply",e,n,{ok:l.length===0,activeTaskCount:o,backupPath:c,backupMethod:"sqlite-online-backup",migratedTasks:_,migratedEntries:g,logicalSourceBytesRemoved:h,failedTasks:Er(l),failures:l,malformedRows:n.malformedRows,remainingTaskCount:ui(t),skippedTasks:n.eventSourceTasks,warnings:$},a)}finally{t.close();}}function bi(r){return basename(r)}var We=class extends d{reason;constructor(e,t=e){super("VALIDATION",t),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function pt(r){if(!r)return {};try{let e=JSON.parse(r);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Ci(r){let t=pt(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 rn=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}validateWorkspaceId(e,t){return e.db.select({id:w.id}).from(w).where(eq(w.id,t)).limit(1).get()?t:null}topLevelTaskPredicateSql(e="child"){return 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(!existsSync(s))continue;let a=k(s);try{let c=e?eq(f.workspace_id,e):void 0,u=a.db.select().from(f).where(c).orderBy(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(!existsSync(a))continue;let c=k(a);try{let u=or$1(inArray(f.id,e),inArray(f.title,e)),l=t?and(u,eq(f.workspace_id,t)):u,p=c.db.select().from(f).where(l).orderBy(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(!existsSync(o))continue;let s=k(o);try{let a=eq(f.id,e),c=t?and(a,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(!existsSync(o))continue;let s=k(o);try{let a=eq(f.id,e),c=t?and(a,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(!existsSync(p))continue;let _=k(p);try{let g=_.db.get(sql`
316
+ )`)}findAllThreads(e){let t=this.resolveDbPaths(),n=new Set,o=[];for(let s of t){if(!existsSync(s))continue;let a=y(s);try{let c=e?eq(f.workspace_id,e):void 0,l=a.db.select().from(f).where(c).orderBy(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(!existsSync(a))continue;let c=y(a);try{let l=or(inArray(f.id,e),inArray(f.title,e)),u=t?and(l,eq(f.workspace_id,t)):l,p=c.db.select().from(f).where(u).orderBy(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(!existsSync(o))continue;let s=y(o);try{let a=eq(f.id,e),c=t?and(a,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(!existsSync(o))continue;let s=y(o);try{let a=eq(f.id,e),c=t?and(a,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(!existsSync(p))continue;let _=y(p);try{let g=_.db.get(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?sql`AND child.workspace_id = ${t}`: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(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(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?sql`AND child.workspace_id = ${t}`:sql``}
333
- `);for(let $ of m)l.add($.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(!existsSync(c))continue;let u=k(c);try{let l;n!==void 0?l=u.db.all(sql`
333
+ `);for(let $ of h)u.add($.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(!existsSync(c))continue;let l=y(c);try{let u;n!==void 0?u=l.db.all(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(sql`
344
+ `):u=l.db.all(sql`
345
345
  SELECT child.* FROM tasks child
346
346
  WHERE child.thread_id = ${e}
347
347
  AND ${this.topLevelTaskPredicateSql()}
348
348
  ${t?sql`AND child.workspace_id = ${t}`: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(!existsSync(a))continue;let c=k(a);try{let u=eq(i.thread_id,e),l=t?and(u,eq(i.workspace_id,t)):u,p=c.db.select().from(i).where(l).orderBy(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(!existsSync(s))continue;let a=k(s);try{let c=and(eq(i.id,t),eq(i.thread_id,e)),u=n?and(c,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(eq(i.parent_task_id,l.id)).orderBy(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 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(!existsSync(a))continue;let c=y(a);try{let l=eq(i.thread_id,e),u=t?and(l,eq(i.workspace_id,t)):l,p=c.db.select().from(i).where(u).orderBy(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(!existsSync(s))continue;let a=y(s);try{let c=and(eq(i.id,t),eq(i.thread_id,e)),l=n?and(c,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(eq(i.parent_task_id,u.id)).orderBy(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 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?sql`AND child.workspace_id = ${t}`: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(!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(!existsSync(o))continue;let s=k(o);try{return s.db.all(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=eq(f.id,e),a=n?and(s,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(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(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(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(eq(f.id,e)).limit(1).get();if(a){s&&!a.workspace_id&&o.db.update(f).set({workspace_id:s}).where(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(eq(f.id,e)).limit(1).get()?.message_count===0;return c.run(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(!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(!existsSync(o))continue;let s=y(o);try{return s.db.all(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=eq(f.id,e),a=n?and(s,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(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(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(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(eq(f.id,e)).limit(1).get();if(a){s&&!a.workspace_id&&o.db.update(f).set({workspace_id:s}).where(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(eq(f.id,e)).limit(1).get()?.message_count===0;return c.run(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(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(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?and(eq(f.id,e),eq(f.workspace_id,t)):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?and(eq(f.pinned,1),eq(f.workspace_id,t)):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?and(eq(f.id,e[o]),eq(f.workspace_id,t)):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?and(eq(f.id,e),eq(f.workspace_id,t)):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?and(eq(f.id,e),eq(f.workspace_id,t)):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,$=o?.updatedBy??"ui",w=new Date().toISOString(),j,T,K,Ie;switch(n){case "enable-count":{let ke=o?.turns??m,ye=o?.consumeCurrent?Math.max(ke-1,0):ke;j=ye>0?"count":"off",T=ye,K=!0,Ie="count";break}case "enable-latch":{j="latch",T=0,K=!0,Ie="latch";break}case "disable":{j="off",T=0,K=!1;break}default:{let ke=g.state??"off",ye=typeof g.remaining=="number"?g.remaining:0;if(ke==="count"&&ye>0){let Ht=ye-1;Ht<=0?(j="off",T=0):(j="count",T=Ht),K=!0,Ie="count";}else ke==="latch"?(j="latch",T=0,K=!0,Ie="latch"):(j="off",T=0,K=!1);break}}return _.overdrive={state:j,remaining:T,defaultTurns:m,updatedAt:w,updatedBy:$},l.update(f).set({metadata:JSON.stringify(_),updated_at:w}).where(c).run(),{applied:K,appliedMode:Ie,state:j,remaining:T}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var Lt=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(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(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(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 Pt=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(n.db,t);}catch(o){throw n.close(),o}return n}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(_e).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(_e).where(eq(_e.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:_e.tool_name,count:sql`count(*)`}).from(_e).where(eq(_e.task_id,e)).groupBy(_e.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 $t=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(n.db,t);}catch(o){throw n.close(),o}return n}ensureThreadExists(e,t){if(!e.db.select({id:f.id}).from(f).where(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(re).where(eq(re.thread_id,e)).orderBy(asc(re.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(re).where(and(eq(re.id,t),eq(re.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(re).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(re).where(eq(re.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 jt=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(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(Ue).values({id: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(Ue).orderBy(desc(Ue.timestamp)).limit(e).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{t.close();}}};function or(r){return new Date(Math.floor(r/3e5)*3e5).toISOString()}var Bt=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(n.db,t);}catch(o){throw n.close(),o}return n}upsert(e){let t=this.openHandle(true);try{let n=or(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(F).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:[F.provider,F.account_ref,F.limit_window,F.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:F.provider,bucket_start:F.bucket_start,used_percent:F.used_percent,remaining_percent:F.remaining_percent,resets_at:F.resets_at}).from(F).where(and(eq(F.limit_window,e.window),gte(F.bucket_start,e.fromIso),lte(F.bucket_start,e.toIso))).orderBy(asc(F.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 qt=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(n.db,t);}catch(o){throw n.close(),o}return n}publish(e){let t=this.openHandle(true);try{t.db.insert(Y).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:[Y.workspace_id,Y.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(Y).where(and(eq(Y.workspace_id,e.workspaceId),eq(Y.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(Y).where(and(eq(Y.workspace_id,e),eq(Y.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(Y).where(eq(Y.workspace_id,e)).orderBy(desc(Y.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{t.close();}}};var ur=500,pr=50,Mt=class extends D{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??ur;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(n.db,t);}catch(o){throw n.close(),o}return n}create(e){let t=this.openHandle(true);try{let n=Oe("ntf"),o=new Date().toISOString();return t.db.insert(E).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:sql`count(*)`}).from(E).where(eq(E.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let c=e.db.select({id:E.id}).from(E).innerJoin(B,eq(B.notification_id,E.id)).where(eq(E.workspace_id,t)).groupBy(E.id).orderBy(asc(E.created_at)).limit(s).all().map(u=>u.id);c.length!==0&&(e.db.delete(B).where(inArray(B.notification_id,c)).run(),e.db.delete(E).where(inArray(E.id,c)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??pr,n=this.openHandle(false);try{return n.db.select({id:E.id,workspace_id:E.workspace_id,agent_id:E.agent_id,task_id:E.task_id,thread_id:E.thread_id,source:E.source,level:E.level,title:E.title,body:E.body,target_user_id:E.target_user_id,created_at:E.created_at,metadata:E.metadata,read_at:B.read_at}).from(E).leftJoin(B,and(eq(B.notification_id,E.id),eq(B.user_id,e.userId))).where(eq(E.workspace_id,e.workspaceId)).orderBy(desc(E.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:sql`count(*)`}).from(E).leftJoin(B,and(eq(B.notification_id,E.id),eq(B.user_id,e.userId))).where(and(eq(E.workspace_id,e.workspaceId),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:E.id}).from(E).where(and(eq(E.id,e.notificationId),eq(E.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:E.id}).from(E).leftJoin(B,and(eq(B.notification_id,E.id),eq(B.user_id,e.userId))).where(and(eq(E.workspace_id,e.workspaceId),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 fr=50,Ft=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=k(t);if(e)try{O(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=Oe("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(v).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:v.task_id}).from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t))).orderBy(desc(v.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(v.task_id):eq(v.task_id,o.task_id);return n.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),s)).orderBy(asc(v.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(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.task_id,n))).orderBy(asc(v.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(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.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(v).set(s).where(eq(v.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=fr){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t))).orderBy(desc(v.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(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.status,"dismissed"))).orderBy(desc(v.updated_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{Ft as AgentSuggestionRepository,D as BaseSqliteRepository,Kt as CREWX_JOURNAL_SIZE_LIMIT_BYTES,fr as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,ur as DEFAULT_NOTIFICATION_CAP,pr as DEFAULT_NOTIFICATION_LIST_LIMIT,hn as DEFAULT_PROJECT_STAGES,Tt as DEFAULT_PROJECT_STAGE_KEYS,Mt as NotificationRepository,St as ProjectRepository,d as RepositoryError,jt as RequestLogRepository,Lt as SpanRepository,Bn as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,gt as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,jn as TASK_LOG_MIGRATION_TERMINAL_STATUSES,Ye as TaskLogRepository,Nt as TaskRepository,$t as ThreadBoxRepository,Ot as ThreadRepository,Pt as ToolCallRepository,Bt as UsageLimitSnapshotRepository,qt as UsageReportRepository,Et as WorkspaceRepository,or as calcBucketStart,Hn as hasSufficientTaskLogMigrationFreeSpace,k as openDrizzleDb,$o as pushSchema,Er as reclaimTemporaryJournal,qn as resolveTaskLogMigrationDbPath,Me as runMigrations,O as runMigrationsOnce,Es as runTaskLogMigration,Ss as taskLogBackupName,i as tasks,Kn as tryCheckpointTaskLogWal};
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(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(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 We("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new We("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 We("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 We("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let c=this.openHandle(true);try{let l=n?and(eq(f.id,e),eq(f.workspace_id,n)):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 _=pt(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 $=Object.keys(_).length>0?JSON.stringify(_):null,k=new Date().toISOString();u.update(f).set({metadata:$,updated_at:k}).where(l).run();let M=u.select({metadata:f.metadata}).from(f).where(l).get();if(!M)throw new d("DB_ERROR","Thread-title metadata update could not be read back");let C=Ci(M.metadata);return {threadId:e,priority:C.priority,state:C.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?and(eq(f.id,e),eq(f.workspace_id,t)):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=pt(a.metadata);if(c){let u=t?and(eq(f.pinned,1),eq(f.workspace_id,t)):eq(f.pinned,1),p=s.select({metadata:f.metadata}).from(f).where(u).all(),_=null;for(let g of p){let h=pt(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?and(eq(f.id,e[s]),eq(f.workspace_id,t)):eq(f.id,e[s]),c=o.select({metadata:f.metadata}).from(f).where(a).get();if(!c)continue;let l=pt(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?and(eq(f.id,e),eq(f.workspace_id,t)):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?and(eq(f.id,e),eq(f.workspace_id,t)):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,$=o?.updatedBy??"ui",k=new Date().toISOString(),M,C,J,Le;switch(n){case "enable-count":{let be=o?.turns??h,Re=o?.consumeCurrent?Math.max(be-1,0):be;M=Re>0?"count":"off",C=Re,J=!0,Le="count";break}case "enable-latch":{M="latch",C=0,J=!0,Le="latch";break}case "disable":{M="off",C=0,J=!1;break}default:{let be=g.state??"off",Re=typeof g.remaining=="number"?g.remaining:0;if(be==="count"&&Re>0){let hn=Re-1;hn<=0?(M="off",C=0):(M="count",C=hn),J=!0,Le="count";}else be==="latch"?(M="latch",C=0,J=!0,Le="latch"):(M="off",C=0,J=!1);break}}return _.overdrive={state:M,remaining:C,defaultTurns:h,updatedAt:k,updatedBy:$},u.update(f).set({metadata:JSON.stringify(_),updated_at:k}).where(c).run(),{applied:J,appliedMode:Le,state:M,remaining:C}},{behavior:"immediate"})}catch(c){throw c instanceof d?c:new d("DB_ERROR","Failed to resolve overdrive",c)}finally{a.close();}}};var tt="THREAD_STATE",It="custom:";function Ai(r){return r.dbPath?r.dbPath:r.dbRoot?join(r.dbRoot,".crewx","crewx.db"):process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(homedir(),".crewx","crewx.db")}function an(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 Nr(r){let t=an(r)?.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t.state;return typeof n=="string"&&n.startsWith(It)?n:null}function on(r){let e=[...r].length;return e>=1&&e<=20}function xi(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=Nr(n.metadata);o!==null&&t.push({id:n.id,workspace_id:n.workspace_id,metadata:n.metadata,label:o.slice(It.length)});}return t}function Ii(r){return r===null?isNull(m.workspace_id):eq(m.workspace_id,r)}function Li(r){return r===null?isNull(m.workspace_id):or(isNull(m.workspace_id),eq(m.workspace_id,r))}function Pi(r,e,t){let n=r.select().from(m).where(and(eq(m.code_group,tt),eq(m.code_name,e),Ii(t),eq(m.is_builtin,0))).limit(1).get();if(n)return {code:n.code,created:false};let o=r.select({maxSortOrder:sql`max(${m.sort_order})`}).from(m).where(and(eq(m.code_group,tt),Li(t))).get(),s=Xe();for(;r.select({code:m.code}).from(m).where(and(eq(m.code_group,tt),eq(m.code,s))).limit(1).get();)s=Xe();let a=new Date().toISOString();return r.insert(m).values({code_group:tt,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 ji(r,e,t,n){let o=r.select({id:f.id,workspace_id:f.workspace_id,metadata:f.metadata}).from(f).all(),s=`${It}${e}`,a=0,c=new Date().toISOString();for(let l of o){if(n!==null&&l.workspace_id!==n||Nr(l.metadata)!==s)continue;let u=an(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(eq(f.id,l.id)).run(),a+=1;}return a}function sn(r,e,t){return r.transaction(n=>{let o=Pi(n,e,t),s=ji(n,e,o.code,t);return {...o,migratedRows:s}},{behavior:"immediate"})}function $i(r,e){return r.select({code:m.code}).from(m).where(and(eq(m.code_group,tt),eq(m.code_name,e),isNull(m.workspace_id),eq(m.is_builtin,0))).limit(1).get()?.code??null}function Mi(r){let e=new Set(r.select({code:m.code}).from(m).where(eq(m.code_group,tt)).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=an(s.metadata)?.threadTitle;if(!c||typeof c!="object"||Array.isArray(c))continue;let l=c.state;typeof l=="string"&&(l.startsWith(It)&&(n+=1),e.has(l)||(o+=1));}return {remainingCustomReferences:n,orphanReferences:o}}function Ar(r={}){let e=Ai(r);if(!existsSync(e))return {migratedRows:0,createdCodes:0,remainingCustomReferences:0,orphanReferences:0};let t=y(e);try{A(t.db,e);let n=xi(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(on(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(!on(p))continue;let _=sn(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(!on(_)||u.has(_))continue;if($i(t.db,_)){let h=sn(t.db,_,null);u.set(_,h.code),c+=h.migratedRows,h.created&&(l+=1);continue}let g=sn(t.db,_,p);c+=g.migratedRows,g.created&&(l+=1);}return {migratedRows:c,createdCodes:l,...Mi(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 Bi=Ar;var dn=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Ce).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(Ce).where(eq(Ce.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(Ce).where(eq(Ce.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 cn=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(me).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(me).where(eq(me.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:me.tool_name,count:sql`count(*)`}).from(me).where(eq(me.task_id,e)).groupBy(me.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 ln=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}ensureThreadExists(e,t){if(!e.db.select({id:f.id}).from(f).where(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(ce).where(eq(ce.thread_id,e)).orderBy(asc(ce.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(ce).where(and(eq(ce.id,t),eq(ce.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(ce).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(ce).where(eq(ce.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 un=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(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(Je).values({id: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(Je).orderBy(desc(Je.timestamp)).limit(e).all()}catch(n){throw new d("DB_ERROR","Failed to find recent request logs",n)}finally{t.close();}}};function Br(r){return new Date(Math.floor(r/3e5)*3e5).toISOString()}var pn=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}upsert(e){let t=this.openHandle(true);try{let n=Br(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(W).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:[W.provider,W.account_ref,W.limit_window,W.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:W.provider,bucket_start:W.bucket_start,used_percent:W.used_percent,remaining_percent:W.remaining_percent,resets_at:W.resets_at}).from(W).where(and(eq(W.limit_window,e.window),gte(W.bucket_start,e.fromIso),lte(W.bucket_start,e.toIso))).orderBy(asc(W.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 _n=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}publish(e){let t=this.openHandle(true);try{t.db.insert(ee).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:[ee.workspace_id,ee.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(ee).where(and(eq(ee.workspace_id,e.workspaceId),eq(ee.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(ee).where(and(eq(ee.workspace_id,e),eq(ee.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(ee).where(eq(ee.workspace_id,e)).orderBy(desc(ee.month)).all()}catch(n){throw new d("DB_ERROR","Failed to list usage reports",n)}finally{t.close();}}};var Gr=500,Vr=50,fn=class extends D{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??Gr;}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(n.db,t);}catch(o){throw n.close(),o}return n}create(e){let t=this.openHandle(true);try{let n=$e("ntf"),o=new Date().toISOString();return t.db.insert(S).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:sql`count(*)`}).from(S).where(eq(S.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let c=e.db.select({id:S.id}).from(S).innerJoin(q,eq(q.notification_id,S.id)).where(eq(S.workspace_id,t)).groupBy(S.id).orderBy(asc(S.created_at)).limit(s).all().map(l=>l.id);c.length!==0&&(e.db.delete(q).where(inArray(q.notification_id,c)).run(),e.db.delete(S).where(inArray(S.id,c)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??Vr,n=this.openHandle(false);try{return n.db.select({id:S.id,workspace_id:S.workspace_id,agent_id:S.agent_id,task_id:S.task_id,thread_id:S.thread_id,source:S.source,level:S.level,title:S.title,body:S.body,target_user_id:S.target_user_id,created_at:S.created_at,metadata:S.metadata,read_at:q.read_at}).from(S).leftJoin(q,and(eq(q.notification_id,S.id),eq(q.user_id,e.userId))).where(eq(S.workspace_id,e.workspaceId)).orderBy(desc(S.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:sql`count(*)`}).from(S).leftJoin(q,and(eq(q.notification_id,S.id),eq(q.user_id,e.userId))).where(and(eq(S.workspace_id,e.workspaceId),isNull(q.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:S.id}).from(S).where(and(eq(S.id,e.notificationId),eq(S.workspace_id,e.workspaceId))).get())throw new d("NOT_FOUND","Notification not found in workspace");return t.db.insert(q).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:S.id}).from(S).leftJoin(q,and(eq(q.notification_id,S.id),eq(q.user_id,e.userId))).where(and(eq(S.workspace_id,e.workspaceId),isNull(q.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(q).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 Yr=50,mn=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new d("NOT_FOUND","Database not found");let n=y(t);if(e)try{A(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=$e("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(v).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:v.task_id}).from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t))).orderBy(desc(v.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(v.task_id):eq(v.task_id,o.task_id);return n.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),s)).orderBy(asc(v.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(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.task_id,n))).orderBy(asc(v.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(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.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(v).set(s).where(eq(v.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=Yr){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t))).orderBy(desc(v.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(v).where(and(eq(v.workspace_id,e),eq(v.agent_id,t),eq(v.status,"dismissed"))).orderBy(desc(v.updated_at)).limit(n).all()}catch(s){throw new d("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{mn as AgentSuggestionRepository,D as BaseSqliteRepository,Rt as COMMON_CODE_COLORS,bt as COMMON_CODE_GROUPS,yn as CREWX_JOURNAL_SIZE_LIMIT_BYTES,Ht as CommonCodeRepository,F as CommonCodeRepositoryError,Yr as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Gr as DEFAULT_NOTIFICATION_CAP,Vr as DEFAULT_NOTIFICATION_LIST_LIMIT,Jn as DEFAULT_PROJECT_STAGES,Jt as DEFAULT_PROJECT_STAGE_KEYS,fn as NotificationRepository,Kt as ProjectRepository,d as RepositoryError,un as RequestLogRepository,dn as SpanRepository,mr as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,Nt as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,gr as TASK_LOG_MIGRATION_TERMINAL_STATUSES,ct as TaskLogRepository,Qt as TaskRepository,ln as ThreadBoxRepository,rn as ThreadRepository,We as ThreadTitleMetadataPatchError,cn as ToolCallRepository,pn as UsageLimitSnapshotRepository,_n as UsageReportRepository,Vt as WorkspaceRepository,Br as calcBucketStart,Xe as generateCommonCodeId,br as hasSufficientTaskLogMigrationFreeSpace,Ar as migrateLegacyThreadTitleCommonCodes,Bi as migrateThreadTitleCommonCodes,y as openDrizzleDb,Is as pushSchema,oo as reclaimTemporaryJournal,hr as resolveTaskLogMigrationDbPath,Ve as runMigrations,A as runMigrationsOnce,yi as runTaskLogMigration,bi as taskLogBackupName,i as tasks,Tr as tryCheckpointTaskLogWal};