@crewx/sdk 0.9.0-rc.78 → 0.9.0-rc.79
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/context-budget/continuity.d.ts +9 -1
- package/dist/context-budget/index.d.ts +2 -1
- package/dist/conversation/sqlite-provider.d.ts +2 -1
- package/dist/conversation/types.d.ts +13 -0
- package/dist/esm/index.js +113 -106
- package/dist/esm/plugins/index.js +113 -113
- package/dist/esm/repository/index.js +15 -15
- package/dist/facade/Crewx.d.ts +3 -3
- package/dist/highlight/thread-highlight-prompt.d.ts +1 -0
- package/dist/highlight/thread-highlighter.d.ts +12 -1
- package/dist/index.browser.js +3 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.js +114 -107
- package/dist/layout/types.d.ts +2 -0
- package/dist/plugins/index.js +113 -113
- package/dist/repository/index.js +15 -15
- package/dist/repository/thread-history.repository.d.ts +1 -0
- package/package.json +1 -1
- package/templates/agents/default.yaml +17 -10
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import*as Ae from'path';import Ae__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as Bn from'fs';import Bn__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import rs,{homedir}from'os';import {randomUUID,createHash,randomBytes}from'crypto';import {sql,and,eq,asc,ne,isNull,desc,isNotNull,gt,lt as lt$1,or as or$1,notLike,like,inArray,gte,lte}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var
|
|
1
|
+
import*as Ae from'path';import Ae__default,{join,dirname,basename,resolve}from'path';import {fileURLToPath}from'url';import*as Bn from'fs';import Bn__default,{existsSync,mkdirSync,readFileSync,statfsSync,statSync}from'fs';import rs,{homedir}from'os';import {randomUUID,createHash,randomBytes}from'crypto';import {sql,and,eq,asc,ne,isNull,desc,isNotNull,gt,lt as lt$1,or as or$1,notLike,like,inArray,gte,lte}from'drizzle-orm';import {sqliteTable,text,integer,real,index,check,uniqueIndex,unique,primaryKey,getTableConfig}from'drizzle-orm/sqlite-core';var rt=(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 Qo=()=>fileURLToPath(import.meta.url),Zo=()=>Ae__default.dirname(Qo()),y=Zo();var D=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(rs.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 Yr=n=>{try{return Bn.statSync(`${n}-wal`).size}catch{return 0}},Qr=32*1024*1024;function k(n){let e=rt("better-sqlite3"),{drizzle:t}=rt("drizzle-orm/better-sqlite3"),r=new e(n);return r.exec("PRAGMA journal_mode = WAL"),r.exec(`PRAGMA journal_size_limit = ${Qr}`),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 ns(n,e="TRUNCATE"){if(e!=="PASSIVE"&&e!=="TRUNCATE")throw new Error(`Unsupported journal reclaim mode: ${e}`);let t=rt("better-sqlite3"),r=Yr(n),o;try{o=new t(n),o.pragma("busy_timeout = 1000");let s=o.pragma(`wal_checkpoint(${e})`),i=Yr(n);return {busy:s[0]?.busy===1,walBytesBefore:r,walBytesAfter:i}}finally{o?.close();}}var Zr=new Set,os={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 ar(n,e){return (n.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function ss(n,e){if(e>0||!ar(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(os))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 as(n,e,t){if(!ar(n,"__drizzle_migrations")||!ar(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(Ae__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=is[i.tag];if(!d)continue;let l=Ae__default.join(e,`${i.tag}.sql`);if(!existsSync(l))continue;let u=readFileSync(l,"utf-8"),p=createHash("sha256").update(u).digest("hex");if(o.has(p))continue;let _=n.all("PRAGMA table_info(tasks)"),g=new Set(_.map(f=>f.name));for(let[f,C]of Object.entries(d))g.has(f)||(n.run(`ALTER TABLE tasks ADD COLUMN ${f} ${C}`),g.add(f));}}function ds(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(Ae__default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let d=Ae__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 p=/ALTER\s+TABLE\s+[`"]?(\w+)[`"]?\s+ADD\s+[`"]?(\w+)[`"]?/gi,_=[],g;for(;(g=p.exec(l))!==null;)_.push({table:g[1],column:g[2]});if(_.length===0||!l.split(/-->\s*statement-breakpoint/).map(w=>w.trim()).filter(Boolean).every(w=>/^ALTER\s+TABLE\s+.+\s+ADD\s+/i.test(w)))continue;_.every(({table:w,column:I})=>n.all(`PRAGMA table_info("${w}")`).some(z=>z.name===I))&&n.run(t`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);}}function nt(n){let{migrate:e}=rt("drizzle-orm/better-sqlite3/migrator"),{sql:t}=rt("drizzle-orm"),r=[Ae__default.join(y,"../migrations"),Ae__default.join(y,"migrations"),Ae__default.join(y,"../../../../drizzle/migrations"),Ae__default.join(process.cwd(),"drizzle/migrations")],o=r.find(u=>existsSync(Ae__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),ss(n,i),s?.cnt&&(ds(n,o,t),as(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 x(n,e){Zr.has(e)||(rt(n),Zr.add(e));}var T=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 Re=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)}));var ws="json_extract(metadata, '$.threadTitle.state')",ks="json_extract(metadata, '$.threadTitle.priority')",h=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>T.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(ws)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(ks))}));var Pe=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(()=>Pe.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 Ee=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 fe=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>h.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 ot=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 Q=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 ie=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 v=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`)})),K=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 O=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),ss(n,i),s?.cnt&&(ds(n,o,t),as(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 x(n,e){Zr.has(e)||(nt(n),Zr.add(e));}var T=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 Re=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)}));var ws="json_extract(metadata, '$.threadTitle.state')",ks="json_extract(metadata, '$.threadTitle.priority')",h=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>T.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(ws)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(n.workspace_id,sql.raw(ks))}));var Pe=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(()=>Pe.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 Ee=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 fe=sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>h.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 st=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 Q=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 ie=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 v=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`)})),K=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 O=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 L=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`)})),ce=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>L.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)})),Te=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>L.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 Ht=["THREAD_STATE","THREAD_PRIORITY"],qt=["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 fn=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted"],mn=["user","agent","system"],wn=["auto","manual"],kn=["decision","judgment","issue","result","pivot"];var P=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>h.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')`),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_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>h.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 J=class extends c{reason;constructor(e,t="VALIDATION",r=e,o){super(t,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Tn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ei(){let n=randomBytes(16),e="";for(let t of n)e+=Tn[t%Tn.length];return e.slice(0,12)}function it(){return `c_${ei()}`}function ti(n){return typeof n=="string"&&Ht.includes(n)}function ri(n){return typeof n=="string"&&qt.includes(n)}function wt(n){if(!ti(n))throw new J("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${n}`)}function bn(n){if(!ri(n))throw new J("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${n}`)}function Rn(n){let e=typeof n=="string"?n.trim():"",t=[...e].length;if(t<1||t>20)throw new J("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function kt(n){if(typeof n!="string"||n.trim().length===0)throw new J("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function gr(n){if(typeof n!="string"||n.trim().length===0)throw new J("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function st(n,e){return and(eq(m.code_group,n),or$1(isNull(m.workspace_id),eq(m.workspace_id,e)))}var fr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new c("NOT_FOUND","Database not found");e&&mkdirSync(dirname(t),{recursive:true});let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}listSelectable(e,t){if(wt(e),kt(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(and(st(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(wt(e),kt(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(st(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();}}resolve(e,t){if(wt(e),gr(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){kt(e.workspaceId);let t=Rn(e.name);bn(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:m.code}).from(m).where(and(st("THREAD_STATE",e.workspaceId),eq(m.is_archived,0),eq(m.code_name,t))).limit(1).get())throw new J("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(st("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),l=it();for(;o.select({code:m.code}).from(m).where(and(eq(m.code_group,"THREAD_STATE"),eq(m.code,l))).limit(1).get();)l=it();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(wt(e.group),gr(e.code),kt(e.workspaceId),e.name===void 0&&e.color===void 0)throw new J("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let t=e.name===void 0||e.name===null?e.name:Rn(e.name);e.color!==void 0&&bn(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 J("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 J("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof t=="string"&&s.is_archived===0){let l=and(st(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 J("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(wt(e),gr(t),kt(r),typeof o!="boolean")throw new J("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 J("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${t}`);if(d.is_builtin===1)throw new J("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(st(e,r),eq(m.is_archived,0),eq(m.code_name,d.code_name),ne(m.code,t))).limit(1).get())throw new J("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 J("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function mr(n){let e=Ae.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 Sn(n){let e=mr(n);return createHash("sha256").update(e).digest("hex")}function zt(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var yr=class extends D{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{rt(r.db);}catch(o){throw r.close(),o}return r}resolveSlug(e,t,r){let o=zt(basename(r)),i=`${zt(basename(dirname(r)))}-${o}`,d=[o,i];try{let l=u=>e.select({id:T.id}).from(T).where(and(eq(T.slug,u),ne(T.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 p=`${i}-${u}`;if(!l(p))return p}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:T.id,slug:T.slug}).from(T).all(),r=0;for(let o of t)if(o.slug.includes("/")){let s=zt(o.slug.replace(/\//g,"-"));e.db.update(T).set({slug:s,updated_at:new Date().toISOString()}).where(eq(T.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(T).values({id:r,slug:o,name:s,workspace_path:i,is_active:1,created_at:d,updated_at:d}).onConflictDoNothing().run(),e.update(T).set({workspace_path:i,updated_at:d}).where(and(eq(T.id,r),isNull(T.workspace_path))).run();}registerWorkspace(e){let t=mr(e),r=this.openHandle(true);try{let o=Sn(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(T.is_active,e.isActive?1:0):void 0,o=t.db.select({count:sql`count(*)`}).from(T).where(r).get();return {rows:t.db.select().from(T).where(r).orderBy(desc(T.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(T).where(eq(T.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 L=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`)})),ce=sqliteTable("project_criteria",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>L.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)})),Te=sqliteTable("project_events",{id:text("id").primaryKey().notNull(),project_id:text("project_id").notNull().references(()=>L.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"],Ft=["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 fn=["thread.snapshot.imported","thread.title.changed","thread.priority.changed","thread.state.changed","thread.highlight.created","thread.highlight.updated","thread.highlight.deleted"],mn=["user","agent","system"],wn=["auto","manual"],kn=["decision","judgment","issue","result","pivot"];var P=sqliteTable("thread_events",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>h.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')`),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_highlights",{id:text("id").primaryKey().notNull(),thread_id:text("thread_id").notNull().references(()=>h.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 J=class extends c{reason;constructor(e,t="VALIDATION",r=e,o){super(t,r,o),this.name="CommonCodeRepositoryError",this.reason=e;}},Tn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function ei(){let n=randomBytes(16),e="";for(let t of n)e+=Tn[t%Tn.length];return e.slice(0,12)}function at(){return `c_${ei()}`}function ti(n){return typeof n=="string"&&qt.includes(n)}function ri(n){return typeof n=="string"&&Ft.includes(n)}function wt(n){if(!ti(n))throw new J("COMMON_CODE_GROUP_INVALID","VALIDATION",`Unsupported common-code group: ${n}`)}function bn(n){if(!ri(n))throw new J("COMMON_CODE_COLOR_INVALID","VALIDATION",`Unsupported common-code color: ${n}`)}function Rn(n){let e=typeof n=="string"?n.trim():"",t=[...e].length;if(t<1||t>20)throw new J("COMMON_CODE_NAME_INVALID","VALIDATION","Common-code names must contain 1 to 20 Unicode characters");return e}function kt(n){if(typeof n!="string"||n.trim().length===0)throw new J("COMMON_CODE_WORKSPACE_INVALID","VALIDATION","Workspace id is required for a user common code")}function gr(n){if(typeof n!="string"||n.trim().length===0)throw new J("COMMON_CODE_CODE_INVALID","VALIDATION","Common-code code is required")}function it(n,e){return and(eq(m.code_group,n),or$1(isNull(m.workspace_id),eq(m.workspace_id,e)))}var fr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new c("NOT_FOUND","Database not found");e&&mkdirSync(dirname(t),{recursive:true});let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}listSelectable(e,t){if(wt(e),kt(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(and(it(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(wt(e),kt(t),!this.dbExists())return [];let r=this.openHandle(false);try{return r.db.select().from(m).where(it(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();}}resolve(e,t){if(wt(e),gr(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){kt(e.workspaceId);let t=Rn(e.name);bn(e.color);let r=this.openHandle(true);try{return r.db.transaction(o=>{if(o.select({code:m.code}).from(m).where(and(it("THREAD_STATE",e.workspaceId),eq(m.is_archived,0),eq(m.code_name,t))).limit(1).get())throw new J("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(it("THREAD_STATE",e.workspaceId)).get(),d=new Date().toISOString(),l=at();for(;o.select({code:m.code}).from(m).where(and(eq(m.code_group,"THREAD_STATE"),eq(m.code,l))).limit(1).get();)l=at();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(wt(e.group),gr(e.code),kt(e.workspaceId),e.name===void 0&&e.color===void 0)throw new J("COMMON_CODE_UPDATE_EMPTY","VALIDATION","At least one display value is required");let t=e.name===void 0||e.name===null?e.name:Rn(e.name);e.color!==void 0&&bn(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 J("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 J("COMMON_CODE_NAME_INVALID","VALIDATION","User common-code names cannot be cleared");if(typeof t=="string"&&s.is_archived===0){let l=and(it(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 J("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(wt(e),gr(t),kt(r),typeof o!="boolean")throw new J("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 J("COMMON_CODE_NOT_FOUND","NOT_FOUND",`Common code not found: ${e}/${t}`);if(d.is_builtin===1)throw new J("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(it(e,r),eq(m.is_archived,0),eq(m.code_name,d.code_name),ne(m.code,t))).limit(1).get())throw new J("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 J("COMMON_CODE_SCOPE_FORBIDDEN","VALIDATION","Workspace does not own this common code")}};function mr(n){let e=Ae.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 Sn(n){let e=mr(n);return createHash("sha256").update(e).digest("hex")}function Wt(n){return n.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}var yr=class extends D{dbRoot;constructor(e={}){super(),this.dbRoot=e.dbRoot;}resolveDbPath(){return this.dbRoot?join(this.dbRoot,".crewx","crewx.db"):super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{nt(r.db);}catch(o){throw r.close(),o}return r}resolveSlug(e,t,r){let o=Wt(basename(r)),i=`${Wt(basename(dirname(r)))}-${o}`,d=[o,i];try{let l=u=>e.select({id:T.id}).from(T).where(and(eq(T.slug,u),ne(T.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 p=`${i}-${u}`;if(!l(p))return p}}catch{}return o}normalizeLegacySlugs(){if(!this.dbExists())return {updated:0,checked:0};let e=this.openHandle(true);try{let t=e.db.select({id:T.id,slug:T.slug}).from(T).all(),r=0;for(let o of t)if(o.slug.includes("/")){let s=Wt(o.slug.replace(/\//g,"-"));e.db.update(T).set({slug:s,updated_at:new Date().toISOString()}).where(eq(T.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(T).values({id:r,slug:o,name:s,workspace_path:i,is_active:1,created_at:d,updated_at:d}).onConflictDoNothing().run(),e.update(T).set({workspace_path:i,updated_at:d}).where(and(eq(T.id,r),isNull(T.workspace_path))).run();}registerWorkspace(e){let t=mr(e),r=this.openHandle(true);try{let o=Sn(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(T.is_active,e.isActive?1:0):void 0,o=t.db.select({count:sql`count(*)`}).from(T).where(r).get();return {rows:t.db.select().from(T).where(r).orderBy(desc(T.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(T).where(eq(T.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.*,
|
|
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(T).where(eq(T.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(T.slug,e),ne(T.id,t)):eq(T.slug,e);return !!r.db.select({id:T.id}).from(T).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(T).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(T).where(eq(T.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(T).where(eq(T.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:T.id,workspace_path:T.workspace_path}).from(T).where(and(eq(T.is_active,1),isNotNull(T.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(T).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(T.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(T).where(eq(T.id,e)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to delete workspace",r)}finally{t.close();}}};var Dn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function di(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+=Dn[o%62]);}for(;t.length<n;)t+=Dn[randomBytes(1)[0]%62];return t}function be(n){return `${n}_${di(8)}`}var br=["outcome_plan","contract_check","feature_link","use_verify","result_review"],gi=new Set(br),Pn=Object.freeze(br.map(n=>({key:n,labelOverride:null}))),fi=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),mi=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),wi=new Set(["pending","verifying","passed","failed"]),ki=new Set(["user","project_manager","system"]),yi=new Set(["task","wi","url"]),Ti=/^\d{4}-\d{2}-\d{2}$/;function H(n){throw new c("VALIDATION",n)}function me(n){throw new c("NOT_FOUND",n)}function Y(n,e){(typeof n!="string"||n.trim().length===0)&&H(`${e} is required`);}function bi(n){if(n==null)return;Ti.test(n)||H("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)&&H("dueDate must be a valid calendar date");}function $n(n){let e=n??Pn;(!Array.isArray(e)||e.length===0)&&H("stages must contain at least one stage");let t=new Set;return e.map(r=>{(!r||typeof r!="object"||Array.isArray(r))&&H("stage must be an object");let o=r;return Y(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&H("stage.labelOverride must be a string or null"),o.labelOverride!==null&&Y(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&H("stage.key is required"),!gi.has(o.key)&&o.labelOverride===null&&H(`custom stage requires a labelOverride: ${o.key}`),t.has(o.key)&&H(`duplicate stage key: ${o.key}`),t.add(o.key),{key:o.key,labelOverride:o.labelOverride}})}function Ri(n){Array.isArray(n)||H("criteria must be an array");for(let e of n)Y(e,"criterion.statement");}function at(n={}){let e=n.actorType??"system";ki.has(e)||H(`invalid actorType: ${String(e)}`);let t=n.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&H(`actorId is required for ${e}`),{actorType:e,actorId:t}}function jn(n,e){let t=n??{};if((t===null||typeof t!="object"||Array.isArray(t))&&H("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)&&H(`accepted payload requires ${r}`);try{return JSON.stringify(t)}catch(r){throw new c("VALIDATION","event payload must be JSON serializable",r)}}function Ei(n){return Array.isArray(n)||H("evidence must be an array"),n.map(e=>((!e||typeof e!="object")&&H("evidence item must be an object"),yi.has(e.kind)||H(`invalid evidence kind: ${String(e.kind)}`),Y(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&H("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 Ln(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 $n(e)}catch(t){throw new c("DB_ERROR","Project stages JSON is invalid",t)}}function Mn(n){return Y(n.projectId,"projectId"),Y(n.title,"title"),fi.has(n.type)||H(`invalid project event type: ${String(n.type)}`),{...at(n),payloadJson:jn(n.payload,n.type)}}function Qe(n,e,t){let r=Mn(e);n.select({id:L.id}).from(L).where(eq(L.id,e.projectId)).get()||me(`Project ${e.projectId} not found`);let s=n.select({maxSeq:sql`COALESCE(MAX(${Te.seq}), 0)`}).from(Te).where(eq(Te.project_id,e.projectId)).get()?.maxSeq??0,i=be("pje");n.insert(Te).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(Te).where(eq(Te.id,i)).get();if(!d)throw new c("DB_ERROR","Event insert did not return a row");return d}var Tr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}getDetailFromHandle(e,t){let r=e.db.select().from(L).where(eq(L.id,t)).get();if(!r)return;let o=e.db.select().from(ce).where(eq(ce.project_id,t)).orderBy(asc(ce.position)).all();return {...r,stages:Ln(r.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||me(`Project ${e} not found`),t}createProject(e){Y(e.workspaceId,"workspaceId"),Y(e.name,"name"),Y(e.outcome,"outcome"),bi(e.dueDate);let t=$n(e.stages);Ri(e.criteria);let r=be("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(i=>{i.insert(L).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(ce).values({id:be("pjc"),project_id:r,position:l+1,statement:d,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),Qe(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(Y(e,"workspaceId"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=t.includeArchived?eq(L.workspace_id,e):and(eq(L.workspace_id,e),isNull(L.archived_at));return r.db.select({id:L.id}).from(L).where(o).orderBy(desc(L.updated_at),desc(L.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){Y(e,"projectId");let t=this.openHandle(true);try{t.db.update(L).set({archived_at:new Date().toISOString()}).where(eq(L.id,e)).run().changes===0&&me(`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={}){Y(e,"projectId"),mi.has(t)||H(`invalid project scene: ${String(t)}`);let o=at(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let l=d.select().from(L).where(eq(L.id,e)).get();l||me(`Project ${e} not found`),d.update(L).set({scene:t,updated_at:s}).where(eq(L.id,e)).run(),Qe(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={}){Y(e,"projectId"),Number.isInteger(t)||H("stage index must be an integer");let o=at(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let l=d.select().from(L).where(eq(L.id,e)).get();l||me(`Project ${e} not found`);let u=Ln(l.stages_json);(t<1||t>u.length)&&H("stage index is outside the project stages"),d.update(L).set({stage_index:t,updated_at:s}).where(eq(L.id,e)).run(),Qe(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||!wi.has(i))&&H(`invalid criterion status: ${String(i)}`),Y(s.criterionId,"criterionId");let d=at(s),l=new Date().toISOString(),u=this.openHandle(true),p;try{u.db.transaction(g=>{let f=g.select().from(ce).where(eq(ce.id,s.criterionId)).get();f||me(`Criterion ${s.criterionId} not found`),p=f.project_id,s.projectId&&s.projectId!==f.project_id&&me(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(ce).set({verify_status:i,verified_at:i==="passed"?l:null,updated_at:l}).where(eq(ce.id,s.criterionId)).run(),Qe(g,{projectId:f.project_id,...d,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:s.criterionId,status:i}},l);});}catch(g){throw g instanceof c?g:new c("DB_ERROR","Failed to set criterion verification",g)}finally{u.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||me(`Criterion ${s.criterionId} not found`),_}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;Y(s.criterionId,"criterionId");let i=Ei(s.evidence),d=at(s),l=new Date().toISOString(),u=this.openHandle(true),p;try{u.db.transaction(g=>{let f=g.select().from(ce).where(eq(ce.id,s.criterionId)).get();f||me(`Criterion ${s.criterionId} not found`),p=f.project_id,s.projectId&&s.projectId!==f.project_id&&me(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(ce).set({evidence_json:JSON.stringify(i),updated_at:l}).where(eq(ce.id,s.criterionId)).run(),Qe(g,{projectId:f.project_id,...d,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:s.criterionId,evidence:i}},l);});}catch(g){throw g instanceof c?g:new c("DB_ERROR","Failed to set criterion evidence",g)}finally{u.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||me(`Criterion ${s.criterionId} not found`),_}appendEvent(e,t){let r=typeof e=="string"?{...t,projectId:e}:e;Mn(r);let o=new Date().toISOString(),s=this.openHandle(true),i;try{s.db.transaction(d=>{i=Qe(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(Y(e,"projectId"),t.afterSeq!==void 0&&(!Number.isInteger(t.afterSeq)||t.afterSeq<0)&&H("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&H("limit must be a positive integer"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=[eq(Te.project_id,e)];t.afterSeq!==void 0&&o.push(gt(Te.seq,t.afterSeq));let s=r.db.select().from(Te).where(and(...o)).orderBy(asc(Te.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){Y(e,"projectId");let r=at(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};jn(o,"accepted");let s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{d.select({id:L.id}).from(L).where(eq(L.id,e)).get()||me(`Project ${e} not found`),d.update(L).set({scene:"accepted",accepted_at:s,updated_at:s}).where(eq(L.id,e)).run(),Qe(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 qn=[T,a,h,Pe,Ee,fe,ot];function Ii(){return Ae__default.join(rs.homedir(),".crewx","crewx.db")}function Ci(n){if(!Bn__default.existsSync(n))return null;let e=Math.floor(Date.now()/1e3),t=`${n}.bak-${e}`;return Bn__default.copyFileSync(n,t),t}function Fn(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 Di(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 Oi(n){let e=n.getSQLType(),t=`"${n.name}" ${e}`,r=Di(n.default);return r!==null&&(t+=` DEFAULT ${r}`),n.notNull&&(t+=" NOT NULL"),t}function Ni(n,e){let t=e?.dbPath??Ii(),r=e?.force??false,o=e?.dryRun??false,s=o?null:Ci(t);if(r&&!o)try{n.run("DELETE FROM __drizzle_migrations");}catch{}let i=Fn(n);if(!o)try{rt(n);}catch(_){let g=_ instanceof Error?`${_.message} ${_.cause?.message??""}`:"";if(!r||!g.includes("duplicate column"))throw _}let d,l;o?(d=qn.map(g=>getTableConfig(g).name).filter(g=>!i.has(g)),l=i):(l=Fn(n),d=[...l].filter(_=>!i.has(_)));let u=[],p=[];for(let _ of qn){let g=getTableConfig(_),f=g.name;if(!l.has(f))continue;let C=n.all(`PRAGMA table_info("${f}")`),w=new Set(C.map(R=>R.name)),I=new Set(g.columns.map(R=>R.name));for(let R of g.columns)if(!w.has(R.name)){if(!o){let z=Oi(R);n.run(`ALTER TABLE "${f}" ADD COLUMN ${z}`);}u.push({table:f,column:R.name});}for(let R of C)I.has(R.name)||p.push(`${f}.${R.name} exists in DB but not in schema (untouched)`);}return {created:d,altered:u,warnings:p,backupPath:s}}function Un(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 Vn(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 Gn(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)=>Vn(r,o))}catch(r){throw r instanceof c?new c("DB_ERROR",`Malformed legacy task logs: ${n}`,r):r}}function Jn(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 Kn(n){return {taskId:n.id,source:Jn(n),revision:n.log_revision,lastSeq:n.last_log_seq}}function Bi(n){if(!Number.isInteger(n)||n<0)throw new c("VALIDATION","Task log tail limit must be a non-negative integer")}var bt=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(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)=>Vn(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=Jn(d);if(l==="blob"){let g=Gn(e,d.logs);if(i.update(a).set({logs:JSON.stringify([...g,...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,p=d.last_log_seq+r.length;if(i.insert(Re).values(r.map((g,f)=>({task_id:e,seq:u+f,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:p,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:p}},{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?Kn(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 Bi(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=Kn(s);if(i.source==="blob"){let p=Gn(e,s.logs);return {...i,entries:t===void 0?p:p.slice(Math.max(0,p.length-t))}}let d=o.select({seq:Re.seq,timestamp:Re.timestamp,level:Re.level,message:Re.message}).from(Re).where(eq(Re.task_id,e)).orderBy(t===void 0?asc(Re.seq):desc(Re.seq)),u=(t===void 0?d.all():d.limit(t).all()).map(({timestamp:p,level:_,message:g})=>({timestamp:p,level:_,message:g}));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 Er=40,He="2026-05-09",Wi="0.8.9-rc.13",qe=10,Fe=parseInt(Wi.split("rc.")[1]);function Yn(){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(T).where(eq(T.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(T.slug,e),ne(T.id,t)):eq(T.slug,e);return !!r.db.select({id:T.id}).from(T).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(T).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(T).where(eq(T.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(T).where(eq(T.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:T.id,workspace_path:T.workspace_path}).from(T).where(and(eq(T.is_active,1),isNotNull(T.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(T).set({is_active:0,updated_at:new Date().toISOString()}).where(eq(T.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(T).where(eq(T.id,e)).run();}catch(r){throw r instanceof c?r:new c("DB_ERROR","Failed to delete workspace",r)}finally{t.close();}}};var Dn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function di(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+=Dn[o%62]);}for(;t.length<n;)t+=Dn[randomBytes(1)[0]%62];return t}function be(n){return `${n}_${di(8)}`}var br=["outcome_plan","contract_check","feature_link","use_verify","result_review"],gi=new Set(br),Pn=Object.freeze(br.map(n=>({key:n,labelOverride:null}))),fi=new Set(["created","plan_proposed","plan_approved","decision_requested","decision_answered","replanned","stage_advanced","criterion_verified","scene_changed","result_submitted","accepted"]),mi=new Set(["planning","plan_review","running","human_wait","limit_wait","failed_stop","analyzing_feedback","replanned","awaiting_review","accepted"]),wi=new Set(["pending","verifying","passed","failed"]),ki=new Set(["user","project_manager","system"]),yi=new Set(["task","wi","url"]),Ti=/^\d{4}-\d{2}-\d{2}$/;function H(n){throw new c("VALIDATION",n)}function me(n){throw new c("NOT_FOUND",n)}function Y(n,e){(typeof n!="string"||n.trim().length===0)&&H(`${e} is required`);}function bi(n){if(n==null)return;Ti.test(n)||H("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)&&H("dueDate must be a valid calendar date");}function $n(n){let e=n??Pn;(!Array.isArray(e)||e.length===0)&&H("stages must contain at least one stage");let t=new Set;return e.map(r=>{(!r||typeof r!="object"||Array.isArray(r))&&H("stage must be an object");let o=r;return Y(o.key,"stage.key"),o.labelOverride!==null&&typeof o.labelOverride!="string"&&H("stage.labelOverride must be a string or null"),o.labelOverride!==null&&Y(o.labelOverride,"stage.labelOverride"),typeof o.key!="string"&&H("stage.key is required"),!gi.has(o.key)&&o.labelOverride===null&&H(`custom stage requires a labelOverride: ${o.key}`),t.has(o.key)&&H(`duplicate stage key: ${o.key}`),t.add(o.key),{key:o.key,labelOverride:o.labelOverride}})}function Ri(n){Array.isArray(n)||H("criteria must be an array");for(let e of n)Y(e,"criterion.statement");}function dt(n={}){let e=n.actorType??"system";ki.has(e)||H(`invalid actorType: ${String(e)}`);let t=n.actorId??null;return (e==="user"||e==="project_manager")&&(!t||t.trim().length===0)&&H(`actorId is required for ${e}`),{actorType:e,actorId:t}}function jn(n,e){let t=n??{};if((t===null||typeof t!="object"||Array.isArray(t))&&H("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)&&H(`accepted payload requires ${r}`);try{return JSON.stringify(t)}catch(r){throw new c("VALIDATION","event payload must be JSON serializable",r)}}function Ei(n){return Array.isArray(n)||H("evidence must be an array"),n.map(e=>((!e||typeof e!="object")&&H("evidence item must be an object"),yi.has(e.kind)||H(`invalid evidence kind: ${String(e.kind)}`),Y(e.ref,"evidence.ref"),e.label!==void 0&&typeof e.label!="string"&&H("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 Ln(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 $n(e)}catch(t){throw new c("DB_ERROR","Project stages JSON is invalid",t)}}function Mn(n){return Y(n.projectId,"projectId"),Y(n.title,"title"),fi.has(n.type)||H(`invalid project event type: ${String(n.type)}`),{...dt(n),payloadJson:jn(n.payload,n.type)}}function Qe(n,e,t){let r=Mn(e);n.select({id:L.id}).from(L).where(eq(L.id,e.projectId)).get()||me(`Project ${e.projectId} not found`);let s=n.select({maxSeq:sql`COALESCE(MAX(${Te.seq}), 0)`}).from(Te).where(eq(Te.project_id,e.projectId)).get()?.maxSeq??0,i=be("pje");n.insert(Te).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(Te).where(eq(Te.id,i)).get();if(!d)throw new c("DB_ERROR","Event insert did not return a row");return d}var Tr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}getDetailFromHandle(e,t){let r=e.db.select().from(L).where(eq(L.id,t)).get();if(!r)return;let o=e.db.select().from(ce).where(eq(ce.project_id,t)).orderBy(asc(ce.position)).all();return {...r,stages:Ln(r.stages_json),criteria:o}}getDetailOrThrow(e){let t=this.getProject(e);return t||me(`Project ${e} not found`),t}createProject(e){Y(e.workspaceId,"workspaceId"),Y(e.name,"name"),Y(e.outcome,"outcome"),bi(e.dueDate);let t=$n(e.stages);Ri(e.criteria);let r=be("prj"),o=new Date().toISOString(),s=this.openHandle(true);try{s.db.transaction(i=>{i.insert(L).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(ce).values({id:be("pjc"),project_id:r,position:l+1,statement:d,verify_status:"pending",verified_at:null,evidence_json:"[]",created_at:o,updated_at:o}).run();}),Qe(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(Y(e,"workspaceId"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=t.includeArchived?eq(L.workspace_id,e):and(eq(L.workspace_id,e),isNull(L.archived_at));return r.db.select({id:L.id}).from(L).where(o).orderBy(desc(L.updated_at),desc(L.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){Y(e,"projectId");let t=this.openHandle(true);try{t.db.update(L).set({archived_at:new Date().toISOString()}).where(eq(L.id,e)).run().changes===0&&me(`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={}){Y(e,"projectId"),mi.has(t)||H(`invalid project scene: ${String(t)}`);let o=dt(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let l=d.select().from(L).where(eq(L.id,e)).get();l||me(`Project ${e} not found`),d.update(L).set({scene:t,updated_at:s}).where(eq(L.id,e)).run(),Qe(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={}){Y(e,"projectId"),Number.isInteger(t)||H("stage index must be an integer");let o=dt(r),s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{let l=d.select().from(L).where(eq(L.id,e)).get();l||me(`Project ${e} not found`);let u=Ln(l.stages_json);(t<1||t>u.length)&&H("stage index is outside the project stages"),d.update(L).set({stage_index:t,updated_at:s}).where(eq(L.id,e)).run(),Qe(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||!wi.has(i))&&H(`invalid criterion status: ${String(i)}`),Y(s.criterionId,"criterionId");let d=dt(s),l=new Date().toISOString(),u=this.openHandle(true),p;try{u.db.transaction(g=>{let f=g.select().from(ce).where(eq(ce.id,s.criterionId)).get();f||me(`Criterion ${s.criterionId} not found`),p=f.project_id,s.projectId&&s.projectId!==f.project_id&&me(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(ce).set({verify_status:i,verified_at:i==="passed"?l:null,updated_at:l}).where(eq(ce.id,s.criterionId)).run(),Qe(g,{projectId:f.project_id,...d,type:"criterion_verified",title:"Criterion verification updated",payload:{criterionId:s.criterionId,status:i}},l);});}catch(g){throw g instanceof c?g:new c("DB_ERROR","Failed to set criterion verification",g)}finally{u.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||me(`Criterion ${s.criterionId} not found`),_}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;Y(s.criterionId,"criterionId");let i=Ei(s.evidence),d=dt(s),l=new Date().toISOString(),u=this.openHandle(true),p;try{u.db.transaction(g=>{let f=g.select().from(ce).where(eq(ce.id,s.criterionId)).get();f||me(`Criterion ${s.criterionId} not found`),p=f.project_id,s.projectId&&s.projectId!==f.project_id&&me(`Criterion ${s.criterionId} not found in project ${s.projectId}`),g.update(ce).set({evidence_json:JSON.stringify(i),updated_at:l}).where(eq(ce.id,s.criterionId)).run(),Qe(g,{projectId:f.project_id,...d,type:"criterion_verified",title:"Criterion evidence updated",payload:{criterionId:s.criterionId,evidence:i}},l);});}catch(g){throw g instanceof c?g:new c("DB_ERROR","Failed to set criterion evidence",g)}finally{u.close();}let _=p?this.getProject(p)?.criteria.find(g=>g.id===s.criterionId):void 0;return _||me(`Criterion ${s.criterionId} not found`),_}appendEvent(e,t){let r=typeof e=="string"?{...t,projectId:e}:e;Mn(r);let o=new Date().toISOString(),s=this.openHandle(true),i;try{s.db.transaction(d=>{i=Qe(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(Y(e,"projectId"),t.afterSeq!==void 0&&(!Number.isInteger(t.afterSeq)||t.afterSeq<0)&&H("afterSeq must be a non-negative integer"),t.limit!==void 0&&(!Number.isInteger(t.limit)||t.limit<1)&&H("limit must be a positive integer"),!this.dbExists())return [];let r=this.openHandle(false);try{let o=[eq(Te.project_id,e)];t.afterSeq!==void 0&&o.push(gt(Te.seq,t.afterSeq));let s=r.db.select().from(Te).where(and(...o)).orderBy(asc(Te.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){Y(e,"projectId");let r=dt(t),o={remainingRisks:t.remainingRisks,nextPlan:t.nextPlan,lessons:t.lessons,evidenceRefs:t.evidenceRefs};jn(o,"accepted");let s=new Date().toISOString(),i=this.openHandle(true);try{i.db.transaction(d=>{d.select({id:L.id}).from(L).where(eq(L.id,e)).get()||me(`Project ${e} not found`),d.update(L).set({scene:"accepted",accepted_at:s,updated_at:s}).where(eq(L.id,e)).run(),Qe(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 qn=[T,a,h,Pe,Ee,fe,st];function Ii(){return Ae__default.join(rs.homedir(),".crewx","crewx.db")}function Ci(n){if(!Bn__default.existsSync(n))return null;let e=Math.floor(Date.now()/1e3),t=`${n}.bak-${e}`;return Bn__default.copyFileSync(n,t),t}function Fn(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 Di(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 Oi(n){let e=n.getSQLType(),t=`"${n.name}" ${e}`,r=Di(n.default);return r!==null&&(t+=` DEFAULT ${r}`),n.notNull&&(t+=" NOT NULL"),t}function Ni(n,e){let t=e?.dbPath??Ii(),r=e?.force??false,o=e?.dryRun??false,s=o?null:Ci(t);if(r&&!o)try{n.run("DELETE FROM __drizzle_migrations");}catch{}let i=Fn(n);if(!o)try{nt(n);}catch(_){let g=_ instanceof Error?`${_.message} ${_.cause?.message??""}`:"";if(!r||!g.includes("duplicate column"))throw _}let d,l;o?(d=qn.map(g=>getTableConfig(g).name).filter(g=>!i.has(g)),l=i):(l=Fn(n),d=[...l].filter(_=>!i.has(_)));let u=[],p=[];for(let _ of qn){let g=getTableConfig(_),f=g.name;if(!l.has(f))continue;let C=n.all(`PRAGMA table_info("${f}")`),w=new Set(C.map(R=>R.name)),I=new Set(g.columns.map(R=>R.name));for(let R of g.columns)if(!w.has(R.name)){if(!o){let z=Oi(R);n.run(`ALTER TABLE "${f}" ADD COLUMN ${z}`);}u.push({table:f,column:R.name});}for(let R of C)I.has(R.name)||p.push(`${f}.${R.name} exists in DB but not in schema (untouched)`);}return {created:d,altered:u,warnings:p,backupPath:s}}function Un(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 Vn(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 Gn(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)=>Vn(r,o))}catch(r){throw r instanceof c?new c("DB_ERROR",`Malformed legacy task logs: ${n}`,r):r}}function Jn(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 Kn(n){return {taskId:n.id,source:Jn(n),revision:n.log_revision,lastSeq:n.last_log_seq}}function Bi(n){if(!Number.isInteger(n)||n<0)throw new c("VALIDATION","Task log tail limit must be a non-negative integer")}var bt=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(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)=>Vn(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=Jn(d);if(l==="blob"){let g=Gn(e,d.logs);if(i.update(a).set({logs:JSON.stringify([...g,...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,p=d.last_log_seq+r.length;if(i.insert(Re).values(r.map((g,f)=>({task_id:e,seq:u+f,timestamp:g.timestamp,level:g.level,message:g.message}))).run(),i.update(a).set({last_log_seq:p,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:p}},{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?Kn(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 Bi(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=Kn(s);if(i.source==="blob"){let p=Gn(e,s.logs);return {...i,entries:t===void 0?p:p.slice(Math.max(0,p.length-t))}}let d=o.select({seq:Re.seq,timestamp:Re.timestamp,level:Re.level,message:Re.message}).from(Re).where(eq(Re.task_id,e)).orderBy(t===void 0?asc(Re.seq):desc(Re.seq)),u=(t===void 0?d.all():d.limit(t).all()).map(({timestamp:p,level:_,message:g})=>({timestamp:p,level:_,message:g}));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 Er=40,He="2026-05-09",Wi="0.8.9-rc.13",qe=10,Fe=parseInt(Wi.split("rc.")[1]);function Yn(){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'
|
|
@@ -294,22 +294,22 @@ ${r.join(`
|
|
|
294
294
|
GROUP BY ${a.caller_agent_id}, ${a.agent_id}
|
|
295
295
|
ORDER BY task_count DESC, ${a.caller_agent_id} ASC, ${a.agent_id} ASC
|
|
296
296
|
LIMIT ${Er+1}
|
|
297
|
-
`),l=d.length>Er;return {edges:d.slice(0,Er).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:l}}catch(s){throw new 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$1(isNull(a.platform),ne(a.platform,"workflow")),or$1(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))),or$1(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 p={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},_=d.get(u.thread_id);_?_.push(p):d.set(u.thread_id,[p]);}let l=[];for(let[u,p]of d){let _=p.filter(g=>g.agentId===e.targetAgentId).length;_<2||l.push({threadId:u,targetAgentTurnCount:_,turns:p});}return l.sort((u,p)=>{let _=u.turns[u.turns.length-1].startedAt,g=p.turns[p.turns.length-1].startedAt;return _<g?1:_>g?-1:0}),l.slice(0,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 to=["success","failed","completed"],
|
|
297
|
+
`),l=d.length>Er;return {edges:d.slice(0,Er).map(p=>({callerAgentId:p.caller_agent_id??null,agentId:p.agent_id,taskCount:p.task_count,totalTokens:p.input_tokens+p.output_tokens,outputTokens:p.output_tokens})),truncated:l}}catch(s){throw new 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$1(isNull(a.platform),ne(a.platform,"workflow")),or$1(isNull(a.metadata),and(notLike(a.metadata,'%"kind":"workflow_card"%'),notLike(a.metadata,'%"kind":"workflow_ui_instance"%'))),or$1(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 p={id:u.id,agentId:u.agent_id,status:u.status,prompt:u.prompt,startedAt:u.started_at,completedAt:u.completed_at},_=d.get(u.thread_id);_?_.push(p):d.set(u.thread_id,[p]);}let l=[];for(let[u,p]of d){let _=p.filter(g=>g.agentId===e.targetAgentId).length;_<2||l.push({threadId:u,targetAgentTurnCount:_,turns:p});}return l.sort((u,p)=>{let _=u.turns[u.turns.length-1].startedAt,g=p.turns[p.turns.length-1].startedAt;return _<g?1:_>g?-1:0}),l.slice(0,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 to=["success","failed","completed"],Xt=10*1024*1024*1024,ro=256,ea=new Set(to),te=class extends Error{constructor(t,r,o="metadata"){super(r);this.taskId=t;this.kind=o;this.name="MigrationTaskError";}taskId;kind};function no(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 ta(){return rt("better-sqlite3")}function oo(n,e){let t=n===":memory:";if(!t&&!existsSync(n))throw new Error(`Database not found: ${n}`);let r=new(ta())(n,{readonly:e,fileMustExist:!t,timeout:5e3});return r.pragma("foreign_keys = ON"),r.pragma("busy_timeout = 5000"),r}function lt(n,e,t=[]){return n.prepare(e).all(...t)}function ct(n,e,t=[]){return n.prepare(e).get(...t)}function ra(n,e,t=[]){return n.prepare(e).run(...t)}function na(n,e,t=[]){return n.prepare(e).iterate(...t)}function oa(n){return typeof n=="string"&&n.length>0?n:"<unknown>"}function so(n){return typeof n=="string"&&ea.has(n)}function Qn(n,e){n.set(e,(n.get(e)??0)+1);}function Zn(n){return Object.fromEntries([...n.entries()].sort(([e],[t])=>e.localeCompare(t)))}function sa(n){let e=new Set(lt(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(lt(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 io(n,e){if(e==null)return {entries:[]};if(typeof e!="string")throw new te(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 te(n,`Malformed JSON in tasks.logs (${s})`,"malformed")}if(!Array.isArray(t))throw new te(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 te(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 Cr(n,e){if(!Number.isInteger(n.last_log_seq)||n.last_log_seq<0)throw new te(n.id,"Invalid last_log_seq metadata","metadata");if(!Number.isInteger(n.log_revision)||n.log_revision<0)throw new te(n.id,"Invalid log_revision metadata","metadata");if(e==="blob"&&n.last_log_seq!==0)throw new te(n.id,"Blob source must have last_log_seq=0","metadata")}function ia(n){let e=lt(n,`SELECT task_id, COUNT(*) AS event_count
|
|
298
298
|
FROM task_log_events GROUP BY task_id`);return new Map(e.map(t=>[t.task_id,t.event_count]))}function aa(n){let e=ia(n),t=new Map,r=[],o=[],s=[],i=new Map,d=new Map,l=0,u=0,p=0,_=0,g=0,f=0;for(let C of na(n,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
299
|
-
FROM tasks ORDER BY id`)){let w=C,I=oa(w.status);if(Qn(i,I),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"){_+=1;try{Cr(w,"events");}catch(Oe){s.push(Dr(Oe,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 R=so(w.status);R||(p+=1,Qn(d,I)),typeof w.logs=="string"?f+=Buffer.byteLength(w.logs,"utf8"):Buffer.isBuffer(w.logs)&&(f+=w.logs.byteLength);let z=e.get(w.id)??0;z>0&&s.push({taskId:w.id,reason:`Blob source already has ${z} task_log_events row(s)`,kind:"mixed-source"});let ze;try{ze=io(w.id,w.logs),g+=ze.entries.length,Cr(w,"blob");}catch(Oe){let Ne=Dr(Oe,w.id);s.push(Ne),Ne.kind==="malformed"&&o.push(Ne);continue}z>0||R&&r.push(w.id);}return {taskCount:l,candidateTaskCount:u,eligibleTaskCount:r.length,eventSourceTasks:_,statusCounts:Zn(i),deferredTaskCount:p,deferredStatusCounts:Zn(d),entryCount:g,sourceBytes:f,candidateIds:r,malformedRows:o,failures:s,tasks:t}}function Dr(n,e){return n instanceof te?{taskId:n.taskId,reason:n.message,kind:n.kind}:{taskId:e,reason:n instanceof Error?n.message:String(n),kind:"metadata"}}function da(n){return
|
|
300
|
-
FROM tasks WHERE id = ?`,[e]);if(!r)throw new te(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 te(e,`Unknown log_storage value: ${r.log_storage}`,"invalid-source");if(!so(r.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=r.logs,s=io(e,o);Cr(r,"blob");let i=
|
|
301
|
-
VALUES (?, ?, ?, ?, ?)`);for(let[_,g]of s.entries.entries())d.run(e,_+1,g.timestamp,g.level,g.message);let l=
|
|
299
|
+
FROM tasks ORDER BY id`)){let w=C,I=oa(w.status);if(Qn(i,I),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"){_+=1;try{Cr(w,"events");}catch(Oe){s.push(Dr(Oe,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 R=so(w.status);R||(p+=1,Qn(d,I)),typeof w.logs=="string"?f+=Buffer.byteLength(w.logs,"utf8"):Buffer.isBuffer(w.logs)&&(f+=w.logs.byteLength);let z=e.get(w.id)??0;z>0&&s.push({taskId:w.id,reason:`Blob source already has ${z} task_log_events row(s)`,kind:"mixed-source"});let ze;try{ze=io(w.id,w.logs),g+=ze.entries.length,Cr(w,"blob");}catch(Oe){let Ne=Dr(Oe,w.id);s.push(Ne),Ne.kind==="malformed"&&o.push(Ne);continue}z>0||R&&r.push(w.id);}return {taskCount:l,candidateTaskCount:u,eligibleTaskCount:r.length,eventSourceTasks:_,statusCounts:Zn(i),deferredTaskCount:p,deferredStatusCounts:Zn(d),entryCount:g,sourceBytes:f,candidateIds:r,malformedRows:o,failures:s,tasks:t}}function Dr(n,e){return n instanceof te?{taskId:n.taskId,reason:n.message,kind:n.kind}:{taskId:e,reason:n instanceof Error?n.message:String(n),kind:"metadata"}}function da(n){return ct(n,"SELECT COUNT(*) AS count FROM tasks WHERE status IN ('pending', 'running')")?.count??0}function ca(n){return ct(n,"SELECT COUNT(*) AS count FROM tasks WHERE log_storage = 'blob'")?.count??0}function la(n){if(n===":memory:")return 0;let e=t=>{try{return statSync(t).size}catch{return 0}};return e(n)+e(`${n}-wal`)}function ua(n,e){return la(n)+e*ro}function ao(n,e){return Number.isFinite(n)&&Number.isFinite(e)&&n>=e+Xt}function eo(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([eo(n),...t?[eo(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=ua(n,e),d=i+Xt;return {estimatedFreeSpaceBytes:i,requiredFreeSpaceBytes:d,availableFreeSpaceBytes:Number.isFinite(s)?Math.floor(s):0,minimumFreeSpaceReserveBytes:Xt,freeSpaceGatePassed:ao(Number.isFinite(s)?Math.floor(s):0,i),warnings:o}}function lo(n){return new Set(n.map(e=>e.taskId)).size}function uo(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 Jt(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??lo(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 _a(n,e){return n.transaction(()=>{let r=ct(n,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
300
|
+
FROM tasks WHERE id = ?`,[e]);if(!r)throw new te(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 te(e,`Unknown log_storage value: ${r.log_storage}`,"invalid-source");if(!so(r.status))return {status:"deferred",entryCount:0,sourceBytes:0};let o=r.logs,s=io(e,o);Cr(r,"blob");let i=ct(n,"SELECT COUNT(*) AS count FROM task_log_events WHERE task_id = ?",[e])?.count??0;if(i!==0)throw new te(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)
|
|
301
|
+
VALUES (?, ?, ?, ?, ?)`);for(let[_,g]of s.entries.entries())d.run(e,_+1,g.timestamp,g.level,g.message);let l=lt(n,`SELECT seq, timestamp, level, message
|
|
302
302
|
FROM task_log_events WHERE task_id = ? ORDER BY seq`,[e]);if(!pa(l,s.entries))throw new te(e,"Event parity check failed before source clear","metadata");if(ra(n,`UPDATE tasks
|
|
303
303
|
SET log_storage = 'events', last_log_seq = ?, log_revision = log_revision + 1, logs = NULL
|
|
304
|
-
WHERE id = ? AND log_storage = 'blob' AND logs IS ?`,[s.entries.length,e,o]).changes!==1)throw new te(e,"Task changed while migration was in progress","metadata");let p=
|
|
305
|
-
FROM tasks WHERE id = ?`,[e]);if(!p||p.log_storage!=="events"||p.logs!==null||p.last_log_seq!==s.entries.length||p.log_revision!==r.log_revision+1)throw new te(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 po(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 ha(n,e,t){let r=t??po(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=oo(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 ga(n){let e=
|
|
304
|
+
WHERE id = ? AND log_storage = 'blob' AND logs IS ?`,[s.entries.length,e,o]).changes!==1)throw new te(e,"Task changed while migration was in progress","metadata");let p=ct(n,`SELECT id, status, logs, log_storage, last_log_seq, log_revision
|
|
305
|
+
FROM tasks WHERE id = ?`,[e]);if(!p||p.log_storage!=="events"||p.logs!==null||p.last_log_seq!==s.entries.length||p.log_revision!==r.log_revision+1)throw new te(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 po(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 ha(n,e,t){let r=t??po(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=oo(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 ga(n){let e=lt(n,`SELECT task_id AS taskId,
|
|
306
306
|
COUNT(*) AS eventCount,
|
|
307
307
|
COUNT(DISTINCT seq) AS distinctSeqCount,
|
|
308
308
|
MIN(seq) AS minSeq,
|
|
309
309
|
MAX(seq) AS maxSeq
|
|
310
|
-
FROM task_log_events GROUP BY task_id`),t=e.reduce((r,o)=>r+o.eventCount,0);return {rows:e,eventCount:t}}function Ue(n,e,t,r={}){return {taskId:n,kind:e,reason:t,...r}}function fa(n,e,t){let r=[];for(let _ of t.failures)_.kind==="malformed"?r.push(Ue(_.taskId,"malformed-blob",_.reason)):_.kind==="mixed-source"?r.push(Ue(_.taskId,"mixed-source",_.reason)):r.push(Ue(_.taskId,"source-invariant",_.reason));let o=ga(n),s=new Map(o.rows.map(_=>[_.taskId,_]));for(let _ of o.rows){let g=t.tasks.get(_.taskId);if(!g){r.push(Ue(null,"orphan-event",`Event rows reference missing task ${_.taskId}`,{actual:_.eventCount}));continue}(_.minSeq===null||_.minSeq<1||_.distinctSeqCount!==_.maxSeq)&&r.push(Ue(g.id,"seq-gap","Task event sequence has a gap or invalid starting sequence",{expected:_.maxSeq??0,actual:_.distinctSeqCount})),g.log_storage==="events"&&g.last_log_seq!==_.eventCount&&r.push(Ue(g.id,"count-mismatch","last_log_seq does not match task_log_events row count",{expected:g.last_log_seq??0,actual:_.eventCount}));}for(let _ of t.tasks.values())_.log_storage==="events"&&!s.has(_.id)&&_.last_log_seq!==0&&r.push(Ue(_.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:_.last_log_seq??0,actual:0}));for(let _ of
|
|
311
|
-
FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))r.push(Ue(_.taskId,"duplicate-seq",`Duplicate task event sequence ${_.seq}`,{actual:_.duplicateCount,seq:_.seq}));let i=
|
|
312
|
-
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(Ue(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:i}));let d=new Set(r.flatMap(_=>_.taskId?[_.taskId]:[])),l=r.map(_=>({taskId:_.taskId??"(orphan)",reason:_.reason,kind:_.kind==="malformed-blob"?"malformed":_.kind==="mixed-source"?"mixed-source":"metadata"})),u=l.filter(_=>_.kind==="malformed"),p={checkedTasks:t.taskCount,eventSourceTasks:t.eventSourceTasks,blobSourceTasks:t.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:r.filter(_=>_.kind==="orphan-event").length,failedTasks:d.size,issues:r};return
|
|
310
|
+
FROM task_log_events GROUP BY task_id`),t=e.reduce((r,o)=>r+o.eventCount,0);return {rows:e,eventCount:t}}function Ue(n,e,t,r={}){return {taskId:n,kind:e,reason:t,...r}}function fa(n,e,t){let r=[];for(let _ of t.failures)_.kind==="malformed"?r.push(Ue(_.taskId,"malformed-blob",_.reason)):_.kind==="mixed-source"?r.push(Ue(_.taskId,"mixed-source",_.reason)):r.push(Ue(_.taskId,"source-invariant",_.reason));let o=ga(n),s=new Map(o.rows.map(_=>[_.taskId,_]));for(let _ of o.rows){let g=t.tasks.get(_.taskId);if(!g){r.push(Ue(null,"orphan-event",`Event rows reference missing task ${_.taskId}`,{actual:_.eventCount}));continue}(_.minSeq===null||_.minSeq<1||_.distinctSeqCount!==_.maxSeq)&&r.push(Ue(g.id,"seq-gap","Task event sequence has a gap or invalid starting sequence",{expected:_.maxSeq??0,actual:_.distinctSeqCount})),g.log_storage==="events"&&g.last_log_seq!==_.eventCount&&r.push(Ue(g.id,"count-mismatch","last_log_seq does not match task_log_events row count",{expected:g.last_log_seq??0,actual:_.eventCount}));}for(let _ of t.tasks.values())_.log_storage==="events"&&!s.has(_.id)&&_.last_log_seq!==0&&r.push(Ue(_.id,"count-mismatch","Event-source task has no rows for its last_log_seq",{expected:_.last_log_seq??0,actual:0}));for(let _ of lt(n,`SELECT task_id AS taskId, seq, COUNT(*) AS duplicateCount
|
|
311
|
+
FROM task_log_events GROUP BY task_id, seq HAVING COUNT(*) > 1`))r.push(Ue(_.taskId,"duplicate-seq",`Duplicate task event sequence ${_.seq}`,{actual:_.duplicateCount,seq:_.seq}));let i=ct(n,`SELECT COUNT(*) AS count FROM task_log_events
|
|
312
|
+
WHERE seq IS NULL OR seq < 1 OR timestamp IS NULL OR level IS NULL OR message IS NULL`)?.count??0;i>0&&r.push(Ue(null,"invalid-event","Event rows contain invalid sequence or null payload fields",{actual:i}));let d=new Set(r.flatMap(_=>_.taskId?[_.taskId]:[])),l=r.map(_=>({taskId:_.taskId??"(orphan)",reason:_.reason,kind:_.kind==="malformed-blob"?"malformed":_.kind==="mixed-source"?"mixed-source":"metadata"})),u=l.filter(_=>_.kind==="malformed"),p={checkedTasks:t.taskCount,eventSourceTasks:t.eventSourceTasks,blobSourceTasks:t.candidateTaskCount,eventCount:o.eventCount,orphanEventCount:r.filter(_=>_.kind==="orphan-event").length,failedTasks:d.size,issues:r};return Jt("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:p})}function ma(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 wa(n){ma(n);let e=no(n.dbPath),t=oo(e,n.mode!=="apply");try{sa(t);let r=aa(t),o=da(t);if(n.mode==="verify")return {...fa(t,e,r),activeTaskCount:o};if(n.mode==="dry-run")return Jt("dry-run",e,r,{ok:r.failures.length===0,activeTaskCount:o,skippedTasks:r.eventSourceTasks,remainingTaskCount:r.candidateTaskCount});let s=n.backupPath??po(e),i=co(e,r.entryCount,s);if(!i.freeSpaceGatePassed)return Jt("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 ha(t,e,s),l=[...r.failures],u=n.batchTasks===void 0?r.candidateIds:r.candidateIds.slice(0,n.batchTasks),p=n.batchTasks??Math.max(u.length,1),_=0,g=0,f=0,C=[...i.warnings];for(let[w,I]of u.entries()){try{let R=_a(t,I);R.status==="migrated"&&(_+=1,g+=R.entryCount,f+=R.sourceBytes);}catch(R){l.push(Dr(R,I));}if((w+1)%p===0||w===u.length-1){let R=uo(t);R&&C.push(R);}}return Jt("apply",e,r,{ok:l.length===0,activeTaskCount:o,backupPath:d,backupMethod:"sqlite-online-backup",migratedTasks:_,migratedEntries:g,logicalSourceBytesRemoved:f,failedTasks:lo(l),failures:l,malformedRows:r.malformedRows,remainingTaskCount:ca(t),skippedTasks:r.eventSourceTasks,warnings:C},i)}finally{t.close();}}function ka(n){return basename(n)}var et=class extends c{reason;constructor(e,t=e){super("VALIDATION",t),this.name="ThreadTitleMetadataPatchError",this.reason=e;}};function St(n){if(!n)return {};try{let e=JSON.parse(n);return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}function Ea(n){let t=St(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 Or=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}validateWorkspaceId(e,t){return e.db.select({id:T.id}).from(T).where(eq(T.id,t)).limit(1).get()?t:null}topLevelTaskPredicateSql(e="child"){return sql.raw(`NOT EXISTS (
|
|
313
313
|
SELECT 1 FROM tasks parent
|
|
314
314
|
WHERE parent.id = ${e}.parent_task_id
|
|
315
315
|
AND parent.thread_id = ${e}.thread_id
|
|
@@ -365,7 +365,7 @@ ${r.join(`
|
|
|
365
365
|
message_count = message_count + 1,
|
|
366
366
|
updated_at = ${s}
|
|
367
367
|
WHERE id = ${e}
|
|
368
|
-
`),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(h).set({last_message:t,updated_at:s}).where(eq(h.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(h).set(o).where(eq(h.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 et("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new et("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 et("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 et("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(h.id,e),eq(h.workspace_id,r)):eq(h.id,e);return d.db.transaction(u=>{let p=u.select({metadata:h.metadata}).from(h).where(l).get();if(!p)return null;let _=St(p.metadata),g=_.threadTitle,f=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};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?_.threadTitle=f:delete _.threadTitle;let C=Object.keys(_).length>0?JSON.stringify(_):null,w=new Date().toISOString();u.update(h).set({metadata:C,updated_at:w}).where(l).run();let I=u.select({metadata:h.metadata}).from(h).where(l).get();if(!I)throw new c("DB_ERROR","Thread-title metadata update could not be read back");let R=Ea(I.metadata);return {threadId:e,priority:R.priority,state:R.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(h.id,e),eq(h.workspace_id,t)):eq(h.id,e);return r.db.transaction(s=>{let i=s.select({pinned:h.pinned,metadata:h.metadata}).from(h).where(o).get();if(!i)return null;let d=i.pinned?0:1,l=St(i.metadata);if(d){let u=t?and(eq(h.pinned,1),eq(h.workspace_id,t)):eq(h.pinned,1),p=s.select({metadata:h.metadata}).from(h).where(u).all(),_=null;for(let g of p){let f=St(g.metadata);typeof f.pinOrder=="number"&&(_===null||f.pinOrder<_)&&(_=f.pinOrder);}l.pinOrder=_===null?0:_-1;}else delete l.pinOrder;return s.update(h).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(h.id,e[s]),eq(h.workspace_id,t)):eq(h.id,e[s]),d=o.select({metadata:h.metadata}).from(h).where(i).get();if(!d)continue;let l=St(d.metadata);l.pinOrder=s+1,o.update(h).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(h.id,e),eq(h.workspace_id,t)):eq(h.id,e),s=r.db.select({starred:h.starred}).from(h).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(h).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(h.id,e),eq(h.workspace_id,t)):eq(h.id,e);return i.db.transaction(u=>{let p=u.select({metadata:h.metadata}).from(h).where(d).get();if(!p)return null;let _=p.metadata?JSON.parse(p.metadata):{},g=_.overdrive??{},f=o?.defaultTurns??g.defaultTurns??3,C=o?.updatedBy??"ui",w=new Date().toISOString(),I,R,z,ze;switch(r){case "enable-count":{let Oe=o?.turns??f,Ne=o?.consumeCurrent?Math.max(Oe-1,0):Oe;I=Ne>0?"count":"off",R=Ne,z=!0,ze="count";break}case "enable-latch":{I="latch",R=0,z=!0,ze="latch";break}case "disable":{I="off",R=0,z=!1;break}default:{let Oe=g.state??"off",Ne=typeof g.remaining=="number"?g.remaining:0;if(Oe==="count"&&Ne>0){let Jr=Ne-1;Jr<=0?(I="off",R=0):(I="count",R=Jr),z=!0,ze="count";}else Oe==="latch"?(I="latch",R=0,z=!0,ze="latch"):(I="off",R=0,z=!1);break}}return _.overdrive={state:I,remaining:R,defaultTurns:f,updatedAt:w,updatedBy:C},u.update(h).set({metadata:JSON.stringify(_),updated_at:w}).where(d).run(),{applied:z,appliedMode:ze,state:I,remaining:R}},{behavior:"immediate"})}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};var lt="THREAD_STATE",Zt="custom:";function Da(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 xr(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 mo(n){let t=xr(n)?.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.state;return typeof r=="string"&&r.startsWith(Zt)?r:null}function Nr(n){let e=[...n].length;return e>=1&&e<=20}function Oa(n){let e=n.select({id:h.id,workspace_id:h.workspace_id,metadata:h.metadata}).from(h).all(),t=[];for(let r of e){let o=mo(r.metadata);o!==null&&t.push({id:r.id,workspace_id:r.workspace_id,metadata:r.metadata,label:o.slice(Zt.length)});}return t}function Na(n){return n===null?isNull(m.workspace_id):eq(m.workspace_id,n)}function Aa(n){return n===null?isNull(m.workspace_id):or$1(isNull(m.workspace_id),eq(m.workspace_id,n))}function xa(n,e,t){let r=n.select().from(m).where(and(eq(m.code_group,lt),eq(m.code_name,e),Na(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,lt),Aa(t))).get(),s=it();for(;n.select({code:m.code}).from(m).where(and(eq(m.code_group,lt),eq(m.code,s))).limit(1).get();)s=it();let i=new Date().toISOString();return n.insert(m).values({code_group:lt,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 La(n,e,t,r){let o=n.select({id:h.id,workspace_id:h.workspace_id,metadata:h.metadata}).from(h).all(),s=`${Zt}${e}`,i=0,d=new Date().toISOString();for(let l of o){if(r!==null&&l.workspace_id!==r||mo(l.metadata)!==s)continue;let u=xr(l.metadata)??{},p=u.threadTitle,_=p&&typeof p=="object"&&!Array.isArray(p)?{...p}:{};_.state=t,u.threadTitle=_,n.update(h).set({metadata:JSON.stringify(u),updated_at:d}).where(eq(h.id,l.id)).run(),i+=1;}return i}function Ar(n,e,t){return n.transaction(r=>{let o=xa(r,e,t),s=La(r,e,o.code,t);return {...o,migratedRows:s}},{behavior:"immediate"})}function Pa(n,e){return n.select({code:m.code}).from(m).where(and(eq(m.code_group,lt),eq(m.code_name,e),isNull(m.workspace_id),eq(m.is_builtin,0))).limit(1).get()?.code??null}function $a(n){let e=new Set(n.select({code:m.code}).from(m).where(eq(m.code_group,lt)).all().map(s=>s.code)),t=n.select({metadata:h.metadata}).from(h).all(),r=0,o=0;for(let s of t){let d=xr(s.metadata)?.threadTitle;if(!d||typeof d!="object"||Array.isArray(d))continue;let l=d.state;typeof l=="string"&&(l.startsWith(Zt)&&(r+=1),e.has(l)||(o+=1));}return {remainingCustomReferences:r,orphanReferences:o}}function wo(n={}){let e=Da(n);if(!existsSync(e))return {migratedRows:0,createdCodes:0,remainingCustomReferences:0,orphanReferences:0};let t=k(e);try{x(t.db,e);let r=Oa(t.db),o=new Set;for(let p of n.configuredLabels??[])typeof p=="string"&&o.add(p);let s=new Set(o),i=new Map;for(let p of r)if(Nr(p.label))if(p.workspace_id===null)s.add(p.label);else {let _=i.get(p.workspace_id)??new Set;_.add(p.label),i.set(p.workspace_id,_);}let d=0,l=0,u=new Map;for(let p of [...s].sort()){if(!Nr(p))continue;let _=Ar(t.db,p,null);u.set(p,_.code),d+=_.migratedRows,_.created&&(l+=1);}for(let p of [...i.keys()].sort())for(let _ of [...i.get(p)].sort()){if(!Nr(_)||u.has(_))continue;if(Pa(t.db,_)){let f=Ar(t.db,_,null);u.set(_,f.code),d+=f.migratedRows,f.created&&(l+=1);continue}let g=Ar(t.db,_,p);d+=g.migratedRows,g.created&&(l+=1);}return {migratedRows:d,createdCodes:l,...$a(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 ja=wo;var yo=["urgent","high","medium","low"],To=["investigating","in-progress","in-review","on-hold","done"],vt="custom:";var Ma=new Set(yo),Ba=new Set(To),Ha={urgent:"U \uAE34\uAE09 Urgent",high:"P0 \uAE09\uD568 High",medium:"P1 \uC911\uC694 Medium",low:"P2 \uBCF4\uD1B5 Low"},Lr={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 ko(n,e){return !e||e.includes(n)?e??n:`${n} ${e}`}function It(n){return typeof n=="string"&&Ma.has(n)}function Ct(n){if(typeof n!="string")return false;if(Ba.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(vt))return false;let e=n.slice(vt.length);return e.length>=1&&e.length<=20}function bo(n){if(n.startsWith(vt))return n.slice(vt.length)}function Pr(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 qa(n){let e=Pr(n);return !!e&&Object.prototype.hasOwnProperty.call(e,"threadTitle")}function er(n){let e=Pr(n);if(!e)return {};let t=e.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {};let r=t,o={};return It(r.priority)&&(o.priority=r.priority),Ct(r.state)&&(o.state=r.state),o}function $r(n,e){let t=Pr(n)??{},r={...er(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 Fa(n,e=new Map){let t=[];return n.priority&&t.push(ko(Ha[n.priority],e.get(n.priority))),n.state&&(n.state.startsWith(vt)?t.push(bo(n.state)??""):Lr[n.state]?t.push(ko(Lr[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(Lr[n.state]??"")),t.filter(Boolean).join(" ")}function Ro(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 Ua(n){return Ro(n,It)}function za(n){return Ro(n,Ct)}function Wa(n,e){return e?n?e.values.has(n):e.includeNone:true}var ir=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;}},ht=class extends ir{},Ja=new Set(mn),Ya=new Set(fn),Xa=new Set(wn),Qa=new Set(kn),Za=50,Io=100,Co=280;function U(n){throw new c("VALIDATION",n)}function pt(n){throw new c("NOT_FOUND",n)}function G(n,e){(typeof n!="string"||n.trim().length===0)&&U(`${e} is required`);}function tr(n={}){let e=n.actor??n,t=e.actorType??"system";return Ja.has(t)||U(`invalid actorType: ${String(t)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&U("actorId must be a string or null"),{actorType:t,actorId:e.actorId??null}}function ed(n){G(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&G(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&U("title must not be empty"),n.title.length>120&&U("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!It(n.priority)&&U(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!Ct(n.state)&&U(`invalid state: ${String(n.state)}`);}function td(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&U("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)&&U(`${t} must be a non-negative integer`);let e=n.limit??Za;return (!Number.isInteger(e)||e<1||e>Io)&&U(`limit must be between 1 and ${Io}`),e}function Do(n){typeof n!="string"&&U("text is required");let e=n.trim();return e.length===0&&U("text must not be empty"),e.length>Co&&U(`text must be at most ${Co} characters`),e}function _t(n,e){return G(n??"",e),n}function Oo(n){Qa.has(n)||U(`invalid highlight kind: ${String(n)}`);}function rd(n){Xa.has(n)||U(`invalid highlight source: ${String(n)}`);}function nd(n){G(n.threadId,"threadId"),G(n.workspaceId,"workspaceId");let e=n.source??"manual";rd(e),Oo(n.kind);let t=Do(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,o=n.coversToTaskId??n.toTaskId??n.taskId;if(e==="manual"){let p=n.taskId??(r&&o&&r===o?r:void 0),_=_t(p,"taskId");return (r!==_||o!==_)&&U("manual highlights must cover exactly one task"),{source:e,kind:n.kind,text:t,coversFromTaskId:_,coversToTaskId:_,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=_t(r,"coversFromTaskId"),i=_t(o,"coversToTaskId"),d=n.sourceTaskId??s,l=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),u=n.contentFingerprint??n.idempotencyKey??null;return _t(d??void 0,"sourceTaskId"),_t(l??void 0,"detectorVersion"),_t(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 sr(n){let e=er(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 od(n){try{let e=JSON.stringify(n);return (!e||e==="null"||e.startsWith("["))&&U("event payload must be a JSON object"),e}catch(e){throw new c("VALIDATION","event payload must be JSON serializable",e)}}function rr(n,e){return n.select({maxSeq:sql`COALESCE(MAX(${P.seq}), 0)`}).from(P).where(eq(P.thread_id,e)).get()?.maxSeq??0}function nr(n,e){return !!n.select({id:P.id}).from(P).where(eq(P.thread_id,e)).limit(1).get()}function Nt(n,e){Ya.has(e.type)||U(`invalid thread event type: ${String(e.type)}`);let t=be("the");n.insert(P).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:od(e.payload),created_at:e.createdAt}).run();let r=n.select().from(P).where(eq(P.id,t)).get();if(!r)throw new c("DB_ERROR","Thread event insert did not return a row");return r}function or(n,e,t,r,o){let s=sr(e);Nt(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 jr(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 Mr(n,e,t,r,o,s,i){let d=o==="thread.highlight.created"?jr(e):{before:i?jr({...e,...i,id:e.id}):void 0,after:jr(e)};return Nt(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})}var Br=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}findThread(e,t,r){let o=eq(h.id,t),s=r===void 0?o:r===null?and(o,isNull(h.workspace_id)):and(o,eq(h.workspace_id,r));return e.select().from(h).where(s).limit(1).get()}resolveWorkspaceId(e){if(G(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let t=this.openHandle(false);try{return t.db.select({workspaceId:h.workspace_id}).from(h).where(eq(h.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();}}updateSnapshot(e){ed(e);let t=tr(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||pt(`Thread ${e.threadId} not found`);let d=sr(i),l=e.title!==void 0,u=l&&e.title!==d.title,p=l&&i.title_locked!==1,_=e.priority!==void 0&&e.priority!==d.priority,g=e.state!==void 0&&e.state!==d.state,f=u||_||g;if(!f&&!p)return d;let C=i.metadata;(_||g)&&(C=$r(i.metadata,{priority:e.priority,state:e.state}));let w={};if(f&&(w.metadata=C,w.updated_at=r),u&&(w.title=e.title),l&&(w.title_locked=1),s.update(h).set(w).where(e.workspaceId===void 0?eq(h.id,e.threadId):e.workspaceId===null?and(eq(h.id,e.threadId),isNull(h.workspace_id)):and(eq(h.id,e.threadId),eq(h.workspace_id,e.workspaceId))).run(),!f){let z={...i,title_locked:1};return sr(z)}let I=rr(s,i.id)+1;nr(s,i.id)||(or(s,i,t,r,I),I+=1),u&&(Nt(s,{threadId:i.id,seq:I,type:"thread.title.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),I+=1),_&&(Nt(s,{threadId:i.id,seq:I,type:"thread.priority.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),I+=1),g&&Nt(s,{threadId:i.id,seq:I,type:"thread.state.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let R={...i,title:u?e.title:i.title,metadata:C,title_locked:l?1:i.title_locked,updated_at:r};return sr(R)},{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(G(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(${P.seq}), 0)`}).from(P).where(eq(P.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();}}listTimeline(e,t,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:t}:e;G(o.threadId,"threadId"),G(o.workspaceId,"workspaceId");let s=td(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(${P.seq}), 0)`}).from(P).where(eq(P.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(P).where(and(eq(P.thread_id,o.threadId),lt$1(P.seq,o.beforeSeq))).orderBy(desc(P.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(P).where(and(eq(P.thread_id,o.threadId),sql`${P.seq} > ${o.afterSeq}`)).orderBy(asc(P.seq)).limit(s+1).all():l=i.db.select().from(P).where(eq(P.thread_id,o.threadId)).orderBy(desc(P.seq)).limit(s+1).all().reverse();let u=l.length>s,p=o.afterSeq!==void 0?l.slice(0,s):u?l.slice(1):l,_=!1,g=p[0];return g&&(_=!!i.db.select({id:P.id}).from(P).where(and(eq(P.thread_id,o.threadId),lt$1(P.seq,g.seq))).limit(1).get()),{items:p,latestSeq:d,hasMoreOlder:_}}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=nd(e),r=tr(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||pt(`Thread ${e.threadId} not found`),t.source==="auto"){let g=i.select().from(A).where(and(eq(A.thread_id,e.threadId),eq(A.source_task_id,t.sourceTaskId),eq(A.detector_version,t.detectorVersion),eq(A.content_fingerprint,t.contentFingerprint))).orderBy(asc(A.created_at),asc(A.id)).limit(1).get();if(g)return g}let l=e.id??be("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(A).values(u).run();let p=i.select().from(A).where(eq(A.id,l)).get();if(!p)throw new c("DB_ERROR","Highlight insert did not return a row");let _=rr(i,d.id)+1;return nr(i,d.id)||(or(i,d,r,o,_),_+=1),Mr(i,p,r,o,"thread.highlight.created",_),p},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){G(e.threadId,"threadId"),G(e.workspaceId,"workspaceId"),G(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&U("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&U("highlight update requires at least one field"),e.kind!==void 0&&Oo(e.kind);let t=e.text===void 0?void 0:Do(e.text),r=tr(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||pt(`Thread ${e.threadId} not found`);let l=i.select().from(A).where(and(eq(A.id,e.highlightId),eq(A.thread_id,d.id))).limit(1).get();if(l||pt(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new ht(d.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new ht(d.id,l.id,e.expectedRevision,l.revision);let u=e.kind??l.kind,p=t??l.text,_=e.coversFromTaskId??l.covers_from_task_id,g=e.coversToTaskId??l.covers_to_task_id;(!p||_.length===0||g.length===0)&&U("highlight projection is incomplete");let f=u!==l.kind||p!==l.text||_!==l.covers_from_task_id||g!==l.covers_to_task_id,C=r.actorType==="user"&&l.source==="auto"&&f?"manual":l.source;if(!(f||C!==l.source))return l;let I=l.revision+1;i.update(A).set({source:C,kind:u,text:p,covers_from_task_id:_,covers_to_task_id:g,revision:I,updated_at:o}).where(and(eq(A.id,l.id),eq(A.revision,l.revision))).run();let R=i.select().from(A).where(eq(A.id,l.id)).get();if(!R)throw new c("DB_ERROR","Highlight update did not return a row");let z=rr(i,d.id)+1;return nr(i,d.id)||(or(i,d,r,o,z),z+=1),Mr(i,R,r,o,"thread.highlight.updated",z,l),R},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){G(e.threadId,"threadId"),G(e.workspaceId,"workspaceId"),G(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&U("expectedRevision must be a non-negative integer");let t=tr(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||pt(`Thread ${e.threadId} not found`);let d=s.select().from(A).where(and(eq(A.id,e.highlightId),eq(A.thread_id,i.id))).limit(1).get();if(d||pt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new ht(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let l=d.revision+1;s.update(A).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(and(eq(A.id,d.id),eq(A.revision,d.revision))).run();let u=s.select().from(A).where(eq(A.id,d.id)).get();if(!u)throw new c("DB_ERROR","Highlight dismissal did not return a row");let p=rr(s,i.id)+1;return nr(s,i.id)||(or(s,i,t,r,p),p+=1),Mr(s,u,t,r,"thread.highlight.deleted",p,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(G(e,"threadId"),G(t,"workspaceId"),r.taskId!==void 0&&G(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&G(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&G(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(A).where(and(eq(A.thread_id,e),eq(A.status,"active"))).orderBy(asc(A.created_at),asc(A.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(sql`
|
|
368
|
+
`),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(h).set({last_message:t,updated_at:s}).where(eq(h.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(h).set(o).where(eq(h.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 et("THREAD_TITLE_PATCH_INVALID","Thread-title metadata patch must be an object");if(Object.keys(o).some(l=>l!=="priority"&&l!=="state"))return new et("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 et("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 et("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(h.id,e),eq(h.workspace_id,r)):eq(h.id,e);return d.db.transaction(u=>{let p=u.select({metadata:h.metadata}).from(h).where(l).get();if(!p)return null;let _=St(p.metadata),g=_.threadTitle,f=g&&typeof g=="object"&&!Array.isArray(g)?{...g}:{};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?_.threadTitle=f:delete _.threadTitle;let C=Object.keys(_).length>0?JSON.stringify(_):null,w=new Date().toISOString();u.update(h).set({metadata:C,updated_at:w}).where(l).run();let I=u.select({metadata:h.metadata}).from(h).where(l).get();if(!I)throw new c("DB_ERROR","Thread-title metadata update could not be read back");let R=Ea(I.metadata);return {threadId:e,priority:R.priority,state:R.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(h.id,e),eq(h.workspace_id,t)):eq(h.id,e);return r.db.transaction(s=>{let i=s.select({pinned:h.pinned,metadata:h.metadata}).from(h).where(o).get();if(!i)return null;let d=i.pinned?0:1,l=St(i.metadata);if(d){let u=t?and(eq(h.pinned,1),eq(h.workspace_id,t)):eq(h.pinned,1),p=s.select({metadata:h.metadata}).from(h).where(u).all(),_=null;for(let g of p){let f=St(g.metadata);typeof f.pinOrder=="number"&&(_===null||f.pinOrder<_)&&(_=f.pinOrder);}l.pinOrder=_===null?0:_-1;}else delete l.pinOrder;return s.update(h).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(h.id,e[s]),eq(h.workspace_id,t)):eq(h.id,e[s]),d=o.select({metadata:h.metadata}).from(h).where(i).get();if(!d)continue;let l=St(d.metadata);l.pinOrder=s+1,o.update(h).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(h.id,e),eq(h.workspace_id,t)):eq(h.id,e),s=r.db.select({starred:h.starred}).from(h).where(o).get();if(!s)return null;let i=s.starred?0:1;return r.db.update(h).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(h.id,e),eq(h.workspace_id,t)):eq(h.id,e);return i.db.transaction(u=>{let p=u.select({metadata:h.metadata}).from(h).where(d).get();if(!p)return null;let _=p.metadata?JSON.parse(p.metadata):{},g=_.overdrive??{},f=o?.defaultTurns??g.defaultTurns??3,C=o?.updatedBy??"ui",w=new Date().toISOString(),I,R,z,ze;switch(r){case "enable-count":{let Oe=o?.turns??f,Ne=o?.consumeCurrent?Math.max(Oe-1,0):Oe;I=Ne>0?"count":"off",R=Ne,z=!0,ze="count";break}case "enable-latch":{I="latch",R=0,z=!0,ze="latch";break}case "disable":{I="off",R=0,z=!1;break}default:{let Oe=g.state??"off",Ne=typeof g.remaining=="number"?g.remaining:0;if(Oe==="count"&&Ne>0){let Jr=Ne-1;Jr<=0?(I="off",R=0):(I="count",R=Jr),z=!0,ze="count";}else Oe==="latch"?(I="latch",R=0,z=!0,ze="latch"):(I="off",R=0,z=!1);break}}return _.overdrive={state:I,remaining:R,defaultTurns:f,updatedAt:w,updatedBy:C},u.update(h).set({metadata:JSON.stringify(_),updated_at:w}).where(d).run(),{applied:z,appliedMode:ze,state:I,remaining:R}},{behavior:"immediate"})}catch(d){throw d instanceof c?d:new c("DB_ERROR","Failed to resolve overdrive",d)}finally{i.close();}}};var ut="THREAD_STATE",er="custom:";function Da(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 xr(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 mo(n){let t=xr(n)?.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t.state;return typeof r=="string"&&r.startsWith(er)?r:null}function Nr(n){let e=[...n].length;return e>=1&&e<=20}function Oa(n){let e=n.select({id:h.id,workspace_id:h.workspace_id,metadata:h.metadata}).from(h).all(),t=[];for(let r of e){let o=mo(r.metadata);o!==null&&t.push({id:r.id,workspace_id:r.workspace_id,metadata:r.metadata,label:o.slice(er.length)});}return t}function Na(n){return n===null?isNull(m.workspace_id):eq(m.workspace_id,n)}function Aa(n){return n===null?isNull(m.workspace_id):or$1(isNull(m.workspace_id),eq(m.workspace_id,n))}function xa(n,e,t){let r=n.select().from(m).where(and(eq(m.code_group,ut),eq(m.code_name,e),Na(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,ut),Aa(t))).get(),s=at();for(;n.select({code:m.code}).from(m).where(and(eq(m.code_group,ut),eq(m.code,s))).limit(1).get();)s=at();let i=new Date().toISOString();return n.insert(m).values({code_group:ut,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 La(n,e,t,r){let o=n.select({id:h.id,workspace_id:h.workspace_id,metadata:h.metadata}).from(h).all(),s=`${er}${e}`,i=0,d=new Date().toISOString();for(let l of o){if(r!==null&&l.workspace_id!==r||mo(l.metadata)!==s)continue;let u=xr(l.metadata)??{},p=u.threadTitle,_=p&&typeof p=="object"&&!Array.isArray(p)?{...p}:{};_.state=t,u.threadTitle=_,n.update(h).set({metadata:JSON.stringify(u),updated_at:d}).where(eq(h.id,l.id)).run(),i+=1;}return i}function Ar(n,e,t){return n.transaction(r=>{let o=xa(r,e,t),s=La(r,e,o.code,t);return {...o,migratedRows:s}},{behavior:"immediate"})}function Pa(n,e){return n.select({code:m.code}).from(m).where(and(eq(m.code_group,ut),eq(m.code_name,e),isNull(m.workspace_id),eq(m.is_builtin,0))).limit(1).get()?.code??null}function $a(n){let e=new Set(n.select({code:m.code}).from(m).where(eq(m.code_group,ut)).all().map(s=>s.code)),t=n.select({metadata:h.metadata}).from(h).all(),r=0,o=0;for(let s of t){let d=xr(s.metadata)?.threadTitle;if(!d||typeof d!="object"||Array.isArray(d))continue;let l=d.state;typeof l=="string"&&(l.startsWith(er)&&(r+=1),e.has(l)||(o+=1));}return {remainingCustomReferences:r,orphanReferences:o}}function wo(n={}){let e=Da(n);if(!existsSync(e))return {migratedRows:0,createdCodes:0,remainingCustomReferences:0,orphanReferences:0};let t=k(e);try{x(t.db,e);let r=Oa(t.db),o=new Set;for(let p of n.configuredLabels??[])typeof p=="string"&&o.add(p);let s=new Set(o),i=new Map;for(let p of r)if(Nr(p.label))if(p.workspace_id===null)s.add(p.label);else {let _=i.get(p.workspace_id)??new Set;_.add(p.label),i.set(p.workspace_id,_);}let d=0,l=0,u=new Map;for(let p of [...s].sort()){if(!Nr(p))continue;let _=Ar(t.db,p,null);u.set(p,_.code),d+=_.migratedRows,_.created&&(l+=1);}for(let p of [...i.keys()].sort())for(let _ of [...i.get(p)].sort()){if(!Nr(_)||u.has(_))continue;if(Pa(t.db,_)){let f=Ar(t.db,_,null);u.set(_,f.code),d+=f.migratedRows,f.created&&(l+=1);continue}let g=Ar(t.db,_,p);d+=g.migratedRows,g.created&&(l+=1);}return {migratedRows:d,createdCodes:l,...$a(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 ja=wo;var yo=["urgent","high","medium","low"],To=["investigating","in-progress","in-review","on-hold","done"],vt="custom:";var Ma=new Set(yo),Ba=new Set(To),Ha={urgent:"U \uAE34\uAE09 Urgent",high:"P0 \uAE09\uD568 High",medium:"P1 \uC911\uC694 Medium",low:"P2 \uBCF4\uD1B5 Low"},Lr={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 ko(n,e){return !e||e.includes(n)?e??n:`${n} ${e}`}function It(n){return typeof n=="string"&&Ma.has(n)}function Ct(n){if(typeof n!="string")return false;if(Ba.has(n))return true;if(n.startsWith("c_"))return n.length>2;if(!n.startsWith(vt))return false;let e=n.slice(vt.length);return e.length>=1&&e.length<=20}function bo(n){if(n.startsWith(vt))return n.slice(vt.length)}function Pr(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 qa(n){let e=Pr(n);return !!e&&Object.prototype.hasOwnProperty.call(e,"threadTitle")}function tr(n){let e=Pr(n);if(!e)return {};let t=e.threadTitle;if(!t||typeof t!="object"||Array.isArray(t))return {};let r=t,o={};return It(r.priority)&&(o.priority=r.priority),Ct(r.state)&&(o.state=r.state),o}function $r(n,e){let t=Pr(n)??{},r={...tr(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 Fa(n,e=new Map){let t=[];return n.priority&&t.push(ko(Ha[n.priority],e.get(n.priority))),n.state&&(n.state.startsWith(vt)?t.push(bo(n.state)??""):Lr[n.state]?t.push(ko(Lr[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(Lr[n.state]??"")),t.filter(Boolean).join(" ")}function Ro(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 Ua(n){return Ro(n,It)}function za(n){return Ro(n,Ct)}function Wa(n,e){return e?n?e.values.has(n):e.includeNone:true}var ir=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;}},ht=class extends ir{},Ja=new Set(mn),Ya=new Set(fn),Xa=new Set(wn),Qa=new Set(kn),Za=50,Io=100,Co=280;function U(n){throw new c("VALIDATION",n)}function pt(n){throw new c("NOT_FOUND",n)}function G(n,e){(typeof n!="string"||n.trim().length===0)&&U(`${e} is required`);}function rr(n={}){let e=n.actor??n,t=e.actorType??"system";return Ja.has(t)||U(`invalid actorType: ${String(t)}`),e.actorId!==void 0&&e.actorId!==null&&typeof e.actorId!="string"&&U("actorId must be a string or null"),{actorType:t,actorId:e.actorId??null}}function ed(n){G(n.threadId,"threadId"),n.workspaceId!==void 0&&n.workspaceId!==null&&G(n.workspaceId,"workspaceId"),n.title!==void 0&&n.title!==null&&((typeof n.title!="string"||n.title.trim().length===0)&&U("title must not be empty"),n.title.length>120&&U("title must be at most 120 characters")),n.priority!==void 0&&n.priority!==null&&!It(n.priority)&&U(`invalid priority: ${String(n.priority)}`),n.state!==void 0&&n.state!==null&&!Ct(n.state)&&U(`invalid state: ${String(n.state)}`);}function td(n){n.beforeSeq!==void 0&&n.afterSeq!==void 0&&U("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)&&U(`${t} must be a non-negative integer`);let e=n.limit??Za;return (!Number.isInteger(e)||e<1||e>Io)&&U(`limit must be between 1 and ${Io}`),e}function Do(n){typeof n!="string"&&U("text is required");let e=n.trim();return e.length===0&&U("text must not be empty"),e.length>Co&&U(`text must be at most ${Co} characters`),e}function _t(n,e){return G(n??"",e),n}function Oo(n){Qa.has(n)||U(`invalid highlight kind: ${String(n)}`);}function rd(n){Xa.has(n)||U(`invalid highlight source: ${String(n)}`);}function nd(n){G(n.threadId,"threadId"),G(n.workspaceId,"workspaceId");let e=n.source??"manual";rd(e),Oo(n.kind);let t=Do(n.text),r=n.coversFromTaskId??n.fromTaskId??n.taskId,o=n.coversToTaskId??n.toTaskId??n.taskId;if(e==="manual"){let p=n.taskId??(r&&o&&r===o?r:void 0),_=_t(p,"taskId");return (r!==_||o!==_)&&U("manual highlights must cover exactly one task"),{source:e,kind:n.kind,text:t,coversFromTaskId:_,coversToTaskId:_,agentId:n.agentId??null,sourceTaskId:null,detectorVersion:null,contentFingerprint:null}}let s=_t(r,"coversFromTaskId"),i=_t(o,"coversToTaskId"),d=n.sourceTaskId??s,l=n.detectorVersion??(n.idempotencyKey!==void 0?"default":null),u=n.contentFingerprint??n.idempotencyKey??null;return _t(d??void 0,"sourceTaskId"),_t(l??void 0,"detectorVersion"),_t(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 Nt(n){let e=tr(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 od(n){try{let e=JSON.stringify(n);return (!e||e==="null"||e.startsWith("["))&&U("event payload must be a JSON object"),e}catch(e){throw new c("VALIDATION","event payload must be JSON serializable",e)}}function nr(n,e){return n.select({maxSeq:sql`COALESCE(MAX(${P.seq}), 0)`}).from(P).where(eq(P.thread_id,e)).get()?.maxSeq??0}function or(n,e){return !!n.select({id:P.id}).from(P).where(eq(P.thread_id,e)).limit(1).get()}function At(n,e){Ya.has(e.type)||U(`invalid thread event type: ${String(e.type)}`);let t=be("the");n.insert(P).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:od(e.payload),created_at:e.createdAt}).run();let r=n.select().from(P).where(eq(P.id,t)).get();if(!r)throw new c("DB_ERROR","Thread event insert did not return a row");return r}function sr(n,e,t,r,o){let s=Nt(e);At(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 jr(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 Mr(n,e,t,r,o,s,i){let d=o==="thread.highlight.created"?jr(e):{before:i?jr({...e,...i,id:e.id}):void 0,after:jr(e)};return At(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})}var Br=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath??super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(!e&&!existsSync(t))throw new c("NOT_FOUND","Database not found");if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}findThread(e,t,r){let o=eq(h.id,t),s=r===void 0?o:r===null?and(o,isNull(h.workspace_id)):and(o,eq(h.workspace_id,r));return e.select().from(h).where(s).limit(1).get()}resolveWorkspaceId(e){if(G(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let t=this.openHandle(false);try{return t.db.select({workspaceId:h.workspace_id}).from(h).where(eq(h.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(G(e,"threadId"),!existsSync(this.resolveDbPath()))return null;let r=this.openHandle(false);try{let o=this.findThread(r.db,e,t);return o?Nt(o):null}catch(o){throw o instanceof c?o:new c("DB_ERROR","Failed to read thread snapshot",o)}finally{r.close();}}updateSnapshot(e){ed(e);let t=rr(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||pt(`Thread ${e.threadId} not found`);let d=Nt(i),l=e.title!==void 0,u=l&&e.title!==d.title,p=l&&i.title_locked!==1,_=e.priority!==void 0&&e.priority!==d.priority,g=e.state!==void 0&&e.state!==d.state,f=u||_||g;if(!f&&!p)return d;let C=i.metadata;(_||g)&&(C=$r(i.metadata,{priority:e.priority,state:e.state}));let w={};if(f&&(w.metadata=C,w.updated_at=r),u&&(w.title=e.title),l&&(w.title_locked=1),s.update(h).set(w).where(e.workspaceId===void 0?eq(h.id,e.threadId):e.workspaceId===null?and(eq(h.id,e.threadId),isNull(h.workspace_id)):and(eq(h.id,e.threadId),eq(h.workspace_id,e.workspaceId))).run(),!f){let z={...i,title_locked:1};return Nt(z)}let I=nr(s,i.id)+1;or(s,i.id)||(sr(s,i,t,r,I),I+=1),u&&(At(s,{threadId:i.id,seq:I,type:"thread.title.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.title,after:e.title}}),I+=1),_&&(At(s,{threadId:i.id,seq:I,type:"thread.priority.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.priority,after:e.priority}}),I+=1),g&&At(s,{threadId:i.id,seq:I,type:"thread.state.changed",actorType:t.actorType,actorId:t.actorId,createdAt:r,taskId:e.taskId,payload:{before:d.state,after:e.state}});let R={...i,title:u?e.title:i.title,metadata:C,title_locked:l?1:i.title_locked,updated_at:r};return Nt(R)},{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(G(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(${P.seq}), 0)`}).from(P).where(eq(P.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();}}listTimeline(e,t,r={}){let o=typeof e=="string"?{...r,threadId:e,workspaceId:t}:e;G(o.threadId,"threadId"),G(o.workspaceId,"workspaceId");let s=td(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(${P.seq}), 0)`}).from(P).where(eq(P.thread_id,o.threadId)).get()?.maxSeq??0,l;o.beforeSeq!==void 0?l=i.db.select().from(P).where(and(eq(P.thread_id,o.threadId),lt$1(P.seq,o.beforeSeq))).orderBy(desc(P.seq)).limit(s+1).all().reverse():o.afterSeq!==void 0?l=i.db.select().from(P).where(and(eq(P.thread_id,o.threadId),sql`${P.seq} > ${o.afterSeq}`)).orderBy(asc(P.seq)).limit(s+1).all():l=i.db.select().from(P).where(eq(P.thread_id,o.threadId)).orderBy(desc(P.seq)).limit(s+1).all().reverse();let u=l.length>s,p=o.afterSeq!==void 0?l.slice(0,s):u?l.slice(1):l,_=!1,g=p[0];return g&&(_=!!i.db.select({id:P.id}).from(P).where(and(eq(P.thread_id,o.threadId),lt$1(P.seq,g.seq))).limit(1).get()),{items:p,latestSeq:d,hasMoreOlder:_}}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=nd(e),r=rr(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||pt(`Thread ${e.threadId} not found`),t.source==="auto"){let g=i.select().from(A).where(and(eq(A.thread_id,e.threadId),eq(A.source_task_id,t.sourceTaskId),eq(A.detector_version,t.detectorVersion),eq(A.content_fingerprint,t.contentFingerprint))).orderBy(asc(A.created_at),asc(A.id)).limit(1).get();if(g)return g}let l=e.id??be("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(A).values(u).run();let p=i.select().from(A).where(eq(A.id,l)).get();if(!p)throw new c("DB_ERROR","Highlight insert did not return a row");let _=nr(i,d.id)+1;return or(i,d.id)||(sr(i,d,r,o,_),_+=1),Mr(i,p,r,o,"thread.highlight.created",_),p},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to create thread highlight",i)}finally{s.close();}}updateHighlight(e){G(e.threadId,"threadId"),G(e.workspaceId,"workspaceId"),G(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&U("expectedRevision must be a non-negative integer"),e.text===void 0&&e.kind===void 0&&e.coversFromTaskId===void 0&&e.coversToTaskId===void 0&&U("highlight update requires at least one field"),e.kind!==void 0&&Oo(e.kind);let t=e.text===void 0?void 0:Do(e.text),r=rr(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||pt(`Thread ${e.threadId} not found`);let l=i.select().from(A).where(and(eq(A.id,e.highlightId),eq(A.thread_id,d.id))).limit(1).get();if(l||pt(`Highlight ${e.highlightId} not found`),l.revision!==e.expectedRevision)throw new ht(d.id,l.id,e.expectedRevision,l.revision);if(l.status!=="active")throw new ht(d.id,l.id,e.expectedRevision,l.revision);let u=e.kind??l.kind,p=t??l.text,_=e.coversFromTaskId??l.covers_from_task_id,g=e.coversToTaskId??l.covers_to_task_id;(!p||_.length===0||g.length===0)&&U("highlight projection is incomplete");let f=u!==l.kind||p!==l.text||_!==l.covers_from_task_id||g!==l.covers_to_task_id,C=r.actorType==="user"&&l.source==="auto"&&f?"manual":l.source;if(!(f||C!==l.source))return l;let I=l.revision+1;i.update(A).set({source:C,kind:u,text:p,covers_from_task_id:_,covers_to_task_id:g,revision:I,updated_at:o}).where(and(eq(A.id,l.id),eq(A.revision,l.revision))).run();let R=i.select().from(A).where(eq(A.id,l.id)).get();if(!R)throw new c("DB_ERROR","Highlight update did not return a row");let z=nr(i,d.id)+1;return or(i,d.id)||(sr(i,d,r,o,z),z+=1),Mr(i,R,r,o,"thread.highlight.updated",z,l),R},{behavior:"immediate"})}catch(i){throw i instanceof c?i:new c("DB_ERROR","Failed to update thread highlight",i)}finally{s.close();}}dismissHighlight(e){G(e.threadId,"threadId"),G(e.workspaceId,"workspaceId"),G(e.highlightId,"highlightId"),(!Number.isInteger(e.expectedRevision)||e.expectedRevision<0)&&U("expectedRevision must be a non-negative integer");let t=rr(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||pt(`Thread ${e.threadId} not found`);let d=s.select().from(A).where(and(eq(A.id,e.highlightId),eq(A.thread_id,i.id))).limit(1).get();if(d||pt(`Highlight ${e.highlightId} not found`),d.revision!==e.expectedRevision)throw new ht(i.id,d.id,e.expectedRevision,d.revision);if(d.status==="dismissed")return d;let l=d.revision+1;s.update(A).set({status:"dismissed",text:null,revision:l,updated_at:r,dismissed_at:r}).where(and(eq(A.id,d.id),eq(A.revision,d.revision))).run();let u=s.select().from(A).where(eq(A.id,d.id)).get();if(!u)throw new c("DB_ERROR","Highlight dismissal did not return a row");let p=nr(s,i.id)+1;return or(s,i.id)||(sr(s,i,t,r,p),p+=1),Mr(s,u,t,r,"thread.highlight.deleted",p,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(G(e,"threadId"),G(t,"workspaceId"),r.taskId!==void 0&&G(r.taskId,"taskId"),r.coversFromTaskId!==void 0&&G(r.coversFromTaskId,"coversFromTaskId"),r.coversToTaskId!==void 0&&G(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(A).where(and(eq(A.thread_id,e),eq(A.status,"active"))).orderBy(asc(A.created_at),asc(A.id)).all();if(r.taskId===void 0&&r.coversFromTaskId===void 0&&r.coversToTaskId===void 0)return i;let d=o.db.all(sql`
|
|
369
369
|
SELECT id, started_at FROM tasks WHERE thread_id = ${e}
|
|
370
370
|
ORDER BY started_at ASC, id ASC
|
|
371
|
-
`),l=new Map(d.map((g,f)=>[g.id,f])),u=r.taskId===void 0?void 0:l.get(r.taskId),p=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),_=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(g=>{let f=l.get(g.covers_from_task_id),C=l.get(g.covers_to_task_id);if(f===void 0||C===void 0)return !1;let w=Math.min(f,C),I=Math.max(f,C);return !(u!==void 0&&(u<w||u>I)||p!==void 0&&I<p||_!==void 0&&w>_)})}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 Hr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Pe).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(Pe).where(eq(Pe.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(Pe).where(eq(Pe.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 qr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(Ee).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(Ee).where(eq(Ee.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:Ee.tool_name,count:sql`count(*)`}).from(Ee).where(eq(Ee.task_id,e)).groupBy(Ee.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 Fr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,t){if(!e.db.select({id:h.id}).from(h).where(eq(h.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(fe).where(eq(fe.thread_id,e)).orderBy(asc(fe.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(fe).where(and(eq(fe.id,t),eq(fe.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(fe).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(fe).where(eq(fe.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 Ur=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(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(ot).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(ot).orderBy(desc(ot.timestamp)).limit(e).all()}catch(r){throw new c("DB_ERROR","Failed to find recent request logs",r)}finally{t.close();}}};function Mo(n){return new Date(Math.floor(n/3e5)*3e5).toISOString()}var zr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}upsert(e){let t=this.openHandle(true);try{let r=Mo(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(Q).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:[Q.provider,Q.account_ref,Q.limit_window,Q.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:Q.provider,bucket_start:Q.bucket_start,used_percent:Q.used_percent,remaining_percent:Q.remaining_percent,resets_at:Q.resets_at}).from(Q).where(and(eq(Q.limit_window,e.window),gte(Q.bucket_start,e.fromIso),lte(Q.bucket_start,e.toIso))).orderBy(asc(Q.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 Wr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}publish(e){let t=this.openHandle(true);try{t.db.insert(ie).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:[ie.workspace_id,ie.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(ie).where(and(eq(ie.workspace_id,e.workspaceId),eq(ie.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(ie).where(and(eq(ie.workspace_id,e),eq(ie.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(ie).where(eq(ie.workspace_id,e)).orderBy(desc(ie.month)).all()}catch(r){throw new c("DB_ERROR","Failed to list usage reports",r)}finally{t.close();}}};var Wo=500,Go=50,Gr=class extends D{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??Wo;}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=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=be("ntf"),o=new Date().toISOString();return t.db.insert(v).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(v).where(eq(v.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:v.id}).from(v).innerJoin(K,eq(K.notification_id,v.id)).where(eq(v.workspace_id,t)).groupBy(v.id).orderBy(asc(v.created_at)).limit(s).all().map(l=>l.id);d.length!==0&&(e.db.delete(K).where(inArray(K.notification_id,d)).run(),e.db.delete(v).where(inArray(v.id,d)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??Go,r=this.openHandle(false);try{return r.db.select({id:v.id,workspace_id:v.workspace_id,agent_id:v.agent_id,task_id:v.task_id,thread_id:v.thread_id,source:v.source,level:v.level,title:v.title,body:v.body,target_user_id:v.target_user_id,created_at:v.created_at,metadata:v.metadata,read_at:K.read_at}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(eq(v.workspace_id,e.workspaceId)).orderBy(desc(v.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(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(and(eq(v.workspace_id,e.workspaceId),isNull(K.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:v.id}).from(v).where(and(eq(v.id,e.notificationId),eq(v.workspace_id,e.workspaceId))).get())throw new c("NOT_FOUND","Notification not found in workspace");return t.db.insert(K).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:v.id}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(and(eq(v.workspace_id,e.workspaceId),isNull(K.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(K).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 Jo=50,Vr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(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=be("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(O).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:O.task_id}).from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t))).orderBy(desc(O.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(O.task_id):eq(O.task_id,o.task_id);return r.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),s)).orderBy(asc(O.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(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.task_id,r))).orderBy(asc(O.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(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.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(O).set(s).where(eq(O.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=Jo){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t))).orderBy(desc(O.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(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.status,"dismissed"))).orderBy(desc(O.updated_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{Vr as AgentSuggestionRepository,To as BUILTIN_THREAD_STATES,D as BaseSqliteRepository,qt as COMMON_CODE_COLORS,Ht as COMMON_CODE_GROUPS,Qr as CREWX_JOURNAL_SIZE_LIMIT_BYTES,fr as CommonCodeRepository,J as CommonCodeRepositoryError,Jo as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Wo as DEFAULT_NOTIFICATION_CAP,Go as DEFAULT_NOTIFICATION_LIST_LIMIT,Pn as DEFAULT_PROJECT_STAGES,br as DEFAULT_PROJECT_STAGE_KEYS,Gr as NotificationRepository,Tr as ProjectRepository,c as RepositoryError,Ur as RequestLogRepository,Hr as SpanRepository,ro as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,Yt as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,to as TASK_LOG_MIGRATION_TERMINAL_STATUSES,yo as THREAD_PRIORITIES,bt as TaskLogRepository,Sr as TaskRepository,Fr as ThreadBoxRepository,ht as ThreadHighlightConflictError,ir as ThreadHistoryConflictError,Br as ThreadHistoryRepository,Or as ThreadRepository,et as ThreadTitleMetadataPatchError,qr as ToolCallRepository,zr as UsageLimitSnapshotRepository,Wr as UsageReportRepository,yr as WorkspaceRepository,Mo as calcBucketStart,bo as customStateLabel,it as generateCommonCodeId,ao as hasSufficientTaskLogMigrationFreeSpace,qa as hasThreadTitleKey,It as isThreadPriority,Ct as isThreadState,Wa as matchesThreadTitleFilter,$r as mergeThreadTitleMeta,wo as migrateLegacyThreadTitleCommonCodes,ja as migrateThreadTitleCommonCodes,k as openDrizzleDb,Ua as parseThreadPriorityFilter,za as parseThreadStateFilter,Ni as pushSchema,er as readThreadTitleMeta,ns as reclaimTemporaryJournal,no as resolveTaskLogMigrationDbPath,rt as runMigrations,x as runMigrationsOnce,wa as runTaskLogMigration,ka as taskLogBackupName,a as tasks,Fa as threadTitleSearchHaystack,uo as tryCheckpointTaskLogWal};
|
|
371
|
+
`),l=new Map(d.map((g,f)=>[g.id,f])),u=r.taskId===void 0?void 0:l.get(r.taskId),p=r.coversFromTaskId===void 0?void 0:l.get(r.coversFromTaskId),_=r.coversToTaskId===void 0?void 0:l.get(r.coversToTaskId);return i.filter(g=>{let f=l.get(g.covers_from_task_id),C=l.get(g.covers_to_task_id);if(f===void 0||C===void 0)return !1;let w=Math.min(f,C),I=Math.max(f,C);return !(u!==void 0&&(u<w||u>I)||p!==void 0&&I<p||_!==void 0&&w>_)})}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 Hr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}insertSpan(e){let t=this.openHandle(true);try{t.db.insert(Pe).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(Pe).where(eq(Pe.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(Pe).where(eq(Pe.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 qr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}insertToolCall(e){let t=this.openHandle(true);try{t.db.insert(Ee).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(Ee).where(eq(Ee.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:Ee.tool_name,count:sql`count(*)`}).from(Ee).where(eq(Ee.task_id,e)).groupBy(Ee.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 Fr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}ensureThreadExists(e,t){if(!e.db.select({id:h.id}).from(h).where(eq(h.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(fe).where(eq(fe.thread_id,e)).orderBy(asc(fe.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(fe).where(and(eq(fe.id,t),eq(fe.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(fe).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(fe).where(eq(fe.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 Ur=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(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(st).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(st).orderBy(desc(st.timestamp)).limit(e).all()}catch(r){throw new c("DB_ERROR","Failed to find recent request logs",r)}finally{t.close();}}};function Mo(n){return new Date(Math.floor(n/3e5)*3e5).toISOString()}var zr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}upsert(e){let t=this.openHandle(true);try{let r=Mo(e.bucketStartMs),o=e.accountRef??"default";t.db.insert(Q).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:[Q.provider,Q.account_ref,Q.limit_window,Q.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:Q.provider,bucket_start:Q.bucket_start,used_percent:Q.used_percent,remaining_percent:Q.remaining_percent,resets_at:Q.resets_at}).from(Q).where(and(eq(Q.limit_window,e.window),gte(Q.bucket_start,e.fromIso),lte(Q.bucket_start,e.toIso))).orderBy(asc(Q.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 Wr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}publish(e){let t=this.openHandle(true);try{t.db.insert(ie).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:[ie.workspace_id,ie.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(ie).where(and(eq(ie.workspace_id,e.workspaceId),eq(ie.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(ie).where(and(eq(ie.workspace_id,e),eq(ie.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(ie).where(eq(ie.workspace_id,e)).orderBy(desc(ie.month)).all()}catch(r){throw new c("DB_ERROR","Failed to list usage reports",r)}finally{t.close();}}};var Wo=500,Go=50,Gr=class extends D{dbPath;cap;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db")),this.cap=e.cap??Wo;}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=k(t);if(e)try{x(r.db,t);}catch(o){throw r.close(),o}return r}create(e){let t=this.openHandle(true);try{let r=be("ntf"),o=new Date().toISOString();return t.db.insert(v).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(v).where(eq(v.workspace_id,t)).get()?.count??0)-this.cap;if(s<=0)return;let d=e.db.select({id:v.id}).from(v).innerJoin(K,eq(K.notification_id,v.id)).where(eq(v.workspace_id,t)).groupBy(v.id).orderBy(asc(v.created_at)).limit(s).all().map(l=>l.id);d.length!==0&&(e.db.delete(K).where(inArray(K.notification_id,d)).run(),e.db.delete(v).where(inArray(v.id,d)).run());}list(e){if(!this.dbExists())return [];let t=e.limit??Go,r=this.openHandle(false);try{return r.db.select({id:v.id,workspace_id:v.workspace_id,agent_id:v.agent_id,task_id:v.task_id,thread_id:v.thread_id,source:v.source,level:v.level,title:v.title,body:v.body,target_user_id:v.target_user_id,created_at:v.created_at,metadata:v.metadata,read_at:K.read_at}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(eq(v.workspace_id,e.workspaceId)).orderBy(desc(v.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(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(and(eq(v.workspace_id,e.workspaceId),isNull(K.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:v.id}).from(v).where(and(eq(v.id,e.notificationId),eq(v.workspace_id,e.workspaceId))).get())throw new c("NOT_FOUND","Notification not found in workspace");return t.db.insert(K).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:v.id}).from(v).leftJoin(K,and(eq(K.notification_id,v.id),eq(K.user_id,e.userId))).where(and(eq(v.workspace_id,e.workspaceId),isNull(K.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(K).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 Jo=50,Vr=class extends D{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new c("NOT_FOUND","Database not found");let r=k(t);if(e)try{x(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=be("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(O).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:O.task_id}).from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t))).orderBy(desc(O.created_at)).limit(1).get();if(!o)return [];let s=o.task_id===null?isNull(O.task_id):eq(O.task_id,o.task_id);return r.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),s)).orderBy(asc(O.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(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.task_id,r))).orderBy(asc(O.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(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.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(O).set(s).where(eq(O.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=Jo){if(!this.dbExists())return [];let o=this.openHandle(false);try{return o.db.select().from(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t))).orderBy(desc(O.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(O).where(and(eq(O.workspace_id,e),eq(O.agent_id,t),eq(O.status,"dismissed"))).orderBy(desc(O.updated_at)).limit(r).all()}catch(s){throw new c("DB_ERROR","Failed to find dismissed agent suggestions",s)}finally{o.close();}}};export{Vr as AgentSuggestionRepository,To as BUILTIN_THREAD_STATES,D as BaseSqliteRepository,Ft as COMMON_CODE_COLORS,qt as COMMON_CODE_GROUPS,Qr as CREWX_JOURNAL_SIZE_LIMIT_BYTES,fr as CommonCodeRepository,J as CommonCodeRepositoryError,Jo as DEFAULT_AGENT_SUGGESTION_LIST_LIMIT,Wo as DEFAULT_NOTIFICATION_CAP,Go as DEFAULT_NOTIFICATION_LIST_LIMIT,Pn as DEFAULT_PROJECT_STAGES,br as DEFAULT_PROJECT_STAGE_KEYS,Gr as NotificationRepository,Tr as ProjectRepository,c as RepositoryError,Ur as RequestLogRepository,Hr as SpanRepository,ro as TASK_LOG_MIGRATION_EVENT_ROW_BYTES,Xt as TASK_LOG_MIGRATION_MIN_FREE_SPACE_BYTES,to as TASK_LOG_MIGRATION_TERMINAL_STATUSES,yo as THREAD_PRIORITIES,bt as TaskLogRepository,Sr as TaskRepository,Fr as ThreadBoxRepository,ht as ThreadHighlightConflictError,ir as ThreadHistoryConflictError,Br as ThreadHistoryRepository,Or as ThreadRepository,et as ThreadTitleMetadataPatchError,qr as ToolCallRepository,zr as UsageLimitSnapshotRepository,Wr as UsageReportRepository,yr as WorkspaceRepository,Mo as calcBucketStart,bo as customStateLabel,at as generateCommonCodeId,ao as hasSufficientTaskLogMigrationFreeSpace,qa as hasThreadTitleKey,It as isThreadPriority,Ct as isThreadState,Wa as matchesThreadTitleFilter,$r as mergeThreadTitleMeta,wo as migrateLegacyThreadTitleCommonCodes,ja as migrateThreadTitleCommonCodes,k as openDrizzleDb,Ua as parseThreadPriorityFilter,za as parseThreadStateFilter,Ni as pushSchema,tr as readThreadTitleMeta,ns as reclaimTemporaryJournal,no as resolveTaskLogMigrationDbPath,nt as runMigrations,x as runMigrationsOnce,wa as runTaskLogMigration,ka as taskLogBackupName,a as tasks,Fa as threadTitleSearchHaystack,uo as tryCheckpointTaskLogWal};
|