@crewx/sdk 0.9.0-rc.83 → 0.9.0-rc.85
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.
- package/dist/esm/index.js +81 -81
- package/dist/esm/plugins/index.js +23 -23
- package/dist/esm/repository/index.js +21 -21
- package/dist/facade/Crewx.d.ts +2 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +86 -86
- package/dist/migrations/0023_red_payback.sql +1 -0
- package/dist/migrations/meta/0023_snapshot.json +3047 -0
- package/dist/migrations/meta/_journal.json +7 -0
- package/dist/plugins/index.js +24 -24
- package/dist/remote/execution-profile.d.ts +9 -0
- package/dist/remote/index.d.ts +1 -0
- package/dist/remote/types.d.ts +28 -0
- package/dist/repository/index.js +21 -21
- package/dist/repository/workspace.repository.d.ts +3 -0
- package/dist/schema/workspaces.d.ts +17 -0
- package/package.json +1 -1
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import*as qe from'path';import qe__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as
|
|
1
|
+
import*as qe from'path';import qe__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as ro from'fs';import ro__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import ys,{homedir}from'os';import {randomUUID,createHash,randomBytes}from'crypto';import {sql,and,eq,asc,ne,isNull,desc,isNotNull,gt as gt$1,lt as lt$1,or,notLike,like,inArray,gte,lte}from'drizzle-orm';import {sqliteTable,integer,text,real,index,check,uniqueIndex,unique,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var ot=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var ms=()=>fileURLToPath(import.meta.url),ws=()=>qe__default.dirname(ms()),R=ws();var x=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(ys.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 c=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};var _n=n=>{try{return ro.statSync(`${n}-wal`).size}catch{return 0}},mn=32*1024*1024;function y(n){let e=ot("better-sqlite3"),{drizzle:t}=ot("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${mn}`),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),r.exec("PRAGMA analysis_limit = 400"),{db:t(r),runRaw:(o,s=[])=>r.prepare(o).run(...s),close:()=>r.close()}}function Rs(n,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=ot("better-sqlite3"),r=_n(n),o;try{o=new t(n),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),i=_n(n);return {busy:s[0]?.busy===1,walBytesBefore:r,walBytesAfter:i}}finally{o?.close();}}var wn=new Set,Es={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 kr(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function bs(n,e){if(e>0||!kr(n,"tasks"))return;let t=n.all("PRAGMA table_info(tasks)"),r=new Set(t.map(o=>o.name));for(let[o,s]of Object.entries(Es))r.has(o)||n.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}var Is={"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 Ss(n,e,t){if(!kr(n,"__drizzle_migrations")||!kr(n,"tasks"))return;let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(qe__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=Is[i.tag];if(!d)continue;let l=qe__default.join(e,`${i.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),h=createHash("sha256").update(u).digest("hex");if(o.has(h))continue;let g=n.all("PRAGMA table_info(tasks)"),p=new Set(g.map(f=>f.name));for(let[f,D]of Object.entries(d))p.has(f)||(n.run(`ALTER TABLE tasks ADD COLUMN ${f} ${D}`),p.add(f));}}function vs(n,e,t){let r=n.all(t`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(readFileSync(qe__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=qe__default.join(e,`${i.tag}.sql`);if(!existsSync(d))continue;let l=readFileSync(d,"utf-8"),u=createHash("sha256").update(l).digest("hex");if(o.has(u))continue;let h=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,g=[],p;for(;(p=h.exec(l))!==null;)g.push({table:p[1],column:p[2]});if(g.length===0||!l.split(/-->\s*statement-breakpoint/).map(w=>w.trim()).filter(Boolean).every(w=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(w)))continue;g.every(({table:w,column:S})=>n.all(`PRAGMA table_info("${w}")`).some(K=>K.name===S))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);}}function ut(n){let{migrate:e}=ot("drizzle-orm/better-sqlite3/migrator"),{sql:t}=ot("drizzle-orm"),r=[qe__default.join(R,"../migrations"),qe__default.join(R,"migrations"),qe__default.join(R,"../../../../drizzle/migrations"),qe__default.join(process.cwd(),"drizzle/migrations")],o=r.find(u=>existsSync(qe__default.join(u,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
2
2
|
${r.join(`
|
|
3
|
-
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),Es(n,i),s?.cnt&&(Ss(n,o,t),Is(n,o,t)),e(n,{migrationsFolder:o});let l=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let u=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${u} (${l} migration${l>1?"s":""} applied).`);}}function $(n,e){wn.has(e)||(ut(n),wn.add(e));}var R=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 a=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)},n=>({log_storage_check:check("tasks_log_storage_ck",sql`${n.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));var Ae=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},n=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(n.task_id,n.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(n.timestamp,n.id)}));var $s="json_extract(metadata, '$.threadTitle.state')",js="json_extract(metadata, '$.threadTitle.priority')",_=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>R.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)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at),idx_threads_title:index("idx_threads_title").on(n.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(n.workspace_id,sql.raw($s)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(js))}));var Ue=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Ue.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")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));var xe=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.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()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));var Re=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.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()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));var gt=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")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));var te=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")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));var le=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")},n=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.month)}));var O=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")},n=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(n.workspace_id,sql`${n.created_at} DESC`)})),X=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},n=>({pk:primaryKey({columns:[n.notification_id,n.user_id]})}));var L=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()},n=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(n.workspace_id,n.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(n.workspace_id,n.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()},n=>({idCheck:check("ui_instances_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128 AND ${n.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${n.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${n.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${n.definition_hash}) = 64 AND ${n.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${n.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${n.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${n.domain_ref_json}) AND json_type(${n.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${n.state_json}) AND json_type(${n.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${n.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${n.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${n.granted_capabilities_json}) AND json_type(${n.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${n.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${n.updated_at} >= ${n.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(n.workspace_id,n.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")},n=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${n.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${n.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${n.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${n.actor_json}) AND json_type(${n.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${n.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${n.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${n.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${n.after_revision} IS NULL OR ${n.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${n.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${n.outcome} IS NULL OR ${n.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${n.input_json}) AND json_type(${n.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${n.result_json} IS NULL OR (json_valid(${n.result_json}) AND json_type(${n.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${n.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${n.settled_at} IS NULL OR ${n.settled_at} >= ${n.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
3
|
+
`)}`);let s=n.get(t`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),bs(n,i),s?.cnt&&(vs(n,o,t),Ss(n,o,t)),e(n,{migrationsFolder:o});let l=(n.get(t`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(l>0){let u=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${u} (${l} migration${l>1?"s":""} applied).`);}}function $(n,e){wn.has(e)||(ut(n),wn.add(e));}var k=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(),starred:integer("starred").notNull().default(0)});var a=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)},n=>({log_storage_check:check("tasks_log_storage_ck",sql`${n.log_storage} IN ('blob', 'events')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(n.agent_id),idx_tasks_status:index("idx_tasks_status").on(n.status),idx_tasks_started_at:index("idx_tasks_started_at").on(n.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(n.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(n.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(n.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(n.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(n.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(n.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(n.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(n.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(n.workspace_id,n.started_at)}));var Ae=sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>a.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},n=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(n.task_id,n.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(n.timestamp,n.id)}));var $s="json_extract(metadata, '$.threadTitle.state')",js="json_extract(metadata, '$.threadTitle.priority')",_=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>k.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)},n=>({idx_threads_updated_at:index("idx_threads_updated_at").on(n.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(n.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(n.workspace_id,n.updated_at),idx_threads_title:index("idx_threads_title").on(n.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(n.workspace_id,sql.raw($s)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(js))}));var Ue=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Ue.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")},n=>({idx_spans_task_id:index("idx_spans_task_id").on(n.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(n.parent_span_id)}));var xe=sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>a.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()},n=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(n.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(n.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(n.timestamp)}));var Re=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>_.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()},n=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(n.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(n.thread_id,n.seq),uniq_thread_boxes_thread_seq:unique().on(n.thread_id,n.seq)}));var gt=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")},n=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(n.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(n.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(n.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(n.partition_key)}));var te=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")},n=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(n.provider,n.account_ref,n.limit_window,n.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(n.limit_window,n.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(n.provider,n.limit_window,n.bucket_start)}));var ue=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")},n=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(n.workspace_id,n.month)}));var O=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")},n=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(n.workspace_id,sql`${n.created_at} DESC`)})),X=sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},n=>({pk:primaryKey({columns:[n.notification_id,n.user_id]})}));var L=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()},n=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(n.workspace_id,n.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(n.workspace_id,n.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()},n=>({idCheck:check("ui_instances_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128 AND ${n.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${n.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${n.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${n.definition_hash}) = 64 AND ${n.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${n.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${n.thread_id}) BETWEEN 1 AND 256`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${n.domain_ref_json}) AND json_type(${n.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${n.state_json}) AND json_type(${n.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${n.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${n.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${n.granted_capabilities_json}) AND json_type(${n.granted_capabilities_json}) = 'array'`),createdAtCheck:check("ui_instances_created_at_ck",sql`${n.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${n.updated_at} >= ${n.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(n.workspace_id,n.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")},n=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${n.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${n.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${n.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${n.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${n.actor_json}) AND json_type(${n.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${n.source} IN ('ui_host', 'cli', 'system')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${n.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${n.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${n.after_revision} IS NULL OR ${n.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${n.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${n.outcome} IS NULL OR ${n.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${n.input_json}) AND json_type(${n.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${n.result_json} IS NULL OR (json_valid(${n.result_json}) AND json_type(${n.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${n.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${n.settled_at} IS NULL OR ${n.settled_at} >= ${n.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",sql`(
|
|
4
4
|
(${n.status} = 'requested' AND ${n.after_revision} IS NULL AND ${n.outcome} IS NULL AND ${n.settled_at} IS NULL)
|
|
5
5
|
OR
|
|
6
6
|
(${n.status} = 'settled' AND ${n.after_revision} IS NOT NULL AND ${n.outcome} IS NOT NULL AND ${n.settled_at} IS NOT NULL)
|
|
7
|
-
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(n.instance_id,n.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(n.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(n.requested_at)}));var j=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")},n=>({idCheck:check("projects_id_ck",sql`${n.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${n.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(${n.stages_json}) AND json_type(${n.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${n.stage_index} >= 1`)})),ge=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>j.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()},n=>({idCheck:check("project_criteria_id_ck",sql`${n.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${n.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${n.evidence_json}) AND json_type(${n.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(n.project_id,n.position)})),Ce=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>j.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()},n=>({idCheck:check("project_events_id_ck",sql`${n.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(n.project_id,n.seq)}));var Qt=["THREAD_STATE","THREAD_PRIORITY"],Zt=["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()},n=>({pk:primaryKey({columns:[n.code_group,n.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${n.metadata} IS NULL OR (json_valid(${n.metadata}) AND json_type(${n.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${n.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${n.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(n.code_group,n.is_archived,n.sort_order)}));var On=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],An=["user","agent","system"],xn=["auto","manual"],Ln=["decision","judgment","issue","result","pivot"];var Pn=["queued","running","completed","failed"],M=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},n=>({typeCheck:check("thread_events_type_ck",sql`${n.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(n.thread_id,n.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(n.thread_id,n.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(n.thread_id,n.seq)})),A=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},n=>({statusCheck:check("thread_highlight_runs_status_ck",sql`${n.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:check("thread_highlight_runs_counts_ck",sql`(${n.previous_auto_count} IS NULL OR ${n.previous_auto_count} >= 0) AND (${n.new_auto_count} IS NULL OR ${n.new_auto_count} >= 0)`),threadRequestUnique:uniqueIndex("thread_highlight_runs_thread_request_uq").on(n.thread_id,n.request_id),inProgressThreadUnique:uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(n.thread_id).where(sql`${n.status} IN ('queued', 'running')`),threadStatusRequestedIndex:index("idx_thread_highlight_runs_thread_status_requested").on(n.thread_id,n.status,n.requested_at)})),v=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},n=>({sourceCheck:check("thread_highlights_source_ck",sql`${n.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${n.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${n.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${n.status} = 'dismissed' OR (${n.text} IS NOT NULL AND length(${n.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${n.covers_from_task_id}) > 0 AND length(${n.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${n.source} = 'manual' OR (${n.source} = 'auto' AND ${n.source_task_id} IS NOT NULL AND ${n.detector_version} IS NOT NULL AND ${n.content_fingerprint} IS NOT NULL AND length(${n.source_task_id}) > 0 AND length(${n.detector_version}) > 0 AND length(${n.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(n.thread_id,n.status,n.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(n.thread_id,n.covers_from_task_id,n.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(n.thread_id,n.source_task_id,n.detector_version,n.content_fingerprint).where(sql`${n.source} = 'auto'`)}));var W=class extends c{reason;constructor(e,t="VALIDATION",r=e,o){super(t,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},$n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ki(){let n=randomBytes(16),e="";for(let t of n)e+=$n[t%$n.length];return e.slice(0,12)}function mt(){return `c_${ki()}`}function Ti(n){return typeof n=="string"&&Qt.includes(n)}function yi(n){return typeof n=="string"&&Zt.includes(n)}function _t(n){if(!Ti(n))throw new W("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${n}`)}function jn(n){if(!yi(n))throw new W("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${n}`)}function Mn(n){let e=typeof n=="string"?n.trim():"",t=[...e].length;if(t<1||t>20)throw new W("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function ft(n){if(typeof n!="string"||n.trim().length===0)throw new W("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function rr(n){if(typeof n!="string"||n.trim().length===0)throw new W("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function et(n,e){return and(eq(m.code_group,n),or(isNull(m.workspace_id),eq(m.workspace_id,e)))}var Cr=class extends x{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 c("NOT_FOUND","Database not found");e&&mkdirSync(dirname(t),{recursive:true});let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}listSelectable(e,t){if(_t(e),ft(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(and(et(e,t),eq(m.is_archived,0))).orderBy(asc(m.sort_order),asc(m.code)).all()}catch(o){throw new c("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,t){if(_t(e),ft(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(et(e,t)).orderBy(asc(m.sort_order),asc(m.code)).all()}catch(o){throw new c("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let t=e.group;if(_t(t),ft(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)rr(o);if(new Set(e.codes).size!==e.codes.length)throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(m).where(et(t,e.workspaceId)).all(),i=s.filter(f=>f.is_archived===0),d=new Set(s.map(f=>f.code)),l=new Set(i.map(f=>f.code)),u=e.codes.find(f=>!d.has(f));if(u)throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${t}/${u}`);if(e.codes.length!==i.length||e.codes.some(f=>!l.has(f)))throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let h=new Map(i.map(f=>[f.code,f])),g=e.codes.map(f=>{let D=h.get(f);if(!D)throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${t}/${f}`);return D}),p;for(let[f,D]of g.entries())D.sort_order!==f&&(p??=new Date().toISOString(),o.update(m).set({sort_order:f,updated_at:p}).where(and(eq(m.code_group,t),eq(m.code,D.code))).run());return o.select().from(m).where(et(t,e.workspaceId)).orderBy(asc(m.sort_order),asc(m.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,t){if(_t(e),rr(t),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get()??null}catch(o){throw new c("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){ft(e.workspaceId);let t=Mn(e.name);jn(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:m.code}).from(m).where(and(et("THREAD_STATE",e.workspaceId),eq(m.is_archived,0),eq(m.code_name,t))).limit(1).get())throw new W("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`);let i=o.select({maxSortOrder:sql`max(${m.sort_order})`}).from(m).where(et("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),l=mt();for(;o.select({code:m.code}).from(m).where(and(eq(m.code_group,"THREAD_STATE"),eq(m.code,l))).limit(1).get();)l=mt();o.insert(m).values({code_group:"THREAD_STATE",code:l,code_name:t,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:d,updated_at:d}).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 c("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(_t(e.group),rr(e.code),ft(e.workspaceId),e.name===void 0&&e.color===void 0)throw new W("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let t=e.name===void 0||e.name===null?e.name:Mn(e.name);e.color!==void 0&&jn(e.color);let r=this.openHandle(true);try{return r.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 W("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 W("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof t=="string"&&s.is_archived===0){let l=and(et(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 W("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=t??null),e.color!==void 0&&(i.color=e.color),o.update(m).set(i).where(and(eq(m.code_group,e.group),eq(m.code,e.code))).run();let d=o.select().from(m).where(and(eq(m.code_group,e.group),eq(m.code,e.code))).limit(1).get();if(!d)throw new c("DB_ERROR","Updated common code could not be read back");return d},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,t,r,o=true){if(_t(e),rr(t),ft(r),typeof o!="boolean")throw new W("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let d=i.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get();if(!d)throw new W("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${t}`);if(d.is_builtin===1)throw new W("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!o&&d.code_name!==null&&i.select({code:m.code}).from(m).where(and(et(e,r),eq(m.is_archived,0),eq(m.code_name,d.code_name),ne(m.code,t))).limit(1).get())throw new W("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${d.code_name}`);i.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=i.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get();if(!l)throw new c("DB_ERROR","Archived common code could not be read back");return l},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,t){if(e.workspace_id!==null&&e.workspace_id!==t)throw new W("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function Dr(n){let e=qe.resolve(n);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function Bn(n){let e=Dr(n);return createHash("sha256").update(e).digest("hex")}function nr(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Ar=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{ut(r.db);}catch(o){throw r.close(),o}return r}resolveSlug(e,t,r){let o=nr(basename(r)),i=`${nr(basename(dirname(r)))}-${o}`,d=[o,i];try{let l=u=>e.select({id:R.id}).from(R).where(and(eq(R.slug,u),ne(R.id,t))).limit(1).all().length>0;for(let u of d)if(!l(u))return u;for(let u=2;u<1e3;u+=1){let h=`${i}-${u}`;if(!l(h))return h}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:R.id,slug:R.slug}).from(R).all(),r=0;for(let o of t)if(o.slug.includes("/")){let s=nr(o.slug.replace(/\//g,"-"));e.db.update(R).set({slug:s,updated_at:new Date().toISOString()}).where(eq(R.id,o.id)).run(),r+=1;}return {updated:r,checked:t.length}}catch(t){throw new c("DB_ERROR","Failed to normalize legacy slugs",t)}finally{e.close();}}ensureRow(e,t){let{id:r,slug:o,name:s,workspacePath:i}=t,d=new Date().toISOString();e.insert(R).values({id:r,slug:o,name:s,workspace_path:i,is_active:1,created_at:d,updated_at:d}).onConflictDoNothing().run(),e.update(R).set({workspace_path:i,updated_at:d}).where(and(eq(R.id,r),isNull(R.workspace_path))).run();}registerWorkspace(e){let t=Dr(e),r=this.openHandle(true);try{let o=Bn(t),s=basename(t),i=this.resolveSlug(r.db,o,t);return this.ensureRow(r.db,{id:o,slug:i,name:s,workspacePath:t}),{id:o,slug:i}}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to register workspace",o)}finally{r.close();}}listProjects(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let r=e.isActive!==void 0?eq(R.is_active,e.isActive?1:0):void 0,o=t.db.select({count:sql`count(*)`}).from(R).where(r).get();return {rows:t.db.select().from(R).where(r).orderBy(desc(R.updated_at)).limit(e.limit).offset(e.offset).all(),total:o?.count??0}}catch(r){throw new c("DB_ERROR","Failed to list projects",r)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(R).where(eq(R.id,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to find workspace",r)}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(r){throw new c("DB_ERROR","Failed to find agents by project",r)}finally{t.close();}}findThreadsByProject(e,t){if(!this.dbExists())return {rows:[],total:0};let r=this.openHandle(false);try{let o=r.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:r.db.all(sql`SELECT t.*,
|
|
7
|
+
)`),instanceRequestUnique:uniqueIndex("ui_action_receipts_instance_request_uq").on(n.instance_id,n.request_id),instanceIdIdx:index("ui_action_receipts_instance_id_idx").on(n.instance_id),requestedAtIdx:index("ui_action_receipts_requested_at_idx").on(n.requested_at)}));var j=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")},n=>({idCheck:check("projects_id_ck",sql`${n.id} GLOB 'prj_*'`),sceneCheck:check("projects_scene_ck",sql`${n.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(${n.stages_json}) AND json_type(${n.stages_json}) = 'array'`),stageIndexCheck:check("projects_stage_index_ck",sql`${n.stage_index} >= 1`)})),pe=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>j.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()},n=>({idCheck:check("project_criteria_id_ck",sql`${n.id} GLOB 'pjc_*'`),verifyStatusCheck:check("project_criteria_verify_status_ck",sql`${n.verify_status} IN ('pending', 'verifying', 'passed', 'failed')`),evidenceJsonCheck:check("project_criteria_evidence_json_ck",sql`json_valid(${n.evidence_json}) AND json_type(${n.evidence_json}) = 'array'`),projectPositionUnique:uniqueIndex("project_criteria_project_position_uq").on(n.project_id,n.position)})),Ce=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>j.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()},n=>({idCheck:check("project_events_id_ck",sql`${n.id} GLOB 'pje_*'`),actorTypeCheck:check("project_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'project_manager', 'system')`),payloadJsonCheck:check("project_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),projectSeqUnique:uniqueIndex("project_events_project_seq_uq").on(n.project_id,n.seq)}));var Qt=["THREAD_STATE","THREAD_PRIORITY"],Zt=["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()},n=>({pk:primaryKey({columns:[n.code_group,n.code]}),metadataCheck:check("common_codes_metadata_ck",sql`${n.metadata} IS NULL OR (json_valid(${n.metadata}) AND json_type(${n.metadata}) = 'object')`),builtinCheck:check("common_codes_builtin_ck",sql`${n.is_builtin} IN (0, 1)`),archivedCheck:check("common_codes_archived_ck",sql`${n.is_archived} IN (0, 1)`),idxCommonCodesSelection:index("idx_common_codes_group_archived_order").on(n.code_group,n.is_archived,n.sort_order)}));var An=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted","thread.highlights.regenerated"],xn=["user","agent","system"],Ln=["auto","manual"],Pn=["decision","judgment","issue","result","pivot"];var Hn=["queued","running","completed","failed"],M=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),type:text("type").notNull(),actor_type:text("actor_type").notNull(),payload_json:text("payload_json").notNull(),created_at:text("created_at").notNull(),actor_id:text("actor_id"),task_id:text("task_id"),highlight_id:text("highlight_id")},n=>({typeCheck:check("thread_events_type_ck",sql`${n.type} IN ('thread.snapshot.imported', 'thread.title.changed', 'thread.priority.changed', 'thread.state.changed', 'thread.highlight.created', 'thread.highlight.updated', 'thread.highlight.deleted', 'thread.highlights.regenerated')`),actorTypeCheck:check("thread_events_actor_type_ck",sql`${n.actor_type} IN ('user', 'agent', 'system')`),payloadJsonCheck:check("thread_events_payload_json_ck",sql`json_valid(${n.payload_json}) AND json_type(${n.payload_json}) = 'object'`),threadSeqIndex:index("idx_thread_events_thread_seq").on(n.thread_id,n.seq),threadCreatedIndex:index("idx_thread_events_thread_created").on(n.thread_id,n.created_at),threadSeqUnique:uniqueIndex("thread_events_thread_seq_uq").on(n.thread_id,n.seq)})),A=sqliteTable("thread_highlight_runs",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),request_id:text("request_id").notNull(),status:text("status").notNull(),detector_version:text("detector_version").notNull(),requested_at:text("requested_at").notNull(),started_at:text("started_at"),completed_at:text("completed_at"),error_code:text("error_code"),previous_auto_count:integer("previous_auto_count"),new_auto_count:integer("new_auto_count")},n=>({statusCheck:check("thread_highlight_runs_status_ck",sql`${n.status} IN ('queued', 'running', 'completed', 'failed')`),countCheck:check("thread_highlight_runs_counts_ck",sql`(${n.previous_auto_count} IS NULL OR ${n.previous_auto_count} >= 0) AND (${n.new_auto_count} IS NULL OR ${n.new_auto_count} >= 0)`),threadRequestUnique:uniqueIndex("thread_highlight_runs_thread_request_uq").on(n.thread_id,n.request_id),inProgressThreadUnique:uniqueIndex("thread_highlight_runs_in_progress_thread_uq").on(n.thread_id).where(sql`${n.status} IN ('queued', 'running')`),threadStatusRequestedIndex:index("idx_thread_highlight_runs_thread_status_requested").on(n.thread_id,n.status,n.requested_at)})),v=sqliteTable("thread_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>_.id,{onDelete:"cascade"}),source:text("source").notNull(),kind:text("kind").notNull(),status:text("status").notNull().default("active"),text:text("text"),covers_from_task_id:text("covers_from_task_id").notNull(),covers_to_task_id:text("covers_to_task_id").notNull(),revision:integer("revision").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),agent_id:text("agent_id"),source_task_id:text("source_task_id"),detector_version:text("detector_version"),content_fingerprint:text("content_fingerprint"),dismissed_at:text("dismissed_at")},n=>({sourceCheck:check("thread_highlights_source_ck",sql`${n.source} IN ('auto', 'manual')`),kindCheck:check("thread_highlights_kind_ck",sql`${n.kind} IN ('decision', 'judgment', 'issue', 'result', 'pivot')`),statusCheck:check("thread_highlights_status_ck",sql`${n.status} IN ('active', 'dismissed')`),activeTextCheck:check("thread_highlights_active_text_ck",sql`${n.status} = 'dismissed' OR (${n.text} IS NOT NULL AND length(${n.text}) > 0)`),coversCheck:check("thread_highlights_covers_ck",sql`length(${n.covers_from_task_id}) > 0 AND length(${n.covers_to_task_id}) > 0`),autoKeyCheck:check("thread_highlights_auto_key_ck",sql`${n.source} = 'manual' OR (${n.source} = 'auto' AND ${n.source_task_id} IS NOT NULL AND ${n.detector_version} IS NOT NULL AND ${n.content_fingerprint} IS NOT NULL AND length(${n.source_task_id}) > 0 AND length(${n.detector_version}) > 0 AND length(${n.content_fingerprint}) > 0)`),threadStatusCreatedIndex:index("idx_thread_highlights_thread_status_created").on(n.thread_id,n.status,n.created_at),threadCoversIndex:index("idx_thread_highlights_thread_covers").on(n.thread_id,n.covers_from_task_id,n.covers_to_task_id),autoIdempotencyUnique:uniqueIndex("thread_highlights_auto_idempotency_uq").on(n.thread_id,n.source_task_id,n.detector_version,n.content_fingerprint).where(sql`${n.source} = 'auto'`)}));var W=class extends c{reason;constructor(e,t="VALIDATION",r=e,o){super(t,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},jn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ki(){let n=randomBytes(16),e="";for(let t of n)e+=jn[t%jn.length];return e.slice(0,12)}function mt(){return `c_${ki()}`}function Ti(n){return typeof n=="string"&&Qt.includes(n)}function yi(n){return typeof n=="string"&&Zt.includes(n)}function _t(n){if(!Ti(n))throw new W("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${n}`)}function Mn(n){if(!yi(n))throw new W("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${n}`)}function qn(n){let e=typeof n=="string"?n.trim():"",t=[...e].length;if(t<1||t>20)throw new W("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function ft(n){if(typeof n!="string"||n.trim().length===0)throw new W("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function rr(n){if(typeof n!="string"||n.trim().length===0)throw new W("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function et(n,e){return and(eq(m.code_group,n),or(isNull(m.workspace_id),eq(m.workspace_id,e)))}var Cr=class extends x{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 c("NOT_FOUND","Database not found");e&&mkdirSync(dirname(t),{recursive:true});let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}listSelectable(e,t){if(_t(e),ft(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(and(et(e,t),eq(m.is_archived,0))).orderBy(asc(m.sort_order),asc(m.code)).all()}catch(o){throw new c("DB_ERROR","Failed to list selectable common codes",o)}finally{r.close();}}listForHistory(e,t){if(_t(e),ft(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(et(e,t)).orderBy(asc(m.sort_order),asc(m.code)).all()}catch(o){throw new c("DB_ERROR","Failed to list common-code history",o)}finally{r.close();}}reorder(e){let t=e.group;if(_t(t),ft(e.workspaceId),!Array.isArray(e.codes)||e.codes.length===0)throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION","At least one common-code code is required for reordering");for(let o of e.codes)rr(o);if(new Set(e.codes).size!==e.codes.length)throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder entries must be unique");if(!this.dbExists())throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder scope does not exist");let r=this.openHandle(true);try{return r.db.transaction(o=>{let s=o.select().from(m).where(et(t,e.workspaceId)).all(),i=s.filter(f=>f.is_archived===0),d=new Set(s.map(f=>f.code)),l=new Set(i.map(f=>f.code)),u=e.codes.find(f=>!d.has(f));if(u)throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not available in this scope: ${t}/${u}`);if(e.codes.length!==i.length||e.codes.some(f=>!l.has(f)))throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION","Common-code reorder must contain every non-archived code in the scope");let h=new Map(i.map(f=>[f.code,f])),g=e.codes.map(f=>{let D=h.get(f);if(!D)throw new W("COMMON_CODE_REORDER_INVALID","VALIDATION",`Common code is not selectable in this scope: ${t}/${f}`);return D}),p;for(let[f,D]of g.entries())D.sort_order!==f&&(p??=new Date().toISOString(),o.update(m).set({sort_order:f,updated_at:p}).where(and(eq(m.code_group,t),eq(m.code,D.code))).run());return o.select().from(m).where(et(t,e.workspaceId)).orderBy(asc(m.sort_order),asc(m.code)).all()},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to reorder common codes",o)}finally{r.close();}}resolve(e,t){if(_t(e),rr(t),!this.dbExists())return null;let r=this.openHandle(false);try{return r.db.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get()??null}catch(o){throw new c("DB_ERROR","Failed to resolve common code",o)}finally{r.close();}}createThreadState(e){ft(e.workspaceId);let t=qn(e.name);Mn(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:m.code}).from(m).where(and(et("THREAD_STATE",e.workspaceId),eq(m.is_archived,0),eq(m.code_name,t))).limit(1).get())throw new W("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`);let i=o.select({maxSortOrder:sql`max(${m.sort_order})`}).from(m).where(et("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),l=mt();for(;o.select({code:m.code}).from(m).where(and(eq(m.code_group,"THREAD_STATE"),eq(m.code,l))).limit(1).get();)l=mt();o.insert(m).values({code_group:"THREAD_STATE",code:l,code_name:t,color:e.color,sort_order:(i?.maxSortOrder??-1)+1,workspace_id:e.workspaceId,is_builtin:0,is_archived:0,metadata:null,created_at:d,updated_at:d}).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 c("DB_ERROR","Created common code could not be read back");return u},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to create thread state common code",o)}finally{r.close();}}updateDisplay(e){if(_t(e.group),rr(e.code),ft(e.workspaceId),e.name===void 0&&e.color===void 0)throw new W("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let t=e.name===void 0||e.name===null?e.name:qn(e.name);e.color!==void 0&&Mn(e.color);let r=this.openHandle(true);try{return r.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 W("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 W("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof t=="string"&&s.is_archived===0){let l=and(et(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 W("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${t}`)}let i={updated_at:new Date().toISOString()};e.name!==void 0&&(i.code_name=t??null),e.color!==void 0&&(i.color=e.color),o.update(m).set(i).where(and(eq(m.code_group,e.group),eq(m.code,e.code))).run();let d=o.select().from(m).where(and(eq(m.code_group,e.group),eq(m.code,e.code))).limit(1).get();if(!d)throw new c("DB_ERROR","Updated common code could not be read back");return d},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to update common-code display values",o)}finally{r.close();}}archive(e,t,r,o=true){if(_t(e),rr(t),ft(r),typeof o!="boolean")throw new W("COMMON_CODE_ARCHIVE_INVALID","VALIDATION","Archive state must be boolean");let s=this.openHandle(true);try{return s.db.transaction(i=>{let d=i.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get();if(!d)throw new W("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${t}`);if(d.is_builtin===1)throw new W("COMMON_CODE_BUILTIN_ARCHIVE_FORBIDDEN","VALIDATION","Builtin common codes cannot be archived");if(this.assertOwnership(d,r),!o&&d.code_name!==null&&i.select({code:m.code}).from(m).where(and(et(e,r),eq(m.is_archived,0),eq(m.code_name,d.code_name),ne(m.code,t))).limit(1).get())throw new W("COMMON_CODE_NAME_CONFLICT","CONFLICT",`Common-code name is already in use: ${d.code_name}`);i.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=i.select().from(m).where(and(eq(m.code_group,e),eq(m.code,t))).limit(1).get();if(!l)throw new c("DB_ERROR","Archived common code could not be read back");return l},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to archive common code",i)}finally{s.close();}}assertOwnership(e,t){if(e.workspace_id!==null&&e.workspace_id!==t)throw new W("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function Dr(n){let e=qe.resolve(n);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function Fn(n){let e=Dr(n);return createHash("sha256").update(e).digest("hex")}function nr(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var Ar=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{ut(r.db);}catch(o){throw r.close(),o}return r}resolveSlug(e,t,r){let o=nr(basename(r)),i=`${nr(basename(dirname(r)))}-${o}`,d=[o,i];try{let l=u=>e.select({id:k.id}).from(k).where(and(eq(k.slug,u),ne(k.id,t))).limit(1).all().length>0;for(let u of d)if(!l(u))return u;for(let u=2;u<1e3;u+=1){let h=`${i}-${u}`;if(!l(h))return h}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:k.id,slug:k.slug}).from(k).all(),r=0;for(let o of t)if(o.slug.includes("/")){let s=nr(o.slug.replace(/\//g,"-"));e.db.update(k).set({slug:s,updated_at:new Date().toISOString()}).where(eq(k.id,o.id)).run(),r+=1;}return {updated:r,checked:t.length}}catch(t){throw new c("DB_ERROR","Failed to normalize legacy slugs",t)}finally{e.close();}}ensureRow(e,t){let{id:r,slug:o,name:s,workspacePath:i}=t,d=new Date().toISOString();e.insert(k).values({id:r,slug:o,name:s,workspace_path:i,is_active:1,created_at:d,updated_at:d}).onConflictDoNothing().run(),e.update(k).set({workspace_path:i,updated_at:d}).where(and(eq(k.id,r),isNull(k.workspace_path))).run();}registerWorkspace(e){let t=Dr(e),r=this.openHandle(true);try{let o=Fn(t),s=basename(t),i=this.resolveSlug(r.db,o,t);return this.ensureRow(r.db,{id:o,slug:i,name:s,workspacePath:t}),{id:o,slug:i}}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to register workspace",o)}finally{r.close();}}listProjects(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let r=e.isActive!==void 0?eq(k.is_active,e.isActive?1:0):void 0,o=t.db.select({count:sql`count(*)`}).from(k).where(r).get();return {rows:t.db.select().from(k).where(r).orderBy(desc(k.updated_at)).limit(e.limit).offset(e.offset).all(),total:o?.count??0}}catch(r){throw new c("DB_ERROR","Failed to list projects",r)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(k).where(eq(k.id,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to find workspace",r)}finally{t.close();}}toggleStar(e){let t=this.openHandle(true);try{let r=t.db.select({starred:k.starred}).from(k).where(eq(k.id,e)).get();if(!r)return null;let o=r.starred?0:1;return t.db.update(k).set({starred:o}).where(eq(k.id,e)).run(),{starred:!!o}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to toggle workspace star",r)}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(r){throw new c("DB_ERROR","Failed to find agents by project",r)}finally{t.close();}}findThreadsByProject(e,t){if(!this.dbExists())return {rows:[],total:0};let r=this.openHandle(false);try{let o=r.db.get(sql`SELECT COUNT(*) as count FROM threads WHERE workspace_id = ${e}`);return {rows:r.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 c("DB_ERROR","Failed to find threads by project",o)}finally{r.close();}}findBySlug(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(R).where(eq(R.slug,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to find workspace by slug",r)}finally{t.close();}}slugExists(e,t){if(!this.dbExists())return false;let r=this.openHandle(false);try{let o=t?and(eq(R.slug,e),ne(R.id,t)):eq(R.slug,e);return !!r.db.select({id:R.id}).from(R).where(o).limit(1).get()}catch(o){throw new c("DB_ERROR","Failed to check slug",o)}finally{r.close();}}insert(e,t,r,o){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(R).values({id:e,slug:t,name:r,workspace_path:o,is_active:1,created_at:i,updated_at:i}).run();let d=s.db.select().from(R).where(eq(R.id,e)).limit(1).get();if(!d)throw new c("DB_ERROR","Insert did not return a row");return d}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(e,t,r){let o=this.openHandle(true);try{o.runRaw(`UPDATE workspaces SET ${t.join(", ")} WHERE id = ?`,r);let s=o.db.select().from(R).where(eq(R.id,e)).limit(1).get();if(!s)throw new c("NOT_FOUND",`Workspace ${e} not found`);return s}catch(s){throw s instanceof c?s:new c("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:R.id,workspace_path:R.workspace_path}).from(R).where(and(eq(R.is_active,1),isNotNull(R.workspace_path))).all(),r=0;for(let o of t){let s=o.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(e.db.update(R).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(R.id,o.id)).run(),r+=1);}return {softDeleted:r,checked:t.length}}catch(t){throw new c("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(R).where(eq(R.id,e)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to delete workspace",r)}finally{t.close();}}};var xr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function vi(n){let e=randomBytes(n*2),t="";for(let r=0;r<e.length&&t.length<n;r++){let o=e[r];o<248&&(t+=xr[o%62]);}for(;t.length<n;)t+=xr[randomBytes(1)[0]%62];return t}function fe(n){return `${n}_${vi(8)}`}function Gn(n,e){let{createHash:t}=ot("crypto"),r=t("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=xr[i%62];return `${n}_${s}`}var Pr=["outcome_plan","contract_check","feature_link","use_verify","result_review"],Li=new Set(Pr),Xn=Object.freeze(Pr.map(n=>({key:n,labelOverride:null}))),Pi=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),Hi=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),$i=new Set(["pending","verifying","passed","failed"]),ji=new Set(["user","project_manager","system"]),Mi=new Set(["task","wi","url"]),qi=/^\d{4}-\d{2}-\d{2}$/;function G(n){throw new c("VALIDATION",n)}function Ee(n){throw new c("NOT_FOUND",n)}function Z(n,e){(typeof n!="string"||n.trim().length===0)&&G(`${e} is required`);}function Bi(n){if(n==null)return;qi.test(n)||G("dueDate must use YYYY-MM-DD");let e=new Date(`${n}T00:00:00.000Z`);(Number.isNaN(e.getTime())||e.toISOString().slice(0,10)!==n)&&G("dueDate must be a valid calendar date");}function Qn(n){let e=n??Xn;(!Array.isArray(e)||e.length===0)&&G("stages must contain at least one stage");let t=new Set;return e.map(r=>{(!r||typeof r!="object"||Array.isArray(r))&&G("stage must be an object");let o=r;return Z(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&G("stage.labelOverride must be a string or null"),o.labelOverride!==null&&Z(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&G("stage.key is required"),!Li.has(o.key)&&o.labelOverride===null&&G(`custom stage requires a labelOverride: ${o.key}`),t.has(o.key)&&G(`duplicate stage key: ${o.key}`),t.add(o.key),{key:o.key,labelOverride:o.labelOverride}})}function Fi(n){Array.isArray(n)||G("criteria must be an array");for(let e of n)Z(e,"criterion.statement");}function wt(n={}){let e=n.actorType??"system";ji.has(e)||G(`invalid actorType: ${String(e)}`);let t=n.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&G(`actorId is required for ${e}`),{actorType:e,actorId:t}}function Zn(n,e){let t=n??{};if((t===null||typeof t!="object"||Array.isArray(t))&&G("event payload must be a JSON object"),e==="accepted")for(let r of ["remainingRisks","nextPlan","lessons","evidenceRefs"])(!Object.prototype.hasOwnProperty.call(t,r)||t[r]===void 0)&&G(`accepted payload requires ${r}`);try{return JSON.stringify(t)}catch(r){throw new c("VALIDATION","event payload must be JSON serializable",r)}}function Ui(n){return Array.isArray(n)||G("evidence must be an array"),n.map(e=>((!e||typeof e!="object")&&G("evidence item must be an object"),Mi.has(e.kind)||G(`invalid evidence kind: ${String(e.kind)}`),Z(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&G("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 Yn(n){let e;try{e=JSON.parse(n);}catch(t){throw new c("DB_ERROR","Project stages JSON is invalid",t)}try{if(!Array.isArray(e))throw new c("DB_ERROR","Project stages JSON is invalid");return Qn(e)}catch(t){throw new c("DB_ERROR","Project stages JSON is invalid",t)}}function eo(n){return Z(n.projectId,"projectId"),Z(n.title,"title"),Pi.has(n.type)||G(`invalid project event type: ${String(n.type)}`),{...wt(n),payloadJson:Zn(n.payload,n.type)}}function at(n,e,t){let r=eo(e);n.select({id:j.id}).from(j).where(eq(j.id,e.projectId)).get()||Ee(`Project ${e.projectId} not found`);let s=n.select({maxSeq:sql`COALESCE(MAX(${Ce.seq}), 0)`}).from(Ce).where(eq(Ce.project_id,e.projectId)).get()?.maxSeq??0,i=fe("pje");n.insert(Ce).values({id:i,project_id:e.projectId,seq:s+1,actor_type:r.actorType,actor_id:r.actorId,type:e.type,title:e.title,summary:e.summary??null,payload_json:r.payloadJson,created_at:t}).run();let d=n.select().from(Ce).where(eq(Ce.id,i)).get();if(!d)throw new c("DB_ERROR","Event insert did not return a row");return d}var Lr=class extends x{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 c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}getDetailFromHandle(e,t){let r=e.db.select().from(j).where(eq(j.id,t)).get();if(!r)return;let o=e.db.select().from(ge).where(eq(ge.project_id,t)).orderBy(asc(ge.position)).all();return {...r,stages:Yn(r.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||Ee(`Project ${e} not found`),t}createProject(e){Z(e.workspaceId,"workspaceId"),Z(e.name,"name"),Z(e.outcome,"outcome"),Bi(e.dueDate);let t=Qn(e.stages);Fi(e.criteria);let r=fe("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(i=>{i.insert(j).values({id:r,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((d,l)=>{i.insert(ge).values({id:fe("pjc"),project_id:r,position:l+1,statement:d,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),at(i,{projectId:r,actorType:"system",type:"created",title:"Project created",payload:{}},o);});}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to create project",i)}finally{s.close();}return this.getDetailOrThrow(r)}getProject(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return this.getDetailFromHandle(t,e)}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to get project",r)}finally{t.close();}}listProjectsByWorkspace(e,t={}){if(Z(e,"workspaceId"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=t.includeArchived?eq(j.workspace_id,e):and(eq(j.workspace_id,e),isNull(j.archived_at));return r.db.select({id:j.id}).from(j).where(o).orderBy(desc(j.updated_at),desc(j.created_at)).all().map(i=>this.getDetailFromHandle(r,i.id)).filter(i=>i!==void 0)}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to list projects",o)}finally{r.close();}}archiveProject(e){Z(e,"projectId");let t=this.openHandle(true);try{t.db.update(j).set({archived_at:new Date().toISOString()}).where(eq(j.id,e)).run().changes===0&&Ee(`Project ${e} not found`);}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to archive project",r)}finally{t.close();}return this.getDetailOrThrow(e)}setScene(e,t,r={}){Z(e,"projectId"),Hi.has(t)||G(`invalid project scene: ${String(t)}`);let o=wt(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let l=d.select().from(j).where(eq(j.id,e)).get();l||Ee(`Project ${e} not found`),d.update(j).set({scene:t,updated_at:s}).where(eq(j.id,e)).run(),at(d,{projectId:e,...o,type:"scene_changed",title:"Project scene changed",payload:{before:l.scene,after:t}},s);});}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to set project scene",d)}finally{i.close();}return this.getDetailOrThrow(e)}setStageIndex(e,t,r={}){Z(e,"projectId"),Number.isInteger(t)||G("stage index must be an integer");let o=wt(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let l=d.select().from(j).where(eq(j.id,e)).get();l||Ee(`Project ${e} not found`);let u=Yn(l.stages_json);(t<1||t>u.length)&&G("stage index is outside the project stages"),d.update(j).set({stage_index:t,updated_at:s}).where(eq(j.id,e)).run(),at(d,{projectId:e,...o,type:"stage_advanced",title:"Project stage advanced",payload:{before:l.stage_index,after:t}},s);});}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to set project stage",d)}finally{i.close();}return this.getDetailOrThrow(e)}setCriterionVerify(e,t,r,o={}){let s=typeof e=="string"?{projectId:typeof r=="string"?e:void 0,criterionId:typeof r=="string"?t:e,verifyStatus:typeof r=="string"?r:t,...typeof r=="string"?o:r}:e,i=s.verifyStatus??s.status;(!i||!$i.has(i))&&G(`invalid criterion status: ${String(i)}`),Z(s.criterionId,"criterionId");let d=wt(s),l=new Date().toISOString(),u=this.openHandle(true),h;try{u.db.transaction(p=>{let f=p.select().from(ge).where(eq(ge.id,s.criterionId)).get();f||Ee(`Criterion ${s.criterionId} not found`),h=f.project_id,s.projectId&&s.projectId!==f.project_id&&Ee(`Criterion ${s.criterionId} not found in project ${s.projectId}`),p.update(ge).set({verify_status:i,verified_at:i==="passed"?l:null,updated_at:l}).where(eq(ge.id,s.criterionId)).run(),at(p,{projectId:f.project_id,...d,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:s.criterionId,status:i}},l);});}catch(p){throw p instanceof c?p:new c("DB_ERROR","Failed to set criterion verification",p)}finally{u.close();}let g=h?this.getProject(h)?.criteria.find(p=>p.id===s.criterionId):void 0;return g||Ee(`Criterion ${s.criterionId} not found`),g}setCriterionEvidence(e,t,r,o={}){let s=typeof e=="string"?{projectId:Array.isArray(r)?e:void 0,criterionId:Array.isArray(r)?t:e,evidence:Array.isArray(r)?r:t,...Array.isArray(r)?o:r}:e;Z(s.criterionId,"criterionId");let i=Ui(s.evidence),d=wt(s),l=new Date().toISOString(),u=this.openHandle(true),h;try{u.db.transaction(p=>{let f=p.select().from(ge).where(eq(ge.id,s.criterionId)).get();f||Ee(`Criterion ${s.criterionId} not found`),h=f.project_id,s.projectId&&s.projectId!==f.project_id&&Ee(`Criterion ${s.criterionId} not found in project ${s.projectId}`),p.update(ge).set({evidence_json:JSON.stringify(i),updated_at:l}).where(eq(ge.id,s.criterionId)).run(),at(p,{projectId:f.project_id,...d,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:s.criterionId,evidence:i}},l);});}catch(p){throw p instanceof c?p:new c("DB_ERROR","Failed to set criterion evidence",p)}finally{u.close();}let g=h?this.getProject(h)?.criteria.find(p=>p.id===s.criterionId):void 0;return g||Ee(`Criterion ${s.criterionId} not found`),g}appendEvent(e,t){let r=typeof e=="string"?{...t,projectId:e}:e;eo(r);let o=new Date().toISOString(),s=this.openHandle(true),i;try{s.db.transaction(d=>{i=at(d,r,o);});}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to append project event",d)}finally{s.close();}if(!i)throw new c("DB_ERROR","Event append did not return a row");return i}listEvents(e,t={}){if(Z(e,"projectId"),t.afterSeq!==void 0&&(!Number.isInteger(t.afterSeq)||t.afterSeq<0)&&G("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&G("limit must be a positive integer"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=[eq(Ce.project_id,e)];t.afterSeq!==void 0&&o.push(gt$1(Ce.seq,t.afterSeq));let s=r.db.select().from(Ce).where(and(...o)).orderBy(asc(Ce.seq));return t.limit!==void 0&&(s=s.limit(t.limit)),s.all()}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to list project events",o)}finally{r.close();}}acceptProject(e,t){Z(e,"projectId");let r=wt(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};Zn(o,"accepted");let s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{d.select({id:j.id}).from(j).where(eq(j.id,e)).get()||Ee(`Project ${e} not found`),d.update(j).set({scene:"accepted",accepted_at:s,updated_at:s}).where(eq(j.id,e)).run(),at(d,{projectId:e,...r,type:"accepted",title:"Project accepted",payload:o},s);});}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to accept project",d)}finally{i.close();}return this.getDetailOrThrow(e)}};var no=[R,a,_,Ue,xe,Re,gt];function Wi(){return qe__default.join(Ts.homedir(),".crewx","crewx.db")}function Vi(n){if(!to__default.existsSync(n))return null;let e=Math.floor(Date.now()/1e3),t=`${n}.bak-${e}`;return to__default.copyFileSync(n,t),t}function oo(n){let e=n.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(e.map(t=>t.name))}function Ki(n){return n==null||typeof n=="object"&&"queryChunks"in n?null:typeof n=="number"?String(n):typeof n=="boolean"?n?"1":"0":typeof n=="string"?`'${n.replace(/'/g,"''")}'`:String(n)}function Ji(n){let e=n.getSQLType(),t=`"${n.name}" ${e}`,r=Ki(n.default);return r!==null&&(t+=` DEFAULT ${r}`),n.notNull&&(t+=" NOT NULL"),t}function Yi(n,e){let t=e?.dbPath??Wi(),r=e?.force??false,o=e?.dryRun??false,s=o?null:Vi(t);if(r&&!o)try{n.run("DELETE FROM __drizzle_migrations");}catch{}let i=oo(n);if(!o)try{ut(n);}catch(g){let p=g instanceof Error?`${g.message} ${g.cause?.message??""}`:"";if(!r||!p.includes("duplicate column"))throw g}let d,l;o?(d=no.map(p=>getTableConfig(p).name).filter(p=>!i.has(p)),l=i):(l=oo(n),d=[...l].filter(g=>!i.has(g)));let u=[],h=[];for(let g of no){let p=getTableConfig(g),f=p.name;if(!l.has(f))continue;let D=n.all(`PRAGMA table_info("${f}")`),w=new Set(D.map(E=>E.name)),S=new Set(p.columns.map(E=>E.name));for(let E of p.columns)if(!w.has(E.name)){if(!o){let K=Ji(E);n.run(`ALTER TABLE "${f}" ADD COLUMN ${K}`);}u.push({table:f,column:E.name});}for(let E of D)S.has(E.name)||h.push(`${f}.${E.name} exists in DB but not in schema (untouched)`);}return {created:d,altered:u,warnings:h,backupPath:s}}function so(n){let e=n.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 uo(n,e){let t=e===void 0?"":` at index ${e}`;if(!n||typeof n!="object")throw new c("VALIDATION",`Task log entry${t} must be an object`);if(typeof n.timestamp!="string"||typeof n.level!="string"||typeof n.message!="string")throw new c("VALIDATION",`Task log entry${t} must contain string timestamp, level, and message fields`);return {timestamp:n.timestamp,level:n.level,message:n.message}}function co(n,e){if(e===null||e.trim()==="")return [];let t;try{t=JSON.parse(e);}catch(r){throw new c("DB_ERROR",`Malformed legacy task logs: ${n}`,r)}if(!Array.isArray(t))throw new c("DB_ERROR",`Malformed legacy task logs: ${n} (expected an array)`);try{return t.map((r,o)=>uo(r,o))}catch(r){throw r instanceof c?new c("DB_ERROR",`Malformed legacy task logs: ${n}`,r):r}}function ho(n){if(n.log_storage!=="blob"&&n.log_storage!=="events")throw new c("DB_ERROR",`Invalid task log storage for task: ${n.id}`);if(!Number.isInteger(n.last_log_seq)||n.last_log_seq<0)throw new c("DB_ERROR",`Invalid task log sequence for task: ${n.id}`);if(!Number.isInteger(n.log_revision)||n.log_revision<0)throw new c("DB_ERROR",`Invalid task log revision for task: ${n.id}`);return n.log_storage}function lo(n){return {taskId:n.id,source:ho(n),revision:n.log_revision,lastSeq:n.last_log_seq}}function oa(n){if(!Number.isInteger(n)||n<0)throw new c("VALIDATION","Task log tail limit must be a non-negative integer")}var Ot=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}findStateRow(e,t){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,t)).limit(1).get()}findStateRowInTransaction(e,t){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,t)).limit(1).get()}requireStateRowInTransaction(e,t){let r=this.findStateRowInTransaction(e,t);if(!r)throw new c("NOT_FOUND",`Task not found: ${t}`);return r}appendLog(e,t){return this.appendLogs(e,[t])}appendLogs(e,t){let r=t.map((s,i)=>uo(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new c("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let d=this.requireStateRowInTransaction(i,e),l=ho(d);if(l==="blob"){let p=co(e,d.logs);if(i.update(a).set({logs:JSON.stringify([...p,...r]),log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new c("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let u=d.last_log_seq+1,h=d.last_log_seq+r.length;if(i.insert(Ae).values(r.map((p,f)=>({task_id:e,seq:u+f,timestamp:p.timestamp,level:p.level,message:p.message}))).run(),i.update(a).set({last_log_seq:h,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new c("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:d.log_revision+1,lastSeq:h}},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let t=this.openHandle(false);try{let r=this.findStateRow(t,e);return r?lo(r):void 0}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to read task log state",r)}finally{t.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,t){return oa(t),this.readLogsInternal(e,t)}readTail(e,t){return this.readLogsTail(e,t)}readLogsInternal(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=lo(s);if(i.source==="blob"){let h=co(e,s.logs);return {...i,entries:t===void 0?h:h.slice(Math.max(0,h.length-t))}}let d=o.select({seq:Ae.seq,timestamp:Ae.timestamp,level:Ae.level,message:Ae.message}).from(Ae).where(eq(Ae.task_id,e)).orderBy(t===void 0?asc(Ae.seq):desc(Ae.seq)),u=(t===void 0?d.all():d.limit(t).all()).map(({timestamp:h,level:g,message:p})=>({timestamp:h,level:g,message:p}));return t!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};var $r=40,Ve="2026-05-09",la="0.8.9-rc.13",Ke=10,Je=parseInt(la.split("rc.")[1]);function go(){let n=sql`
|
|
12
|
+
LIMIT ${t.limit} OFFSET ${t.offset}`),total:o?.count??0}}catch(o){throw new c("DB_ERROR","Failed to find threads by project",o)}finally{r.close();}}findBySlug(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(k).where(eq(k.slug,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to find workspace by slug",r)}finally{t.close();}}slugExists(e,t){if(!this.dbExists())return false;let r=this.openHandle(false);try{let o=t?and(eq(k.slug,e),ne(k.id,t)):eq(k.slug,e);return !!r.db.select({id:k.id}).from(k).where(o).limit(1).get()}catch(o){throw new c("DB_ERROR","Failed to check slug",o)}finally{r.close();}}insert(e,t,r,o){let s=this.openHandle(true);try{let i=new Date().toISOString();s.db.insert(k).values({id:e,slug:t,name:r,workspace_path:o,is_active:1,created_at:i,updated_at:i}).run();let d=s.db.select().from(k).where(eq(k.id,e)).limit(1).get();if(!d)throw new c("DB_ERROR","Insert did not return a row");return d}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to insert workspace",i)}finally{s.close();}}update(e,t,r){let o=this.openHandle(true);try{o.runRaw(`UPDATE workspaces SET ${t.join(", ")} WHERE id = ?`,r);let s=o.db.select().from(k).where(eq(k.id,e)).limit(1).get();if(!s)throw new c("NOT_FOUND",`Workspace ${e} not found`);return s}catch(s){throw s instanceof c?s:new c("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:k.id,workspace_path:k.workspace_path}).from(k).where(and(eq(k.is_active,1),isNotNull(k.workspace_path))).all(),r=0;for(let o of t){let s=o.workspace_path;existsSync(join(s,"crewx.yaml"))||existsSync(join(s,"crewx.yml"))||(e.db.update(k).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(k.id,o.id)).run(),r+=1);}return {softDeleted:r,checked:t.length}}catch(t){throw new c("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(k).where(eq(k.id,e)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to delete workspace",r)}finally{t.close();}}};var xr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function vi(n){let e=randomBytes(n*2),t="";for(let r=0;r<e.length&&t.length<n;r++){let o=e[r];o<248&&(t+=xr[o%62]);}for(;t.length<n;)t+=xr[randomBytes(1)[0]%62];return t}function fe(n){return `${n}_${vi(8)}`}function Wn(n,e){let{createHash:t}=ot("crypto"),r=t("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=r[i];let s="";for(let i of o)s+=xr[i%62];return `${n}_${s}`}var Pr=["outcome_plan","contract_check","feature_link","use_verify","result_review"],Li=new Set(Pr),Qn=Object.freeze(Pr.map(n=>({key:n,labelOverride:null}))),Pi=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),Hi=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),$i=new Set(["pending","verifying","passed","failed"]),ji=new Set(["user","project_manager","system"]),Mi=new Set(["task","wi","url"]),qi=/^\d{4}-\d{2}-\d{2}$/;function G(n){throw new c("VALIDATION",n)}function Ee(n){throw new c("NOT_FOUND",n)}function Z(n,e){(typeof n!="string"||n.trim().length===0)&&G(`${e} is required`);}function Bi(n){if(n==null)return;qi.test(n)||G("dueDate must use YYYY-MM-DD");let e=new Date(`${n}T00:00:00.000Z`);(Number.isNaN(e.getTime())||e.toISOString().slice(0,10)!==n)&&G("dueDate must be a valid calendar date");}function Zn(n){let e=n??Qn;(!Array.isArray(e)||e.length===0)&&G("stages must contain at least one stage");let t=new Set;return e.map(r=>{(!r||typeof r!="object"||Array.isArray(r))&&G("stage must be an object");let o=r;return Z(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&G("stage.labelOverride must be a string or null"),o.labelOverride!==null&&Z(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&G("stage.key is required"),!Li.has(o.key)&&o.labelOverride===null&&G(`custom stage requires a labelOverride: ${o.key}`),t.has(o.key)&&G(`duplicate stage key: ${o.key}`),t.add(o.key),{key:o.key,labelOverride:o.labelOverride}})}function Fi(n){Array.isArray(n)||G("criteria must be an array");for(let e of n)Z(e,"criterion.statement");}function wt(n={}){let e=n.actorType??"system";ji.has(e)||G(`invalid actorType: ${String(e)}`);let t=n.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&G(`actorId is required for ${e}`),{actorType:e,actorId:t}}function eo(n,e){let t=n??{};if((t===null||typeof t!="object"||Array.isArray(t))&&G("event payload must be a JSON object"),e==="accepted")for(let r of ["remainingRisks","nextPlan","lessons","evidenceRefs"])(!Object.prototype.hasOwnProperty.call(t,r)||t[r]===void 0)&&G(`accepted payload requires ${r}`);try{return JSON.stringify(t)}catch(r){throw new c("VALIDATION","event payload must be JSON serializable",r)}}function Ui(n){return Array.isArray(n)||G("evidence must be an array"),n.map(e=>((!e||typeof e!="object")&&G("evidence item must be an object"),Mi.has(e.kind)||G(`invalid evidence kind: ${String(e.kind)}`),Z(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&G("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 Xn(n){let e;try{e=JSON.parse(n);}catch(t){throw new c("DB_ERROR","Project stages JSON is invalid",t)}try{if(!Array.isArray(e))throw new c("DB_ERROR","Project stages JSON is invalid");return Zn(e)}catch(t){throw new c("DB_ERROR","Project stages JSON is invalid",t)}}function to(n){return Z(n.projectId,"projectId"),Z(n.title,"title"),Pi.has(n.type)||G(`invalid project event type: ${String(n.type)}`),{...wt(n),payloadJson:eo(n.payload,n.type)}}function at(n,e,t){let r=to(e);n.select({id:j.id}).from(j).where(eq(j.id,e.projectId)).get()||Ee(`Project ${e.projectId} not found`);let s=n.select({maxSeq:sql`COALESCE(MAX(${Ce.seq}), 0)`}).from(Ce).where(eq(Ce.project_id,e.projectId)).get()?.maxSeq??0,i=fe("pje");n.insert(Ce).values({id:i,project_id:e.projectId,seq:s+1,actor_type:r.actorType,actor_id:r.actorId,type:e.type,title:e.title,summary:e.summary??null,payload_json:r.payloadJson,created_at:t}).run();let d=n.select().from(Ce).where(eq(Ce.id,i)).get();if(!d)throw new c("DB_ERROR","Event insert did not return a row");return d}var Lr=class extends x{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 c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}getDetailFromHandle(e,t){let r=e.db.select().from(j).where(eq(j.id,t)).get();if(!r)return;let o=e.db.select().from(pe).where(eq(pe.project_id,t)).orderBy(asc(pe.position)).all();return {...r,stages:Xn(r.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||Ee(`Project ${e} not found`),t}createProject(e){Z(e.workspaceId,"workspaceId"),Z(e.name,"name"),Z(e.outcome,"outcome"),Bi(e.dueDate);let t=Zn(e.stages);Fi(e.criteria);let r=fe("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(i=>{i.insert(j).values({id:r,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((d,l)=>{i.insert(pe).values({id:fe("pjc"),project_id:r,position:l+1,statement:d,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),at(i,{projectId:r,actorType:"system",type:"created",title:"Project created",payload:{}},o);});}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to create project",i)}finally{s.close();}return this.getDetailOrThrow(r)}getProject(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return this.getDetailFromHandle(t,e)}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to get project",r)}finally{t.close();}}listProjectsByWorkspace(e,t={}){if(Z(e,"workspaceId"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=t.includeArchived?eq(j.workspace_id,e):and(eq(j.workspace_id,e),isNull(j.archived_at));return r.db.select({id:j.id}).from(j).where(o).orderBy(desc(j.updated_at),desc(j.created_at)).all().map(i=>this.getDetailFromHandle(r,i.id)).filter(i=>i!==void 0)}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to list projects",o)}finally{r.close();}}archiveProject(e){Z(e,"projectId");let t=this.openHandle(true);try{t.db.update(j).set({archived_at:new Date().toISOString()}).where(eq(j.id,e)).run().changes===0&&Ee(`Project ${e} not found`);}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to archive project",r)}finally{t.close();}return this.getDetailOrThrow(e)}setScene(e,t,r={}){Z(e,"projectId"),Hi.has(t)||G(`invalid project scene: ${String(t)}`);let o=wt(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let l=d.select().from(j).where(eq(j.id,e)).get();l||Ee(`Project ${e} not found`),d.update(j).set({scene:t,updated_at:s}).where(eq(j.id,e)).run(),at(d,{projectId:e,...o,type:"scene_changed",title:"Project scene changed",payload:{before:l.scene,after:t}},s);});}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to set project scene",d)}finally{i.close();}return this.getDetailOrThrow(e)}setStageIndex(e,t,r={}){Z(e,"projectId"),Number.isInteger(t)||G("stage index must be an integer");let o=wt(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let l=d.select().from(j).where(eq(j.id,e)).get();l||Ee(`Project ${e} not found`);let u=Xn(l.stages_json);(t<1||t>u.length)&&G("stage index is outside the project stages"),d.update(j).set({stage_index:t,updated_at:s}).where(eq(j.id,e)).run(),at(d,{projectId:e,...o,type:"stage_advanced",title:"Project stage advanced",payload:{before:l.stage_index,after:t}},s);});}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to set project stage",d)}finally{i.close();}return this.getDetailOrThrow(e)}setCriterionVerify(e,t,r,o={}){let s=typeof e=="string"?{projectId:typeof r=="string"?e:void 0,criterionId:typeof r=="string"?t:e,verifyStatus:typeof r=="string"?r:t,...typeof r=="string"?o:r}:e,i=s.verifyStatus??s.status;(!i||!$i.has(i))&&G(`invalid criterion status: ${String(i)}`),Z(s.criterionId,"criterionId");let d=wt(s),l=new Date().toISOString(),u=this.openHandle(true),h;try{u.db.transaction(p=>{let f=p.select().from(pe).where(eq(pe.id,s.criterionId)).get();f||Ee(`Criterion ${s.criterionId} not found`),h=f.project_id,s.projectId&&s.projectId!==f.project_id&&Ee(`Criterion ${s.criterionId} not found in project ${s.projectId}`),p.update(pe).set({verify_status:i,verified_at:i==="passed"?l:null,updated_at:l}).where(eq(pe.id,s.criterionId)).run(),at(p,{projectId:f.project_id,...d,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:s.criterionId,status:i}},l);});}catch(p){throw p instanceof c?p:new c("DB_ERROR","Failed to set criterion verification",p)}finally{u.close();}let g=h?this.getProject(h)?.criteria.find(p=>p.id===s.criterionId):void 0;return g||Ee(`Criterion ${s.criterionId} not found`),g}setCriterionEvidence(e,t,r,o={}){let s=typeof e=="string"?{projectId:Array.isArray(r)?e:void 0,criterionId:Array.isArray(r)?t:e,evidence:Array.isArray(r)?r:t,...Array.isArray(r)?o:r}:e;Z(s.criterionId,"criterionId");let i=Ui(s.evidence),d=wt(s),l=new Date().toISOString(),u=this.openHandle(true),h;try{u.db.transaction(p=>{let f=p.select().from(pe).where(eq(pe.id,s.criterionId)).get();f||Ee(`Criterion ${s.criterionId} not found`),h=f.project_id,s.projectId&&s.projectId!==f.project_id&&Ee(`Criterion ${s.criterionId} not found in project ${s.projectId}`),p.update(pe).set({evidence_json:JSON.stringify(i),updated_at:l}).where(eq(pe.id,s.criterionId)).run(),at(p,{projectId:f.project_id,...d,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:s.criterionId,evidence:i}},l);});}catch(p){throw p instanceof c?p:new c("DB_ERROR","Failed to set criterion evidence",p)}finally{u.close();}let g=h?this.getProject(h)?.criteria.find(p=>p.id===s.criterionId):void 0;return g||Ee(`Criterion ${s.criterionId} not found`),g}appendEvent(e,t){let r=typeof e=="string"?{...t,projectId:e}:e;to(r);let o=new Date().toISOString(),s=this.openHandle(true),i;try{s.db.transaction(d=>{i=at(d,r,o);});}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to append project event",d)}finally{s.close();}if(!i)throw new c("DB_ERROR","Event append did not return a row");return i}listEvents(e,t={}){if(Z(e,"projectId"),t.afterSeq!==void 0&&(!Number.isInteger(t.afterSeq)||t.afterSeq<0)&&G("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&G("limit must be a positive integer"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=[eq(Ce.project_id,e)];t.afterSeq!==void 0&&o.push(gt$1(Ce.seq,t.afterSeq));let s=r.db.select().from(Ce).where(and(...o)).orderBy(asc(Ce.seq));return t.limit!==void 0&&(s=s.limit(t.limit)),s.all()}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to list project events",o)}finally{r.close();}}acceptProject(e,t){Z(e,"projectId");let r=wt(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};eo(o,"accepted");let s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{d.select({id:j.id}).from(j).where(eq(j.id,e)).get()||Ee(`Project ${e} not found`),d.update(j).set({scene:"accepted",accepted_at:s,updated_at:s}).where(eq(j.id,e)).run(),at(d,{projectId:e,...r,type:"accepted",title:"Project accepted",payload:o},s);});}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to accept project",d)}finally{i.close();}return this.getDetailOrThrow(e)}};var oo=[k,a,_,Ue,xe,Re,gt];function Wi(){return qe__default.join(ys.homedir(),".crewx","crewx.db")}function Vi(n){if(!ro__default.existsSync(n))return null;let e=Math.floor(Date.now()/1e3),t=`${n}.bak-${e}`;return ro__default.copyFileSync(n,t),t}function so(n){let e=n.all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");return new Set(e.map(t=>t.name))}function Ki(n){return n==null||typeof n=="object"&&"queryChunks"in n?null:typeof n=="number"?String(n):typeof n=="boolean"?n?"1":"0":typeof n=="string"?`'${n.replace(/'/g,"''")}'`:String(n)}function Ji(n){let e=n.getSQLType(),t=`"${n.name}" ${e}`,r=Ki(n.default);return r!==null&&(t+=` DEFAULT ${r}`),n.notNull&&(t+=" NOT NULL"),t}function Yi(n,e){let t=e?.dbPath??Wi(),r=e?.force??false,o=e?.dryRun??false,s=o?null:Vi(t);if(r&&!o)try{n.run("DELETE FROM __drizzle_migrations");}catch{}let i=so(n);if(!o)try{ut(n);}catch(g){let p=g instanceof Error?`${g.message} ${g.cause?.message??""}`:"";if(!r||!p.includes("duplicate column"))throw g}let d,l;o?(d=oo.map(p=>getTableConfig(p).name).filter(p=>!i.has(p)),l=i):(l=so(n),d=[...l].filter(g=>!i.has(g)));let u=[],h=[];for(let g of oo){let p=getTableConfig(g),f=p.name;if(!l.has(f))continue;let D=n.all(`PRAGMA table_info("${f}")`),w=new Set(D.map(E=>E.name)),S=new Set(p.columns.map(E=>E.name));for(let E of p.columns)if(!w.has(E.name)){if(!o){let K=Ji(E);n.run(`ALTER TABLE "${f}" ADD COLUMN ${K}`);}u.push({table:f,column:E.name});}for(let E of D)S.has(E.name)||h.push(`${f}.${E.name} exists in DB but not in schema (untouched)`);}return {created:d,altered:u,warnings:h,backupPath:s}}function io(n){let e=n.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 ho(n,e){let t=e===void 0?"":` at index ${e}`;if(!n||typeof n!="object")throw new c("VALIDATION",`Task log entry${t} must be an object`);if(typeof n.timestamp!="string"||typeof n.level!="string"||typeof n.message!="string")throw new c("VALIDATION",`Task log entry${t} must contain string timestamp, level, and message fields`);return {timestamp:n.timestamp,level:n.level,message:n.message}}function lo(n,e){if(e===null||e.trim()==="")return [];let t;try{t=JSON.parse(e);}catch(r){throw new c("DB_ERROR",`Malformed legacy task logs: ${n}`,r)}if(!Array.isArray(t))throw new c("DB_ERROR",`Malformed legacy task logs: ${n} (expected an array)`);try{return t.map((r,o)=>ho(r,o))}catch(r){throw r instanceof c?new c("DB_ERROR",`Malformed legacy task logs: ${n}`,r):r}}function go(n){if(n.log_storage!=="blob"&&n.log_storage!=="events")throw new c("DB_ERROR",`Invalid task log storage for task: ${n.id}`);if(!Number.isInteger(n.last_log_seq)||n.last_log_seq<0)throw new c("DB_ERROR",`Invalid task log sequence for task: ${n.id}`);if(!Number.isInteger(n.log_revision)||n.log_revision<0)throw new c("DB_ERROR",`Invalid task log revision for task: ${n.id}`);return n.log_storage}function uo(n){return {taskId:n.id,source:go(n),revision:n.log_revision,lastSeq:n.last_log_seq}}function oa(n){if(!Number.isInteger(n)||n<0)throw new c("VALIDATION","Task log tail limit must be a non-negative integer")}var Ot=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}findStateRow(e,t){return e.db.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,t)).limit(1).get()}findStateRowInTransaction(e,t){return e.select({id:a.id,log_storage:a.log_storage,last_log_seq:a.last_log_seq,log_revision:a.log_revision,logs:a.logs}).from(a).where(eq(a.id,t)).limit(1).get()}requireStateRowInTransaction(e,t){let r=this.findStateRowInTransaction(e,t);if(!r)throw new c("NOT_FOUND",`Task not found: ${t}`);return r}appendLog(e,t){return this.appendLogs(e,[t])}appendLogs(e,t){let r=t.map((s,i)=>ho(s,i));if(r.length===0){let s=this.getLogState(e);if(!s)throw new c("NOT_FOUND",`Task not found: ${e}`);return s}let o=this.openHandle(true);try{return o.db.transaction(i=>{let d=this.requireStateRowInTransaction(i,e),l=go(d);if(l==="blob"){let p=lo(e,d.logs);if(i.update(a).set({logs:JSON.stringify([...p,...r]),log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new c("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:d.log_revision+1,lastSeq:d.last_log_seq}}let u=d.last_log_seq+1,h=d.last_log_seq+r.length;if(i.insert(Ae).values(r.map((p,f)=>({task_id:e,seq:u+f,timestamp:p.timestamp,level:p.level,message:p.message}))).run(),i.update(a).set({last_log_seq:h,log_revision:sql`${a.log_revision} + 1`}).where(eq(a.id,e)).run().changes!==1)throw new c("NOT_FOUND",`Task not found: ${e}`);return {taskId:e,source:l,revision:d.log_revision+1,lastSeq:h}},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to append task log",s)}finally{o.close();}}getLogState(e){if(!this.dbExists())return;let t=this.openHandle(false);try{let r=this.findStateRow(t,e);return r?uo(r):void 0}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to read task log state",r)}finally{t.close();}}readLogs(e){return this.readLogsInternal(e)}readLogsTail(e,t){return oa(t),this.readLogsInternal(e,t)}readTail(e,t){return this.readLogsTail(e,t)}readLogsInternal(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.transaction(o=>{let s=this.findStateRowInTransaction(o,e);if(!s)return;let i=uo(s);if(i.source==="blob"){let h=lo(e,s.logs);return {...i,entries:t===void 0?h:h.slice(Math.max(0,h.length-t))}}let d=o.select({seq:Ae.seq,timestamp:Ae.timestamp,level:Ae.level,message:Ae.message}).from(Ae).where(eq(Ae.task_id,e)).orderBy(t===void 0?asc(Ae.seq):desc(Ae.seq)),u=(t===void 0?d.all():d.limit(t).all()).map(({timestamp:h,level:g,message:p})=>({timestamp:h,level:g,message:p}));return t!==void 0&&u.reverse(),{...i,entries:u}},{behavior:"deferred"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read task logs",o)}finally{r.close();}}};var $r=40,Ve="2026-05-09",la="0.8.9-rc.13",Ke=10,Je=parseInt(la.split("rc.")[1]);function po(){let n=sql`
|
|
13
13
|
CASE
|
|
14
14
|
WHEN ${a.model} LIKE 'claude-%' OR ${a.model} IN ('opus', 'sonnet', 'haiku', 'opus[1m]', 'sonnet[1m]') THEN 'claude'
|
|
15
15
|
WHEN ${a.model} LIKE 'gpt-%' OR ${a.model} LIKE 'codex-%' THEN 'codex'
|
|
@@ -38,14 +38,14 @@ ${r.join(`
|
|
|
38
38
|
WHEN trim(${o}) = '' THEN 'unknown'
|
|
39
39
|
ELSE ${o}
|
|
40
40
|
END
|
|
41
|
-
`}var ua=new Set(["workflow","mcp"]),jr="usageByEpoch";function qr(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function
|
|
41
|
+
`}var ua=new Set(["workflow","mcp"]),jr="usageByEpoch";function qr(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function _o(n){if(!n)return {};try{let e=JSON.parse(n);return qr(e)?{...e}:{}}catch{return {}}}function be(n){return typeof n=="number"&&Number.isFinite(n)?n:0}function fo(n){return typeof n=="number"&&Number.isFinite(n)?Math.trunc(n):0}function ha(n){return {inputTokens:be(n.inputTokens??0),outputTokens:be(n.outputTokens??0),cachedInputTokens:be(n.cachedInputTokens??0),costUsd:be(n.costUsd??0)}}function ga(n){if(qr(n))return {inputTokens:be(n.inputTokens),outputTokens:be(n.outputTokens),cachedInputTokens:be(n.cachedInputTokens),costUsd:be(n.costUsd)}}function pa(n){let e={inputTokens:0,outputTokens:0,cachedInputTokens:0,costUsd:0};for(let t of Object.values(n)){let r=ga(t);r&&(e.inputTokens+=r.inputTokens,e.outputTokens+=r.outputTokens,e.cachedInputTokens+=r.cachedInputTokens,e.costUsd+=r.costUsd);}return e}function _a(n,e,t){let r=Date.parse(n),o=Date.parse(e);return Number.isFinite(r)&&Number.isFinite(o)?o-r:t??null}var mo=600*1e3,Mr=class extends x{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 Ot({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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}startTask(e){let t=this.openHandle(true);try{let r={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(a).values(s).onConflictDoUpdate({target:a.id,set:{pid:sql`COALESCE(excluded.pid, ${a.pid})`},setWhere:eq(a.status,"running")}).run();};try{o(r);}catch(s){let i=s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s);if(!/log_storage/i.test(i)||!/no such column|no column named/i.test(i))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,
|
|
45
45
|
model, rendered_prompt, coding_agent_command
|
|
46
46
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
47
47
|
ON CONFLICT(id) DO UPDATE SET pid = COALESCE(excluded.pid, tasks.pid)
|
|
48
|
-
WHERE tasks.status = 'running'`,[r.id,r.agent_id,r.prompt,r.mode,r.status,r.started_at,r.pid,r.parent_task_id,r.caller_agent_id,r.trace_id,r.command,r.metadata,r.workspace_id,r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command]);}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to start task",r)}finally{t.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(a).where(eq(a.project_id,e)).orderBy(desc(a.started_at)).all()}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to list tasks by project",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{t.db.transaction(r=>{let o=r.select({status:a.status,run_epoch:a.run_epoch,started_at:a.started_at,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!o)return;let s=
|
|
48
|
+
WHERE tasks.status = 'running'`,[r.id,r.agent_id,r.prompt,r.mode,r.status,r.started_at,r.pid,r.parent_task_id,r.caller_agent_id,r.trace_id,r.command,r.metadata,r.workspace_id,r.project_id,r.platform,r.crewx_version,r.thread_id,r.model,r.rendered_prompt,r.coding_agent_command]);}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to start task",r)}finally{t.close();}}listTasksByProjectId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(a).where(eq(a.project_id,e)).orderBy(desc(a.started_at)).all()}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to list tasks by project",r)}finally{t.close();}}finishTask(e){let t=this.openHandle(true);try{t.db.transaction(r=>{let o=r.select({status:a.status,run_epoch:a.run_epoch,started_at:a.started_at,metadata:a.metadata}).from(a).where(eq(a.id,e.id)).limit(1).get();if(!o)return;let s=fo(o.run_epoch),i=fo(e.runEpoch),d=o.status==="running"&&s===i,l=s>0||i>0||e.runEpoch!==void 0&&e.runEpoch!==null||s!==i,u={},h;if(l){h=_o(o.metadata);let g=qr(h[jr])?{...h[jr]}:{};g[String(i)]=ha(e),h[jr]=g;let p=pa(g);u.metadata=JSON.stringify(h),u.input_tokens=p.inputTokens,u.output_tokens=p.outputTokens,u.cached_input_tokens=p.cachedInputTokens,u.cost_usd=p.costUsd;}else d&&(u.input_tokens=be(e.inputTokens??0),u.output_tokens=be(e.outputTokens??0),u.cached_input_tokens=be(e.cachedInputTokens??0),u.cost_usd=be(e.costUsd??0));d&&e.model!==void 0&&e.model!==null&&(u.model=e.model),e.partialResultRecovered===!0&&d&&(h??=_o(o.metadata),h.partialResultRecovered=!0,u.metadata=JSON.stringify(h)),d&&(u.status=e.status,u.result=e.result??null,u.error=e.error??null,u.completed_at=e.completedAt,u.duration_ms=s>0?_a(o.started_at,e.completedAt,e.durationMs):e.durationMs??null,u.exit_code=e.exitCode??null),Object.keys(u).length>0&&r.update(a).set(u).where(eq(a.id,e.id)).run();},{behavior:"immediate"});}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to finish task",r)}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(a).where(eq(a.status,"running")).orderBy(desc(a.started_at)).all()}catch(t){throw new c("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(a).orderBy(desc(a.started_at)).limit(100).all()}catch(t){throw new c("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(a).where(eq(a.id,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to get task",r)}finally{t.close();}}killTask(e){if(!this.dbExists())return {killed:false};let t=this.openHandle(true);try{let r=t.db.select({id:a.id,status:a.status,pid:a.pid}).from(a).where(eq(a.id,e)).limit(1).get();if(!r||r.status!=="running")return {killed:!1};if(r.pid)try{process.kill(r.pid,"SIGTERM");}catch{}return t.db.update(a).set({status:"failed",error:"Killed by user",completed_at:new Date().toISOString()}).where(and(eq(a.id,e),eq(a.status,"running"))).run(),{killed:!0,pid:r.pid??void 0}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to kill task",r)}finally{t.close();}}reapOrphanedTasks(){if(!this.dbExists())return 0;let e=this.openHandle(true);try{let t=e.db.select({id:a.id,pid:a.pid,platform:a.platform,run_epoch:a.run_epoch}).from(a).where(eq(a.status,"running")).all(),r=Date.now(),o=new Set,s=0;for(let i of t){if(i.pid){let u=!1;try{process.kill(i.pid,0),u=!0;}catch{}u||(e.db.update(a).set({status:"failed",error:"Reaped: process not found (orphaned task)",completed_at:new Date().toISOString()}).where(and(eq(a.id,i.id),eq(a.status,"running"))).run(),s++);continue}if(ua.has(i.platform??"cli"))continue;let d=`${i.id}:${i.run_epoch??0}`;o.add(d);let l=this.pidNullObservedSince.get(d);if(l===void 0){this.pidNullObservedSince.set(d,r);continue}r-l>=mo&&(e.db.update(a).set({status:"failed",error:"Reaped: pid never recorded after resume (stale running_instruction)",completed_at:new Date().toISOString()}).where(and(eq(a.id,i.id),eq(a.status,"running"))).run(),s++,this.pidNullObservedSince.delete(d));}for(let i of Array.from(this.pidNullObservedSince.keys()))o.has(i)||this.pidNullObservedSince.delete(i);return s}finally{e.close();}}reapRunningWorkflowTasks(e=mo){if(!this.dbExists())return 0;let t=this.openHandle(true);try{let r=new Date(Date.now()-e).toISOString();return t.db.update(a).set({status:"failed",error:"Reaped: stale workflow run (finally not executed)",completed_at:new Date().toISOString()}).where(and(eq(a.status,"running"),eq(a.platform,"workflow"),isNull(a.pid),lt$1(a.started_at,r),or(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))))).run().changes??0}finally{t.close();}}findTaskStatus(e,t){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=y(o);try{let i=t?eq(a.workspace_id,t):void 0,d=i?and(eq(a.id,e),i):eq(a.id,e),l=s.db.select().from(a).where(d).limit(1).get()??void 0;if(!l){let u=i?and(eq(a.thread_id,e),i):eq(a.thread_id,e);l=s.db.select().from(a).where(u).orderBy(desc(a.started_at)).limit(1).get()??void 0;}if(l)return l}catch(i){throw new c("DB_ERROR","Failed to find task status",i)}finally{s.close();}}}findChildTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let d=y(i);try{let l=t?and(eq(a.parent_task_id,e),eq(a.workspace_id,t)):eq(a.parent_task_id,e),u=d.db.select().from(a).where(l).orderBy(asc(a.started_at)).all();for(let h of u)o.has(h.id)||(o.add(h.id),s.push(h));}catch(l){throw new c("DB_ERROR","Failed to find child tasks",l)}finally{d.close();}}return s}getWorkspaceUsageSummary(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.all(e?sql`
|
|
49
49
|
SELECT
|
|
50
50
|
COALESCE(workspace_id, 'unknown') AS workspace_id,
|
|
51
51
|
COALESCE(SUM(input_tokens), 0) AS input_tokens,
|
|
@@ -66,7 +66,7 @@ ${r.join(`
|
|
|
66
66
|
FROM tasks
|
|
67
67
|
GROUP BY workspace_id
|
|
68
68
|
ORDER BY (COALESCE(SUM(input_tokens), 0) + COALESCE(SUM(output_tokens), 0)) DESC
|
|
69
|
-
`)}catch(r){throw new c("DB_ERROR","Failed to get workspace usage summary",r)}finally{t.close();}}getThreadTokenUsage(e,t){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,d=0;for(let l of r){if(!existsSync(l))continue;let u=
|
|
69
|
+
`)}catch(r){throw new c("DB_ERROR","Failed to get workspace usage summary",r)}finally{t.close();}}getThreadTokenUsage(e,t){let r=this.resolveDbPaths(),o=new Set,s=0,i=0,d=0;for(let l of r){if(!existsSync(l))continue;let u=y(l);try{let h=eq(a.thread_id,e),g=t?and(h,eq(a.workspace_id,t)):h,p=u.db.select({id:a.id,input_tokens:a.input_tokens,output_tokens:a.output_tokens,cost_usd:a.cost_usd}).from(a).where(g).all();for(let f of p)o.has(f.id)||(o.add(f.id),s+=f.input_tokens??0,i+=f.output_tokens??0,d+=f.cost_usd??0);}catch(h){throw new c("DB_ERROR","Failed to get thread token usage",h)}finally{u.close();}}return {inputTokens:s,outputTokens:i,costUsd:d}}findTasksByThread(e,t,r){let o=this.resolveDbPaths(),s=new Set,i=[],d=r?.projection==="activity-log";for(let l of o){if(!existsSync(l))continue;let u=y(l);try{let h=eq(a.thread_id,e),g=t?and(h,eq(a.workspace_id,t)):h,p=d?u.db.select({id:a.id,thread_id:a.thread_id,agent_id:a.agent_id,parent_task_id:a.parent_task_id,started_at:a.started_at,completed_at:a.completed_at}).from(a).where(g).orderBy(asc(a.started_at)).all():u.db.select().from(a).where(g).orderBy(asc(a.started_at)).all();for(let f of p)s.has(f.id)||(s.add(f.id),i.push(f));}catch(h){throw new c("DB_ERROR","Failed to find tasks by thread",h)}finally{u.close();}}return i}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 r=y(t);try{e.push(...r.db.select({id:a.id,agent_id:a.agent_id,thread_id:a.thread_id,workspace_id:a.workspace_id,platform:a.platform,status:a.status,error:a.error,completed_at:a.completed_at,duration_ms:a.duration_ms,started_at:a.started_at,metadata:a.metadata}).from(a).where(and(eq(a.platform,"workflow"),or(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%')))).orderBy(desc(a.started_at)).all());}catch(o){throw new c("DB_ERROR","Failed to find workflow parent tasks",o)}finally{r.close();}}return e}batchFetchWorkflowCards(e,t){let r=new Map;if(e.length===0)return r;let o=new Set(e),s=new Map,i=t?eq(a.workspace_id,t):void 0,d=(l,u)=>{if(!l)return;let h=s.get(l);if(h&&u.started_at<=h)return;let g=this.parseWorkflowCardMetadata(u.metadata);g.kind!=="workflow_card"&&g.kind!=="workflow_ui_instance"||(s.set(l,u.started_at),r.set(l,{taskId:u.id,workflowRunId:g.workflowRunId,raw:u.result??void 0}));};for(let l of this.resolveDbPaths()){if(!existsSync(l))continue;let u=y(l);try{let h=and(inArray(a.thread_id,e),or(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%'))),g=u.db.select({id:a.id,thread_id:a.thread_id,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(h,i):h).all();for(let D of g)d(D.thread_id,D);let p=and(isNull(a.thread_id),or(like(a.metadata,'%"kind":"workflow_card"%'),like(a.metadata,'%"kind":"workflow_ui_instance"%'))),f=u.db.select({id:a.id,command:a.command,metadata:a.metadata,result:a.result,started_at:a.started_at}).from(a).where(i?and(p,i):p).all();for(let D of f){let w=this.extractThreadIdFromCommand(D.command);!w||!o.has(w)||d(w,D);}}catch(h){throw new c("DB_ERROR","Failed to batch fetch workflow cards",h)}finally{u.close();}}return r}findAllTasks(e){if(!this.dbExists())return {rows:[],total:0};let t=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(a.workspace_id,e.workspaceId));let o=e.agents&&e.agents.length>0?e.agents:e.agentId?[e.agentId]:null;o&&r.push(inArray(a.agent_id,o));let s=e.statuses&&e.statuses.length>0?e.statuses:e.status?[e.status]:null;s&&r.push(inArray(a.status,s));let i=e.q??e.search;i&&r.push(like(a.prompt,`%${i}%`)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt$1(a.started_at,e.to));let d=r.length>0?and(...r):void 0,l=t.db.select({count:sql`count(*)`}).from(a).where(d).get(),u=(e.sortDir??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at);return {rows:t.db.select().from(a).where(d).orderBy(u).limit(e.limit).offset(e.offset).all(),total:l?.count??0}}catch(r){throw new c("DB_ERROR","Failed to find all tasks",r)}finally{t.close();}}getAgentUsage(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.all(r?sql`
|
|
70
70
|
SELECT
|
|
71
71
|
t.agent_id,
|
|
72
72
|
t.workspace_id,
|
|
@@ -204,7 +204,7 @@ ${r.join(`
|
|
|
204
204
|
AND t.started_at < ${t}
|
|
205
205
|
GROUP BY date(t.started_at), t.agent_id
|
|
206
206
|
ORDER BY date(t.started_at) ASC
|
|
207
|
-
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new c("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(a).where(and(eq(a.id,e),eq(a.workspace_id,t))).limit(1).get()??void 0}catch(o){throw new c("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let t=this.openHandle(false);try{return t.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(and(eq(a.agent_id,e.agentId),eq(a.workspace_id,e.workspaceId),sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(a.started_at)).limit(1).get()??null}catch(r){throw new c("DB_ERROR","Failed to find latest task by metadata",r)}finally{t.close();}}markTaskFailed(e,t,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString(),i=r?and(eq(a.id,e),eq(a.status,"running"),eq(a.workspace_id,r)):and(eq(a.id,e),eq(a.status,"running"));o.db.update(a).set({status:"failed",error:t,completed_at:s}).where(i).run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to mark task failed",s)}finally{o.close();}}findTasksByPromptHint(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let d=
|
|
207
|
+
`).map(i=>({date:i.date,agentId:i.agent_id,inputTokens:i.input_tokens,outputTokens:i.output_tokens,cachedInputTokens:i.cached_input_tokens,costUsd:i.cost_usd,totalTokens:i.input_tokens+i.output_tokens}))}catch(s){throw new c("DB_ERROR","Failed to get agent usage trend",s)}finally{o.close();}}findTaskForStop(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(a).where(and(eq(a.id,e),eq(a.workspace_id,t))).limit(1).get()??void 0}catch(o){throw new c("DB_ERROR","Failed to find task for stop",o)}finally{r.close();}}findLatestTaskByMetadata(e){if(!this.dbExists())return null;let t=this.openHandle(false);try{return t.db.select({id:a.id,thread_id:a.thread_id,status:a.status,result:a.result,error:a.error,started_at:a.started_at,completed_at:a.completed_at,metadata:a.metadata}).from(a).where(and(eq(a.agent_id,e.agentId),eq(a.workspace_id,e.workspaceId),sql`${a.metadata} IS NOT NULL AND json_valid(${a.metadata}) AND json_extract(${a.metadata}, '$.' || ${e.metaKey}) = ${e.metaValue}`)).orderBy(desc(a.started_at)).limit(1).get()??null}catch(r){throw new c("DB_ERROR","Failed to find latest task by metadata",r)}finally{t.close();}}markTaskFailed(e,t,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString(),i=r?and(eq(a.id,e),eq(a.status,"running"),eq(a.workspace_id,r)):and(eq(a.id,e),eq(a.status,"running"));o.db.update(a).set({status:"failed",error:t,completed_at:s}).where(i).run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to mark task failed",s)}finally{o.close();}}findTasksByPromptHint(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let d=y(i);try{let l=t?and(like(a.prompt,`%${e}%`),eq(a.workspace_id,t)):like(a.prompt,`%${e}%`),u=d.db.select().from(a).where(l).orderBy(asc(a.started_at)).all();for(let h of u)o.has(h.id)||(o.add(h.id),s.push(h));}catch(l){throw new c("DB_ERROR","Failed to find tasks by prompt hint",l)}finally{d.close();}}return s}getProviderUsage(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=po(),i=sql`
|
|
208
208
|
COALESCE(${a.input_tokens}, 0)
|
|
209
209
|
+ CASE
|
|
210
210
|
WHEN ${a.started_at} >= ${Ve}
|
|
@@ -230,7 +230,7 @@ ${r.join(`
|
|
|
230
230
|
${d}
|
|
231
231
|
GROUP BY ${s}
|
|
232
232
|
ORDER BY (COALESCE(SUM(${i}), 0) + COALESCE(SUM(${a.output_tokens}), 0)) DESC
|
|
233
|
-
`).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 c("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=
|
|
233
|
+
`).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 c("DB_ERROR","Failed to get provider usage",s)}finally{o.close();}}getModelUsage(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=po(),i=sql`
|
|
234
234
|
COALESCE(${a.input_tokens}, 0)
|
|
235
235
|
+ CASE
|
|
236
236
|
WHEN ${a.started_at} >= ${Ve}
|
|
@@ -256,7 +256,7 @@ ${r.join(`
|
|
|
256
256
|
FROM ${a}
|
|
257
257
|
${d}
|
|
258
258
|
GROUP BY ${a.model}, ${s}
|
|
259
|
-
`),u=new Map;for(let h of l){let g=
|
|
259
|
+
`),u=new Map;for(let h of l){let g=io(h.model??""),p=JSON.stringify([h.provider,g]),f=u.get(p);f?(f.totalTasks+=h.total_tasks,f.inputTokens+=h.input_tokens,f.outputTokens+=h.output_tokens,f.cachedInputTokens+=h.cached_input_tokens,f.costUsd+=h.cost_usd,f.totalTokens+=h.input_tokens+h.output_tokens,f.activeDurationMs+=h.active_duration_ms??0,h.last_active_at&&(!f.lastActiveAt||h.last_active_at>f.lastActiveAt)&&(f.lastActiveAt=h.last_active_at)):u.set(p,{model:g,provider:h.provider,totalTasks:h.total_tasks,inputTokens:h.input_tokens,outputTokens:h.output_tokens,cachedInputTokens:h.cached_input_tokens,costUsd:h.cost_usd,totalTokens:h.input_tokens+h.output_tokens,activeDurationMs:h.active_duration_ms??0,lastActiveAt:h.last_active_at??null});}return Array.from(u.values()).sort((h,g)=>g.costUsd-h.costUsd)}catch(s){throw new c("DB_ERROR","Failed to get model usage",s)}finally{o.close();}}getTasksForReport(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{let s=r?sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${t} AND ${a.workspace_id} = ${r}`:sql`WHERE ${a.started_at} >= ${e} AND ${a.started_at} < ${t}`;return o.db.all(sql`
|
|
260
260
|
SELECT
|
|
261
261
|
${a.thread_id} AS thread_id,
|
|
262
262
|
${a.agent_id} AS agent_id,
|
|
@@ -291,26 +291,26 @@ ${r.join(`
|
|
|
291
291
|
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
292
292
|
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
293
293
|
LIMIT ${$r+1}
|
|
294
|
-
`),l=d.length>$r;return {edges:d.slice(0,$r).map(h=>({callerAgentId:h.caller_agent_id??null,agentId:h.agent_id,taskCount:h.task_count,totalTokens:h.input_tokens+h.output_tokens,outputTokens:h.output_tokens})),truncated:l}}catch(s){throw new c("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(a.status,e.statuses)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt$1(a.started_at,e.to));let o=r.length>0?and(...r):void 0,s=(e.order??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at),i={id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id};return e.limit?t.db.select(i).from(a).where(o).orderBy(s).limit(e.limit).all():t.db.select(i).from(a).where(o).orderBy(s).all()}catch(r){throw new c("DB_ERROR","Failed to find task evidence",r)}finally{t.close();}}findThreadChains(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[isNotNull(a.thread_id),isNull(a.parent_task_id),isNull(a.caller_agent_id),or(isNull(a.platform),ne(a.platform,"workflow")),or(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(a.metadata),notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(a.workspace_id,e.workspaceId)),e.from&&s.push(gte(a.started_at,e.from)),e.to&&s.push(lt$1(a.started_at,e.to));let i=t.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(and(...s)).orderBy(asc(a.started_at),asc(a.id)).all(),d=new Map;for(let u of i){if(!u.thread_id)continue;let h={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},g=d.get(u.thread_id);g?g.push(h):d.set(u.thread_id,[h]);}let l=[];for(let[u,h]of d){let g=h.filter(p=>p.agentId===e.targetAgentId).length;g<2||l.push({threadId:u,targetAgentTurnCount:g,turns:h});}return l.sort((u,h)=>{let g=u.turns[u.turns.length-1].startedAt,p=h.turns[h.turns.length-1].startedAt;return g<p?1:g>p?-1:0}),l.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new c("DB_ERROR","Failed to find thread chains",r)}finally{t.close();}}};var
|
|
294
|
+
`),l=d.length>$r;return {edges:d.slice(0,$r).map(h=>({callerAgentId:h.caller_agent_id??null,agentId:h.agent_id,taskCount:h.task_count,totalTokens:h.input_tokens+h.output_tokens,outputTokens:h.output_tokens})),truncated:l}}catch(s){throw new c("DB_ERROR","Failed to get delegation matrix",s)}finally{o.close();}}findTaskEvidence(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=[];e.workspaceId&&r.push(eq(a.workspace_id,e.workspaceId)),e.agents&&e.agents.length>0&&r.push(inArray(a.agent_id,e.agents)),e.statuses&&e.statuses.length>0&&r.push(inArray(a.status,e.statuses)),e.from&&r.push(gte(a.started_at,e.from)),e.to&&r.push(lt$1(a.started_at,e.to));let o=r.length>0?and(...r):void 0,s=(e.order??"DESC")==="ASC"?asc(a.started_at):desc(a.started_at),i={id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id};return e.limit?t.db.select(i).from(a).where(o).orderBy(s).limit(e.limit).all():t.db.select(i).from(a).where(o).orderBy(s).all()}catch(r){throw new c("DB_ERROR","Failed to find task evidence",r)}finally{t.close();}}findThreadChains(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=e.maxThreads??8,o=e.maxTurnsPerThread??4,s=[isNotNull(a.thread_id),isNull(a.parent_task_id),isNull(a.caller_agent_id),or(isNull(a.platform),ne(a.platform,"workflow")),or(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))),or(isNull(a.metadata),notLike(a.metadata,'%"retriedFromTaskId"%'))];e.workspaceId&&s.push(eq(a.workspace_id,e.workspaceId)),e.from&&s.push(gte(a.started_at,e.from)),e.to&&s.push(lt$1(a.started_at,e.to));let i=t.db.select({id:a.id,agent_id:a.agent_id,status:a.status,prompt:a.prompt,started_at:a.started_at,completed_at:a.completed_at,thread_id:a.thread_id}).from(a).where(and(...s)).orderBy(asc(a.started_at),asc(a.id)).all(),d=new Map;for(let u of i){if(!u.thread_id)continue;let h={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},g=d.get(u.thread_id);g?g.push(h):d.set(u.thread_id,[h]);}let l=[];for(let[u,h]of d){let g=h.filter(p=>p.agentId===e.targetAgentId).length;g<2||l.push({threadId:u,targetAgentTurnCount:g,turns:h});}return l.sort((u,h)=>{let g=u.turns[u.turns.length-1].startedAt,p=h.turns[h.turns.length-1].startedAt;return g<p?1:g>p?-1:0}),l.slice(0,r).map(u=>({threadId:u.threadId,targetAgentTurnCount:u.targetAgentTurnCount,turns:u.turns.slice(-o)}))}catch(r){throw new c("DB_ERROR","Failed to find thread chains",r)}finally{t.close();}}};var yo=["success","failed","completed"],cr=10*1024*1024*1024,Ro=256,Ea=new Set(yo),se=class extends Error{constructor(t,r,o="metadata"){super(r);this.taskId=t;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function Eo(n){return n||(process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(homedir(),".crewx","crewx.db"))}function ba(){return ot("better-sqlite3")}function bo(n,e){let t=n===":memory:";if(!t&&!existsSync(n))throw new Error(`Database not found: ${n}`);let r=new(ba())(n,{readonly:e,fileMustExist:!t,timeout:5e3});return r.pragma("foreign_keys = ON"),r.pragma("busy_timeout = 5000"),r}function Tt(n,e,t=[]){return n.prepare(e).all(...t)}function kt(n,e,t=[]){return n.prepare(e).get(...t)}function Ia(n,e,t=[]){return n.prepare(e).run(...t)}function Sa(n,e,t=[]){return n.prepare(e).iterate(...t)}function va(n){return typeof n=="string"&&n.length>0?n:"<unknown>"}function Io(n){return typeof n=="string"&&Ea.has(n)}function wo(n,e){n.set(e,(n.get(e)??0)+1);}function ko(n){return Object.fromEntries([...n.entries()].sort(([e],[t])=>e.localeCompare(t)))}function Ca(n){let e=new Set(Tt(n,"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('tasks', 'task_log_events')").map(i=>i.name)),t=["tasks","task_log_events"].filter(i=>!e.has(i));if(t.length>0)throw new Error(`Database schema is missing required table(s): ${t.join(", ")}`);let r=new Set(Tt(n,"PRAGMA table_info('tasks')").map(i=>i.name)),s=["id","status","logs","log_storage","last_log_seq","log_revision"].filter(i=>!r.has(i));if(s.length>0)throw new Error(`Database schema is missing required tasks column(s): ${s.join(", ")}`)}function So(n,e){if(e==null)return {entries:[]};if(typeof e!="string")throw new se(n,"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 se(n,`Malformed JSON in tasks.logs (${s})`,"malformed")}if(!Array.isArray(t))throw new se(n,"Malformed task logs: expected a JSON array","malformed");let r=[];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 se(n,`Malformed task logs: entry ${o} must contain string timestamp, level, and message fields`,"malformed");let i=s;r.push({timestamp:i.timestamp,level:i.level,message:i.message});}return {entries:r}}function Ur(n,e){if(!Number.isInteger(n.last_log_seq)||n.last_log_seq<0)throw new se(n.id,"Invalid last_log_seq metadata","metadata");if(!Number.isInteger(n.log_revision)||n.log_revision<0)throw new se(n.id,"Invalid log_revision metadata","metadata");if(e==="blob"&&n.last_log_seq!==0)throw new se(n.id,"Blob source must have last_log_seq=0","metadata")}function Da(n){let e=Tt(n,`SELECT task_id, COUNT(*) AS event_count
|
|
295
295
|
FROM task_log_events GROUP BY task_id`);return new Map(e.map(t=>[t.task_id,t.event_count]))}function Na(n){let e=Da(n),t=new Map,r=[],o=[],s=[],i=new Map,d=new Map,l=0,u=0,h=0,g=0,p=0,f=0;for(let D of Sa(n,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
296
|
-
FROM tasks ORDER BY id`)){let w=D,S=va(w.status);if(
|
|
297
|
-
FROM tasks WHERE id = ?`,[e]);if(!r)throw new se(e,"Task disappeared before migration","metadata");if(r.log_storage==="events")return {status:"skipped",entryCount:0,sourceBytes:0};if(r.log_storage!=="blob")throw new se(e,`Unknown log_storage value: ${r.log_storage}`,"invalid-source");if(!
|
|
296
|
+
FROM tasks ORDER BY id`)){let w=D,S=va(w.status);if(wo(i,S),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}),l+=1,w.log_storage==="events"){g+=1;try{Ur(w,"events");}catch(le){s.push(zr(le,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}u+=1;let E=Io(w.status);E||(h+=1,wo(d,S)),typeof w.logs=="string"?f+=Buffer.byteLength(w.logs,"utf8"):Buffer.isBuffer(w.logs)&&(f+=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 Me;try{Me=So(w.id,w.logs),p+=Me.entries.length,Ur(w,"blob");}catch(le){let ke=zr(le,w.id);s.push(ke),ke.kind==="malformed"&&o.push(ke);continue}K>0||E&&r.push(w.id);}return {taskCount:l,candidateTaskCount:u,eligibleTaskCount:r.length,eventSourceTasks:g,statusCounts:ko(i),deferredTaskCount:h,deferredStatusCounts:ko(d),entryCount:p,sourceBytes:f,candidateIds:r,malformedRows:o,failures:s,tasks:t}}function zr(n,e){return n instanceof se?{taskId:n.taskId,reason:n.message,kind:n.kind}:{taskId:e,reason:n instanceof Error?n.message:String(n),kind:"metadata"}}function Oa(n){return kt(n,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function Aa(n){return kt(n,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function xa(n){if(n===":memory:")return 0;let e=t=>{try{return statSync(t).size}catch{return 0}};return e(n)+e(`${n}-wal`)}function La(n,e){return xa(n)+e*Ro}function vo(n,e){return Number.isFinite(n)&&Number.isFinite(e)&&n>=e+cr}function To(n){let e=dirname(resolve(n));for(;!existsSync(e);){let t=dirname(e);if(t===e)break;e=t;}return e}function Co(n,e,t){let r=[...new Set([To(n),...t?[To(t)]:[]])],o=[],s=Number.POSITIVE_INFINITY;for(let l of r)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 i=La(n,e),d=i+cr;return {estimatedFreeSpaceBytes:i,requiredFreeSpaceBytes:d,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:cr,freeSpaceGatePassed:vo(Number.isFinite(s)?Math.floor(s):0,i),warnings:o}}function Do(n){return new Set(n.map(e=>e.taskId)).size}function No(n){try{let e=n.pragma("wal_checkpoint(TRUNCATE)"),t=Array.isArray(e)?e[0]:e,r=t!==null&&typeof t=="object"&&"busy"in t?Number(t.busy):0;return r>0?`WAL checkpoint(TRUNCATE) busy (${r}); 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 ar(n,e,t,r,o=Co(e,t.entryCount)){let s=r.failures??t.failures,i=r.malformedRows??t.malformedRows,{ok:d,...l}=r;return {mode:n,ok:d,dbPath:e,activeTaskCount:r.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:r.migratedTasks??0,migratedEntries:r.migratedEntries??0,skippedTasks:r.skippedTasks??t.eventSourceTasks,failedTasks:r.failedTasks??Do(s),malformedRows:i,failures:s,logicalSourceBytesRemoved:r.logicalSourceBytesRemoved??0,warnings:r.warnings??o.warnings,remainingTaskCount:r.remainingTaskCount??t.candidateTaskCount,...l}}function Pa(n,e){return n.length!==e.length?false:n.every((t,r)=>{let o=e[r];return t.seq===r+1&&t.timestamp===o.timestamp&&t.level===o.level&&t.message===o.message})}function Ha(n,e){return n.transaction(()=>{let r=kt(n,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
297
|
+
FROM tasks WHERE id = ?`,[e]);if(!r)throw new se(e,"Task disappeared before migration","metadata");if(r.log_storage==="events")return {status:"skipped",entryCount:0,sourceBytes:0};if(r.log_storage!=="blob")throw new se(e,`Unknown log_storage value: ${r.log_storage}`,"invalid-source");if(!Io(r.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=r.logs,s=So(e,o);Ur(r,"blob");let i=kt(n,"SELECT COUNT(*) AS count FROM task_log_events WHERE task_id = ?",[e])?.count??0;if(i!==0)throw new se(e,`Blob source already has ${i} task_log_events row(s)`,"mixed-source");let d=n.prepare(`INSERT INTO task_log_events (task_id, seq, timestamp, level, message)
|
|
298
298
|
VALUES (?, ?, ?, ?, ?)`);for(let[g,p]of s.entries.entries())d.run(e,g+1,p.timestamp,p.level,p.message);let l=Tt(n,`SELECT seq, timestamp, level, message
|
|
299
299
|
FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!Pa(l,s.entries))throw new se(e,"Event parity check failed before source clear","metadata");if(Ia(n,`UPDATE tasks
|
|
300
300
|
SET log_storage = 'events', last_log_seq = ?, log_revision = log_revision + 1, logs = NULL
|
|
301
301
|
WHERE id = ? AND log_storage = 'blob' AND logs IS ?`,[s.entries.length,e,o]).changes!==1)throw new se(e,"Task changed while migration was in progress","metadata");let h=kt(n,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
302
|
-
FROM tasks WHERE id = ?`,[e]);if(!h||h.log_storage!=="events"||h.logs!==null||h.last_log_seq!==s.entries.length||h.log_revision!==r.log_revision+1)throw new se(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
|
|
302
|
+
FROM tasks WHERE id = ?`,[e]);if(!h||h.log_storage!=="events"||h.logs!==null||h.last_log_seq!==s.entries.length||h.log_revision!==r.log_revision+1)throw new se(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 Oo(n){let e=new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14),t=randomBytes(6).toString("hex");return `${n}.task-log-backup-${e}-${t}.sqlite`}async function $a(n,e,t){let r=t??Oo(e);if(resolve(r)===resolve(e))throw new Error("Backup path must be different from the source database");if(existsSync(r))throw new Error(`Refusing to overwrite existing backup: ${r}`);if(mkdirSync(dirname(r),{recursive:true}),await n.backup(r),!existsSync(r))throw new Error(`SQLite backup was not created: ${r}`);let o=bo(r,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 r}function ja(n){let e=Tt(n,`SELECT task_id AS taskId,
|
|
303
303
|
COUNT(*) AS eventCount,
|
|
304
304
|
COUNT(DISTINCT seq) AS distinctSeqCount,
|
|
305
305
|
MIN(seq) AS minSeq,
|
|
306
306
|
MAX(seq) AS maxSeq
|
|
307
307
|
FROM task_log_events GROUP BY task_id`),t=e.reduce((r,o)=>r+o.eventCount,0);return {rows:e,eventCount:t}}function Ye(n,e,t,r={}){return {taskId:n,kind:e,reason:t,...r}}function Ma(n,e,t){let r=[];for(let g of t.failures)g.kind==="malformed"?r.push(Ye(g.taskId,"malformed-blob",g.reason)):g.kind==="mixed-source"?r.push(Ye(g.taskId,"mixed-source",g.reason)):r.push(Ye(g.taskId,"source-invariant",g.reason));let o=ja(n),s=new Map(o.rows.map(g=>[g.taskId,g]));for(let g of o.rows){let p=t.tasks.get(g.taskId);if(!p){r.push(Ye(null,"orphan-event",`Event rows reference missing task ${g.taskId}`,{actual:g.eventCount}));continue}(g.minSeq===null||g.minSeq<1||g.distinctSeqCount!==g.maxSeq)&&r.push(Ye(p.id,"seq-gap","Task event sequence has a gap or invalid starting sequence",{expected:g.maxSeq??0,actual:g.distinctSeqCount})),p.log_storage==="events"&&p.last_log_seq!==g.eventCount&&r.push(Ye(p.id,"count-mismatch","last_log_seq does not match task_log_events row count",{expected:p.last_log_seq??0,actual:g.eventCount}));}for(let g of t.tasks.values())g.log_storage==="events"&&!s.has(g.id)&&g.last_log_seq!==0&&r.push(Ye(g.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:g.last_log_seq??0,actual:0}));for(let g of Tt(n,`SELECT task_id AS taskId, seq, COUNT(*) AS duplicateCount
|
|
308
308
|
FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))r.push(Ye(g.taskId,"duplicate-seq",`Duplicate task event sequence ${g.seq}`,{actual:g.duplicateCount,seq:g.seq}));let i=kt(n,`SELECT COUNT(*) AS count FROM task_log_events
|
|
309
|
-
WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;i>0&&r.push(Ye(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:i}));let d=new Set(r.flatMap(g=>g.taskId?[g.taskId]:[])),l=r.map(g=>({taskId:g.taskId??"(orphan)",reason:g.reason,kind:g.kind==="malformed-blob"?"malformed":g.kind==="mixed-source"?"mixed-source":"metadata"})),u=l.filter(g=>g.kind==="malformed"),h={checkedTasks:t.taskCount,eventSourceTasks:t.eventSourceTasks,blobSourceTasks:t.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:r.filter(g=>g.kind==="orphan-event").length,failedTasks:d.size,issues:r};return ar("verify",e,t,{ok:r.length===0,migratedTasks:t.eventSourceTasks,migratedEntries:o.eventCount,skippedTasks:t.candidateTaskCount,failedTasks:d.size,malformedRows:u,failures:l,remainingTaskCount:t.candidateTaskCount,verification:h})}function qa(n){if(n.mode!=="apply"&&n.batchTasks!==void 0)throw new Error("--batch-tasks is only valid with --apply");if(n.batchTasks!==void 0&&(!Number.isInteger(n.batchTasks)||n.batchTasks<1))throw new Error("--batch-tasks must be a positive integer")}async function Ba(n){qa(n);let e=
|
|
309
|
+
WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;i>0&&r.push(Ye(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:i}));let d=new Set(r.flatMap(g=>g.taskId?[g.taskId]:[])),l=r.map(g=>({taskId:g.taskId??"(orphan)",reason:g.reason,kind:g.kind==="malformed-blob"?"malformed":g.kind==="mixed-source"?"mixed-source":"metadata"})),u=l.filter(g=>g.kind==="malformed"),h={checkedTasks:t.taskCount,eventSourceTasks:t.eventSourceTasks,blobSourceTasks:t.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:r.filter(g=>g.kind==="orphan-event").length,failedTasks:d.size,issues:r};return ar("verify",e,t,{ok:r.length===0,migratedTasks:t.eventSourceTasks,migratedEntries:o.eventCount,skippedTasks:t.candidateTaskCount,failedTasks:d.size,malformedRows:u,failures:l,remainingTaskCount:t.candidateTaskCount,verification:h})}function qa(n){if(n.mode!=="apply"&&n.batchTasks!==void 0)throw new Error("--batch-tasks is only valid with --apply");if(n.batchTasks!==void 0&&(!Number.isInteger(n.batchTasks)||n.batchTasks<1))throw new Error("--batch-tasks must be a positive integer")}async function Ba(n){qa(n);let e=Eo(n.dbPath),t=bo(e,n.mode!=="apply");try{Ca(t);let r=Na(t),o=Oa(t);if(n.mode==="verify")return {...Ma(t,e,r),activeTaskCount:o};if(n.mode==="dry-run")return ar("dry-run",e,r,{ok:r.failures.length===0,activeTaskCount:o,skippedTasks:r.eventSourceTasks,remainingTaskCount:r.candidateTaskCount});let s=n.backupPath??Oo(e),i=Co(e,r.entryCount,s);if(!i.freeSpaceGatePassed)return ar("apply",e,r,{ok:!1,activeTaskCount:o,blockedReason:`Apply blocked: available free space (${i.availableFreeSpaceBytes} bytes) is below the required ${i.requiredFreeSpaceBytes} bytes (including a ${i.minimumFreeSpaceReserveBytes} byte reserve)`,skippedTasks:r.eventSourceTasks,remainingTaskCount:r.candidateTaskCount},i);let d=await $a(t,e,s),l=[...r.failures],u=n.batchTasks===void 0?r.candidateIds:r.candidateIds.slice(0,n.batchTasks),h=n.batchTasks??Math.max(u.length,1),g=0,p=0,f=0,D=[...i.warnings];for(let[w,S]of u.entries()){try{let E=Ha(t,S);E.status==="migrated"&&(g+=1,p+=E.entryCount,f+=E.sourceBytes);}catch(E){l.push(zr(E,S));}if((w+1)%h===0||w===u.length-1){let E=No(t);E&&D.push(E);}}return ar("apply",e,r,{ok:l.length===0,activeTaskCount:o,backupPath:d,backupMethod:"sqlite-online-backup",migratedTasks:g,migratedEntries:p,logicalSourceBytesRemoved:f,failedTasks:Do(l),failures:l,malformedRows:r.malformedRows,remainingTaskCount:Aa(t),skippedTasks:r.eventSourceTasks,warnings:D},i)}finally{t.close();}}function Fa(n){return basename(n)}var ct=class extends c{reason;constructor(e,t=e){super("VALIDATION",t),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function Lt(n){if(!n)return {};try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Va(n){let t=Lt(n).threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {priority:null,state:null};let r=t;return {priority:typeof r.priority=="string"?r.priority:null,state:typeof r.state=="string"?r.state:null}}var Gr=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,t){return e.db.select({id:k.id}).from(k).where(eq(k.id,t)).limit(1).get()?t:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
310
310
|
SELECT 1 FROM tasks parent
|
|
311
311
|
WHERE parent.id = ${e}.parent_task_id
|
|
312
312
|
AND parent.thread_id = ${e}.thread_id
|
|
313
|
-
)`)}findAllThreads(e){let t=this.resolveDbPaths(),r=new Set,o=[];for(let s of t){if(!existsSync(s))continue;let i=
|
|
313
|
+
)`)}findAllThreads(e){let t=this.resolveDbPaths(),r=new Set,o=[];for(let s of t){if(!existsSync(s))continue;let i=y(s);try{let d=e?eq(_.workspace_id,e):void 0,l=i.db.select().from(_).where(d).orderBy(desc(_.updated_at)).all();for(let u of l)r.has(u.id)||(r.add(u.id),o.push(u));}catch(d){throw new c("DB_ERROR","Failed to find all threads",d)}finally{i.close();}}return o}findThreadsByIdsOrTitles(e,t){if(e.length===0)return [];let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let d=y(i);try{let l=or(inArray(_.id,e),inArray(_.title,e)),u=t?and(l,eq(_.workspace_id,t)):l,h=d.db.select().from(_).where(u).orderBy(desc(_.updated_at)).all();for(let g of h)o.has(g.id)||(o.add(g.id),s.push(g));}catch(l){throw new c("DB_ERROR","Failed to find threads by ids or titles",l)}finally{d.close();}}return s}findThreadById(e,t){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=y(o);try{let i=eq(_.id,e),d=t?and(i,eq(_.workspace_id,t)):i,l=s.db.select().from(_).where(d).limit(1).get()??void 0;if(l)return l}catch(i){throw new c("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(e,t){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=y(o);try{let i=eq(_.id,e),d=t?and(i,eq(_.workspace_id,t)):i;if(s.db.select({id:_.id}).from(_).where(d).limit(1).get())return !0}catch(i){throw new c("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,t){let r=this.resolveDbPaths(),o=0,s=0,i=0,d=0,l=0,u=new Set;for(let h of r){if(!existsSync(h))continue;let g=y(h);try{let p=g.db.get(sql`
|
|
314
314
|
SELECT
|
|
315
315
|
count(*) AS cnt,
|
|
316
316
|
COALESCE(SUM(child.input_tokens), 0) AS total_input,
|
|
@@ -327,7 +327,7 @@ ${r.join(`
|
|
|
327
327
|
AND child.agent_id IS NOT NULL AND child.agent_id != ''
|
|
328
328
|
AND ${this.topLevelTaskPredicateSql()}
|
|
329
329
|
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
330
|
-
`);for(let D of f)u.add(D.agent_id);}catch(p){throw new c("DB_ERROR","Failed to aggregate task stats",p)}finally{g.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:d,costUsd:l,agentIds:Array.from(u)}}findTopLevelTasks(e,t,r){let o=this.resolveDbPaths(),s=new Set,i=[];for(let d of o){if(!existsSync(d))continue;let l=
|
|
330
|
+
`);for(let D of f)u.add(D.agent_id);}catch(p){throw new c("DB_ERROR","Failed to aggregate task stats",p)}finally{g.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:d,costUsd:l,agentIds:Array.from(u)}}findTopLevelTasks(e,t,r){let o=this.resolveDbPaths(),s=new Set,i=[];for(let d of o){if(!existsSync(d))continue;let l=y(d);try{let u;r!==void 0?u=l.db.all(sql`
|
|
331
331
|
SELECT * FROM (
|
|
332
332
|
SELECT child.*,
|
|
333
333
|
ROW_NUMBER() OVER (PARTITION BY child.agent_id ORDER BY child.started_at DESC) AS rn
|
|
@@ -344,7 +344,7 @@ ${r.join(`
|
|
|
344
344
|
AND ${this.topLevelTaskPredicateSql()}
|
|
345
345
|
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
346
346
|
ORDER BY child.started_at ASC
|
|
347
|
-
`);for(let h of u)s.has(h.id)||(s.add(h.id),i.push(h));}catch(u){throw new c("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}if(r!==void 0&&o.length>1){let d=new Map;for(let l of i){let u=l.agent_id??"";d.has(u)||d.set(u,[]),d.get(u).push(l);}i=[];for(let l of d.values())l.sort((u,h)=>(h.started_at??"").localeCompare(u.started_at??"")),i.push(...l.slice(0,r));i.sort((l,u)=>(l.started_at??"").localeCompare(u.started_at??""));}return i}findAllTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let d=
|
|
347
|
+
`);for(let h of u)s.has(h.id)||(s.add(h.id),i.push(h));}catch(u){throw new c("DB_ERROR","Failed to find top-level tasks",u)}finally{l.close();}}if(r!==void 0&&o.length>1){let d=new Map;for(let l of i){let u=l.agent_id??"";d.has(u)||d.set(u,[]),d.get(u).push(l);}i=[];for(let l of d.values())l.sort((u,h)=>(h.started_at??"").localeCompare(u.started_at??"")),i.push(...l.slice(0,r));i.sort((l,u)=>(l.started_at??"").localeCompare(u.started_at??""));}return i}findAllTasks(e,t){let r=this.resolveDbPaths(),o=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let d=y(i);try{let l=eq(a.thread_id,e),u=t?and(l,eq(a.workspace_id,t)):l,h=d.db.select().from(a).where(u).orderBy(asc(a.started_at)).all();for(let g of h)o.has(g.id)||(o.add(g.id),s.push(g));}catch(l){throw new c("DB_ERROR","Failed to find all tasks for thread",l)}finally{d.close();}}return s}findTaskById(e,t,r){let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=y(s);try{let d=and(eq(a.id,t),eq(a.thread_id,e)),l=r?and(d,eq(a.workspace_id,r)):d,u=i.db.select().from(a).where(l).limit(1).get();if(!u)continue;let h=i.db.select().from(a).where(eq(a.parent_task_id,u.id)).orderBy(asc(a.started_at)).all();return {task:u,children:h}}catch(d){throw new c("DB_ERROR","Failed to find task by id",d)}finally{i.close();}}}batchFetchTasksQuery(e,t){return sql`
|
|
348
348
|
SELECT child.id, child.thread_id, child.agent_id, child.status,
|
|
349
349
|
child.parent_task_id, child.started_at, child.completed_at,
|
|
350
350
|
child.duration_ms, child.input_tokens, child.output_tokens,
|
|
@@ -354,7 +354,7 @@ ${r.join(`
|
|
|
354
354
|
AND ${this.topLevelTaskPredicateSql()}
|
|
355
355
|
${t?sql`AND child.workspace_id = ${t}`:sql``}
|
|
356
356
|
ORDER BY child.started_at ASC
|
|
357
|
-
`}batchFetchTasks(e,t){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=
|
|
357
|
+
`}batchFetchTasks(e,t){let r=new Map;if(e.length===0)return r;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=y(s);try{let d=i.db.all(this.batchFetchTasksQuery(e,t));for(let l of d){let u=l.thread_id;r.has(u)||r.set(u,[]),r.get(u).push(l);}}catch(d){throw new c("DB_ERROR","Failed to batch fetch tasks",d)}finally{i.close();}}return r}explainBatchFetchTasksPlan(e,t){let r=this.resolveDbPaths();for(let o of r){if(!existsSync(o))continue;let s=y(o);try{return s.db.all(sql`EXPLAIN QUERY PLAN ${this.batchFetchTasksQuery(e,t)}`).map(d=>d.detail)}finally{s.close();}}return []}updateThreadTitle(e,t,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=eq(_.id,e),i=r?and(s,eq(_.workspace_id,r)):s;if(!o.db.select({id:_.id}).from(_).where(i).limit(1).get())return;o.db.update(_).set({title:t,title_locked:1,updated_at:new Date().toISOString()}).where(eq(_.id,e)).run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,t){let r=this.openHandle(true);try{let o=t.workspaceId?this.validateWorkspaceId(r,t.workspaceId):null,s=new Date().toISOString();if(r.db.select({id:_.id,message_count:_.message_count}).from(_).where(eq(_.id,e)).limit(1).get()){let d={updated_at:s};t.title!==void 0&&(d.title=t.title),t.titleLocked!==void 0&&(d.title_locked=t.titleLocked?1:0),r.db.update(_).set(d).where(eq(_.id,e)).run();}else r.db.insert(_).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 c?o:new c("DB_ERROR","Failed to upsert thread",o)}finally{r.close();}}ensureThread(e,t,r){let o=this.openHandle(true);try{let s=r?this.validateWorkspaceId(o,r):null,i=o.db.select({id:_.id,platform:_.platform,workspace_id:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get();if(i){s&&!i.workspace_id&&o.db.update(_).set({workspace_id:s}).where(eq(_.id,e)).run();return}let d=new Date().toISOString();o.db.insert(_).values({id:e,platform:t,workspace_id:s,message_count:0,created_at:d,updated_at:d}).run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to ensure thread",s)}finally{o.close();}}saveUserMessage(e,t,r){if(!this.dbExists())return {firstMessage:false};let o=this.openHandle(true);try{let s=new Date().toISOString();return {firstMessage:o.db.transaction(d=>{let u=d.select({message_count:_.message_count}).from(_).where(eq(_.id,e)).limit(1).get()?.message_count===0;return d.run(sql`
|
|
358
358
|
UPDATE threads
|
|
359
359
|
SET first_message = COALESCE(first_message, ${t}),
|
|
360
360
|
title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${t}, 1, 60) ELSE title END,
|
|
@@ -362,7 +362,7 @@ ${r.join(`
|
|
|
362
362
|
message_count = message_count + 1,
|
|
363
363
|
updated_at = ${s}
|
|
364
364
|
WHERE id = ${e}
|
|
365
|
-
`),u},{behavior:"immediate"})}}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,t,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(_).set({last_message:t,updated_at:s}).where(eq(_.id,e)).run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,t){if(!this.dbExists())return;let r=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),r.db.update(_).set(o).where(eq(_.id,e)).run();}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,t,r){let o=t;if(!o||typeof o!="object"||Array.isArray(o))return new ct("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new ct("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new ct("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let l of [i.priority,i.state])if(l!=null&&(typeof l!="string"||l.length===0))return new ct("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let l=r?and(eq(_.id,e),eq(_.workspace_id,r)):eq(_.id,e);return d.db.transaction(u=>{let h=u.select({metadata:_.metadata}).from(_).where(l).get();if(!h)return null;let g=Lt(h.metadata),p=g.threadTitle,f=p&&typeof p=="object"&&!Array.isArray(p)?{...p}:{};i.priority===null?delete f.priority:i.priority!==void 0&&(f.priority=i.priority),i.state===null?delete f.state:i.state!==void 0&&(f.state=i.state),Object.keys(f).length>0?g.threadTitle=f:delete g.threadTitle;let D=Object.keys(g).length>0?JSON.stringify(g):null,w=new Date().toISOString();u.update(_).set({metadata:D,updated_at:w}).where(l).run();let S=u.select({metadata:_.metadata}).from(_).where(l).get();if(!S)throw new c("DB_ERROR","Thread-title metadata update could not be read back");let E=Va(S.metadata);return {threadId:e,priority:E.priority,state:E.state}},{behavior:"immediate"})}catch(l){throw l instanceof c?l:new c("DB_ERROR","Failed to patch thread-title metadata",l)}finally{d.close();}}togglePin(e,t){let r=this.openHandle(true);try{let o=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e);return r.db.transaction(s=>{let i=s.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(o).get();if(!i)return null;let d=i.pinned?0:1,l=Lt(i.metadata);if(d){let u=t?and(eq(_.pinned,1),eq(_.workspace_id,t)):eq(_.pinned,1),h=s.select({metadata:_.metadata}).from(_).where(u).all(),g=null;for(let p of h){let f=Lt(p.metadata);typeof f.pinOrder=="number"&&(g===null||f.pinOrder<g)&&(g=f.pinOrder);}l.pinOrder=g===null?0:g-1;}else delete l.pinOrder;return s.update(_).set({pinned:d,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!d}},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let i=t?and(eq(_.id,e[s]),eq(_.workspace_id,t)):eq(_.id,e[s]),d=o.select({metadata:_.metadata}).from(_).where(i).get();if(!d)continue;let l=Lt(d.metadata);l.pinOrder=s+1,o.update(_).set({metadata:JSON.stringify(l)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,t){let r=this.openHandle(true);try{let o=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e),s=r.db.select({starred:_.starred}).from(_).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(_).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,t,r,o){let i=this.openHandle(true);try{let d=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e);return i.db.transaction(u=>{let h=u.select({metadata:_.metadata}).from(_).where(d).get();if(!h)return null;let g=h.metadata?JSON.parse(h.metadata):{},p=g.overdrive??{},f=o?.defaultTurns??p.defaultTurns??3,D=o?.updatedBy??"ui",w=new Date().toISOString(),S,E,K,Me;switch(r){case "enable-count":{let ce=o?.turns??f,ke=o?.consumeCurrent?Math.max(ce-1,0):ce;S=ke>0?"count":"off",E=ke,K=!0,Me="count";break}case "enable-latch":{S="latch",E=0,K=!0,Me="latch";break}case "disable":{S="off",E=0,K=!1;break}default:{let ce=p.state??"off",ke=typeof p.remaining=="number"?p.remaining:0;if(ce==="count"&&ke>0){let H=ke-1;H<=0?(S="off",E=0):(S="count",E=H),K=!0,Me="count";}else ce==="latch"?(S="latch",E=0,K=!0,Me="latch"):(S="off",E=0,K=!1);break}}return g.overdrive={state:S,remaining:E,defaultTurns:f,updatedAt:w,updatedBy:D},u.update(_).set({metadata:JSON.stringify(g),updated_at:w}).where(d).run(),{applied:K,appliedMode:Me,state:S,remaining:E}},{behavior:"immediate"})}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};var yt="THREAD_STATE",hr="custom:";function Qa(n){return n.dbPath?n.dbPath:n.dbRoot?join(n.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 Kr(n){if(!n)return null;try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function Po(n){let t=Kr(n)?.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.state;return typeof r=="string"&&r.startsWith(hr)?r:null}function Wr(n){let e=[...n].length;return e>=1&&e<=20}function Za(n){let e=n.select({id:_.id,workspace_id:_.workspace_id,metadata:_.metadata}).from(_).all(),t=[];for(let r of e){let o=Po(r.metadata);o!==null&&t.push({id:r.id,workspace_id:r.workspace_id,metadata:r.metadata,label:o.slice(hr.length)});}return t}function ed(n){return n===null?isNull(m.workspace_id):eq(m.workspace_id,n)}function td(n){return n===null?isNull(m.workspace_id):or(isNull(m.workspace_id),eq(m.workspace_id,n))}function rd(n,e,t){let r=n.select().from(m).where(and(eq(m.code_group,yt),eq(m.code_name,e),ed(t),eq(m.is_builtin,0))).limit(1).get();if(r)return {code:r.code,created:false};let o=n.select({maxSortOrder:sql`max(${m.sort_order})`}).from(m).where(and(eq(m.code_group,yt),td(t))).get(),s=mt();for(;n.select({code:m.code}).from(m).where(and(eq(m.code_group,yt),eq(m.code,s))).limit(1).get();)s=mt();let i=new Date().toISOString();return n.insert(m).values({code_group:yt,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:i,updated_at:i}).run(),{code:s,created:true}}function nd(n,e,t,r){let o=n.select({id:_.id,workspace_id:_.workspace_id,metadata:_.metadata}).from(_).all(),s=`${hr}${e}`,i=0,d=new Date().toISOString();for(let l of o){if(r!==null&&l.workspace_id!==r||Po(l.metadata)!==s)continue;let u=Kr(l.metadata)??{},h=u.threadTitle,g=h&&typeof h=="object"&&!Array.isArray(h)?{...h}:{};g.state=t,u.threadTitle=g,n.update(_).set({metadata:JSON.stringify(u),updated_at:d}).where(eq(_.id,l.id)).run(),i+=1;}return i}function Vr(n,e,t){return n.transaction(r=>{let o=rd(r,e,t),s=nd(r,e,o.code,t);return {...o,migratedRows:s}},{behavior:"immediate"})}function od(n,e){return n.select({code:m.code}).from(m).where(and(eq(m.code_group,yt),eq(m.code_name,e),isNull(m.workspace_id),eq(m.is_builtin,0))).limit(1).get()?.code??null}function sd(n){let e=new Set(n.select({code:m.code}).from(m).where(eq(m.code_group,yt)).all().map(s=>s.code)),t=n.select({metadata:_.metadata}).from(_).all(),r=0,o=0;for(let s of t){let d=Kr(s.metadata)?.threadTitle;if(!d||typeof d!="object"||Array.isArray(d))continue;let l=d.state;typeof l=="string"&&(l.startsWith(hr)&&(r+=1),e.has(l)||(o+=1));}return {remainingCustomReferences:r,orphanReferences:o}}function Ho(n={}){let e=Qa(n);if(!existsSync(e))return {migratedRows:0,createdCodes:0,remainingCustomReferences:0,orphanReferences:0};let t=T(e);try{$(t.db,e);let r=Za(t.db),o=new Set;for(let h of n.configuredLabels??[])typeof h=="string"&&o.add(h);let s=new Set(o),i=new Map;for(let h of r)if(Wr(h.label))if(h.workspace_id===null)s.add(h.label);else {let g=i.get(h.workspace_id)??new Set;g.add(h.label),i.set(h.workspace_id,g);}let d=0,l=0,u=new Map;for(let h of [...s].sort()){if(!Wr(h))continue;let g=Vr(t.db,h,null);u.set(h,g.code),d+=g.migratedRows,g.created&&(l+=1);}for(let h of [...i.keys()].sort())for(let g of [...i.get(h)].sort()){if(!Wr(g)||u.has(g))continue;if(od(t.db,g)){let f=Vr(t.db,g,null);u.set(g,f.code),d+=f.migratedRows,f.created&&(l+=1);continue}let p=Vr(t.db,g,h);d+=p.migratedRows,p.created&&(l+=1);}return {migratedRows:d,createdCodes:l,...sd(t.db)}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to migrate legacy thread-title common codes",r)}finally{t.close();}}var id=Ho;var jo=["urgent","high","medium","low"],Mo=["investigating","in-progress","in-review","on-hold","done"],Pt="custom:";var ad=new Set(jo),dd=new Set(Mo),cd={urgent:"U \uAE34\uAE09 Urgent",high:"P0 \uAE09\uD568 High",medium:"P1 \uC911\uC694 Medium",low:"P2 \uBCF4\uD1B5 Low"},Jr={investigating:"\uC870\uC0AC\uC911 Looking into","in-progress":"\uC9C4\uD589\uC911 In progress","in-review":"\uAC80\uD1A0\uC911 In review","on-hold":"\uBCF4\uB958 On hold",done:"\uC644\uB8CC Done"};function $o(n,e){return !e||e.includes(n)?e??n:`${n} ${e}`}function Ht(n){return typeof n=="string"&&ad.has(n)}function $t(n){if(typeof n!="string")return false;if(dd.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(Pt))return false;let e=n.slice(Pt.length);return e.length>=1&&e.length<=20}function qo(n){if(n.startsWith(Pt))return n.slice(Pt.length)}function Yr(n){if(!n)return null;try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function ld(n){let e=Yr(n);return !!e&&Object.prototype.hasOwnProperty.call(e,"threadTitle")}function gr(n){let e=Yr(n);if(!e)return {};let t=e.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {};let r=t,o={};return Ht(r.priority)&&(o.priority=r.priority),$t(r.state)&&(o.state=r.state),o}function Xr(n,e){let t=Yr(n)??{},r={...gr(n)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete t.threadTitle:t.threadTitle=r,Object.keys(t).length===0?null:JSON.stringify(t)}function ud(n,e=new Map){let t=[];return n.priority&&t.push($o(cd[n.priority],e.get(n.priority))),n.state&&(n.state.startsWith(Pt)?t.push(qo(n.state)??""):Jr[n.state]?t.push($o(Jr[n.state],e.get(n.state))):e.has(n.state)?t.push(n.state,e.get(n.state)??""):n.state.startsWith("c_")?t.push(n.state):t.push(Jr[n.state]??"")),t.filter(Boolean).join(" ")}function Bo(n,e){if(!n||n.trim().length===0)return;let t=new Set,r=false,o=false;for(let s of n.split(",")){let i=s.trim();if(i){if(i==="none"){r=true,o=true;continue}e(i)&&(t.add(i),o=true);}}if(o)return {values:t,includeNone:r}}function hd(n){return Bo(n,Ht)}function gd(n){return Bo(n,$t)}function pd(n,e){return e?n?e.values.has(n):e.includeNone:true}var Wo="regeneration_replaced",kd="THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS",Vo="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED",Td="THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED",Ko="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",mr=class extends c{threadId;highlightId;expectedRevision;currentRevision;constructor(e,t,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=t,this.expectedRevision=r,this.currentRevision=o;}},bt=class extends mr{},wr=class extends c{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},yd=new Set(An),Rd=new Set(On),Ed=new Set(xn),bd=new Set(Ln),Id=50,Uo=100,zo=280,Go=40,Sd=new Set(Pn),pr=["queued","running"],vd=["success","completed","done","failed","error"];function Zr(n){return Sd.has(n)}function F(n){throw new c("VALIDATION",n)}function Oe(n){throw new c("NOT_FOUND",n)}function I(n,e){(typeof n!="string"||n.trim().length===0)&&F(`${e} is required`);}function Mt(n={}){let e=n.actor??n,t=e.actorType??"system";return yd.has(t)||F(`invalid actorType: ${String(t)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&F("actorId must be a string or null"),{actorType:t,actorId:e.actorId??null}}function Cd(n){I(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&I(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&F("title must not be empty"),n.title.length>120&&F("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!Ht(n.priority)&&F(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!$t(n.state)&&F(`invalid state: ${String(n.state)}`);}function Dd(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&F("beforeSeq and afterSeq cannot be used together");for(let[t,r]of [["beforeSeq",n.beforeSeq],["afterSeq",n.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&F(`${t} must be a non-negative integer`);let e=n.limit??Id;return (!Number.isInteger(e)||e<1||e>Uo)&&F(`limit must be between 1 and ${Uo}`),e}function tn(n){typeof n!="string"&&F("text is required");let e=n.trim();return e.length===0&&F("text must not be empty"),e.length>zo&&F(`text must be at most ${zo} characters`),e}function Xe(n,e){return I(n??"",e),n}function rn(n){bd.has(n)||F(`invalid highlight kind: ${String(n)}`);}function Nd(n){Ed.has(n)||F(`invalid highlight source: ${String(n)}`);}function Od(n){I(n.threadId,"threadId"),I(n.workspaceId,"workspaceId");let e=n.source??"manual";Nd(e),rn(n.kind);let t=tn(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,o=n.coversToTaskId??n.toTaskId??n.taskId;if(e==="manual"){let h=n.taskId??(r&&o&&r===o?r:void 0),g=Xe(h,"taskId");return (r!==g||o!==g)&&F("manual highlights must cover exactly one task"),{source:e,kind:n.kind,text:t,coversFromTaskId:g,coversToTaskId:g,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Xe(r,"coversFromTaskId"),i=Xe(o,"coversToTaskId"),d=n.sourceTaskId??s,l=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),u=n.contentFingerprint??n.idempotencyKey??null;return Xe(d??void 0,"sourceTaskId"),Xe(l??void 0,"detectorVersion"),Xe(u??void 0,"contentFingerprint"),{source:e,kind:n.kind,text:t,coversFromTaskId:s,coversToTaskId:i,agentId:n.agentId??null,sourceTaskId:d,detectorVersion:l,contentFingerprint:u}}function Ad(n,e){(!n||typeof n!="object")&&F(`candidates[${e}] is required`),rn(n.kind);let t=tn(n.text),r=Xe(n.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Xe(n.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Xe(n.coversToTaskId,`candidates[${e}].coversToTaskId`),i=n.contentFingerprint?.trim()||Gn("thl",JSON.stringify({kind:n.kind,text:t,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return I(i,`candidates[${e}].contentFingerprint`),{kind:n.kind,text:t,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function xd(n){Array.isArray(n)||F("candidates must be an array"),n.length>Go&&F(`candidates must contain at most ${Go} items`);let e=new Map;for(let[t,r]of n.entries()){let o=Ad(r,t);e.set(o.contentFingerprint,o);}return [...e.values()]}function Ut(n){let e=gr(n.metadata);return {threadId:n.id,workspaceId:n.workspace_id,title:n.title,priority:e.priority??null,state:e.state??null,metadata:n.metadata,titleLocked:n.title_locked===1,updatedAt:n.updated_at}}function Ld(n){try{let e=JSON.stringify(n);return (!e||e==="null"||e.startsWith("["))&&F("event payload must be a JSON object"),e}catch(e){throw new c("VALIDATION","event payload must be JSON serializable",e)}}function qt(n,e){return n.select({maxSeq:sql`COALESCE(MAX(${M.seq}), 0)`}).from(M).where(eq(M.thread_id,e)).get()?.maxSeq??0}function Bt(n,e){return !!n.select({id:M.id}).from(M).where(eq(M.thread_id,e)).limit(1).get()}function lt(n,e){Rd.has(e.type)||F(`invalid thread event type: ${String(e.type)}`);let t=fe("the");n.insert(M).values({id:t,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:Ld(e.payload),created_at:e.createdAt}).run();let r=n.select().from(M).where(eq(M.id,t)).get();if(!r)throw new c("DB_ERROR","Thread event insert did not return a row");return r}function Ft(n,e,t,r,o){let s=Ut(e);lt(n,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:t.actorType,actorId:t.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function fr(n){return {highlightId:n.id,source:n.source,kind:n.kind,status:n.status,coversFromTaskId:n.covers_from_task_id,coversToTaskId:n.covers_to_task_id,revision:n.revision,...n.dismissed_at===null?{}:{dismissedAt:n.dismissed_at}}}function _r(n,e,t,r,o,s,i){let d=o==="thread.highlight.created"?fr(e):{before:i?fr({...e,...i,id:e.id}):void 0,after:fr(e)};return lt(n,{threadId:e.thread_id,seq:s,type:o,actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:d})}function Pd(n,e,t,r,o,s){return lt(n,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:fr(e),...s??{}}})}var en=class extends x{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 c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}findThread(e,t,r){let o=eq(_.id,t),s=r===void 0?o:r===null?and(o,isNull(_.workspace_id)):and(o,eq(_.workspace_id,r));return e.select().from(_).where(s).limit(1).get()}findRegenerationRun(e,t,r){let o=e.select().from(A).where(eq(A.id,t)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(I(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let t=this.openHandle(false);try{return t.db.select({workspaceId:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to resolve thread workspace",r)}finally{t.close();}}getSnapshot(e,t){if(I(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,t);return o?Ut(o):null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Cd(e);let t=Mt(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||Oe(`Thread ${e.threadId} not found`);let d=Ut(i),l=e.title!==void 0,u=l&&e.title!==d.title,h=l&&i.title_locked!==1,g=e.priority!==void 0&&e.priority!==d.priority,p=e.state!==void 0&&e.state!==d.state,f=u||g||p;if(!f&&!h)return d;let D=i.metadata;(g||p)&&(D=Xr(i.metadata,{priority:e.priority,state:e.state}));let w={};if(f&&(w.metadata=D,w.updated_at=r),u&&(w.title=e.title),l&&(w.title_locked=1),s.update(_).set(w).where(e.workspaceId===void 0?eq(_.id,e.threadId):e.workspaceId===null?and(eq(_.id,e.threadId),isNull(_.workspace_id)):and(eq(_.id,e.threadId),eq(_.workspace_id,e.workspaceId))).run(),!f){let K={...i,title_locked:1};return Ut(K)}let S=qt(s,i.id)+1;Bt(s,i.id)||(Ft(s,i,t,r,S),S+=1),u&&(lt(s,{threadId:i.id,seq:S,type:"thread.title.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),S+=1),g&&(lt(s,{threadId:i.id,seq:S,type:"thread.priority.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),S+=1),p&<(s,{threadId:i.id,seq:S,type:"thread.state.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let E={...i,title:u?e.title:i.title,metadata:D,title_locked:l?1:i.title_locked,updated_at:r};return Ut(E)},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,t){if(I(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,t)?r.db.select({maxSeq:sql`COALESCE(MAX(${M.seq}), 0)`}).from(M).where(eq(M.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,t){if(I(e,"threadId"),I(t,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,t)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(and(eq(a.thread_id,e),eq(a.workspace_id,t),inArray(a.status,vd),or(isNull(a.parent_task_id),eq(a.parent_task_id,"")),sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(asc(a.started_at),asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){I(e.threadId,"threadId"),I(e.workspaceId,"workspaceId"),I(e.requestId,"requestId"),I(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&I(e.runId,"runId");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||Oe(`Thread ${e.threadId} not found`);let i=o.select().from(A).where(and(eq(A.thread_id,s.id),eq(A.request_id,e.requestId))).orderBy(desc(A.requested_at),desc(A.id)).limit(1).get();if(i)return {run:i,created:!1};let d=o.select().from(A).where(and(eq(A.thread_id,s.id),inArray(A.status,pr))).orderBy(asc(A.requested_at),asc(A.id)).limit(1).get();if(d)throw new wr(d);let l=e.runId??fe("thr");o.insert(A).values({id:l,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:t,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let u=o.select().from(A).where(eq(A.id,l)).get();if(!u)throw new c("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,t){if(I(e,"runId"),t!==void 0&&I(t,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,t)??null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,t,r){if(I(e,"threadId"),I(t,"workspaceId"),I(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,t)?o.db.select().from(A).where(and(eq(A.thread_id,e),eq(A.request_id,r))).orderBy(desc(A.requested_at),desc(A.id)).limit(1).get()??null:null}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,t,r){return this.getHighlightRegenerationRunByRequest(e,t,r)}startHighlightRegenerationRun(e,t){I(e,"runId"),t!==void 0&&I(t,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,t);if(i||Oe(`Highlight regeneration run ${e} not found`),Zr(i.status)||F(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(A).set({status:"running",started_at:r}).where(and(eq(A.id,i.id),eq(A.status,"queued"))).run();let d=s.select().from(A).where(eq(A.id,i.id)).get();if(!d)throw new c("DB_ERROR","Highlight regeneration run start did not return a row");return d},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,t){return this.startHighlightRegenerationRun(e,t)}failHighlightRegenerationRun(e){I(e.runId,"runId"),I(e.errorCode,"errorCode"),e.workspaceId!==void 0&&I(e.workspaceId,"workspaceId");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||Oe(`Highlight regeneration run ${e.runId} not found`),Zr(s.status)||F(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(A).set({status:"failed",completed_at:t,error_code:e.errorCode}).where(and(eq(A.id,s.id),inArray(A.status,pr))).run();let i=o.select().from(A).where(eq(A.id,s.id)).get();if(!i)throw new c("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=Vo){I(e,"errorCode");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(A).set({status:"failed",completed_at:t,error_code:e}).where(inArray(A.status,pr)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){I(e.runId,"runId"),I(e.threadId,"threadId"),I(e.workspaceId,"workspaceId"),I(e.detectorVersion,"detectorVersion");let t=xd(e.candidates),r=Mt(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let d=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&Oe(`Highlight regeneration run ${e.runId} not found`),Zr(d.status)||F(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new c("CONFLICT","Highlight regeneration run has already failed");if(d.status==="completed")return {run:d,deletedCount:0,createdCount:0,previousAutoCount:d.previous_auto_count??0,newAutoCount:d.new_auto_count??0};s=!0;let l=this.findThread(i,e.threadId,e.workspaceId);l||Oe(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&F("detectorVersion does not match the regeneration run");let u=i.select().from(v).where(eq(v.thread_id,l.id)).orderBy(asc(v.created_at),asc(v.id)).all(),h=new Set(t.map(H=>H.contentFingerprint)),g=u.filter(H=>H.source==="auto"&&H.status==="active"&&H.revision===0&&!h.has(H.content_fingerprint??"")),p=u.filter(H=>H.source==="auto"&&H.status==="active").length,f=new Set(u.filter(H=>!g.includes(H)&&H.content_fingerprint).map(H=>H.content_fingerprint)),D=t.filter(H=>!f.has(H.contentFingerprint)),w=new Date().toISOString(),S=qt(i,l.id)+1;Bt(i,l.id)||(Ft(i,l,r,w,S),S+=1);for(let H of g)i.delete(v).where(eq(v.id,H.id)).run(),Pd(i,H,r,w,S,{runId:e.runId,reason:Wo}),S+=1;let E=0,K=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let H of D){let gn=fe("thl");i.insert(v).values({id:gn,thread_id:l.id,source:"auto",kind:H.kind,status:"active",text:H.text,covers_from_task_id:H.coversFromTaskId,covers_to_task_id:H.coversToTaskId,revision:0,created_at:w,updated_at:w,agent_id:K,source_task_id:H.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:H.contentFingerprint,dismissed_at:null}).run();let pn=i.select().from(v).where(eq(v.id,gn)).get();if(!pn)throw new c("DB_ERROR","Regenerated highlight insert did not return a row");_r(i,pn,r,w,"thread.highlight.created",S),S+=1,E+=1;}let ce=i.select().from(v).where(eq(v.thread_id,l.id)).all().filter(H=>H.source==="auto"&&H.status==="active").length;lt(i,{threadId:l.id,seq:S,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:w,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:p,newAutoCount:ce,deletedCount:g.length,createdCount:E}}),i.update(A).set({status:"completed",started_at:d.started_at??w,completed_at:w,error_code:null,previous_auto_count:p,new_auto_count:ce}).where(and(eq(A.id,d.id),inArray(A.status,pr))).run();let ke=i.select().from(A).where(eq(A.id,d.id)).get();if(!ke)throw new c("DB_ERROR","Highlight regeneration completion did not return a row");return {run:ke,deletedCount:g.length,createdCount:E,previousAutoCount:p,newAutoCount:ce}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Ko});}catch{}throw i instanceof c?i:new c("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,t,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:t}:e;I(o.threadId,"threadId"),I(o.workspaceId,"workspaceId");let s=Dd(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let d=i.db.select({maxSeq:sql`COALESCE(MAX(${M.seq}), 0)`}).from(M).where(eq(M.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(M).where(and(eq(M.thread_id,o.threadId),lt$1(M.seq,o.beforeSeq))).orderBy(desc(M.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(M).where(and(eq(M.thread_id,o.threadId),sql`${M.seq} > ${o.afterSeq}`)).orderBy(asc(M.seq)).limit(s+1).all():l=i.db.select().from(M).where(eq(M.thread_id,o.threadId)).orderBy(desc(M.seq)).limit(s+1).all().reverse();let u=l.length>s,h=o.afterSeq!==void 0?l.slice(0,s):u?l.slice(1):l,g=!1,p=h[0];return p&&(g=!!i.db.select({id:M.id}).from(M).where(and(eq(M.thread_id,o.threadId),lt$1(M.seq,p.seq))).limit(1).get()),{items:h,latestSeq:d,hasMoreOlder:g}}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to list thread timeline",d)}finally{i.close();}}listEvents(e,t,r){return this.listTimeline(e,t,r)}getTimeline(e,t,r){return this.listTimeline(e,t,r)}createHighlight(e){let t=Od(e),r=Mt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);if(d||Oe(`Thread ${e.threadId} not found`),t.source==="auto"){let p=i.select().from(v).where(and(eq(v.thread_id,e.threadId),eq(v.source_task_id,t.sourceTaskId),eq(v.detector_version,t.detectorVersion),eq(v.content_fingerprint,t.contentFingerprint))).orderBy(asc(v.created_at),asc(v.id)).limit(1).get();if(p)return p}let l=e.id??fe("thl"),u={id:l,thread_id:e.threadId,source:t.source,kind:t.kind,status:"active",text:t.text,covers_from_task_id:t.coversFromTaskId,covers_to_task_id:t.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:t.agentId,source_task_id:t.sourceTaskId,detector_version:t.detectorVersion,content_fingerprint:t.contentFingerprint,dismissed_at:null};i.insert(v).values(u).run();let h=i.select().from(v).where(eq(v.id,l)).get();if(!h)throw new c("DB_ERROR","Highlight insert did not return a row");let g=qt(i,d.id)+1;return Bt(i,d.id)||(Ft(i,d,r,o,g),g+=1),_r(i,h,r,o,"thread.highlight.created",g),h},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){I(e.threadId,"threadId"),I(e.workspaceId,"workspaceId"),I(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&F("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&F("highlight update requires at least one field"),e.kind!==void 0&&rn(e.kind);let t=e.text===void 0?void 0:tn(e.text),r=Mt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);d||Oe(`Thread ${e.threadId} not found`);let l=i.select().from(v).where(and(eq(v.id,e.highlightId),eq(v.thread_id,d.id))).limit(1).get();if(l||Oe(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new bt(d.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new bt(d.id,l.id,e.expectedRevision,l.revision);let u=e.kind??l.kind,h=t??l.text,g=e.coversFromTaskId??l.covers_from_task_id,p=e.coversToTaskId??l.covers_to_task_id;(!h||g.length===0||p.length===0)&&F("highlight projection is incomplete");let f=u!==l.kind||h!==l.text||g!==l.covers_from_task_id||p!==l.covers_to_task_id,D=r.actorType==="user"&&l.source==="auto"&&f?"manual":l.source;if(!(f||D!==l.source))return l;let S=l.revision+1;i.update(v).set({source:D,kind:u,text:h,covers_from_task_id:g,covers_to_task_id:p,revision:S,updated_at:o}).where(and(eq(v.id,l.id),eq(v.revision,l.revision))).run();let E=i.select().from(v).where(eq(v.id,l.id)).get();if(!E)throw new c("DB_ERROR","Highlight update did not return a row");let K=qt(i,d.id)+1;return Bt(i,d.id)||(Ft(i,d,r,o,K),K+=1),_r(i,E,r,o,"thread.highlight.updated",K,l),E},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){I(e.threadId,"threadId"),I(e.workspaceId,"workspaceId"),I(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&F("expectedRevision must be a non-negative integer");let t=Mt(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||Oe(`Thread ${e.threadId} not found`);let d=s.select().from(v).where(and(eq(v.id,e.highlightId),eq(v.thread_id,i.id))).limit(1).get();if(d||Oe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new bt(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let l=d.revision+1;s.update(v).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(and(eq(v.id,d.id),eq(v.revision,d.revision))).run();let u=s.select().from(v).where(eq(v.id,d.id)).get();if(!u)throw new c("DB_ERROR","Highlight dismissal did not return a row");let h=qt(s,i.id)+1;return Bt(s,i.id)||(Ft(s,i,t,r,h),h+=1),_r(s,u,t,r,"thread.highlight.deleted",h,d),u},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,t,r={}){if(I(e,"threadId"),I(t,"workspaceId"),r.taskId!==void 0&&I(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&I(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&I(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,t))return null;let i=o.db.select().from(v).where(and(eq(v.thread_id,e),eq(v.status,"active"))).orderBy(asc(v.created_at),asc(v.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(sql`
|
|
365
|
+
`),u},{behavior:"immediate"})}}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,t,r){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(_).set({last_message:t,updated_at:s}).where(eq(_.id,e)).run();}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,t){if(!this.dbExists())return;let r=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),r.db.update(_).set(o).where(eq(_.id,e)).run();}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to update thread",o)}finally{r.close();}}patchThreadTitleMetadata(e,t,r){let o=t;if(!o||typeof o!="object"||Array.isArray(o))return new ct("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new ct("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch only supports priority and state");let i=o;if(i.priority===void 0&&i.state===void 0)return new ct("THREAD_TITLE_PATCH_EMPTY","Thread-title metadata patch must change priority or state");for(let l of [i.priority,i.state])if(l!=null&&(typeof l!="string"||l.length===0))return new ct("THREAD_TITLE_PATCH_INVALID","Thread-title metadata values must be non-empty strings or null");let d=this.openHandle(true);try{let l=r?and(eq(_.id,e),eq(_.workspace_id,r)):eq(_.id,e);return d.db.transaction(u=>{let h=u.select({metadata:_.metadata}).from(_).where(l).get();if(!h)return null;let g=Lt(h.metadata),p=g.threadTitle,f=p&&typeof p=="object"&&!Array.isArray(p)?{...p}:{};i.priority===null?delete f.priority:i.priority!==void 0&&(f.priority=i.priority),i.state===null?delete f.state:i.state!==void 0&&(f.state=i.state),Object.keys(f).length>0?g.threadTitle=f:delete g.threadTitle;let D=Object.keys(g).length>0?JSON.stringify(g):null,w=new Date().toISOString();u.update(_).set({metadata:D,updated_at:w}).where(l).run();let S=u.select({metadata:_.metadata}).from(_).where(l).get();if(!S)throw new c("DB_ERROR","Thread-title metadata update could not be read back");let E=Va(S.metadata);return {threadId:e,priority:E.priority,state:E.state}},{behavior:"immediate"})}catch(l){throw l instanceof c?l:new c("DB_ERROR","Failed to patch thread-title metadata",l)}finally{d.close();}}togglePin(e,t){let r=this.openHandle(true);try{let o=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e);return r.db.transaction(s=>{let i=s.select({pinned:_.pinned,metadata:_.metadata}).from(_).where(o).get();if(!i)return null;let d=i.pinned?0:1,l=Lt(i.metadata);if(d){let u=t?and(eq(_.pinned,1),eq(_.workspace_id,t)):eq(_.pinned,1),h=s.select({metadata:_.metadata}).from(_).where(u).all(),g=null;for(let p of h){let f=Lt(p.metadata);typeof f.pinOrder=="number"&&(g===null||f.pinOrder<g)&&(g=f.pinOrder);}l.pinOrder=g===null?0:g-1;}else delete l.pinOrder;return s.update(_).set({pinned:d,metadata:Object.keys(l).length>0?JSON.stringify(l):null}).where(o).run(),{pinned:!!d}},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to toggle pin",o)}finally{r.close();}}reorderPins(e,t){let r=this.openHandle(true);try{r.db.transaction(o=>{for(let s=0;s<e.length;s++){let i=t?and(eq(_.id,e[s]),eq(_.workspace_id,t)):eq(_.id,e[s]),d=o.select({metadata:_.metadata}).from(_).where(i).get();if(!d)continue;let l=Lt(d.metadata);l.pinOrder=s+1,o.update(_).set({metadata:JSON.stringify(l)}).where(i).run();}},{behavior:"immediate"});}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to reorder pins",o)}finally{r.close();}}toggleStar(e,t){let r=this.openHandle(true);try{let o=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e),s=r.db.select({starred:_.starred}).from(_).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(_).set({starred:i}).where(o).run(),{starred:!!i}}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to toggle star",o)}finally{r.close();}}resolveOverdriveForRequest(e,t,r,o){let i=this.openHandle(true);try{let d=t?and(eq(_.id,e),eq(_.workspace_id,t)):eq(_.id,e);return i.db.transaction(u=>{let h=u.select({metadata:_.metadata}).from(_).where(d).get();if(!h)return null;let g=h.metadata?JSON.parse(h.metadata):{},p=g.overdrive??{},f=o?.defaultTurns??p.defaultTurns??3,D=o?.updatedBy??"ui",w=new Date().toISOString(),S,E,K,Me;switch(r){case "enable-count":{let le=o?.turns??f,ke=o?.consumeCurrent?Math.max(le-1,0):le;S=ke>0?"count":"off",E=ke,K=!0,Me="count";break}case "enable-latch":{S="latch",E=0,K=!0,Me="latch";break}case "disable":{S="off",E=0,K=!1;break}default:{let le=p.state??"off",ke=typeof p.remaining=="number"?p.remaining:0;if(le==="count"&&ke>0){let H=ke-1;H<=0?(S="off",E=0):(S="count",E=H),K=!0,Me="count";}else le==="latch"?(S="latch",E=0,K=!0,Me="latch"):(S="off",E=0,K=!1);break}}return g.overdrive={state:S,remaining:E,defaultTurns:f,updatedAt:w,updatedBy:D},u.update(_).set({metadata:JSON.stringify(g),updated_at:w}).where(d).run(),{applied:K,appliedMode:Me,state:S,remaining:E}},{behavior:"immediate"})}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};var yt="THREAD_STATE",hr="custom:";function Qa(n){return n.dbPath?n.dbPath:n.dbRoot?join(n.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 Kr(n){if(!n)return null;try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function Ho(n){let t=Kr(n)?.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.state;return typeof r=="string"&&r.startsWith(hr)?r:null}function Wr(n){let e=[...n].length;return e>=1&&e<=20}function Za(n){let e=n.select({id:_.id,workspace_id:_.workspace_id,metadata:_.metadata}).from(_).all(),t=[];for(let r of e){let o=Ho(r.metadata);o!==null&&t.push({id:r.id,workspace_id:r.workspace_id,metadata:r.metadata,label:o.slice(hr.length)});}return t}function ed(n){return n===null?isNull(m.workspace_id):eq(m.workspace_id,n)}function td(n){return n===null?isNull(m.workspace_id):or(isNull(m.workspace_id),eq(m.workspace_id,n))}function rd(n,e,t){let r=n.select().from(m).where(and(eq(m.code_group,yt),eq(m.code_name,e),ed(t),eq(m.is_builtin,0))).limit(1).get();if(r)return {code:r.code,created:false};let o=n.select({maxSortOrder:sql`max(${m.sort_order})`}).from(m).where(and(eq(m.code_group,yt),td(t))).get(),s=mt();for(;n.select({code:m.code}).from(m).where(and(eq(m.code_group,yt),eq(m.code,s))).limit(1).get();)s=mt();let i=new Date().toISOString();return n.insert(m).values({code_group:yt,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:i,updated_at:i}).run(),{code:s,created:true}}function nd(n,e,t,r){let o=n.select({id:_.id,workspace_id:_.workspace_id,metadata:_.metadata}).from(_).all(),s=`${hr}${e}`,i=0,d=new Date().toISOString();for(let l of o){if(r!==null&&l.workspace_id!==r||Ho(l.metadata)!==s)continue;let u=Kr(l.metadata)??{},h=u.threadTitle,g=h&&typeof h=="object"&&!Array.isArray(h)?{...h}:{};g.state=t,u.threadTitle=g,n.update(_).set({metadata:JSON.stringify(u),updated_at:d}).where(eq(_.id,l.id)).run(),i+=1;}return i}function Vr(n,e,t){return n.transaction(r=>{let o=rd(r,e,t),s=nd(r,e,o.code,t);return {...o,migratedRows:s}},{behavior:"immediate"})}function od(n,e){return n.select({code:m.code}).from(m).where(and(eq(m.code_group,yt),eq(m.code_name,e),isNull(m.workspace_id),eq(m.is_builtin,0))).limit(1).get()?.code??null}function sd(n){let e=new Set(n.select({code:m.code}).from(m).where(eq(m.code_group,yt)).all().map(s=>s.code)),t=n.select({metadata:_.metadata}).from(_).all(),r=0,o=0;for(let s of t){let d=Kr(s.metadata)?.threadTitle;if(!d||typeof d!="object"||Array.isArray(d))continue;let l=d.state;typeof l=="string"&&(l.startsWith(hr)&&(r+=1),e.has(l)||(o+=1));}return {remainingCustomReferences:r,orphanReferences:o}}function $o(n={}){let e=Qa(n);if(!existsSync(e))return {migratedRows:0,createdCodes:0,remainingCustomReferences:0,orphanReferences:0};let t=y(e);try{$(t.db,e);let r=Za(t.db),o=new Set;for(let h of n.configuredLabels??[])typeof h=="string"&&o.add(h);let s=new Set(o),i=new Map;for(let h of r)if(Wr(h.label))if(h.workspace_id===null)s.add(h.label);else {let g=i.get(h.workspace_id)??new Set;g.add(h.label),i.set(h.workspace_id,g);}let d=0,l=0,u=new Map;for(let h of [...s].sort()){if(!Wr(h))continue;let g=Vr(t.db,h,null);u.set(h,g.code),d+=g.migratedRows,g.created&&(l+=1);}for(let h of [...i.keys()].sort())for(let g of [...i.get(h)].sort()){if(!Wr(g)||u.has(g))continue;if(od(t.db,g)){let f=Vr(t.db,g,null);u.set(g,f.code),d+=f.migratedRows,f.created&&(l+=1);continue}let p=Vr(t.db,g,h);d+=p.migratedRows,p.created&&(l+=1);}return {migratedRows:d,createdCodes:l,...sd(t.db)}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to migrate legacy thread-title common codes",r)}finally{t.close();}}var id=$o;var Mo=["urgent","high","medium","low"],qo=["investigating","in-progress","in-review","on-hold","done"],Pt="custom:";var ad=new Set(Mo),dd=new Set(qo),cd={urgent:"U \uAE34\uAE09 Urgent",high:"P0 \uAE09\uD568 High",medium:"P1 \uC911\uC694 Medium",low:"P2 \uBCF4\uD1B5 Low"},Jr={investigating:"\uC870\uC0AC\uC911 Looking into","in-progress":"\uC9C4\uD589\uC911 In progress","in-review":"\uAC80\uD1A0\uC911 In review","on-hold":"\uBCF4\uB958 On hold",done:"\uC644\uB8CC Done"};function jo(n,e){return !e||e.includes(n)?e??n:`${n} ${e}`}function Ht(n){return typeof n=="string"&&ad.has(n)}function $t(n){if(typeof n!="string")return false;if(dd.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(Pt))return false;let e=n.slice(Pt.length);return e.length>=1&&e.length<=20}function Bo(n){if(n.startsWith(Pt))return n.slice(Pt.length)}function Yr(n){if(!n)return null;try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?null:e}catch{return null}}function ld(n){let e=Yr(n);return !!e&&Object.prototype.hasOwnProperty.call(e,"threadTitle")}function gr(n){let e=Yr(n);if(!e)return {};let t=e.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {};let r=t,o={};return Ht(r.priority)&&(o.priority=r.priority),$t(r.state)&&(o.state=r.state),o}function Xr(n,e){let t=Yr(n)??{},r={...gr(n)};return e.priority===null?delete r.priority:e.priority!==void 0&&(r.priority=e.priority),e.state===null?delete r.state:e.state!==void 0&&(r.state=e.state),r.priority===void 0&&r.state===void 0?delete t.threadTitle:t.threadTitle=r,Object.keys(t).length===0?null:JSON.stringify(t)}function ud(n,e=new Map){let t=[];return n.priority&&t.push(jo(cd[n.priority],e.get(n.priority))),n.state&&(n.state.startsWith(Pt)?t.push(Bo(n.state)??""):Jr[n.state]?t.push(jo(Jr[n.state],e.get(n.state))):e.has(n.state)?t.push(n.state,e.get(n.state)??""):n.state.startsWith("c_")?t.push(n.state):t.push(Jr[n.state]??"")),t.filter(Boolean).join(" ")}function Fo(n,e){if(!n||n.trim().length===0)return;let t=new Set,r=false,o=false;for(let s of n.split(",")){let i=s.trim();if(i){if(i==="none"){r=true,o=true;continue}e(i)&&(t.add(i),o=true);}}if(o)return {values:t,includeNone:r}}function hd(n){return Fo(n,Ht)}function gd(n){return Fo(n,$t)}function pd(n,e){return e?n?e.values.has(n):e.includeNone:true}var Vo="regeneration_replaced",kd="THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS",Ko="THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED",Td="THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED",Jo="THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED",mr=class extends c{threadId;highlightId;expectedRevision;currentRevision;constructor(e,t,r,o){super("CONFLICT",`Highlight revision conflict: expected ${r}, current ${o}`),this.name="ThreadHistoryConflictError",this.threadId=e,this.highlightId=t,this.expectedRevision=r,this.currentRevision=o;}},bt=class extends mr{},wr=class extends c{stableCode="THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS";run;constructor(e){super("CONFLICT","THREAD_HIGHLIGHT_REGENERATION_IN_PROGRESS"),this.name="ThreadHighlightRegenerationConflictError",this.run=e;}},yd=new Set(xn),Rd=new Set(An),Ed=new Set(Ln),bd=new Set(Pn),Id=50,zo=100,Go=280,Wo=40,Sd=new Set(Hn),pr=["queued","running"],vd=["success","completed","done","failed","error"];function Zr(n){return Sd.has(n)}function F(n){throw new c("VALIDATION",n)}function Oe(n){throw new c("NOT_FOUND",n)}function I(n,e){(typeof n!="string"||n.trim().length===0)&&F(`${e} is required`);}function Mt(n={}){let e=n.actor??n,t=e.actorType??"system";return yd.has(t)||F(`invalid actorType: ${String(t)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&F("actorId must be a string or null"),{actorType:t,actorId:e.actorId??null}}function Cd(n){I(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&I(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&F("title must not be empty"),n.title.length>120&&F("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!Ht(n.priority)&&F(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!$t(n.state)&&F(`invalid state: ${String(n.state)}`);}function Dd(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&F("beforeSeq and afterSeq cannot be used together");for(let[t,r]of [["beforeSeq",n.beforeSeq],["afterSeq",n.afterSeq]])r!==void 0&&(!Number.isInteger(r)||r<0)&&F(`${t} must be a non-negative integer`);let e=n.limit??Id;return (!Number.isInteger(e)||e<1||e>zo)&&F(`limit must be between 1 and ${zo}`),e}function tn(n){typeof n!="string"&&F("text is required");let e=n.trim();return e.length===0&&F("text must not be empty"),e.length>Go&&F(`text must be at most ${Go} characters`),e}function Xe(n,e){return I(n??"",e),n}function rn(n){bd.has(n)||F(`invalid highlight kind: ${String(n)}`);}function Nd(n){Ed.has(n)||F(`invalid highlight source: ${String(n)}`);}function Od(n){I(n.threadId,"threadId"),I(n.workspaceId,"workspaceId");let e=n.source??"manual";Nd(e),rn(n.kind);let t=tn(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,o=n.coversToTaskId??n.toTaskId??n.taskId;if(e==="manual"){let h=n.taskId??(r&&o&&r===o?r:void 0),g=Xe(h,"taskId");return (r!==g||o!==g)&&F("manual highlights must cover exactly one task"),{source:e,kind:n.kind,text:t,coversFromTaskId:g,coversToTaskId:g,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=Xe(r,"coversFromTaskId"),i=Xe(o,"coversToTaskId"),d=n.sourceTaskId??s,l=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),u=n.contentFingerprint??n.idempotencyKey??null;return Xe(d??void 0,"sourceTaskId"),Xe(l??void 0,"detectorVersion"),Xe(u??void 0,"contentFingerprint"),{source:e,kind:n.kind,text:t,coversFromTaskId:s,coversToTaskId:i,agentId:n.agentId??null,sourceTaskId:d,detectorVersion:l,contentFingerprint:u}}function Ad(n,e){(!n||typeof n!="object")&&F(`candidates[${e}] is required`),rn(n.kind);let t=tn(n.text),r=Xe(n.anchorTaskId,`candidates[${e}].anchorTaskId`),o=Xe(n.coversFromTaskId,`candidates[${e}].coversFromTaskId`),s=Xe(n.coversToTaskId,`candidates[${e}].coversToTaskId`),i=n.contentFingerprint?.trim()||Wn("thl",JSON.stringify({kind:n.kind,text:t,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s}));return I(i,`candidates[${e}].contentFingerprint`),{kind:n.kind,text:t,anchorTaskId:r,coversFromTaskId:o,coversToTaskId:s,contentFingerprint:i}}function xd(n){Array.isArray(n)||F("candidates must be an array"),n.length>Wo&&F(`candidates must contain at most ${Wo} items`);let e=new Map;for(let[t,r]of n.entries()){let o=Ad(r,t);e.set(o.contentFingerprint,o);}return [...e.values()]}function Ut(n){let e=gr(n.metadata);return {threadId:n.id,workspaceId:n.workspace_id,title:n.title,priority:e.priority??null,state:e.state??null,metadata:n.metadata,titleLocked:n.title_locked===1,updatedAt:n.updated_at}}function Ld(n){try{let e=JSON.stringify(n);return (!e||e==="null"||e.startsWith("["))&&F("event payload must be a JSON object"),e}catch(e){throw new c("VALIDATION","event payload must be JSON serializable",e)}}function qt(n,e){return n.select({maxSeq:sql`COALESCE(MAX(${M.seq}), 0)`}).from(M).where(eq(M.thread_id,e)).get()?.maxSeq??0}function Bt(n,e){return !!n.select({id:M.id}).from(M).where(eq(M.thread_id,e)).limit(1).get()}function lt(n,e){Rd.has(e.type)||F(`invalid thread event type: ${String(e.type)}`);let t=fe("the");n.insert(M).values({id:t,thread_id:e.threadId,seq:e.seq,type:e.type,actor_type:e.actorType,actor_id:e.actorId,task_id:e.taskId??null,highlight_id:e.highlightId??null,payload_json:Ld(e.payload),created_at:e.createdAt}).run();let r=n.select().from(M).where(eq(M.id,t)).get();if(!r)throw new c("DB_ERROR","Thread event insert did not return a row");return r}function Ft(n,e,t,r,o){let s=Ut(e);lt(n,{threadId:e.id,seq:o,type:"thread.snapshot.imported",actorType:t.actorType,actorId:t.actorId,createdAt:r,payload:{title:s.title,priority:s.priority,state:s.state}});}function fr(n){return {highlightId:n.id,source:n.source,kind:n.kind,status:n.status,coversFromTaskId:n.covers_from_task_id,coversToTaskId:n.covers_to_task_id,revision:n.revision,...n.dismissed_at===null?{}:{dismissedAt:n.dismissed_at}}}function _r(n,e,t,r,o,s,i){let d=o==="thread.highlight.created"?fr(e):{before:i?fr({...e,...i,id:e.id}):void 0,after:fr(e)};return lt(n,{threadId:e.thread_id,seq:s,type:o,actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.source==="manual"?e.covers_from_task_id:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:d})}function Pd(n,e,t,r,o,s){return lt(n,{threadId:e.thread_id,seq:o,type:"thread.highlight.deleted",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.source_task_id??e.covers_from_task_id,highlightId:e.id,payload:{before:fr(e),...s??{}}})}var en=class extends x{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 c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}findThread(e,t,r){let o=eq(_.id,t),s=r===void 0?o:r===null?and(o,isNull(_.workspace_id)):and(o,eq(_.workspace_id,r));return e.select().from(_).where(s).limit(1).get()}findRegenerationRun(e,t,r){let o=e.select().from(A).where(eq(A.id,t)).limit(1).get();if(o&&!(r!==void 0&&!this.findThread(e,o.thread_id,r)))return o}resolveWorkspaceId(e){if(I(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let t=this.openHandle(false);try{return t.db.select({workspaceId:_.workspace_id}).from(_).where(eq(_.id,e)).limit(1).get()?.workspaceId??null}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to resolve thread workspace",r)}finally{t.close();}}getSnapshot(e,t){if(I(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,t);return o?Ut(o):null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){Cd(e);let t=Mt(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||Oe(`Thread ${e.threadId} not found`);let d=Ut(i),l=e.title!==void 0,u=l&&e.title!==d.title,h=l&&i.title_locked!==1,g=e.priority!==void 0&&e.priority!==d.priority,p=e.state!==void 0&&e.state!==d.state,f=u||g||p;if(!f&&!h)return d;let D=i.metadata;(g||p)&&(D=Xr(i.metadata,{priority:e.priority,state:e.state}));let w={};if(f&&(w.metadata=D,w.updated_at=r),u&&(w.title=e.title),l&&(w.title_locked=1),s.update(_).set(w).where(e.workspaceId===void 0?eq(_.id,e.threadId):e.workspaceId===null?and(eq(_.id,e.threadId),isNull(_.workspace_id)):and(eq(_.id,e.threadId),eq(_.workspace_id,e.workspaceId))).run(),!f){let K={...i,title_locked:1};return Ut(K)}let S=qt(s,i.id)+1;Bt(s,i.id)||(Ft(s,i,t,r,S),S+=1),u&&(lt(s,{threadId:i.id,seq:S,type:"thread.title.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),S+=1),g&&(lt(s,{threadId:i.id,seq:S,type:"thread.priority.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),S+=1),p&<(s,{threadId:i.id,seq:S,type:"thread.state.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let E={...i,title:u?e.title:i.title,metadata:D,title_locked:l?1:i.title_locked,updated_at:r};return Ut(E)},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to update thread snapshot",s)}finally{o.close();}}mutateSnapshot(e){return this.updateSnapshot(e)}updateThreadSnapshot(e){return this.updateSnapshot(e)}getLatestSeq(e,t){if(I(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,t)?r.db.select({maxSeq:sql`COALESCE(MAX(${M.seq}), 0)`}).from(M).where(eq(M.thread_id,e)).get()?.maxSeq??0:null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read latest thread event sequence",o)}finally{r.close();}}listCompletedThreadHighlightTurns(e,t){if(I(e,"threadId"),I(t,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findThread(r.db,e,t)?r.db.select({taskId:a.id,prompt:a.prompt,result:a.result,status:a.status,startedAt:a.started_at,completedAt:a.completed_at}).from(a).where(and(eq(a.thread_id,e),eq(a.workspace_id,t),inArray(a.status,vd),or(isNull(a.parent_task_id),eq(a.parent_task_id,"")),sql`${a.result} IS NOT NULL AND length(trim(${a.result})) > 0`)).orderBy(asc(a.started_at),asc(a.id)).all().map(i=>({taskId:i.taskId,prompt:i.prompt,result:i.result,status:i.status,startedAt:i.startedAt,completedAt:i.completedAt})):null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read completed thread highlight turns",o)}finally{r.close();}}createHighlightRegenerationRun(e){I(e.threadId,"threadId"),I(e.workspaceId,"workspaceId"),I(e.requestId,"requestId"),I(e.detectorVersion,"detectorVersion"),e.runId!==void 0&&I(e.runId,"runId");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findThread(o,e.threadId,e.workspaceId);s||Oe(`Thread ${e.threadId} not found`);let i=o.select().from(A).where(and(eq(A.thread_id,s.id),eq(A.request_id,e.requestId))).orderBy(desc(A.requested_at),desc(A.id)).limit(1).get();if(i)return {run:i,created:!1};let d=o.select().from(A).where(and(eq(A.thread_id,s.id),inArray(A.status,pr))).orderBy(asc(A.requested_at),asc(A.id)).limit(1).get();if(d)throw new wr(d);let l=e.runId??fe("thr");o.insert(A).values({id:l,thread_id:s.id,request_id:e.requestId,status:"queued",detector_version:e.detectorVersion,requested_at:t,started_at:null,completed_at:null,error_code:null,previous_auto_count:null,new_auto_count:null}).run();let u=o.select().from(A).where(eq(A.id,l)).get();if(!u)throw new c("DB_ERROR","Highlight regeneration run insert did not return a row");return {run:u,created:!0}},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to create highlight regeneration run",o)}finally{r.close();}}beginHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}queueHighlightRegenerationRun(e){return this.createHighlightRegenerationRun(e)}getHighlightRegenerationRun(e,t){if(I(e,"runId"),t!==void 0&&I(t,"workspaceId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{return this.findRegenerationRun(r.db,e,t)??null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read highlight regeneration run",o)}finally{r.close();}}getHighlightRegenerationRunByRequest(e,t,r){if(I(e,"threadId"),I(t,"workspaceId"),I(r,"requestId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{return this.findThread(o.db,e,t)?o.db.select().from(A).where(and(eq(A.thread_id,e),eq(A.request_id,r))).orderBy(desc(A.requested_at),desc(A.id)).limit(1).get()??null:null}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to read highlight regeneration request",s)}finally{o.close();}}findHighlightRegenerationRun(e,t,r){return this.getHighlightRegenerationRunByRequest(e,t,r)}startHighlightRegenerationRun(e,t){I(e,"runId"),t!==void 0&&I(t,"workspaceId");let r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findRegenerationRun(s,e,t);if(i||Oe(`Highlight regeneration run ${e} not found`),Zr(i.status)||F(`invalid highlight regeneration status: ${i.status}`),i.status!=="queued")return i;s.update(A).set({status:"running",started_at:r}).where(and(eq(A.id,i.id),eq(A.status,"queued"))).run();let d=s.select().from(A).where(eq(A.id,i.id)).get();if(!d)throw new c("DB_ERROR","Highlight regeneration run start did not return a row");return d},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to start highlight regeneration run",s)}finally{o.close();}}startHighlightRegeneration(e,t){return this.startHighlightRegenerationRun(e,t)}failHighlightRegenerationRun(e){I(e.runId,"runId"),I(e.errorCode,"errorCode"),e.workspaceId!==void 0&&I(e.workspaceId,"workspaceId");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>{let s=this.findRegenerationRun(o,e.runId,e.workspaceId);if(s||Oe(`Highlight regeneration run ${e.runId} not found`),Zr(s.status)||F(`invalid highlight regeneration status: ${s.status}`),s.status==="completed"||s.status==="failed")return s;o.update(A).set({status:"failed",completed_at:t,error_code:e.errorCode}).where(and(eq(A.id,s.id),inArray(A.status,pr))).run();let i=o.select().from(A).where(eq(A.id,s.id)).get();if(!i)throw new c("DB_ERROR","Highlight regeneration run failure did not return a row");return i},{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to fail highlight regeneration run",o)}finally{r.close();}}failHighlightRegeneration(e){return this.failHighlightRegenerationRun(e)}recoverInterruptedHighlightRegenerationRuns(e=Ko){I(e,"errorCode");let t=new Date().toISOString(),r=this.openHandle(true);try{return r.db.transaction(o=>o.update(A).set({status:"failed",completed_at:t,error_code:e}).where(inArray(A.status,pr)).run().changes,{behavior:"immediate"})}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to recover interrupted highlight runs",o)}finally{r.close();}}completeHighlightRegenerationRun(e){I(e.runId,"runId"),I(e.threadId,"threadId"),I(e.workspaceId,"workspaceId"),I(e.detectorVersion,"detectorVersion");let t=xd(e.candidates),r=Mt(e),o=this.openHandle(true),s=false;try{return o.db.transaction(i=>{let d=this.findRegenerationRun(i,e.runId,e.workspaceId);if((!d||d.thread_id!==e.threadId)&&Oe(`Highlight regeneration run ${e.runId} not found`),Zr(d.status)||F(`invalid highlight regeneration status: ${d.status}`),d.status==="failed")throw new c("CONFLICT","Highlight regeneration run has already failed");if(d.status==="completed")return {run:d,deletedCount:0,createdCount:0,previousAutoCount:d.previous_auto_count??0,newAutoCount:d.new_auto_count??0};s=!0;let l=this.findThread(i,e.threadId,e.workspaceId);l||Oe(`Thread ${e.threadId} not found`),d.detector_version!==e.detectorVersion&&F("detectorVersion does not match the regeneration run");let u=i.select().from(v).where(eq(v.thread_id,l.id)).orderBy(asc(v.created_at),asc(v.id)).all(),h=new Set(t.map(H=>H.contentFingerprint)),g=u.filter(H=>H.source==="auto"&&H.status==="active"&&H.revision===0&&!h.has(H.content_fingerprint??"")),p=u.filter(H=>H.source==="auto"&&H.status==="active").length,f=new Set(u.filter(H=>!g.includes(H)&&H.content_fingerprint).map(H=>H.content_fingerprint)),D=t.filter(H=>!f.has(H.contentFingerprint)),w=new Date().toISOString(),S=qt(i,l.id)+1;Bt(i,l.id)||(Ft(i,l,r,w,S),S+=1);for(let H of g)i.delete(v).where(eq(v.id,H.id)).run(),Pd(i,H,r,w,S,{runId:e.runId,reason:Vo}),S+=1;let E=0,K=e.agentId??(r.actorType==="agent"?r.actorId:null);for(let H of D){let gn=fe("thl");i.insert(v).values({id:gn,thread_id:l.id,source:"auto",kind:H.kind,status:"active",text:H.text,covers_from_task_id:H.coversFromTaskId,covers_to_task_id:H.coversToTaskId,revision:0,created_at:w,updated_at:w,agent_id:K,source_task_id:H.anchorTaskId,detector_version:e.detectorVersion,content_fingerprint:H.contentFingerprint,dismissed_at:null}).run();let pn=i.select().from(v).where(eq(v.id,gn)).get();if(!pn)throw new c("DB_ERROR","Regenerated highlight insert did not return a row");_r(i,pn,r,w,"thread.highlight.created",S),S+=1,E+=1;}let le=i.select().from(v).where(eq(v.thread_id,l.id)).all().filter(H=>H.source==="auto"&&H.status==="active").length;lt(i,{threadId:l.id,seq:S,type:"thread.highlights.regenerated",actorType:r.actorType,actorId:r.actorId,createdAt:w,payload:{runId:d.id,detectorVersion:e.detectorVersion,previousAutoCount:p,newAutoCount:le,deletedCount:g.length,createdCount:E}}),i.update(A).set({status:"completed",started_at:d.started_at??w,completed_at:w,error_code:null,previous_auto_count:p,new_auto_count:le}).where(and(eq(A.id,d.id),inArray(A.status,pr))).run();let ke=i.select().from(A).where(eq(A.id,d.id)).get();if(!ke)throw new c("DB_ERROR","Highlight regeneration completion did not return a row");return {run:ke,deletedCount:g.length,createdCount:E,previousAutoCount:p,newAutoCount:le}},{behavior:"immediate"})}catch(i){if(s)try{this.failHighlightRegenerationRun({runId:e.runId,workspaceId:e.workspaceId,errorCode:Jo});}catch{}throw i instanceof c?i:new c("DB_ERROR","Failed to complete highlight regeneration",i)}finally{o.close();}}completeHighlightRegeneration(e){return this.completeHighlightRegenerationRun(e)}replaceAutoHighlightsAtomically(e){return this.completeHighlightRegenerationRun(e)}listTimeline(e,t,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:t}:e;I(o.threadId,"threadId"),I(o.workspaceId,"workspaceId");let s=Dd(o);if(!existsSync(this.resolveDbPath()))return null;let i=this.openHandle(false);try{if(!this.findThread(i.db,o.threadId,o.workspaceId))return null;let d=i.db.select({maxSeq:sql`COALESCE(MAX(${M.seq}), 0)`}).from(M).where(eq(M.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(M).where(and(eq(M.thread_id,o.threadId),lt$1(M.seq,o.beforeSeq))).orderBy(desc(M.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(M).where(and(eq(M.thread_id,o.threadId),sql`${M.seq} > ${o.afterSeq}`)).orderBy(asc(M.seq)).limit(s+1).all():l=i.db.select().from(M).where(eq(M.thread_id,o.threadId)).orderBy(desc(M.seq)).limit(s+1).all().reverse();let u=l.length>s,h=o.afterSeq!==void 0?l.slice(0,s):u?l.slice(1):l,g=!1,p=h[0];return p&&(g=!!i.db.select({id:M.id}).from(M).where(and(eq(M.thread_id,o.threadId),lt$1(M.seq,p.seq))).limit(1).get()),{items:h,latestSeq:d,hasMoreOlder:g}}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to list thread timeline",d)}finally{i.close();}}listEvents(e,t,r){return this.listTimeline(e,t,r)}getTimeline(e,t,r){return this.listTimeline(e,t,r)}createHighlight(e){let t=Od(e),r=Mt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);if(d||Oe(`Thread ${e.threadId} not found`),t.source==="auto"){let p=i.select().from(v).where(and(eq(v.thread_id,e.threadId),eq(v.source_task_id,t.sourceTaskId),eq(v.detector_version,t.detectorVersion),eq(v.content_fingerprint,t.contentFingerprint))).orderBy(asc(v.created_at),asc(v.id)).limit(1).get();if(p)return p}let l=e.id??fe("thl"),u={id:l,thread_id:e.threadId,source:t.source,kind:t.kind,status:"active",text:t.text,covers_from_task_id:t.coversFromTaskId,covers_to_task_id:t.coversToTaskId,revision:0,created_at:o,updated_at:o,agent_id:t.agentId,source_task_id:t.sourceTaskId,detector_version:t.detectorVersion,content_fingerprint:t.contentFingerprint,dismissed_at:null};i.insert(v).values(u).run();let h=i.select().from(v).where(eq(v.id,l)).get();if(!h)throw new c("DB_ERROR","Highlight insert did not return a row");let g=qt(i,d.id)+1;return Bt(i,d.id)||(Ft(i,d,r,o,g),g+=1),_r(i,h,r,o,"thread.highlight.created",g),h},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){I(e.threadId,"threadId"),I(e.workspaceId,"workspaceId"),I(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&F("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&F("highlight update requires at least one field"),e.kind!==void 0&&rn(e.kind);let t=e.text===void 0?void 0:tn(e.text),r=Mt(e),o=new Date().toISOString(),s=this.openHandle(true);try{return s.db.transaction(i=>{let d=this.findThread(i,e.threadId,e.workspaceId);d||Oe(`Thread ${e.threadId} not found`);let l=i.select().from(v).where(and(eq(v.id,e.highlightId),eq(v.thread_id,d.id))).limit(1).get();if(l||Oe(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new bt(d.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new bt(d.id,l.id,e.expectedRevision,l.revision);let u=e.kind??l.kind,h=t??l.text,g=e.coversFromTaskId??l.covers_from_task_id,p=e.coversToTaskId??l.covers_to_task_id;(!h||g.length===0||p.length===0)&&F("highlight projection is incomplete");let f=u!==l.kind||h!==l.text||g!==l.covers_from_task_id||p!==l.covers_to_task_id,D=r.actorType==="user"&&l.source==="auto"&&f?"manual":l.source;if(!(f||D!==l.source))return l;let S=l.revision+1;i.update(v).set({source:D,kind:u,text:h,covers_from_task_id:g,covers_to_task_id:p,revision:S,updated_at:o}).where(and(eq(v.id,l.id),eq(v.revision,l.revision))).run();let E=i.select().from(v).where(eq(v.id,l.id)).get();if(!E)throw new c("DB_ERROR","Highlight update did not return a row");let K=qt(i,d.id)+1;return Bt(i,d.id)||(Ft(i,d,r,o,K),K+=1),_r(i,E,r,o,"thread.highlight.updated",K,l),E},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){I(e.threadId,"threadId"),I(e.workspaceId,"workspaceId"),I(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&F("expectedRevision must be a non-negative integer");let t=Mt(e),r=new Date().toISOString(),o=this.openHandle(true);try{return o.db.transaction(s=>{let i=this.findThread(s,e.threadId,e.workspaceId);i||Oe(`Thread ${e.threadId} not found`);let d=s.select().from(v).where(and(eq(v.id,e.highlightId),eq(v.thread_id,i.id))).limit(1).get();if(d||Oe(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new bt(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let l=d.revision+1;s.update(v).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(and(eq(v.id,d.id),eq(v.revision,d.revision))).run();let u=s.select().from(v).where(eq(v.id,d.id)).get();if(!u)throw new c("DB_ERROR","Highlight dismissal did not return a row");let h=qt(s,i.id)+1;return Bt(s,i.id)||(Ft(s,i,t,r,h),h+=1),_r(s,u,t,r,"thread.highlight.deleted",h,d),u},{behavior:"immediate"})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to dismiss thread highlight",s)}finally{o.close();}}listActiveHighlights(e,t,r={}){if(I(e,"threadId"),I(t,"workspaceId"),r.taskId!==void 0&&I(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&I(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&I(r.coversToTaskId,"coversToTaskId"),!existsSync(this.resolveDbPath()))return null;let o=this.openHandle(false);try{if(!this.findThread(o.db,e,t))return null;let i=o.db.select().from(v).where(and(eq(v.thread_id,e),eq(v.status,"active"))).orderBy(asc(v.created_at),asc(v.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(sql`
|
|
366
366
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
367
367
|
ORDER BY started_at ASC, id ASC
|
|
368
|
-
`),l=new Map(d.map((p,f)=>[p.id,f])),u=r.taskId===void 0?void 0:l.get(r.taskId),h=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),g=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(p=>{let f=l.get(p.covers_from_task_id),D=l.get(p.covers_to_task_id);if(f===void 0||D===void 0)return !1;let w=Math.min(f,D),S=Math.max(f,D);return !(u!==void 0&&(u<w||u>S)||h!==void 0&&S<h||g!==void 0&&w>g)})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}getActiveHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}};var nn=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Ue).values(e).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert span",r)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Ue).where(eq(Ue.task_id,e)).all()}catch(r){throw new c("DB_ERROR","Failed to find spans by task id",r)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(Ue).where(eq(Ue.id,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to find span by id",r)}finally{t.close();}}};var on=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(xe).values(e).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert tool call",r)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(xe).where(eq(xe.task_id,e)).all()}catch(r){throw new c("DB_ERROR","Failed to find tool calls by task id",r)}finally{t.close();}}aggregateByName(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select({toolName:xe.tool_name,count:sql`count(*)`}).from(xe).where(eq(xe.task_id,e)).groupBy(xe.tool_name).all().map(r=>({toolName:r.toolName,count:r.count}))}catch(r){throw new c("DB_ERROR","Failed to aggregate tool calls by name",r)}finally{t.close();}}};var sn=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,t){if(!e.db.select({id:_.id}).from(_).where(eq(_.id,t)).limit(1).get())throw new c("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(r){throw r instanceof c?r:new c("DB_ERROR","Failed to find boxes by thread id",r)}finally{t.close();}}findById(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.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 c?o:new c("DB_ERROR","Failed to find box by id",o)}finally{r.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 c("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let r=t.db.select().from(Re).where(eq(Re.id,e.id)).limit(1).get();if(!r)throw new c("DB_ERROR","Insert did not return a row");return r}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert thread box",r)}finally{t.close();}}};var an=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}bulkInsert(e){if(e.length===0)return;let t=this.openHandle(true);try{t.db.transaction(r=>{for(let o of e)r.insert(gt).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:o.timestamp??new Date().toISOString(),metadata:o.metadata??null}).run();});}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to bulk insert request logs",r)}finally{t.close();}}findRecent(e=100){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(gt).orderBy(desc(gt.timestamp)).limit(e).all()}catch(r){throw new c("DB_ERROR","Failed to find recent request logs",r)}finally{t.close();}}};function rs(n){return new Date(Math.floor(n/3e5)*3e5).toISOString()}var dn=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}upsert(e){let t=this.openHandle(true);try{let r=rs(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(te).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:r,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:[te.provider,te.account_ref,te.limit_window,te.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(r){throw r instanceof c?r:new c("DB_ERROR","Failed to upsert usage limit snapshot",r)}finally{t.close();}}getTrends(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=t.db.select({provider:te.provider,bucket_start:te.bucket_start,used_percent:te.used_percent,remaining_percent:te.remaining_percent,resets_at:te.resets_at}).from(te).where(and(eq(te.limit_window,e.window),gte(te.bucket_start,e.fromIso),lte(te.bucket_start,e.toIso))).orderBy(asc(te.bucket_start)).all(),o=new Map;for(let s of r)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,i])=>({provider:s,points:i}))}catch(r){throw new c("DB_ERROR","Failed to get usage limit trends",r)}finally{t.close();}}};var cn=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}publish(e){let t=this.openHandle(true);try{t.db.insert(le).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:[le.workspace_id,le.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 r=t.db.select().from(le).where(and(eq(le.workspace_id,e.workspaceId),eq(le.month,e.month))).limit(1).get();if(!r)throw new c("DB_ERROR","Failed to read back published usage report");return r}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to publish usage report",r)}finally{t.close();}}findByMonth(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(le).where(and(eq(le.workspace_id,e),eq(le.month,t))).limit(1).get()??void 0}catch(o){throw new c("DB_ERROR","Failed to find usage report",o)}finally{r.close();}}listByWorkspace(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(le).where(eq(le.workspace_id,e)).orderBy(desc(le.month)).all()}catch(r){throw new c("DB_ERROR","Failed to list usage reports",r)}finally{t.close();}}};var cs=500,ls=50,ln=class extends x{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??cs;}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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=fe("ntf"),o=new Date().toISOString();return t.db.insert(O).values({id:r,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:r}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to create notification",r)}finally{t.close();}}enforceCap(e,t){let s=(e.db.select({count:sql`count(*)`}).from(O).where(eq(O.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:O.id}).from(O).innerJoin(X,eq(X.notification_id,O.id)).where(eq(O.workspace_id,t)).groupBy(O.id).orderBy(asc(O.created_at)).limit(s).all().map(l=>l.id);d.length!==0&&(e.db.delete(X).where(inArray(X.notification_id,d)).run(),e.db.delete(O).where(inArray(O.id,d)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??ls,r=this.openHandle(false);try{return r.db.select({id:O.id,workspace_id:O.workspace_id,agent_id:O.agent_id,task_id:O.task_id,thread_id:O.thread_id,source:O.source,level:O.level,title:O.title,body:O.body,target_user_id:O.target_user_id,created_at:O.created_at,metadata:O.metadata,read_at:X.read_at}).from(O).leftJoin(X,and(eq(X.notification_id,O.id),eq(X.user_id,e.userId))).where(eq(O.workspace_id,e.workspaceId)).orderBy(desc(O.created_at)).limit(t).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new c("DB_ERROR","Failed to list notifications",o)}finally{r.close();}}unreadCount(e){if(!this.dbExists())return 0;let t=this.openHandle(false);try{return t.db.select({count:sql`count(*)`}).from(O).leftJoin(X,and(eq(X.notification_id,O.id),eq(X.user_id,e.userId))).where(and(eq(O.workspace_id,e.workspaceId),isNull(X.notification_id))).get()?.count??0}catch(r){throw new c("DB_ERROR","Failed to count unread notifications",r)}finally{t.close();}}markRead(e){let t=this.openHandle(true);try{if(!t.db.select({id:O.id}).from(O).where(and(eq(O.id,e.notificationId),eq(O.workspace_id,e.workspaceId))).get())throw new c("NOT_FOUND","Notification not found in workspace");return t.db.insert(X).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark notification read",r)}finally{t.close();}}markAllRead(e){let t=this.openHandle(true);try{let r=t.db.select({id:O.id}).from(O).leftJoin(X,and(eq(X.notification_id,O.id),eq(X.user_id,e.userId))).where(and(eq(O.workspace_id,e.workspaceId),isNull(X.notification_id))).all();if(r.length===0)return 0;let o=new Date().toISOString();return t.db.transaction(s=>{for(let i of r)s.insert(X).values({notification_id:i.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),r.length}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark all notifications read",r)}finally{t.close();}}};var gs=50,hn=class extends x{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 c("NOT_FOUND","Database not found");let r=T(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=new Date().toISOString(),o=[],s=e.map(i=>{let d=fe("sug");return o.push(d),{id:d,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:r,updated_at:r}});return s.length>0&&t.db.insert(L).values(s).run(),{ids:o}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to create agent suggestions",r)}finally{t.close();}}findLatestSet(e,t){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({task_id:L.task_id}).from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t))).orderBy(desc(L.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(L.task_id):eq(L.task_id,o.task_id);return r.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t),s)).orderBy(asc(L.created_at)).all()}catch(o){throw new c("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{r.close();}}findSetByTaskId(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t),eq(L.task_id,r))).orderBy(asc(L.created_at)).all()}catch(s){throw new c("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,t,r){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t),eq(L.id,r))).get()??null}catch(s){throw new c("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,t,r){let o=this.openHandle(true);try{let s={status:t,updated_at:new Date().toISOString()};return r!==void 0&&(s.applied_commit_sha=r),o.db.update(L).set(s).where(eq(L.id,e)).run().changes>0}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,t,r=gs){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t))).orderBy(desc(L.created_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,t,r=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t),eq(L.status,"dismissed"))).orderBy(desc(L.updated_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{hn as AgentSuggestionRepository,Mo as BUILTIN_THREAD_STATES,x as BaseSqliteRepository,Zt as COMMON_CODE_COLORS,Qt as COMMON_CODE_GROUPS,mn as CREWX_JOURNAL_SIZE_LIMIT_BYTES,Cr as CommonCodeRepository,W as CommonCodeRepositoryError,gs as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,cs as DEFAULT_NOTIFICATION_CAP,ls as DEFAULT_NOTIFICATION_LIST_LIMIT,Xn as DEFAULT_PROJECT_STAGES,Pr as DEFAULT_PROJECT_STAGE_KEYS,ln as NotificationRepository,Lr as ProjectRepository,c as RepositoryError,an as RequestLogRepository,nn as SpanRepository,yo as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,cr as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,To as TASK_LOG_MIGRATION_TERMINAL_STATUSES,Wo as THREAD_HIGHLIGHT_DELETION_REASON_REGENERATION_REPLACED,Ko as THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED,Td as THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED,Vo as THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED,kd as THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS,jo as THREAD_PRIORITIES,Ot as TaskLogRepository,Mr as TaskRepository,sn as ThreadBoxRepository,bt as ThreadHighlightConflictError,wr as ThreadHighlightRegenerationConflictError,mr as ThreadHistoryConflictError,en as ThreadHistoryRepository,Gr as ThreadRepository,ct as ThreadTitleMetadataPatchError,on as ToolCallRepository,dn as UsageLimitSnapshotRepository,cn as UsageReportRepository,Ar as WorkspaceRepository,rs as calcBucketStart,qo as customStateLabel,mt as generateCommonCodeId,So as hasSufficientTaskLogMigrationFreeSpace,ld as hasThreadTitleKey,Ht as isThreadPriority,$t as isThreadState,pd as matchesThreadTitleFilter,Xr as mergeThreadTitleMeta,Ho as migrateLegacyThreadTitleCommonCodes,id as migrateThreadTitleCommonCodes,T as openDrizzleDb,hd as parseThreadPriorityFilter,gd as parseThreadStateFilter,Yi as pushSchema,gr as readThreadTitleMeta,ys as reclaimTemporaryJournal,Ro as resolveTaskLogMigrationDbPath,ut as runMigrations,$ as runMigrationsOnce,Ba as runTaskLogMigration,Fa as taskLogBackupName,a as tasks,ud as threadTitleSearchHaystack,Do as tryCheckpointTaskLogWal};
|
|
368
|
+
`),l=new Map(d.map((p,f)=>[p.id,f])),u=r.taskId===void 0?void 0:l.get(r.taskId),h=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),g=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(p=>{let f=l.get(p.covers_from_task_id),D=l.get(p.covers_to_task_id);if(f===void 0||D===void 0)return !1;let w=Math.min(f,D),S=Math.max(f,D);return !(u!==void 0&&(u<w||u>S)||h!==void 0&&S<h||g!==void 0&&w>g)})}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to list active thread highlights",s)}finally{o.close();}}listHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}getActiveHighlights(e,t,r){return this.listActiveHighlights(e,t,r)}};var nn=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Ue).values(e).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert span",r)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(Ue).where(eq(Ue.task_id,e)).all()}catch(r){throw new c("DB_ERROR","Failed to find spans by task id",r)}finally{t.close();}}findById(e){if(!this.dbExists())return;let t=this.openHandle(false);try{return t.db.select().from(Ue).where(eq(Ue.id,e)).limit(1).get()??void 0}catch(r){throw new c("DB_ERROR","Failed to find span by id",r)}finally{t.close();}}};var on=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(xe).values(e).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert tool call",r)}finally{t.close();}}findByTaskId(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(xe).where(eq(xe.task_id,e)).all()}catch(r){throw new c("DB_ERROR","Failed to find tool calls by task id",r)}finally{t.close();}}aggregateByName(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select({toolName:xe.tool_name,count:sql`count(*)`}).from(xe).where(eq(xe.task_id,e)).groupBy(xe.tool_name).all().map(r=>({toolName:r.toolName,count:r.count}))}catch(r){throw new c("DB_ERROR","Failed to aggregate tool calls by name",r)}finally{t.close();}}};var sn=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,t){if(!e.db.select({id:_.id}).from(_).where(eq(_.id,t)).limit(1).get())throw new c("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(r){throw r instanceof c?r:new c("DB_ERROR","Failed to find boxes by thread id",r)}finally{t.close();}}findById(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.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 c?o:new c("DB_ERROR","Failed to find box by id",o)}finally{r.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 c("CONFLICT",`Duplicate seq ${String(e.seq)} for thread ${e.threadId}`,o):o}let r=t.db.select().from(Re).where(eq(Re.id,e.id)).limit(1).get();if(!r)throw new c("DB_ERROR","Insert did not return a row");return r}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to insert thread box",r)}finally{t.close();}}};var an=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}bulkInsert(e){if(e.length===0)return;let t=this.openHandle(true);try{t.db.transaction(r=>{for(let o of e)r.insert(gt).values({id:randomUUID(),path:o.path,method:o.method,status_code:o.statusCode,duration_ms:o.durationMs,ip:o.ip??null,request_headers:o.requestHeaders??null,response_headers:o.responseHeaders??null,request_body:o.requestBody??null,response_body:o.responseBody??null,query:o.query??null,user_id:o.userId??null,project_id:o.projectId??null,partition_key:o.partitionKey??"default",timestamp:o.timestamp??new Date().toISOString(),metadata:o.metadata??null}).run();});}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to bulk insert request logs",r)}finally{t.close();}}findRecent(e=100){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(gt).orderBy(desc(gt.timestamp)).limit(e).all()}catch(r){throw new c("DB_ERROR","Failed to find recent request logs",r)}finally{t.close();}}};function ns(n){return new Date(Math.floor(n/3e5)*3e5).toISOString()}var dn=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}upsert(e){let t=this.openHandle(true);try{let r=ns(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(te).values({id:e.id,provider:e.provider,account_ref:o,limit_window:e.limitWindow,bucket_start:r,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:[te.provider,te.account_ref,te.limit_window,te.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(r){throw r instanceof c?r:new c("DB_ERROR","Failed to upsert usage limit snapshot",r)}finally{t.close();}}getTrends(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{let r=t.db.select({provider:te.provider,bucket_start:te.bucket_start,used_percent:te.used_percent,remaining_percent:te.remaining_percent,resets_at:te.resets_at}).from(te).where(and(eq(te.limit_window,e.window),gte(te.bucket_start,e.fromIso),lte(te.bucket_start,e.toIso))).orderBy(asc(te.bucket_start)).all(),o=new Map;for(let s of r)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,i])=>({provider:s,points:i}))}catch(r){throw new c("DB_ERROR","Failed to get usage limit trends",r)}finally{t.close();}}};var cn=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}publish(e){let t=this.openHandle(true);try{t.db.insert(ue).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:[ue.workspace_id,ue.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 r=t.db.select().from(ue).where(and(eq(ue.workspace_id,e.workspaceId),eq(ue.month,e.month))).limit(1).get();if(!r)throw new c("DB_ERROR","Failed to read back published usage report");return r}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to publish usage report",r)}finally{t.close();}}findByMonth(e,t){if(!this.dbExists())return;let r=this.openHandle(false);try{return r.db.select().from(ue).where(and(eq(ue.workspace_id,e),eq(ue.month,t))).limit(1).get()??void 0}catch(o){throw new c("DB_ERROR","Failed to find usage report",o)}finally{r.close();}}listByWorkspace(e){if(!this.dbExists())return [];let t=this.openHandle(false);try{return t.db.select().from(ue).where(eq(ue.workspace_id,e)).orderBy(desc(ue.month)).all()}catch(r){throw new c("DB_ERROR","Failed to list usage reports",r)}finally{t.close();}}};var ls=500,us=50,ln=class extends x{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??ls;}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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=fe("ntf"),o=new Date().toISOString();return t.db.insert(O).values({id:r,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:r}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to create notification",r)}finally{t.close();}}enforceCap(e,t){let s=(e.db.select({count:sql`count(*)`}).from(O).where(eq(O.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:O.id}).from(O).innerJoin(X,eq(X.notification_id,O.id)).where(eq(O.workspace_id,t)).groupBy(O.id).orderBy(asc(O.created_at)).limit(s).all().map(l=>l.id);d.length!==0&&(e.db.delete(X).where(inArray(X.notification_id,d)).run(),e.db.delete(O).where(inArray(O.id,d)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??us,r=this.openHandle(false);try{return r.db.select({id:O.id,workspace_id:O.workspace_id,agent_id:O.agent_id,task_id:O.task_id,thread_id:O.thread_id,source:O.source,level:O.level,title:O.title,body:O.body,target_user_id:O.target_user_id,created_at:O.created_at,metadata:O.metadata,read_at:X.read_at}).from(O).leftJoin(X,and(eq(X.notification_id,O.id),eq(X.user_id,e.userId))).where(eq(O.workspace_id,e.workspaceId)).orderBy(desc(O.created_at)).limit(t).all().map(s=>({...s,read_at:s.read_at??null,read:s.read_at!=null}))}catch(o){throw new c("DB_ERROR","Failed to list notifications",o)}finally{r.close();}}unreadCount(e){if(!this.dbExists())return 0;let t=this.openHandle(false);try{return t.db.select({count:sql`count(*)`}).from(O).leftJoin(X,and(eq(X.notification_id,O.id),eq(X.user_id,e.userId))).where(and(eq(O.workspace_id,e.workspaceId),isNull(X.notification_id))).get()?.count??0}catch(r){throw new c("DB_ERROR","Failed to count unread notifications",r)}finally{t.close();}}markRead(e){let t=this.openHandle(true);try{if(!t.db.select({id:O.id}).from(O).where(and(eq(O.id,e.notificationId),eq(O.workspace_id,e.workspaceId))).get())throw new c("NOT_FOUND","Notification not found in workspace");return t.db.insert(X).values({notification_id:e.notificationId,user_id:e.userId,read_at:new Date().toISOString()}).onConflictDoNothing().run().changes>0}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark notification read",r)}finally{t.close();}}markAllRead(e){let t=this.openHandle(true);try{let r=t.db.select({id:O.id}).from(O).leftJoin(X,and(eq(X.notification_id,O.id),eq(X.user_id,e.userId))).where(and(eq(O.workspace_id,e.workspaceId),isNull(X.notification_id))).all();if(r.length===0)return 0;let o=new Date().toISOString();return t.db.transaction(s=>{for(let i of r)s.insert(X).values({notification_id:i.id,user_id:e.userId,read_at:o}).onConflictDoNothing().run();}),r.length}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to mark all notifications read",r)}finally{t.close();}}};var ps=50,hn=class extends x{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 c("NOT_FOUND","Database not found");let r=y(t);if(e)try{$(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=new Date().toISOString(),o=[],s=e.map(i=>{let d=fe("sug");return o.push(d),{id:d,workspace_id:i.workspaceId,agent_id:i.agentId,task_id:i.taskId??null,type:i.type,status:i.status??"pending",payload:i.payload,applied_commit_sha:i.appliedCommitSha??null,created_at:r,updated_at:r}});return s.length>0&&t.db.insert(L).values(s).run(),{ids:o}}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to create agent suggestions",r)}finally{t.close();}}findLatestSet(e,t){if(!this.dbExists())return [];let r=this.openHandle(false);try{let o=r.db.select({task_id:L.task_id}).from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t))).orderBy(desc(L.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(L.task_id):eq(L.task_id,o.task_id);return r.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t),s)).orderBy(asc(L.created_at)).all()}catch(o){throw new c("DB_ERROR","Failed to find latest agent suggestion set",o)}finally{r.close();}}findSetByTaskId(e,t,r){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t),eq(L.task_id,r))).orderBy(asc(L.created_at)).all()}catch(s){throw new c("DB_ERROR","Failed to find agent suggestion set by task id",s)}finally{o.close();}}findById(e,t,r){if(!this.dbExists())return null;let o=this.openHandle(false);try{return o.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t),eq(L.id,r))).get()??null}catch(s){throw new c("DB_ERROR","Failed to find agent suggestion by id",s)}finally{o.close();}}updateStatus(e,t,r){let o=this.openHandle(true);try{let s={status:t,updated_at:new Date().toISOString()};return r!==void 0&&(s.applied_commit_sha=r),o.db.update(L).set(s).where(eq(L.id,e)).run().changes>0}catch(s){throw s instanceof c?s:new c("DB_ERROR","Failed to update agent suggestion status",s)}finally{o.close();}}listByAgent(e,t,r=ps){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t))).orderBy(desc(L.created_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to list agent suggestions",s)}finally{o.close();}}findDismissed(e,t,r=20){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(L).where(and(eq(L.workspace_id,e),eq(L.agent_id,t),eq(L.status,"dismissed"))).orderBy(desc(L.updated_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{hn as AgentSuggestionRepository,qo as BUILTIN_THREAD_STATES,x as BaseSqliteRepository,Zt as COMMON_CODE_COLORS,Qt as COMMON_CODE_GROUPS,mn as CREWX_JOURNAL_SIZE_LIMIT_BYTES,Cr as CommonCodeRepository,W as CommonCodeRepositoryError,ps as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,ls as DEFAULT_NOTIFICATION_CAP,us as DEFAULT_NOTIFICATION_LIST_LIMIT,Qn as DEFAULT_PROJECT_STAGES,Pr as DEFAULT_PROJECT_STAGE_KEYS,ln as NotificationRepository,Lr as ProjectRepository,c as RepositoryError,an as RequestLogRepository,nn as SpanRepository,Ro as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,cr as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,yo as TASK_LOG_MIGRATION_TERMINAL_STATUSES,Vo as THREAD_HIGHLIGHT_DELETION_REASON_REGENERATION_REPLACED,Jo as THREAD_HIGHLIGHT_REGENERATION_COMMIT_FAILED,Td as THREAD_HIGHLIGHT_REGENERATION_DETECTION_FAILED,Ko as THREAD_HIGHLIGHT_REGENERATION_INTERRUPTED,kd as THREAD_HIGHLIGHT_REGENERATION_NO_ELIGIBLE_TURNS,Mo as THREAD_PRIORITIES,Ot as TaskLogRepository,Mr as TaskRepository,sn as ThreadBoxRepository,bt as ThreadHighlightConflictError,wr as ThreadHighlightRegenerationConflictError,mr as ThreadHistoryConflictError,en as ThreadHistoryRepository,Gr as ThreadRepository,ct as ThreadTitleMetadataPatchError,on as ToolCallRepository,dn as UsageLimitSnapshotRepository,cn as UsageReportRepository,Ar as WorkspaceRepository,ns as calcBucketStart,Bo as customStateLabel,mt as generateCommonCodeId,vo as hasSufficientTaskLogMigrationFreeSpace,ld as hasThreadTitleKey,Ht as isThreadPriority,$t as isThreadState,pd as matchesThreadTitleFilter,Xr as mergeThreadTitleMeta,$o as migrateLegacyThreadTitleCommonCodes,id as migrateThreadTitleCommonCodes,y as openDrizzleDb,hd as parseThreadPriorityFilter,gd as parseThreadStateFilter,Yi as pushSchema,gr as readThreadTitleMeta,Rs as reclaimTemporaryJournal,Eo as resolveTaskLogMigrationDbPath,ut as runMigrations,$ as runMigrationsOnce,Ba as runTaskLogMigration,Fa as taskLogBackupName,a as tasks,ud as threadTitleSearchHaystack,No as tryCheckpointTaskLogWal};
|