@kelceyp/caw-server 1.0.174 → 1.0.175
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/main.js +2 -2
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -739,7 +739,7 @@ globstar while`,$,w,K,T,G),this.matchOne($.slice(w),K.slice(T),q))return this.de
|
|
|
739
739
|
field_definition_id UNINDEXED,
|
|
740
740
|
tokenize = 'porter unicode61'
|
|
741
741
|
)
|
|
742
|
-
`.execute($)};var xI8=()=>new Date().toISOString(),F8=xI8;var gI8=async($,K,q,Y)=>{return await $.insertInto("sequences").values({scope_type:K,scope_id:q,type_code:Y,next_value:j8`(SELECT COALESCE(MAX(seq), 0) + 1 FROM entities WHERE store_id ${q===null?j8`IS NULL`:j8`= ${q}`} AND type_code = ${Y})`}).onConflict((J)=>J.doNothing()).execute(),(await $.updateTable("sequences").set((J)=>({next_value:J("next_value","+",1)})).where("scope_type","=",K).where("scope_id",q===null?"is":"=",q).where("type_code","=",Y).returning("next_value").executeTakeFirstOrThrow()).next_value-1},R2=Object.freeze({nextSeq:gI8});var uI8=Object.freeze([{name:"agent",label:"Agent",description:"Agent type (claude or codex)"},{name:"model",label:"Model",description:"Model name (optional)",multiplicity:"multi"},{name:"status",label:"Status",description:"Job status (pending/running/completed/error)"},{name:"startedAt",label:"Started At",description:"Job start timestamp",primitiveType:"date",multiplicity:"multi"},{name:"completedAt",label:"Completed At",description:"Job completion timestamp",primitiveType:"date",multiplicity:"multi"},{name:"tokensUsed",label:"Tokens Used",description:"Total tokens used by the job",primitiveType:"int",multiplicity:"multi"},{name:"exitCode",label:"Exit Code",description:"Process exit code",primitiveType:"int",multiplicity:"multi"},{name:"errorMessage",label:"Error Message",description:"Error message if job failed",multiplicity:"multi"},{name:"durationMs",label:"Duration (ms)",description:"Job execution duration in milliseconds",primitiveType:"int",multiplicity:"multi"},{name:"totalCostUsd",label:"Total Cost (USD)",description:"API cost in USD",primitiveType:"float",multiplicity:"multi"},{name:"numTurns",label:"Number of Turns",description:"Number of agent conversation turns",primitiveType:"int"},{name:"sessionId",label:"Session ID",description:"Agent session ID for conversation continuity",colSpan:2},{name:"workingDirectory",label:"Working Directory",description:"Working directory for job execution (optional, defaults to projectPath)",multiplicity:"multi"},{name:"pid",label:"PID",description:"Process ID of the running job",primitiveType:"int",multiplicity:"multi"},{name:"objectId",label:"Object ID",description:"ID of the entity this job is associated with",primitiveType:"object_ref"},{name:"parentJobId",label:"Parent Job",description:"ID of parent job",primitiveType:"object_ref"},{name:"blocking",label:"Blocking",description:"Whether parent is blocking on this job"},{name:"dockerImage",label:"Docker Image",description:"Docker image name for containerized execution (optional)",multiplicity:"multi"},{name:"skipPermissions",label:"Skip Permissions",description:"Skip permission prompts for Claude agent (true/false)",multiplicity:"multi"},{name:"clearStoryFlag",label:"Clear Story Flag",description:"Clear story flag field on job start (true/false)",hidden:!0},{name:"clearStatusMessage",label:"Clear Status Message",description:"Clear story statusMessage field on job start (true/false)",hidden:!0},{name:"resumePromptRef",label:"Resume Prompt",description:"ID of the prompt template to use when auto-resuming this job",primitiveType:"object_ref"},{name:"resumeAt",label:"Resume At",description:"UTC timestamp when the job should be automatically resumed",primitiveType:"date"},{name:"resumeAttempts",label:"Resume Attempts",description:"Number of auto-resume attempts made for this job",primitiveType:"int"},{name:"accumulatedMs",label:"Accumulated (ms)",description:"Total accumulated active time in milliseconds (excludes time spent waiting for blocking children)",primitiveType:"int"},{name:"segmentStartedAt",label:"Segment Started At",description:"Start timestamp of the current active segment (null when blocked on a child job)",primitiveType:"date",hidden:!0}]),qW=uI8;var yI8=Object.freeze([{name:"hash",label:"Hash",description:"SHA-256 content hash",required:!0},{name:"mimeType",label:"MIME Type",description:"Content type",required:!0},{name:"sizeBytes",label:"Size (bytes)",description:"File size in bytes",primitiveType:"int",required:!0},{name:"originalFilename",label:"Original Filename",description:"Original upload filename"},{name:"widthPx",label:"Width (px)",description:"Native pixel width",primitiveType:"int"},{name:"heightPx",label:"Height (px)",description:"Native pixel height",primitiveType:"int"},{name:"displayWidth",label:"Display Width",description:"CSS display width",primitiveType:"int"},{name:"displayHeight",label:"Display Height",description:"CSS display height",primitiveType:"int"}]),KX=yI8;var Cq1=[{code:"f",name:"Folder",subtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"d",name:"Document",subtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"t",name:"Template",subtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"s",name:"Story",subtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"r",name:"Store",subtype:"local",is_pathable:0,can_have_children:0,scope:"global",sequence_scope:"global"},{code:"r",name:"Store",subtype:"demux",is_pathable:0,can_have_children:0,scope:"global",sequence_scope:"global"},{code:"p",name:"Project",subtype:null,is_pathable:0,can_have_children:0,scope:"global",sequence_scope:"global"},{code:"j",name:"Job",subtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"v",name:"Version",subtype:null,is_pathable:0,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"n",name:"field_definition",subtype:null,is_pathable:0,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"a",name:"asset",subtype:null,is_pathable:0,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Setting",subtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"f",name:"Document Root Folder",subtype:"root_d",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Template Root Folder",subtype:"root_t",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Story Root Folder",subtype:"root_s",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Job Root Folder",subtype:"root_j",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Settings Root Folder",subtype:"root_settings",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Tasks Folder",subtype:"tasks",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Epic Folder",subtype:"epic",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Orphaned Root Folder",subtype:"root_orphaned",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"d",name:"Task",subtype:"task",parentCode:"d",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"d",name:"Cartridge",subtype:"cartridge",parentCode:"d",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"d",name:"Scratch",subtype:"scratch",parentCode:"d",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"t",name:"Prompt",subtype:"prompt",parentCode:"t",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Track",subtype:"track",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Auto Archive Config",subtype:"auto-archive-config",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Job Config",subtype:"job-config",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Disposal Config",subtype:"disposal-config",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Resume Config",subtype:"resume-config",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"}],Eq1=async($)=>{return(await $.selectFrom("entity_types").select("id").limit(1).execute()).length>0},p8=async($,K,q=null)=>{return(await $.selectFrom("entity_types").select("id").where("code","=",K).where((z)=>q?z("subtype","=",q):z("subtype","is",null)).executeTakeFirstOrThrow()).id},Ik=async($,K,q,Y)=>{let z=F8(),W={d:"root_d",t:"root_t",s:"root_s",j:"root_j"}[Y],O={d:"Documents",t:"Templates",s:"Stories",j:"Jobs"}[Y],H=await p8($,"f",W);if(!await $.selectFrom("sequences").select("next_value").where("scope_type","=","store").where("scope_id","=",K).where("type_code","=","f").executeTakeFirst())await $.insertInto("sequences").values({scope_type:"store",scope_id:K,type_code:"f",next_value:1}).execute();let w=await $.selectFrom("sequences").select("next_value").where("scope_type","=","store").where("scope_id","=",K).where("type_code","=","f").executeTakeFirst();await $.updateTable("sequences").set((M)=>({next_value:M("next_value","+",1)})).where("scope_type","=","store").where("scope_id","=",K).where("type_code","=","f").execute();let T=`${q}f${w.next_value}`,G=await $.insertInto("entities").values({store_id:K,object_id:T,entity_type_id:H,type_code:"f",seq:w.next_value,parent_folder_id:null,parent_object_id:null,name:O,path:O,created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow();await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${G.id}, ${O??""}, ${O??""})`.execute($);let v={d:"document",t:"template",s:"story",j:"job"}[Y];return G.id},bI8=async($)=>{for(let K of Cq1)await $.insertInto("entity_types").values({code:K.code,name:K.name,subtype:K.subtype,parent_type_id:null,is_pathable:K.is_pathable,can_have_children:K.can_have_children,scope:K.scope,sequence_scope:K.sequence_scope}).execute();for(let K of Cq1)if(K.parentCode!==void 0){let q=await $.selectFrom("entity_types").select("id").where("code","=",K.parentCode).where((Y)=>K.parentSubtype===null?Y("subtype","is",null):Y("subtype","=",K.parentSubtype)).executeTakeFirstOrThrow();await $.updateTable("entity_types").set({parent_type_id:q.id}).where("code","=",K.code).where((Y)=>K.subtype===null?Y("subtype","is",null):Y("subtype","=",K.subtype)).execute()}},BI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((J)=>({next_value:J("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let z=`_n${Y.next_value}`;await $.insertInto("field_definitions").values({store_id:null,object_id:z,entity_type_id:q,type_code:"n",seq:Y.next_value,owner_entity_id:null,name:"state",label:"State",description:"Track state",primitive_type:"string",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).execute()},mI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"state",label:"State",description:"Story track state",primitive_type:"string",required:0,multiplicity:"single",is_system:1,config:JSON.stringify({allowed:{type:"function",name:"resolve-states-for-track",dependsOn:["track"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},UI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"state",label:"State",description:"Task track state",primitive_type:"string",required:0,multiplicity:"single",is_system:1,config:JSON.stringify({allowed:{type:"function",name:"resolve-task-states"}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},FI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"j",null);for(let z=0;z<qW.length;z++){let J=qW[z],W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:J.name,label:J.label,description:J.description,primitive_type:J.primitiveType||"string",required:0,multiplicity:J.multiplicity||"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:O.id,required:0,sort_order:z+1,hidden:J.hidden?1:0,colspan:J.colSpan??null}).execute()}},cI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"a",null);for(let z=0;z<KX.length;z++){let J=KX[z],W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:J.name,label:J.label,description:J.description,primitive_type:J.primitiveType||"string",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:O.id,required:J.required?1:0,sort_order:z+1}).execute()}},xk=Object.freeze(["prep","spec","design","plan","build","review","done"]),_X=Object.freeze(["waiting","ready","in-progress","done"]),QI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"f","tasks"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"states",label:"States",description:"Ordered list of valid task states",primitive_type:"string",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:1,sort_order:1}).execute()},pI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"f","epic"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"state",label:"State",description:"Epic lifecycle stage: discovery, inception, build, or done",primitive_type:"string",required:0,multiplicity:"single",is_system:1,config:JSON.stringify({allowed:{type:"enum",values:["discovery","inception","build","done"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},lI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"f","epic"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"stories",label:"Stories",description:"Constituent stories in this epic",primitive_type:"object_ref",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:2,colspan:3}).execute()},iI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"dependsOn",label:"Depends On",description:"Tasks that block this task",primitive_type:"object_ref",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:2}).execute()},nI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"cardContent",label:"Card Content",description:"Display text for task cards",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:3}).execute()},dI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"colour",label:"Colour",description:"CSS colour value for card styling",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:4}).execute()},aI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"progress",label:"Progress",description:"Checkbox completion percentage (0-100)",primitive_type:"float",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:5}).execute()},oI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","cartridge"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"synopsis",label:"Synopsis",description:"Brief description of the cartridge",primitive_type:"text",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1,colspan:3}).execute()},rI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","cartridge"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"relatedActivities",label:"Related Activities",description:"Associated activity types",primitive_type:"string",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:2}).execute()},sI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"t","prompt"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"associatedType",label:"Associated Type",description:"Entity types this template is associated with",primitive_type:"string",required:0,multiplicity:"multi",is_system:1,config:JSON.stringify({allowed:{type:"enum",values:["s","d/task","j"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1,hidden:1}).execute()},tI8=Object.freeze({$id:"caw:visibility-config",type:"object",properties:{visibility:{type:"object",properties:{story:{type:"object",additionalProperties:{type:"array",items:{type:"string"}}},task:{type:"object",properties:{_stages:{type:"array",items:{type:"string"}}},additionalProperties:!1},job:{type:"object",properties:{_contexts:{type:"array",items:{type:"string"}}},additionalProperties:!1}},additionalProperties:!1}},additionalProperties:!1}),Lq1=Object.freeze({story:"s",task:"d/task",job:"j"}),eI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"t","prompt"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((O)=>({next_value:O("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=JSON.stringify({jsonSchema:tI8}),Z=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"config",label:"Config",description:"Prompt visibility configuration",primitive_type:"string",required:0,multiplicity:"single",is_system:1,config:W,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:Z.id,required:0,sort_order:2,colspan:1}).execute()},$x8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"flag",label:"Flag",description:"Visual indicator for story attention",primitive_type:"string",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:2}).execute()},Kx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"activeJobCount",label:"Active Job Count",description:"Number of active jobs associated with this story",primitive_type:"int",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:5}).execute()},_x8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"statusMessage",label:"Status Message",description:"Agent status message displayed in stories list",primitive_type:"string",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:3}).execute()},qx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"dateCompleted",label:"Date Completed",description:"Timestamp when story transitioned to done state",primitive_type:"date",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:4}).execute()},Yx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null),J=await p8($,"f",null),W=await p8($,"s",null),Z=await p8($,"j",null),O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((w)=>({next_value:w("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=`_n${O.next_value}`,X=await $.insertInto("field_definitions").values({store_id:null,object_id:H,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:"delete_date",label:"Delete Date",description:"Eligible for deletion after this date",primitive_type:"date",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();for(let w of[Y,z,J,W,Z])await $.insertInto("class_field_defs").values({store_id:null,class_type_id:w,field_definition_id:X.id,required:0,sort_order:null}).execute()},zx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","track"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"states",label:"States",description:"Ordered list of track states",primitive_type:"string",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:1,sort_order:1}).execute()},Jx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","auto-archive-config"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"delayMs",label:"Delay (ms)",description:"Auto-archive delay threshold in milliseconds",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},Wx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","job-config"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"maxConcurrentJobs",label:"Max Concurrent Jobs",description:"Maximum number of concurrent jobs allowed",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},Zx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","disposal-config"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${z.next_value}`,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"scratchDocDelayDays",label:"Scratch Document Delay (days)",description:"Number of days before scratch documents are disposed",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:J.id,required:0,sort_order:1}).execute();let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${W.next_value}`,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:"jobDelayDays",label:"Job Delay (days)",description:"Number of days before completed jobs are disposed",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:Z.id,required:0,sort_order:2}).execute();let O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${O.next_value}`,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:"retentionDays",label:"Retention Days",description:"Number of days soft-deleted entities are retained before permanent deletion",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:H.id,required:0,sort_order:3}).execute()},Ox8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","resume-config"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${z.next_value}`,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"defaultResumePromptRef",label:"Default Resume Prompt",description:"Default prompt template used when auto-resuming jobs in this project",primitive_type:"object_ref",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:J.id,required:0,sort_order:1}).execute();let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${W.next_value}`,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:"maxResumeAttempts",label:"Max Resume Attempts",description:"Maximum number of automatic resume attempts per job",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:Z.id,required:0,sort_order:2}).execute();let O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${O.next_value}`,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:"cronIntervalMs",label:"Cron Interval (ms)",description:"Polling interval for the ResumeAwaitingJobsCronJob in milliseconds",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:H.id,required:0,sort_order:3}).execute()},Hx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"track",label:"Track",description:"Assigned track",primitive_type:"object_ref",required:0,multiplicity:"single",is_system:1,config:JSON.stringify({allowed:{type:"function",name:"resolve-tracks"}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:6}).execute()},Xx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"phase",label:"Phase",description:"Lifecycle phase: backlog, active, or history",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,config:JSON.stringify({allowed:{type:"enum",values:["backlog","active","history"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:7}).execute()},wx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"size",label:"Size",description:"Story point estimate using modified Fibonacci scale",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,config:JSON.stringify({allowed:{type:"enum",values:["0","½","1","2","3","5","8","13","20","40","100","∞"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:8}).execute()},Gx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"priority",label:"Priority",description:"Story urgency level",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,config:JSON.stringify({allowed:{type:"enum",values:["Critical","High priority","Medium priority","Low priority","Cosmetic"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:9}).execute()},Tx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"ranking",label:"Ranking",description:"Sparse integer for user-controlled story ordering within a phase",primitive_type:"int",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:10}).execute()},Px8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"pendingJobCount",label:"Pending Job Count",description:"Number of pending jobs associated with this story",primitive_type:"int",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:11}).execute()},vx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"worktree_branch",label:"Worktree Branch",description:"Stores the git worktree branch name for a story",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:8}).execute()},Ax8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null),J=[{name:"draft_version",label:"Draft Version",description:"Points to current draft version entity",sortOrder:1},{name:"latest_published_version",label:"Latest Published Version",description:"Points to most recent published version entity",sortOrder:2}];for(let W of[Y,z])for(let Z of J){let O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((w)=>({next_value:w("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=`_n${O.next_value}`,X=await $.insertInto("field_definitions").values({store_id:null,object_id:H,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:Z.name,label:Z.label,description:Z.description,primitive_type:"object_ref",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:W,field_definition_id:X.id,required:0,sort_order:Z.sortOrder}).execute()}},Vx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null),J=[{name:"edit_session_id",label:"Edit Session ID",description:"UUID of the editing session",primitiveType:"string",sortOrder:3,hidden:!0},{name:"edit_started_at",label:"Edit Started At",description:"When edit lock was acquired",primitiveType:"date",sortOrder:4,hidden:!0},{name:"edit_last_activity_at",label:"Edit Last Activity At",description:"Last activity during edit session",primitiveType:"date",sortOrder:5,hidden:!0}];for(let W of[Y,z])for(let Z of J){let O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((w)=>({next_value:w("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=`_n${O.next_value}`,X=await $.insertInto("field_definitions").values({store_id:null,object_id:H,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:Z.name,label:Z.label,description:Z.description,primitive_type:Z.primitiveType,required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:W,field_definition_id:X.id,required:0,sort_order:Z.sortOrder,hidden:Z.hidden?1:0}).execute()}},Mx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null);for(let J of[Y,z]){let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:"size",label:"Size",description:"Content size in bytes",primitive_type:"int",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:J,field_definition_id:O.id,required:0,sort_order:6}).execute()}},Nx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null);for(let J of[Y,z]){let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:"orphanedFrom",label:"Orphaned From",description:"ID of the job or story from which this document was orphaned during disposal",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:J,field_definition_id:O.id,required:0,sort_order:null}).execute()}},jx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"v",null),z=[{name:"attachments",label:"Attachments",description:"Referenced asset entities",sortOrder:5,colSpan:2},{name:"includes",label:"Includes",description:"Included documents and templates",sortOrder:6,colSpan:2},{name:"hyperlinks",label:"Hyperlinks",description:"Linked entities in content",sortOrder:7,colSpan:2}];for(let J of z){let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:J.name,label:J.label,description:J.description,primitive_type:"object_ref",required:0,multiplicity:"multi",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:O.id,required:0,sort_order:J.sortOrder,colspan:J.colSpan??null}).execute()}},fx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"v",null),z=[{name:"document",label:"Document",description:"Parent document or template entity",primitiveType:"object_ref",required:1,sortOrder:1},{name:"version_number",label:"Version Number",description:"Version number (1, 2, 3...)",primitiveType:"int",required:1,sortOrder:2,hidden:!0},{name:"published_at",label:"Published At",description:"When this version was published",primitiveType:"date",required:0,sortOrder:3},{name:"content_hash",label:"Content Hash",description:"SHA-256 hex fingerprint of content for change detection",primitiveType:"string",required:0,sortOrder:4,colSpan:2}];for(let J of z){let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:J.name,label:J.label,description:J.description,primitive_type:J.primitiveType,required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:O.id,required:J.required,sort_order:J.sortOrder,colspan:J.colSpan??null,hidden:J.hidden?1:0}).execute()}},kx8=async($,K,q)=>{let Y=F8(),z=await p8($,"f","root_settings"),J=await R2.nextSeq($,"store",K,"f"),W=`${q}f${J}`,Z=await $.insertInto("entities").values({store_id:K,object_id:W,entity_type_id:z,type_code:"f",seq:J,parent_folder_id:null,parent_object_id:null,name:"Settings",path:"Settings",created_at:Y,updated_at:Y}).returning("id").executeTakeFirstOrThrow();return await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${Z.id}, ${"Settings"}, ${"Settings"})`.execute($),Z.id},Dx8=async($,K,q)=>{let Y=F8(),z=await p8($,"f","root_orphaned"),J=await R2.nextSeq($,"store",K,"f"),W=`${q}f${J}`,Z=await $.insertInto("entities").values({store_id:K,object_id:W,entity_type_id:z,type_code:"f",seq:J,parent_folder_id:null,parent_object_id:null,name:"Orphaned",path:"Orphaned",created_at:Y,updated_at:Y}).returning("id").executeTakeFirstOrThrow();return await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${Z.id}, ${"Orphaned"}, ${"Orphaned"})`.execute($),Z.id},Rx8=async($,K,q,Y)=>{let z=F8(),J=await p8($,"f",null),W=await $.selectFrom("entities").select("object_id").where("id","=",Y).executeTakeFirstOrThrow(),Z=await R2.nextSeq($,"store",K,"f"),O=`${q}f${Z}`,H=await $.insertInto("entities").values({store_id:K,object_id:O,entity_type_id:J,type_code:"f",seq:Z,parent_folder_id:Y,parent_object_id:W.object_id,name:"Stories",path:"Settings/Stories",created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow();await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${H.id}, ${"Stories"}, ${"Settings/Stories"})`.execute($);let X=H.id,w=await R2.nextSeq($,"store",K,"f"),T=`${q}f${w}`,G=await $.insertInto("entities").values({store_id:K,object_id:T,entity_type_id:J,type_code:"f",seq:w,parent_folder_id:X,parent_object_id:O,name:"Tracks",path:"Settings/Stories/Tracks",created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow();return await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${G.id}, ${"Tracks"}, ${"Settings/Stories/Tracks"})`.execute($),G.id},Cx8=async($,K,q,Y)=>{let z=F8(),J=await p8($,"e","track"),W=await $.selectFrom("entities").select("object_id").where("id","=",Y).executeTakeFirstOrThrow(),Z=await R2.nextSeq($,"store",K,"e"),O=`${q}e${Z}`,X=(await $.insertInto("entities").values({store_id:K,object_id:O,entity_type_id:J,type_code:"e",seq:Z,parent_folder_id:Y,parent_object_id:W.object_id,name:"Default",path:"Settings/Stories/Tracks/Default",created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow()).id,w=await $.selectFrom("field_definitions").innerJoin("class_field_defs","class_field_defs.field_definition_id","field_definitions.id").innerJoin("entity_types","entity_types.id","class_field_defs.class_type_id").select("field_definitions.id").where("field_definitions.store_id","is",null).where("field_definitions.name","=","states").where("entity_types.code","=","e").where("entity_types.subtype","=","track").executeTakeFirstOrThrow();for(let T=0;T<xk.length;T++)await $.insertInto("string_fields").values({entity_id:X,field_definition_id:w.id,value:xk[T],ordinal:T}).execute()},Ex8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"r","local");if(!await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirst())await $.insertInto("sequences").values({scope_type:"global",scope_id:null,type_code:"n",next_value:1}).execute();let J=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((O)=>({next_value:O("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let W=`_n${J.next_value}`,Z=await $.insertInto("field_definitions").values({store_id:null,object_id:W,entity_type_id:q,type_code:"n",seq:J.next_value,owner_entity_id:null,name:"code",label:"Store Code",description:"Unique code identifying the local store (e.g., A, B)",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();return await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:Z.id,required:1,sort_order:null}).execute(),Z.id},Lx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"p",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"path",label:"Project Path",description:"Filesystem path for the project",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();return await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:1,sort_order:null}).execute(),W.id},Sx8=async($)=>{let K=await Ex8($);await Lx8($);let q=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","r").executeTakeFirstOrThrow();await $.updateTable("sequences").set((w)=>({next_value:w("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","r").execute();let Y=`S${q.next_value}`,z=F8(),J=await p8($,"r","local"),Z=(await $.insertInto("entities").values({store_id:null,object_id:Y,entity_type_id:J,type_code:"r",seq:q.next_value,parent_folder_id:null,parent_object_id:null,name:"Shared",created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow()).id;await $.insertInto("string_fields").values({entity_id:Z,field_definition_id:K,value:"B",ordinal:0}).execute(),await Ik($,Z,"B","d"),await Ik($,Z,"B","t");let O=await Ik($,Z,"B","s");await Ik($,Z,"B","j");let H=await kx8($,Z,"B");await Dx8($,Z,"B"),await BI8($),await FI8($),await cI8($),await UI8($),await iI8($),await nI8($),await dI8($),await aI8($),await oI8($),await rI8($),await QI8($),await sI8($),await eI8($),await mI8($),await $x8($),await Kx8($),await _x8($),await qx8($),await Yx8($),await Hx8($),await Xx8($),await wx8($),await Gx8($),await Tx8($),await Px8($),await vx8($),await pI8($),await lI8($),await zx8($),await Jx8($),await Wx8($),await Zx8($),await Ox8($);let X=await Rx8($,Z,"B",H);await Cx8($,Z,"B",X),await Ax8($),await Vx8($),await Mx8($),await Nx8($),await jx8($),await fx8($),await $.insertInto("sequences").values({scope_type:"store",scope_id:Z,type_code:"v",next_value:1}).execute()},Sq1=async($)=>{await bI8($),await $.insertInto("sequences").values([{scope_type:"global",scope_id:null,type_code:"r",next_value:1},{scope_type:"global",scope_id:null,type_code:"p",next_value:1}]).execute(),await Sx8($)};var gk=Z6(Iq1(),1),hx8=($,K)=>{if($)throw Error(K)},xq1=($,K)=>{if(gk.default.null($)||gk.default.undefined($))throw Error(`${K} is required`)},Ix8=($,K)=>{if(xq1($,K),gk.default.empty($))throw Error(`${K} cannot be empty`)},xx8=($,K,...q)=>{if($)throw K(...q)},gx8={condition:hx8,nullish:xq1,empty:Ix8,factory:xx8},c=gx8;var Mi8=typeof Bun<"u",Ni8=async($)=>{if(Mi8){let{Database:K}=await import("bun:sqlite"),{BunSqliteDialect:q}=await Promise.resolve().then(() => Z6(HA1(),1)),Y=new K($);return Y.exec("PRAGMA journal_mode = WAL"),Y.exec("PRAGMA foreign_keys = ON"),new Q_({dialect:new q({database:Y})})}else{let q=new(await import("better-sqlite3")).default($);return q.pragma("journal_mode = WAL"),q.pragma("foreign_keys = ON"),new Q_({dialect:new UB({database:q})})}},ji8=($,K)=>{if(!vi8($)){if(!K)throw Error(`Database file not found: ${$}`);Ai8(Vi8($),{recursive:!0})}},fi8=async($,K)=>{if(!await Dq1($)){if(!K)throw Error("Database schema not found");await Rq1($)}},ki8=async($,K)=>{if(!await Eq1($)){if(!K)throw Error("Database seed data not found");await Sq1($)}},Di8=($)=>{let{kyselyFactory:K=Ni8}=$??{};return Object.freeze({getDb:async(Y,z)=>{if(c.nullish(Y,"databaseFilepath"),Y!==":memory:")ji8(Y,z);let J=await K(Y);return await fi8(J,z),await ki8(J,z),J}})},XA1={create:Di8};var Ri8=($)=>{let{id:K,name:q,createdAt:Y,updatedAt:z,deletedAt:J}=$,w=Object.freeze({getObjectId:()=>K,getName:()=>q,getCreatedAt:()=>Y,getUpdatedAt:()=>z,getDeletedAt:()=>J??null}),P=Object.freeze({setName:(v)=>{q=v},setUpdatedAt:(v)=>{z=v}});return{entityFns:w,mutationFns:P}},d_=Object.freeze({create:Ri8});var Ci8=($)=>{let{id:K,name:q,path:Y,createdAt:z,updatedAt:J}=$,{entityFns:W,mutationFns:Z}=d_.create({id:K,name:q,createdAt:z,updatedAt:J}),O=()=>Y,X=Object.freeze({...W,getPath:O,toJSON:()=>({objectId:W.getObjectId(),name:W.getName(),path:O(),createdAt:W.getCreatedAt(),updatedAt:W.getUpdatedAt()})}),T=Object.freeze({...Z,setPath:(G)=>{Y=G}});return{entity:X,mutationApi:T}},wA1=Object.freeze({create:Ci8});var Ei8=($,K,q)=>{return Object.freeze({getEntity:()=>$,getMutationApi:()=>K,getPk:()=>q})},i6=Object.freeze({create:Ei8});F$();F6();var Bi8=($)=>$.object_id,VR=($)=>{if(!$||$.length<2||$[0]!=="P")return null;let K=parseInt($.slice(1),10);return isNaN(K)?null:K},xc=async($,K)=>{let q=await $.selectFrom("field_definitions").select("id").where("name","=","path").where("store_id","is",null).where("is_system","=",1).executeTakeFirst();if(!q)return null;return(await $.selectFrom("string_fields").select("value").where("entity_id","=",K).where("field_definition_id","=",q.id).executeTakeFirst())?.value??null},mi8=async($,K,q)=>{let Y=await $.selectFrom("field_definitions").select("id").where("name","=","path").where("store_id","is",null).where("is_system","=",1).executeTakeFirstOrThrow();await $.insertInto("string_fields").values({entity_id:K,field_definition_id:Y.id,value:q,ordinal:0}).execute()},LA=($,K)=>{let q=Bi8($),Y=$.id,{entity:z,mutationApi:J}=wA1.create({id:q,name:$.name,path:K,createdAt:$.created_at,updatedAt:$.updated_at});return{entity:z,mutationApi:J,id:q,pk:Y}},Ui8=()=>{let $=new Map,K=new Map,q=async(X,w,{name:T,path:G},P)=>{let v=await J(X,w,G);c.factory(v,h.validation,`Project with path already exists: ${G}`,"DUPLICATE_PROJECT_PATH");let M=F8(),V=await R2.nextSeq(X,"global",null,"p"),k=`P${V}`,j=await s8.readEntityTypeId(X,w,"p",null),C=await X.insertInto("entities").values({store_id:null,object_id:k,entity_type_id:j,type_code:"p",seq:V,parent_folder_id:null,parent_object_id:null,name:T,created_at:M,updated_at:M}).returningAll().executeTakeFirstOrThrow(),g=C.id;await mi8(X,g,G);let{entity:y,mutationApi:S,id:x}=LA(C,G);return P(`cache-set:${x}`,()=>{$.set(x,i6.create(y,S,g)),K.set(g,x)}),y},Y=async(X,w,T)=>{let G=$.get(T);if(G)return G.getEntity();let P=VR(T);if(P===null)return null;let v=await X.selectFrom("entities").selectAll().where("type_code","=","p").where("seq","=",P).where("deleted_at","is",null).executeTakeFirst();if(!v)return null;let M=await xc(X,v.id),{entity:V,mutationApi:k,id:j,pk:C}=LA(v,M);return $.set(j,i6.create(V,k,C)),K.set(C,j),V},z=async(X,w,T)=>{let G=$.get(T);if(G)return G.getEntity();if(VR(T)===null)return null;let v=await X.selectFrom("entities").selectAll().where("type_code","=","p").where("object_id","=",T).where("deleted_at","is",null).executeTakeFirst();if(!v)return null;let M=await xc(X,v.id),{entity:V,mutationApi:k,id:j,pk:C}=LA(v,M);return $.set(j,i6.create(V,k,C)),K.set(C,j),V},J=async(X,w,T)=>{let G=await X.selectFrom("entities").innerJoin("string_fields","string_fields.entity_id","entities.id").innerJoin("field_definitions","field_definitions.id","string_fields.field_definition_id").select(["entities.id","entities.object_id","entities.name","entities.created_at","entities.updated_at","string_fields.value as path"]).where("entities.type_code","=","p").where("entities.deleted_at","is",null).where("field_definitions.name","=","path").where("field_definitions.store_id","is",null).where("field_definitions.is_system","=",1).where("string_fields.value","=",T).executeTakeFirst();if(!G)return null;let{entity:P,mutationApi:v,id:M,pk:V}=LA(G,G.path),k=$.get(M);if(k)return k.getEntity();return $.set(M,i6.create(P,v,V)),K.set(V,M),P},W=(X)=>{let w=$.get(X);if(w)K.delete(w.getPk());$.delete(X)},Z=async(X,w,{id:T,name:G},P)=>{let v=VR(T);c.factory(v===null,h.validation,`Invalid project ID: ${T}`,"INVALID_ID");let M=await X.selectFrom("entities").selectAll().where("type_code","=","p").where("seq","=",v).where("deleted_at","is",null).executeTakeFirst();c.factory(!M,h.notFound,`Project not found: ${T}`,"PROJECT_NOT_FOUND");let V=M.id,k=F8(),j=await X.updateTable("entities").set({name:G,updated_at:k}).where("id","=",V).returningAll().executeTakeFirstOrThrow(),C=await xc(X,V),{entity:g,mutationApi:y,id:S}=LA(j,C);return P(`cache-update:${S}`,()=>{W(S),$.set(S,i6.create(g,y,V)),K.set(V,S)}),g},O=async(X,w)=>{let T=await X.selectFrom("field_definitions").select("id").where("name","=","code").where("store_id","is",null).where("is_system","=",1).executeTakeFirst();if(!T)return null;return(await X.selectFrom("string_fields").select("value").where("entity_id","=",w).where("field_definition_id","=",T.id).executeTakeFirst())?.value??null};return Object.freeze({createProject:q,readProject:Y,readProjectByObjectId:z,readProjectByPath:J,evictProject:W,updateProject:Z,deleteProject:async(X,w,{id:T},G)=>{let P=VR(T);c.factory(P===null,h.validation,`Invalid project ID: ${T}`,"INVALID_ID");let v=await X.selectFrom("entities").selectAll().where("type_code","=","p").where("seq","=",P).where("deleted_at","is",null).executeTakeFirst();c.factory(!v,h.notFound,`Project not found: ${T}`,"PROJECT_NOT_FOUND");let M=v.id,V=F8(),k=await X.selectFrom("project_stores").innerJoin("entities","entities.id","project_stores.store_id").innerJoin("entity_types","entity_types.id","entities.entity_type_id").select(["entities.id as storePk","entities.object_id as storeObjectId","entity_types.subtype"]).where("project_stores.project_id","=",M).where("entities.deleted_at","is",null).execute(),j=null,C=null,g=null,y=null;for(let E of k)if(E.subtype==="demux")g=E.storePk,y=E.storeObjectId;else if(E.subtype==="local"){if(await O(X,E.storePk)==="A")j=E.storePk,C=E.storeObjectId}let S=j?await X.selectFrom("entities").select(["id","object_id"]).where("store_id","=",j).where("deleted_at","is",null).execute():[],x=S.map((E)=>E.id),R=S.map((E)=>E.object_id);if(x.length>0)await X.updateTable("entities").set({deleted_at:V}).where("id","in",x).execute();let D=0;if(j)await X.updateTable("entities").set({deleted_at:V}).where("id","=",j).execute(),D++;if(g)await X.updateTable("entities").set({deleted_at:V}).where("id","=",g).execute(),D++;return await X.updateTable("entities").set({deleted_at:V}).where("id","=",M).execute(),G(`cache-evict:${T}`,()=>{for(let E of R);W(T)}),{id:T,deleted:!0,storeCount:D,entityCount:x.length,storeAObjectId:C,demuxObjectId:y,storeAEntityIds:R}}})},GA1=Object.freeze({create:Ui8});var Fi8=()=>{let $=new Map,K=new Map;return Object.freeze({get:(T)=>$.get(T),getByPk:(T)=>{let G=K.get(T);return G?$.get(G):void 0},has:(T)=>$.has(T),set:(T,G)=>{$.set(T,G),K.set(G.getPk(),T)},remove:(T)=>{let G=$.get(T);if(G)K.delete(G.getPk());$.delete(T)},getIdByPk:(T)=>K.get(T),setIdByPk:(T,G)=>K.set(T,G),clear:()=>{$.clear(),K.clear()},entries:()=>$.entries(),size:()=>$.size})},gc=Object.freeze({create:Fi8});var pA1=Z6(x6(),1);import{createHash as Qn8}from"crypto";F$();var ci8=($)=>{let{id:K,name:q,createdAt:Y,updatedAt:z,deletedAt:J}=$,{entityFns:W,mutationFns:Z}=d_.create({id:K,name:q,createdAt:Y,updatedAt:z,deletedAt:J}),O=new Map,w=Object.freeze({...W,getField:(v)=>{return O.get(v)},getFields:()=>{let v={};for(let[M,V]of O.entries())v[M]=V;return v}}),P=Object.freeze({...Z,setField:(v,M)=>{O.set(v,M)},removeField:(v)=>{O.delete(v)}});return{entityFns:w,mutationFns:P}},SX=Object.freeze({create:ci8});var Qi8=($)=>{let{id:K,name:q,parentId:Y,path:z,createdAt:J,updatedAt:W,deletedAt:Z}=$,{entityFns:O,mutationFns:H}=SX.create({id:K,name:q,createdAt:J,updatedAt:W,deletedAt:Z}),G=Object.freeze({...O,getParentId:()=>Y,getPath:()=>z,getIsFolder:()=>!1}),M=Object.freeze({...H,setParentId:(V)=>{Y=V},setPath:(V)=>{z=V}});return{entityFns:G,mutationFns:M}},a_=Object.freeze({create:Qi8});var JS4=Object.freeze(["name","updatedAt","parentId","path"]),TA1=($)=>{let{entityFns:K,mutationFns:q}=a_.create($),Y=$.subtype||null,z=()=>"f",J=()=>Y,W=()=>K.getParentId()===null,Z=()=>!0,H=Object.freeze({...K,getTypeCode:z,getSubtype:J,isRoot:W,getIsFolder:Z,toJSON:()=>{let w={};for(let[T,G]of Object.entries(K.getFields()))w[T]=G.toJSON();return{id:K.getObjectId(),parentId:K.getParentId(),name:K.getName(),path:K.getPath(),type:z(),subtype:J(),createdAt:K.getCreatedAt(),updatedAt:K.getUpdatedAt(),isFolder:Z(),isRoot:W(),fields:w}}}),X=Object.freeze({...q});return{entity:H,mutationApi:X}},pi8=($,K,q,Y)=>{return TA1({id:K,parentId:q,name:$.name,path:Y,subtype:$.subtype||null,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null})},h5=Object.freeze({create:TA1,createFromRow:pi8});var OS4=Object.freeze(["name","updatedAt","parentId","path"]),PA1=($)=>{let{entityFns:K,mutationFns:q}=a_.create($),O=Object.freeze({...K,getTypeCode:()=>"s",getSubtype:()=>null,isStory:()=>!0,getIsFolder:()=>!1,toJSON:()=>{let X={};for(let[w,T]of Object.entries(K.getFields()))X[w]=T.toJSON();return{id:K.getObjectId(),parentId:K.getParentId(),name:K.getName(),path:K.getPath(),createdAt:K.getCreatedAt(),updatedAt:K.getUpdatedAt(),type:"s",isStory:!0,isFolder:!1,fields:X}}}),H=Object.freeze({...q});return{entity:O,mutationApi:H}},li8=($,K,q,Y)=>{return PA1({id:K,parentId:q,name:$.name,path:Y,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null})},v0=Object.freeze({create:PA1,createFromRow:li8});var wS4=Object.freeze(["name","updatedAt","parentId","path"]),vA1=($)=>{let{subtype:K,...q}=$,{entityFns:Y,mutationFns:z}=a_.create(q),J=()=>"e",W=()=>K??null,O=Object.freeze({...Y,getTypeCode:J,getSubtype:W,toJSON:()=>{let X={};for(let[w,T]of Object.entries(Y.getFields()))X[w]=T.toJSON();return{id:Y.getObjectId(),parentId:Y.getParentId(),name:Y.getName(),path:Y.getPath(),createdAt:Y.getCreatedAt(),updatedAt:Y.getUpdatedAt(),isFolder:Y.getIsFolder(),type:J(),subtype:W(),fields:X}}}),H=Object.freeze({...z});return{entity:O,mutationApi:H}},ii8=($,K,q,Y)=>{return vA1({id:K,parentId:q,name:$.name,path:Y,createdAt:$.created_at,updatedAt:$.updated_at,subtype:$.subtype||null})},hX=Object.freeze({create:vA1,createFromRow:ii8});var PS4=Object.freeze(["name","updatedAt","parentId","path"]),AA1=($)=>{let{entityFns:K,mutationFns:q}=a_.create($),Z=Object.freeze({...K,getTypeCode:()=>"j",isJob:()=>!0,getIsFolder:()=>!1,toJSON:()=>{let H={};for(let[X,w]of Object.entries(K.getFields()))H[X]=w.toJSON();return{id:K.getObjectId(),parentId:K.getParentId(),name:K.getName(),path:K.getPath(),createdAt:K.getCreatedAt(),updatedAt:K.getUpdatedAt(),type:"j",isJob:!0,isFolder:!1,fields:H}}}),O=Object.freeze({...q});return{entity:Z,mutationApi:O}},ni8=($,K,q,Y)=>{return AA1({id:K,parentId:q,name:$.name,path:Y,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null})},yW=Object.freeze({create:AA1,createFromRow:ni8});var VS4=Object.freeze(["name","updatedAt"]),di8=($)=>{let{entityFns:K,mutationFns:q}=SX.create({id:$.id,name:$.name,createdAt:$.createdAt,updatedAt:$.updatedAt}),Y=()=>"a",z=()=>!0,J=()=>K.getField("hash")?.getValue(),W=()=>K.getField("mimeType")?.getValue(),Z=()=>K.getField("sizeBytes")?.getValue(),O=()=>K.getField("originalFilename")?.getValue()??null,H=()=>K.getField("widthPx")?.getValue()??null,X=()=>K.getField("heightPx")?.getValue()??null,w=()=>K.getField("displayWidth")?.getValue()??null,T=()=>K.getField("displayHeight")?.getValue()??null,P=Object.freeze({...K,getTypeCode:Y,isAsset:z,getHash:J,getMimeType:W,getSizeBytes:Z,getOriginalFilename:O,getWidthPx:H,getHeightPx:X,getDisplayWidth:w,getDisplayHeight:T,toJSON:()=>({id:K.getObjectId(),type:"a",hash:J(),mimeType:W(),sizeBytes:Z(),originalFilename:O(),widthPx:H(),heightPx:X(),displayWidth:w(),displayHeight:T(),createdAt:K.getCreatedAt(),updatedAt:K.getUpdatedAt()})}),v=Object.freeze({...q});return{entity:P,mutationApi:v}},IX=Object.freeze({create:di8});var VA1=Object.freeze(["string","object_ref","int","text","date","float"]),ai8=($)=>{let{id:K,name:q,ownerEntityId:Y,label:z,description:J,primitiveType:W,required:Z,multiplicity:O,isSystem:H,allowed:X,jsonSchema:w,createdAt:T,updatedAt:G,isVirtual:P,editable:v}=$;if(!VA1.includes(W))throw Error(`Invalid primitive type: "${W}". Valid types are: ${VA1.join(", ")}`);let{entityFns:M,mutationFns:V}=d_.create({id:K,name:q,createdAt:T,updatedAt:G}),k=()=>Y,j=()=>z,C=()=>J,g=()=>W,y=()=>Z,S=()=>O,x=()=>H,R=()=>X??null,D=()=>w??null,E=()=>P??!1,I=()=>v??!0,F=Object.freeze({...M,getOwnerEntityId:k,getLabel:j,getDescription:C,getPrimitiveType:g,getRequired:y,getMultiplicity:S,getIsSystem:x,getAllowed:R,getJsonSchema:D,getIsVirtual:E,getEditable:I,toJSON:()=>({id:M.getObjectId(),ownerEntityId:k(),name:M.getName(),label:j(),description:C(),primitiveType:g(),required:y(),multiplicity:S(),isSystem:x(),allowed:R(),jsonSchema:D(),isVirtual:E(),editable:I(),createdAt:M.getCreatedAt(),updatedAt:M.getUpdatedAt()})}),Y1=Object.freeze({...V});return{entity:F,mutationApi:Y1}},o_=Object.freeze({create:ai8});var oi8=({definition:$,values:K=[]})=>{let q=$,Y=[...K];if(q.getMultiplicity()==="single"&&Y.length>1)throw Error(`Field "${q.getName()}" is single-valued but received ${Y.length} values`);let z=(G=0)=>{return Y[G]},J=()=>{return[...Y]},W=()=>{return q},Z=()=>{return q.getMultiplicity()==="multi"};return Object.freeze({getValue:z,getValues:J,getDefinition:W,isMultiValued:Z,isRequired:()=>{return q.getRequired()},getType:()=>{return q.getPrimitiveType()},getLabel:()=>{return q.getLabel()||q.getName()},getName:()=>{return q.getName()},toJSON:()=>{if(Z())return Y;else return Y[0]}})},l3=Object.freeze({create:oi8});F6();F6();var ri8=($)=>{let K=$.trim();c.factory(!K,h.validation,"Folder name cannot be empty","EMPTY_NAME"),c.factory(K.length>255,h.validation,"Folder name cannot exceed 255 characters","NAME_TOO_LONG");let q=/[/\\:*?"<>|]/;return c.factory(q.test(K),h.validation,'Folder name contains invalid characters: /\\:*?"<>|',"INVALID_CHARS"),K},si8=($)=>{return $.getParentId()===null},d9=Object.freeze({validateFolderName:ri8,isRootFolder:si8});F6();var ti8=($)=>{if(!$||$.length<3)return null;let K=$[0],q=$[1],Y=parseInt($.slice(2),10);if(isNaN(Y))return null;return{storeCode:K,typeCode:q,seq:Y}},ei8=($,K,q)=>`${$}${K}${q}`,$n8=($,K)=>{c.factory($!==K,h.validation,`Store code mismatch: expected ${K}, got ${$}`,"STORE_CODE_MISMATCH")},Kn8=($)=>typeof $==="string"&&$[0]==="_",M2=Object.freeze({parseId:ti8,buildId:ei8,validateStoreCode:$n8,isVirtualId:Kn8});var _n8=($)=>{let{publishedVersionNumber:K,hasDraft:q,draftContent:Y,publishedContent:z,...J}=$,{entityFns:W,mutationFns:Z}=a_.create(J),O=K??null,H=q??!1,X=Y??null,w=z??null,T=null,g=Object.freeze({...W,getPublishedVersionNumber:()=>O,hasDraftContent:()=>H,getDraftContent:()=>X,getPublishedContent:()=>w,getEditState:()=>T,hasPublished:()=>O>0,isBeingEdited:()=>T!==null,getVersionCount:()=>O??0}),E=Object.freeze({...Z,setPublishedVersionNumber:(I)=>{O=I},setHasDraft:(I)=>{H=I},setDraftContent:(I)=>{X=I},setPublishedContent:(I)=>{w=I},setEditState:(I)=>{T=I}});return{entityFns:g,mutationFns:E}},MR=Object.freeze({create:_n8});var xS4=Object.freeze(["name","updatedAt","parentId","path","publishedVersionNumber","hasDraft","draftContent","publishedContent","editState"]),MA1=($)=>{let{subtype:K,...q}=$,{entityFns:Y,mutationFns:z}=MR.create(q),J=()=>"d",W=()=>K??null,O=Object.freeze({...Y,getTypeCode:J,getSubtype:W,toJSON:()=>{let X={};for(let[w,T]of Object.entries(Y.getFields()))X[w]=T.toJSON();return{id:Y.getObjectId(),parentId:Y.getParentId(),name:Y.getName(),path:Y.getPath(),publishedVersionNumber:Y.getPublishedVersionNumber(),hasDraft:Y.hasDraftContent(),draftContent:Y.getDraftContent(),publishedContent:Y.getPublishedContent(),editState:Y.getEditState(),createdAt:Y.getCreatedAt(),updatedAt:Y.getUpdatedAt(),versionCount:Y.getVersionCount(),isFolder:Y.getIsFolder(),type:J(),subtype:W(),hasPublished:Y.hasPublished(),isBeingEdited:Y.isBeingEdited(),fields:X}}}),H=Object.freeze({...z});return{entity:O,mutationApi:H}},qn8=($,K,q,Y,z,J,W=null,Z=null)=>{return MA1({id:K,parentId:q,name:$.name,path:Y,publishedVersionNumber:z,hasDraft:J,draftContent:W,publishedContent:Z,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null,subtype:$.subtype||null})},NR=Object.freeze({create:MA1,createFromRow:qn8});var yS4=Object.freeze(["name","updatedAt","parentId","path","publishedVersionNumber","hasDraft","draftContent","publishedContent","editState"]),NA1=($)=>{let{subtype:K,...q}=$,{entityFns:Y,mutationFns:z}=MR.create(q),J=()=>"t",W=()=>K??null,O=Object.freeze({...Y,getTypeCode:J,getSubtype:W,toJSON:()=>{let X={};for(let[w,T]of Object.entries(Y.getFields()))X[w]=T.toJSON();return{id:Y.getObjectId(),parentId:Y.getParentId(),name:Y.getName(),path:Y.getPath(),publishedVersionNumber:Y.getPublishedVersionNumber(),hasDraft:Y.hasDraftContent(),draftContent:Y.getDraftContent(),publishedContent:Y.getPublishedContent(),editState:Y.getEditState(),createdAt:Y.getCreatedAt(),updatedAt:Y.getUpdatedAt(),versionCount:Y.getVersionCount(),isFolder:Y.getIsFolder(),type:J(),subtype:W(),hasPublished:Y.hasPublished(),isBeingEdited:Y.isBeingEdited(),fields:X}}}),H=Object.freeze({...z});return{entity:O,mutationApi:H}},Yn8=($,K,q,Y,z,J,W=null,Z=null)=>{return NA1({id:K,parentId:q,name:$.name,path:Y,publishedVersionNumber:z,hasDraft:J,draftContent:W,publishedContent:Z,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null,subtype:$.subtype||null})},jR=Object.freeze({create:NA1,createFromRow:Yn8});var mS4=Object.freeze(["name","updatedAt"]),jA1=($)=>{let{id:K,documentId:q,versionNumber:Y,publishedAt:z,content:J,createdAt:W,updatedAt:Z}=$,{entityFns:O,mutationFns:H}=SX.create({id:K,name:null,createdAt:W,updatedAt:Z}),X=()=>q,w=()=>Y,T=()=>z,G=()=>J,V=Object.freeze({...O,getDocumentId:X,getVersionNumber:w,getPublishedAt:T,getContent:G,isDraft:()=>z===null,getTypeCode:()=>"v",toJSON:()=>({id:O.getObjectId(),documentId:X(),versionNumber:w(),publishedAt:T(),content:G(),createdAt:O.getCreatedAt(),updatedAt:O.getUpdatedAt()})}),k=Object.freeze({...H});return{entity:V,mutationApi:k}},zn8=($,K,q,Y,z,J=null)=>{return jA1({id:K,documentId:q,versionNumber:Y,publishedAt:z,content:J,createdAt:$.created_at,updatedAt:$.updated_at})},fR=Object.freeze({create:jA1,createFromRow:zn8});F6();var fA1=($)=>{let K=M2.parseId($);if(!K)throw h.notFound(`Invalid entity ID format: ${$}`,"NOT_FOUND");let{storeCode:q,typeCode:Y,seq:z}=K;return{entityId:`${Y}${z}`,storeCode:q,typeCode:Y,seq:z}},Jn8=($)=>{let{typeCode:K}=fA1($);return K},uc={d:NR.createFromRow,t:jR.createFromRow,v:fR.createFromRow,f:h5.createFromRow},Wn8=($)=>{if($==="s")return uc.d;if(!$)return uc.d;let K=uc[$];if(!K)throw Error(`Unknown content type: ${$}`);return K},Zn8=($)=>{return{d:"document",t:"template",v:"version"}[$]||"content"},n6=Object.freeze({resolveEntityId:fA1,getTypeFromId:Jn8,getEntityFactory:Wn8,getContentTypeLabel:Zn8,buildId:M2.buildId,parseId:M2.parseId});var c$=Object.freeze([{name:"name",label:"Name",primitiveType:"string",editable:!0,columnName:"name",description:"Entity display name",sortOrder:-4,colSpan:2,hiddenForTypes:["v"]},{name:"parent",label:"Parent",primitiveType:"object_ref",editable:!0,columnName:"parent_folder_id",description:"Parent folder reference",sortOrder:-1,colSpan:1,hiddenForTypes:["v","j","s"]},{name:"created_at",label:"Created At",primitiveType:"date",editable:!1,columnName:"created_at",description:"Creation timestamp",sortOrder:-3,colSpan:1},{name:"updated_at",label:"Updated At",primitiveType:"date",editable:!1,columnName:"updated_at",description:"Last modification timestamp",sortOrder:-2,colSpan:1},{name:"ancestor",label:"Ancestor",primitiveType:"ancestor_ref",searchOnly:!0,editable:!1,description:"Ancestor folder/story reference for subtree search"},{name:"id",label:"ID",primitiveType:"string",editable:!1,columnName:"object_id",searchOnly:!0,description:"Entity object ID for search filtering"}]);for(let $ of c$)if(!$.searchOnly){if(!$.columnName)throw Error(`Virtual field '${$.name}': non-searchOnly fields must have columnName`)}var SA=($)=>c$.some((K)=>K.name===$),kR=($)=>c$.find((K)=>K.name===$),A0=Object.freeze(new Set(c$.map(($)=>$.name)));F6();var q6=Object.freeze({FOLDER_CREATED:"folderCreated",FOLDER_RENAMED:"folderRenamed",FOLDER_MOVED:"folderMoved",FOLDER_DELETED:"folderDeleted",FOLDER_RESTORED:"folderRestored",DOCUMENT_CREATED:"documentCreated",DOCUMENT_RENAMED:"documentRenamed",DOCUMENT_MOVED:"documentMoved",DOCUMENT_DELETED:"documentDeleted",DOCUMENT_RESTORED:"documentRestored",DOCUMENT_PUBLISHED:"documentPublished",DRAFT_SAVED:"draftSaved",DRAFT_DISCARDED:"draftDiscarded",TEMPLATE_CREATED:"templateCreated",TEMPLATE_RENAMED:"templateRenamed",TEMPLATE_MOVED:"templateMoved",TEMPLATE_DELETED:"templateDeleted",TEMPLATE_PUBLISHED:"templatePublished",TEMPLATE_DRAFT_SAVED:"templateDraftSaved",TEMPLATE_DRAFT_DISCARDED:"templateDraftDiscarded",EDIT_STATE_ACQUIRED:"editStateAcquired",EDIT_STATE_REFRESHED:"editStateRefreshed",EDIT_STATE_CLEARED:"editStateCleared",STORY_CREATED:"storyCreated",STORY_RENAMED:"storyRenamed",STORY_DELETED:"storyDeleted",STORY_STATE_CHANGED:"storyStateChanged",JOB_CREATED:"jobCreated",JOB_UPDATED:"jobUpdated",JOB_STATUS_CHANGED:"jobStatusChanged",JOB_COMPLETED:"jobCompleted",JOB_DELETED:"jobDeleted",JOB_RESTORED:"jobRestored",FIELD_ADDED:"fieldAdded",FIELD_VALUE_CHANGED:"fieldValueChanged",FIELD_REMOVED:"fieldRemoved",FIELD_DEFINITION_CREATED:"fieldDefinitionCreated",FIELD_DEFINITION_DELETED:"fieldDefinitionDeleted",ENTITY_TYPE_CREATED:"entityTypeCreated",ENTITY_TYPE_UPDATED:"entityTypeUpdated",ASSET_CREATED:"assetCreated",ASSET_DELETED:"assetDeleted"});var Vz=null,RR=!1,DR=null,xX=[],On8=async($,K=null)=>{if(DR=$,await kA1(),RR=!0,K)Hn8(K)},Hn8=($)=>{xX.forEach((K)=>K()),xX=[],xX.push($.subscribe(q6.ENTITY_TYPE_CREATED,()=>hA()),$.subscribe(q6.ENTITY_TYPE_UPDATED,()=>hA())),xX.push($.subscribe(q6.FIELD_DEFINITION_CREATED,()=>hA()),$.subscribe(q6.FIELD_DEFINITION_DELETED,()=>hA()))},kA1=async()=>{let $=await DR.selectFrom("entity_types").select(["code","subtype","is_pathable","can_have_children","scope","sequence_scope"]).execute();Vz=new Map;for(let q of $){let Y=q.subtype||q.code;Vz.set(Y,{isPathable:q.is_pathable===1,isVersioned:!1,isContainer:q.can_have_children===1,isFieldable:!0,isGlobal:q.scope==="global",sequenceScope:q.sequence_scope})}let K=await DR.selectFrom("class_field_defs").innerJoin("field_definitions","field_definitions.id","class_field_defs.field_definition_id").innerJoin("entity_types","entity_types.id","class_field_defs.class_type_id").select(["entity_types.code","entity_types.subtype","field_definitions.name"]).where("field_definitions.name","in",["draft_version","latest_published_version"]).execute();for(let q of K){let Y=q.subtype||q.code,z=Vz.get(Y);if(z)z.isVersioned=!0}},Xn8=($)=>{if(!RR)throw h.validation("CapabilityRegistry not initialized","REGISTRY_NOT_INITIALIZED");if(Vz===null)throw h.validation("CapabilityRegistry cache invalidated. Call ensureLoaded() before get().","REGISTRY_CACHE_INVALIDATED");let K=Vz.get($);if(!K)throw h.validation(`Unknown typeCode: ${$}. Capability metadata missing.`,"UNKNOWN_TYPE_CODE");return K},wn8=()=>RR,hA=()=>{Vz=null},Gn8=async()=>{if(Vz===null)await kA1()},Tn8=()=>{Vz=null,RR=!1,DR=null,xX.forEach(($)=>$()),xX=[]},Q$=Object.freeze({initialize:On8,get:Xn8,isInitialized:wn8,invalidate:hA,ensureLoaded:Gn8,reset:Tn8});F6();F$();var{parseId:Pn8,buildId:vn8}=M2,An8=({entityCache:$,storePk:K,storeCode:q})=>{let Y=async(O,H,{includeDeleted:X=!1}={})=>{if(!H)return null;if($&&!X){let P=$.get(H);if(P)return P.getPk()}if(!Pn8(H))c.factory(!0,h.validation,`Invalid parent folder ID: ${H}`,"INVALID_ID");let T=O.selectFrom("entities").select("id").where("store_id","=",K).where("object_id","=",H);if(!X)T=T.where("deleted_at","is",null);let G=await T.executeTakeFirst();return G?G.id:null},z=async(O,H)=>{let X=await O.selectFrom("entities").select(["name","parent_folder_id"]).where("id","=",H).executeTakeFirst();c.factory(!X,h.notFound,`Entity not found for PK ${H}`,"ENTITY_NOT_FOUND");let w=await J(O,X.parent_folder_id);return w!=null?`${w}/${X.name}`:X.name},J=async(O,H)=>{if(!H)return null;let X=await O.selectFrom("entities").select("path").where("id","=",H).where("deleted_at","is",null).executeTakeFirst();return X?X.path:null};return{getParentPk:Y,getParentStoredPath:J,computePath:z,cascadePathUpdate:async(O,H,X,w)=>{let T=H.length+1;await j8`UPDATE entities SET path = ${X} || SUBSTR(path, ${T})
|
|
742
|
+
`.execute($)};var xI8=()=>new Date().toISOString(),F8=xI8;var gI8=async($,K,q,Y)=>{return await $.insertInto("sequences").values({scope_type:K,scope_id:q,type_code:Y,next_value:j8`(SELECT COALESCE(MAX(seq), 0) + 1 FROM entities WHERE store_id ${q===null?j8`IS NULL`:j8`= ${q}`} AND type_code = ${Y})`}).onConflict((J)=>J.doNothing()).execute(),(await $.updateTable("sequences").set((J)=>({next_value:J("next_value","+",1)})).where("scope_type","=",K).where("scope_id",q===null?"is":"=",q).where("type_code","=",Y).returning("next_value").executeTakeFirstOrThrow()).next_value-1},R2=Object.freeze({nextSeq:gI8});var uI8=Object.freeze([{name:"agent",label:"Agent",description:"Agent type (claude or codex)"},{name:"status",label:"Status",description:"Job status (pending/running/completed/error)"},{name:"sessionId",label:"Session ID",description:"Agent session ID for conversation continuity",colSpan:2},{name:"objectId",label:"Object ID",description:"ID of the entity this job is associated with",primitiveType:"object_ref"},{name:"parentJobId",label:"Parent Job",description:"ID of parent job",primitiveType:"object_ref"},{name:"blocking",label:"Blocking",description:"Whether parent is blocking on this job"},{name:"skipPermissions",label:"Skip Permissions",description:"Skip permission prompts for Claude agent (true/false)",multiplicity:"multi"},{name:"workingDirectory",label:"Working Directory",description:"Working directory for job execution (optional, defaults to projectPath)",multiplicity:"multi"},{name:"errorMessage",label:"Error Message",description:"Error message if job failed",multiplicity:"multi"},{name:"dockerImage",label:"Docker Image",description:"Docker image name for containerized execution (optional)",multiplicity:"multi"},{name:"accumulatedMs",label:"Accumulated (ms)",description:"Total accumulated active time in milliseconds (excludes time spent waiting for blocking children)",primitiveType:"int"},{name:"resumeAttempts",label:"Resume Attempts",description:"Number of auto-resume attempts made for this job",primitiveType:"int"},{name:"resumeAt",label:"Resume At",description:"UTC timestamp when the job should be automatically resumed",primitiveType:"date"},{name:"resumePromptRef",label:"Resume Prompt",description:"ID of the prompt template to use when auto-resuming this job",primitiveType:"object_ref"},{name:"numTurns",label:"Number of Turns",description:"Number of agent conversation turns",primitiveType:"int"},{name:"model",label:"Model",description:"Model name (optional)",multiplicity:"multi"},{name:"startedAt",label:"Started At",description:"Job start timestamp",primitiveType:"date",multiplicity:"multi"},{name:"completedAt",label:"Completed At",description:"Job completion timestamp",primitiveType:"date",multiplicity:"multi"},{name:"exitCode",label:"Exit Code",description:"Process exit code",primitiveType:"int",multiplicity:"multi"},{name:"tokensUsed",label:"Tokens Used",description:"Total tokens used by the job",primitiveType:"int",multiplicity:"multi"},{name:"totalCostUsd",label:"Total Cost (USD)",description:"API cost in USD",primitiveType:"float",multiplicity:"multi"},{name:"durationMs",label:"Duration (ms)",description:"Job execution duration in milliseconds",primitiveType:"int",multiplicity:"multi"},{name:"pid",label:"PID",description:"Process ID of the running job",primitiveType:"int",multiplicity:"multi"},{name:"clearStoryFlag",label:"Clear Story Flag",description:"Clear story flag field on job start (true/false)",hidden:!0},{name:"clearStatusMessage",label:"Clear Status Message",description:"Clear story statusMessage field on job start (true/false)",hidden:!0},{name:"segmentStartedAt",label:"Segment Started At",description:"Start timestamp of the current active segment (null when blocked on a child job)",primitiveType:"date",hidden:!0}]),qW=uI8;var yI8=Object.freeze([{name:"hash",label:"Hash",description:"SHA-256 content hash",required:!0},{name:"mimeType",label:"MIME Type",description:"Content type",required:!0},{name:"sizeBytes",label:"Size (bytes)",description:"File size in bytes",primitiveType:"int",required:!0},{name:"originalFilename",label:"Original Filename",description:"Original upload filename"},{name:"widthPx",label:"Width (px)",description:"Native pixel width",primitiveType:"int"},{name:"heightPx",label:"Height (px)",description:"Native pixel height",primitiveType:"int"},{name:"displayWidth",label:"Display Width",description:"CSS display width",primitiveType:"int"},{name:"displayHeight",label:"Display Height",description:"CSS display height",primitiveType:"int"}]),KX=yI8;var Cq1=[{code:"f",name:"Folder",subtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"d",name:"Document",subtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"t",name:"Template",subtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"s",name:"Story",subtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"r",name:"Store",subtype:"local",is_pathable:0,can_have_children:0,scope:"global",sequence_scope:"global"},{code:"r",name:"Store",subtype:"demux",is_pathable:0,can_have_children:0,scope:"global",sequence_scope:"global"},{code:"p",name:"Project",subtype:null,is_pathable:0,can_have_children:0,scope:"global",sequence_scope:"global"},{code:"j",name:"Job",subtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"v",name:"Version",subtype:null,is_pathable:0,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"n",name:"field_definition",subtype:null,is_pathable:0,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"a",name:"asset",subtype:null,is_pathable:0,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Setting",subtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"f",name:"Document Root Folder",subtype:"root_d",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Template Root Folder",subtype:"root_t",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Story Root Folder",subtype:"root_s",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Job Root Folder",subtype:"root_j",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Settings Root Folder",subtype:"root_settings",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Tasks Folder",subtype:"tasks",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Epic Folder",subtype:"epic",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"f",name:"Orphaned Root Folder",subtype:"root_orphaned",parentCode:"f",parentSubtype:null,is_pathable:1,can_have_children:1,scope:"store",sequence_scope:"store"},{code:"d",name:"Task",subtype:"task",parentCode:"d",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"d",name:"Cartridge",subtype:"cartridge",parentCode:"d",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"d",name:"Scratch",subtype:"scratch",parentCode:"d",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"t",name:"Prompt",subtype:"prompt",parentCode:"t",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Track",subtype:"track",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Auto Archive Config",subtype:"auto-archive-config",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Job Config",subtype:"job-config",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Disposal Config",subtype:"disposal-config",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"},{code:"e",name:"Resume Config",subtype:"resume-config",parentCode:"e",parentSubtype:null,is_pathable:1,can_have_children:0,scope:"store",sequence_scope:"store"}],Eq1=async($)=>{return(await $.selectFrom("entity_types").select("id").limit(1).execute()).length>0},p8=async($,K,q=null)=>{return(await $.selectFrom("entity_types").select("id").where("code","=",K).where((z)=>q?z("subtype","=",q):z("subtype","is",null)).executeTakeFirstOrThrow()).id},Ik=async($,K,q,Y)=>{let z=F8(),W={d:"root_d",t:"root_t",s:"root_s",j:"root_j"}[Y],O={d:"Documents",t:"Templates",s:"Stories",j:"Jobs"}[Y],H=await p8($,"f",W);if(!await $.selectFrom("sequences").select("next_value").where("scope_type","=","store").where("scope_id","=",K).where("type_code","=","f").executeTakeFirst())await $.insertInto("sequences").values({scope_type:"store",scope_id:K,type_code:"f",next_value:1}).execute();let w=await $.selectFrom("sequences").select("next_value").where("scope_type","=","store").where("scope_id","=",K).where("type_code","=","f").executeTakeFirst();await $.updateTable("sequences").set((M)=>({next_value:M("next_value","+",1)})).where("scope_type","=","store").where("scope_id","=",K).where("type_code","=","f").execute();let T=`${q}f${w.next_value}`,G=await $.insertInto("entities").values({store_id:K,object_id:T,entity_type_id:H,type_code:"f",seq:w.next_value,parent_folder_id:null,parent_object_id:null,name:O,path:O,created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow();await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${G.id}, ${O??""}, ${O??""})`.execute($);let v={d:"document",t:"template",s:"story",j:"job"}[Y];return G.id},bI8=async($)=>{for(let K of Cq1)await $.insertInto("entity_types").values({code:K.code,name:K.name,subtype:K.subtype,parent_type_id:null,is_pathable:K.is_pathable,can_have_children:K.can_have_children,scope:K.scope,sequence_scope:K.sequence_scope}).execute();for(let K of Cq1)if(K.parentCode!==void 0){let q=await $.selectFrom("entity_types").select("id").where("code","=",K.parentCode).where((Y)=>K.parentSubtype===null?Y("subtype","is",null):Y("subtype","=",K.parentSubtype)).executeTakeFirstOrThrow();await $.updateTable("entity_types").set({parent_type_id:q.id}).where("code","=",K.code).where((Y)=>K.subtype===null?Y("subtype","is",null):Y("subtype","=",K.subtype)).execute()}},BI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((J)=>({next_value:J("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let z=`_n${Y.next_value}`;await $.insertInto("field_definitions").values({store_id:null,object_id:z,entity_type_id:q,type_code:"n",seq:Y.next_value,owner_entity_id:null,name:"state",label:"State",description:"Track state",primitive_type:"string",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).execute()},mI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"state",label:"State",description:"Story track state",primitive_type:"string",required:0,multiplicity:"single",is_system:1,config:JSON.stringify({allowed:{type:"function",name:"resolve-states-for-track",dependsOn:["track"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},UI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"state",label:"State",description:"Task track state",primitive_type:"string",required:0,multiplicity:"single",is_system:1,config:JSON.stringify({allowed:{type:"function",name:"resolve-task-states"}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},FI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"j",null);for(let z=0;z<qW.length;z++){let J=qW[z],W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:J.name,label:J.label,description:J.description,primitive_type:J.primitiveType||"string",required:0,multiplicity:J.multiplicity||"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:O.id,required:0,sort_order:z+1,hidden:J.hidden?1:0,colspan:J.colSpan??null}).execute()}},cI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"a",null);for(let z=0;z<KX.length;z++){let J=KX[z],W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:J.name,label:J.label,description:J.description,primitive_type:J.primitiveType||"string",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:O.id,required:J.required?1:0,sort_order:z+1}).execute()}},xk=Object.freeze(["prep","spec","design","plan","build","review","done"]),_X=Object.freeze(["waiting","ready","in-progress","done"]),QI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"f","tasks"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"states",label:"States",description:"Ordered list of valid task states",primitive_type:"string",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:1,sort_order:1}).execute()},pI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"f","epic"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"state",label:"State",description:"Epic lifecycle stage: discovery, inception, build, or done",primitive_type:"string",required:0,multiplicity:"single",is_system:1,config:JSON.stringify({allowed:{type:"enum",values:["discovery","inception","build","done"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},lI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"f","epic"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"stories",label:"Stories",description:"Constituent stories in this epic",primitive_type:"object_ref",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:2,colspan:3}).execute()},iI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"dependsOn",label:"Depends On",description:"Tasks that block this task",primitive_type:"object_ref",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:2}).execute()},nI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"cardContent",label:"Card Content",description:"Display text for task cards",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:3}).execute()},dI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"colour",label:"Colour",description:"CSS colour value for card styling",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:4}).execute()},aI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","task"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"progress",label:"Progress",description:"Checkbox completion percentage (0-100)",primitive_type:"float",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:5}).execute()},oI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","cartridge"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"synopsis",label:"Synopsis",description:"Brief description of the cartridge",primitive_type:"text",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1,colspan:3}).execute()},rI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d","cartridge"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"relatedActivities",label:"Related Activities",description:"Associated activity types",primitive_type:"string",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:2}).execute()},sI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"t","prompt"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"associatedType",label:"Associated Type",description:"Entity types this template is associated with",primitive_type:"string",required:0,multiplicity:"multi",is_system:1,config:JSON.stringify({allowed:{type:"enum",values:["s","d/task","j"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1,hidden:1}).execute()},tI8=Object.freeze({$id:"caw:visibility-config",type:"object",properties:{visibility:{type:"object",properties:{story:{type:"object",additionalProperties:{type:"array",items:{type:"string"}}},task:{type:"object",properties:{_stages:{type:"array",items:{type:"string"}}},additionalProperties:!1},job:{type:"object",properties:{_contexts:{type:"array",items:{type:"string"}}},additionalProperties:!1}},additionalProperties:!1}},additionalProperties:!1}),Lq1=Object.freeze({story:"s",task:"d/task",job:"j"}),eI8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"t","prompt"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((O)=>({next_value:O("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=JSON.stringify({jsonSchema:tI8}),Z=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"config",label:"Config",description:"Prompt visibility configuration",primitive_type:"string",required:0,multiplicity:"single",is_system:1,config:W,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:Z.id,required:0,sort_order:2,colspan:1}).execute()},$x8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"flag",label:"Flag",description:"Visual indicator for story attention",primitive_type:"string",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:2}).execute()},Kx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"activeJobCount",label:"Active Job Count",description:"Number of active jobs associated with this story",primitive_type:"int",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:5}).execute()},_x8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"statusMessage",label:"Status Message",description:"Agent status message displayed in stories list",primitive_type:"string",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:3}).execute()},qx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"dateCompleted",label:"Date Completed",description:"Timestamp when story transitioned to done state",primitive_type:"date",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:4}).execute()},Yx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null),J=await p8($,"f",null),W=await p8($,"s",null),Z=await p8($,"j",null),O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((w)=>({next_value:w("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=`_n${O.next_value}`,X=await $.insertInto("field_definitions").values({store_id:null,object_id:H,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:"delete_date",label:"Delete Date",description:"Eligible for deletion after this date",primitive_type:"date",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();for(let w of[Y,z,J,W,Z])await $.insertInto("class_field_defs").values({store_id:null,class_type_id:w,field_definition_id:X.id,required:0,sort_order:null}).execute()},zx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","track"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"states",label:"States",description:"Ordered list of track states",primitive_type:"string",required:0,multiplicity:"multi",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:1,sort_order:1}).execute()},Jx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","auto-archive-config"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"delayMs",label:"Delay (ms)",description:"Auto-archive delay threshold in milliseconds",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},Wx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","job-config"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"maxConcurrentJobs",label:"Max Concurrent Jobs",description:"Maximum number of concurrent jobs allowed",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:1}).execute()},Zx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","disposal-config"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${z.next_value}`,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"scratchDocDelayDays",label:"Scratch Document Delay (days)",description:"Number of days before scratch documents are disposed",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:J.id,required:0,sort_order:1}).execute();let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${W.next_value}`,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:"jobDelayDays",label:"Job Delay (days)",description:"Number of days before completed jobs are disposed",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:Z.id,required:0,sort_order:2}).execute();let O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${O.next_value}`,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:"retentionDays",label:"Retention Days",description:"Number of days soft-deleted entities are retained before permanent deletion",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:H.id,required:0,sort_order:3}).execute()},Ox8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"e","resume-config"),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${z.next_value}`,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"defaultResumePromptRef",label:"Default Resume Prompt",description:"Default prompt template used when auto-resuming jobs in this project",primitive_type:"object_ref",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:J.id,required:0,sort_order:1}).execute();let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${W.next_value}`,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:"maxResumeAttempts",label:"Max Resume Attempts",description:"Maximum number of automatic resume attempts per job",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:Z.id,required:0,sort_order:2}).execute();let O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((X)=>({next_value:X("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=await $.insertInto("field_definitions").values({store_id:null,object_id:`_n${O.next_value}`,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:"cronIntervalMs",label:"Cron Interval (ms)",description:"Polling interval for the ResumeAwaitingJobsCronJob in milliseconds",primitive_type:"int",required:0,multiplicity:"single",is_system:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:H.id,required:0,sort_order:3}).execute()},Hx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"track",label:"Track",description:"Assigned track",primitive_type:"object_ref",required:0,multiplicity:"single",is_system:1,config:JSON.stringify({allowed:{type:"function",name:"resolve-tracks"}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:6}).execute()},Xx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"phase",label:"Phase",description:"Lifecycle phase: backlog, active, or history",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,config:JSON.stringify({allowed:{type:"enum",values:["backlog","active","history"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:7}).execute()},wx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"size",label:"Size",description:"Story point estimate using modified Fibonacci scale",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,config:JSON.stringify({allowed:{type:"enum",values:["0","½","1","2","3","5","8","13","20","40","100","∞"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:8}).execute()},Gx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"priority",label:"Priority",description:"Story urgency level",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,config:JSON.stringify({allowed:{type:"enum",values:["Critical","High priority","Medium priority","Low priority","Cosmetic"]}}),created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:9}).execute()},Tx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"ranking",label:"Ranking",description:"Sparse integer for user-controlled story ordering within a phase",primitive_type:"int",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:10}).execute()},Px8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"pendingJobCount",label:"Pending Job Count",description:"Number of pending jobs associated with this story",primitive_type:"int",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:11}).execute()},vx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"s",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"worktree_branch",label:"Worktree Branch",description:"Stores the git worktree branch name for a story",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:1,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:0,sort_order:8}).execute()},Ax8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null),J=[{name:"draft_version",label:"Draft Version",description:"Points to current draft version entity",sortOrder:1},{name:"latest_published_version",label:"Latest Published Version",description:"Points to most recent published version entity",sortOrder:2}];for(let W of[Y,z])for(let Z of J){let O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((w)=>({next_value:w("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=`_n${O.next_value}`,X=await $.insertInto("field_definitions").values({store_id:null,object_id:H,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:Z.name,label:Z.label,description:Z.description,primitive_type:"object_ref",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:W,field_definition_id:X.id,required:0,sort_order:Z.sortOrder}).execute()}},Vx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null),J=[{name:"edit_session_id",label:"Edit Session ID",description:"UUID of the editing session",primitiveType:"string",sortOrder:3,hidden:!0},{name:"edit_started_at",label:"Edit Started At",description:"When edit lock was acquired",primitiveType:"date",sortOrder:4,hidden:!0},{name:"edit_last_activity_at",label:"Edit Last Activity At",description:"Last activity during edit session",primitiveType:"date",sortOrder:5,hidden:!0}];for(let W of[Y,z])for(let Z of J){let O=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((w)=>({next_value:w("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let H=`_n${O.next_value}`,X=await $.insertInto("field_definitions").values({store_id:null,object_id:H,entity_type_id:q,type_code:"n",seq:O.next_value,owner_entity_id:null,name:Z.name,label:Z.label,description:Z.description,primitive_type:Z.primitiveType,required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:W,field_definition_id:X.id,required:0,sort_order:Z.sortOrder,hidden:Z.hidden?1:0}).execute()}},Mx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null);for(let J of[Y,z]){let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:"size",label:"Size",description:"Content size in bytes",primitive_type:"int",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:J,field_definition_id:O.id,required:0,sort_order:6}).execute()}},Nx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"d",null),z=await p8($,"t",null);for(let J of[Y,z]){let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:"orphanedFrom",label:"Orphaned From",description:"ID of the job or story from which this document was orphaned during disposal",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:J,field_definition_id:O.id,required:0,sort_order:null}).execute()}},jx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"v",null),z=[{name:"attachments",label:"Attachments",description:"Referenced asset entities",sortOrder:5,colSpan:2},{name:"includes",label:"Includes",description:"Included documents and templates",sortOrder:6,colSpan:2},{name:"hyperlinks",label:"Hyperlinks",description:"Linked entities in content",sortOrder:7,colSpan:2}];for(let J of z){let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:J.name,label:J.label,description:J.description,primitive_type:"object_ref",required:0,multiplicity:"multi",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:O.id,required:0,sort_order:J.sortOrder,colspan:J.colSpan??null}).execute()}},fx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"v",null),z=[{name:"document",label:"Document",description:"Parent document or template entity",primitiveType:"object_ref",required:1,sortOrder:1},{name:"version_number",label:"Version Number",description:"Version number (1, 2, 3...)",primitiveType:"int",required:1,sortOrder:2,hidden:!0},{name:"published_at",label:"Published At",description:"When this version was published",primitiveType:"date",required:0,sortOrder:3},{name:"content_hash",label:"Content Hash",description:"SHA-256 hex fingerprint of content for change detection",primitiveType:"string",required:0,sortOrder:4,colSpan:2}];for(let J of z){let W=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((H)=>({next_value:H("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let Z=`_n${W.next_value}`,O=await $.insertInto("field_definitions").values({store_id:null,object_id:Z,entity_type_id:q,type_code:"n",seq:W.next_value,owner_entity_id:null,name:J.name,label:J.label,description:J.description,primitive_type:J.primitiveType,required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:O.id,required:J.required,sort_order:J.sortOrder,colspan:J.colSpan??null,hidden:J.hidden?1:0}).execute()}},kx8=async($,K,q)=>{let Y=F8(),z=await p8($,"f","root_settings"),J=await R2.nextSeq($,"store",K,"f"),W=`${q}f${J}`,Z=await $.insertInto("entities").values({store_id:K,object_id:W,entity_type_id:z,type_code:"f",seq:J,parent_folder_id:null,parent_object_id:null,name:"Settings",path:"Settings",created_at:Y,updated_at:Y}).returning("id").executeTakeFirstOrThrow();return await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${Z.id}, ${"Settings"}, ${"Settings"})`.execute($),Z.id},Dx8=async($,K,q)=>{let Y=F8(),z=await p8($,"f","root_orphaned"),J=await R2.nextSeq($,"store",K,"f"),W=`${q}f${J}`,Z=await $.insertInto("entities").values({store_id:K,object_id:W,entity_type_id:z,type_code:"f",seq:J,parent_folder_id:null,parent_object_id:null,name:"Orphaned",path:"Orphaned",created_at:Y,updated_at:Y}).returning("id").executeTakeFirstOrThrow();return await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${Z.id}, ${"Orphaned"}, ${"Orphaned"})`.execute($),Z.id},Rx8=async($,K,q,Y)=>{let z=F8(),J=await p8($,"f",null),W=await $.selectFrom("entities").select("object_id").where("id","=",Y).executeTakeFirstOrThrow(),Z=await R2.nextSeq($,"store",K,"f"),O=`${q}f${Z}`,H=await $.insertInto("entities").values({store_id:K,object_id:O,entity_type_id:J,type_code:"f",seq:Z,parent_folder_id:Y,parent_object_id:W.object_id,name:"Stories",path:"Settings/Stories",created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow();await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${H.id}, ${"Stories"}, ${"Settings/Stories"})`.execute($);let X=H.id,w=await R2.nextSeq($,"store",K,"f"),T=`${q}f${w}`,G=await $.insertInto("entities").values({store_id:K,object_id:T,entity_type_id:J,type_code:"f",seq:w,parent_folder_id:X,parent_object_id:O,name:"Tracks",path:"Settings/Stories/Tracks",created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow();return await j8`INSERT INTO entity_content_fts(rowid, name, content_text) VALUES (${G.id}, ${"Tracks"}, ${"Settings/Stories/Tracks"})`.execute($),G.id},Cx8=async($,K,q,Y)=>{let z=F8(),J=await p8($,"e","track"),W=await $.selectFrom("entities").select("object_id").where("id","=",Y).executeTakeFirstOrThrow(),Z=await R2.nextSeq($,"store",K,"e"),O=`${q}e${Z}`,X=(await $.insertInto("entities").values({store_id:K,object_id:O,entity_type_id:J,type_code:"e",seq:Z,parent_folder_id:Y,parent_object_id:W.object_id,name:"Default",path:"Settings/Stories/Tracks/Default",created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow()).id,w=await $.selectFrom("field_definitions").innerJoin("class_field_defs","class_field_defs.field_definition_id","field_definitions.id").innerJoin("entity_types","entity_types.id","class_field_defs.class_type_id").select("field_definitions.id").where("field_definitions.store_id","is",null).where("field_definitions.name","=","states").where("entity_types.code","=","e").where("entity_types.subtype","=","track").executeTakeFirstOrThrow();for(let T=0;T<xk.length;T++)await $.insertInto("string_fields").values({entity_id:X,field_definition_id:w.id,value:xk[T],ordinal:T}).execute()},Ex8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"r","local");if(!await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirst())await $.insertInto("sequences").values({scope_type:"global",scope_id:null,type_code:"n",next_value:1}).execute();let J=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((O)=>({next_value:O("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let W=`_n${J.next_value}`,Z=await $.insertInto("field_definitions").values({store_id:null,object_id:W,entity_type_id:q,type_code:"n",seq:J.next_value,owner_entity_id:null,name:"code",label:"Store Code",description:"Unique code identifying the local store (e.g., A, B)",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();return await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:Z.id,required:1,sort_order:null}).execute(),Z.id},Lx8=async($)=>{let K=F8(),q=await p8($,"n",null),Y=await p8($,"p",null),z=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").executeTakeFirstOrThrow();await $.updateTable("sequences").set((Z)=>({next_value:Z("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","n").execute();let J=`_n${z.next_value}`,W=await $.insertInto("field_definitions").values({store_id:null,object_id:J,entity_type_id:q,type_code:"n",seq:z.next_value,owner_entity_id:null,name:"path",label:"Project Path",description:"Filesystem path for the project",primitive_type:"string",required:0,multiplicity:"single",is_system:1,editable:0,created_at:K,updated_at:K}).returning("id").executeTakeFirstOrThrow();return await $.insertInto("class_field_defs").values({store_id:null,class_type_id:Y,field_definition_id:W.id,required:1,sort_order:null}).execute(),W.id},Sx8=async($)=>{let K=await Ex8($);await Lx8($);let q=await $.selectFrom("sequences").select("next_value").where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","r").executeTakeFirstOrThrow();await $.updateTable("sequences").set((w)=>({next_value:w("next_value","+",1)})).where("scope_type","=","global").where("scope_id","is",null).where("type_code","=","r").execute();let Y=`S${q.next_value}`,z=F8(),J=await p8($,"r","local"),Z=(await $.insertInto("entities").values({store_id:null,object_id:Y,entity_type_id:J,type_code:"r",seq:q.next_value,parent_folder_id:null,parent_object_id:null,name:"Shared",created_at:z,updated_at:z}).returning("id").executeTakeFirstOrThrow()).id;await $.insertInto("string_fields").values({entity_id:Z,field_definition_id:K,value:"B",ordinal:0}).execute(),await Ik($,Z,"B","d"),await Ik($,Z,"B","t");let O=await Ik($,Z,"B","s");await Ik($,Z,"B","j");let H=await kx8($,Z,"B");await Dx8($,Z,"B"),await BI8($),await FI8($),await cI8($),await UI8($),await iI8($),await nI8($),await dI8($),await aI8($),await oI8($),await rI8($),await QI8($),await sI8($),await eI8($),await mI8($),await $x8($),await Kx8($),await _x8($),await qx8($),await Yx8($),await Hx8($),await Xx8($),await wx8($),await Gx8($),await Tx8($),await Px8($),await vx8($),await pI8($),await lI8($),await zx8($),await Jx8($),await Wx8($),await Zx8($),await Ox8($);let X=await Rx8($,Z,"B",H);await Cx8($,Z,"B",X),await Ax8($),await Vx8($),await Mx8($),await Nx8($),await jx8($),await fx8($),await $.insertInto("sequences").values({scope_type:"store",scope_id:Z,type_code:"v",next_value:1}).execute()},Sq1=async($)=>{await bI8($),await $.insertInto("sequences").values([{scope_type:"global",scope_id:null,type_code:"r",next_value:1},{scope_type:"global",scope_id:null,type_code:"p",next_value:1}]).execute(),await Sx8($)};var gk=Z6(Iq1(),1),hx8=($,K)=>{if($)throw Error(K)},xq1=($,K)=>{if(gk.default.null($)||gk.default.undefined($))throw Error(`${K} is required`)},Ix8=($,K)=>{if(xq1($,K),gk.default.empty($))throw Error(`${K} cannot be empty`)},xx8=($,K,...q)=>{if($)throw K(...q)},gx8={condition:hx8,nullish:xq1,empty:Ix8,factory:xx8},c=gx8;var Mi8=typeof Bun<"u",Ni8=async($)=>{if(Mi8){let{Database:K}=await import("bun:sqlite"),{BunSqliteDialect:q}=await Promise.resolve().then(() => Z6(HA1(),1)),Y=new K($);return Y.exec("PRAGMA journal_mode = WAL"),Y.exec("PRAGMA foreign_keys = ON"),new Q_({dialect:new q({database:Y})})}else{let q=new(await import("better-sqlite3")).default($);return q.pragma("journal_mode = WAL"),q.pragma("foreign_keys = ON"),new Q_({dialect:new UB({database:q})})}},ji8=($,K)=>{if(!vi8($)){if(!K)throw Error(`Database file not found: ${$}`);Ai8(Vi8($),{recursive:!0})}},fi8=async($,K)=>{if(!await Dq1($)){if(!K)throw Error("Database schema not found");await Rq1($)}},ki8=async($,K)=>{if(!await Eq1($)){if(!K)throw Error("Database seed data not found");await Sq1($)}},Di8=($)=>{let{kyselyFactory:K=Ni8}=$??{};return Object.freeze({getDb:async(Y,z)=>{if(c.nullish(Y,"databaseFilepath"),Y!==":memory:")ji8(Y,z);let J=await K(Y);return await fi8(J,z),await ki8(J,z),J}})},XA1={create:Di8};var Ri8=($)=>{let{id:K,name:q,createdAt:Y,updatedAt:z,deletedAt:J}=$,w=Object.freeze({getObjectId:()=>K,getName:()=>q,getCreatedAt:()=>Y,getUpdatedAt:()=>z,getDeletedAt:()=>J??null}),P=Object.freeze({setName:(v)=>{q=v},setUpdatedAt:(v)=>{z=v}});return{entityFns:w,mutationFns:P}},d_=Object.freeze({create:Ri8});var Ci8=($)=>{let{id:K,name:q,path:Y,createdAt:z,updatedAt:J}=$,{entityFns:W,mutationFns:Z}=d_.create({id:K,name:q,createdAt:z,updatedAt:J}),O=()=>Y,X=Object.freeze({...W,getPath:O,toJSON:()=>({objectId:W.getObjectId(),name:W.getName(),path:O(),createdAt:W.getCreatedAt(),updatedAt:W.getUpdatedAt()})}),T=Object.freeze({...Z,setPath:(G)=>{Y=G}});return{entity:X,mutationApi:T}},wA1=Object.freeze({create:Ci8});var Ei8=($,K,q)=>{return Object.freeze({getEntity:()=>$,getMutationApi:()=>K,getPk:()=>q})},i6=Object.freeze({create:Ei8});F$();F6();var Bi8=($)=>$.object_id,VR=($)=>{if(!$||$.length<2||$[0]!=="P")return null;let K=parseInt($.slice(1),10);return isNaN(K)?null:K},xc=async($,K)=>{let q=await $.selectFrom("field_definitions").select("id").where("name","=","path").where("store_id","is",null).where("is_system","=",1).executeTakeFirst();if(!q)return null;return(await $.selectFrom("string_fields").select("value").where("entity_id","=",K).where("field_definition_id","=",q.id).executeTakeFirst())?.value??null},mi8=async($,K,q)=>{let Y=await $.selectFrom("field_definitions").select("id").where("name","=","path").where("store_id","is",null).where("is_system","=",1).executeTakeFirstOrThrow();await $.insertInto("string_fields").values({entity_id:K,field_definition_id:Y.id,value:q,ordinal:0}).execute()},LA=($,K)=>{let q=Bi8($),Y=$.id,{entity:z,mutationApi:J}=wA1.create({id:q,name:$.name,path:K,createdAt:$.created_at,updatedAt:$.updated_at});return{entity:z,mutationApi:J,id:q,pk:Y}},Ui8=()=>{let $=new Map,K=new Map,q=async(X,w,{name:T,path:G},P)=>{let v=await J(X,w,G);c.factory(v,h.validation,`Project with path already exists: ${G}`,"DUPLICATE_PROJECT_PATH");let M=F8(),V=await R2.nextSeq(X,"global",null,"p"),k=`P${V}`,j=await s8.readEntityTypeId(X,w,"p",null),C=await X.insertInto("entities").values({store_id:null,object_id:k,entity_type_id:j,type_code:"p",seq:V,parent_folder_id:null,parent_object_id:null,name:T,created_at:M,updated_at:M}).returningAll().executeTakeFirstOrThrow(),g=C.id;await mi8(X,g,G);let{entity:y,mutationApi:S,id:x}=LA(C,G);return P(`cache-set:${x}`,()=>{$.set(x,i6.create(y,S,g)),K.set(g,x)}),y},Y=async(X,w,T)=>{let G=$.get(T);if(G)return G.getEntity();let P=VR(T);if(P===null)return null;let v=await X.selectFrom("entities").selectAll().where("type_code","=","p").where("seq","=",P).where("deleted_at","is",null).executeTakeFirst();if(!v)return null;let M=await xc(X,v.id),{entity:V,mutationApi:k,id:j,pk:C}=LA(v,M);return $.set(j,i6.create(V,k,C)),K.set(C,j),V},z=async(X,w,T)=>{let G=$.get(T);if(G)return G.getEntity();if(VR(T)===null)return null;let v=await X.selectFrom("entities").selectAll().where("type_code","=","p").where("object_id","=",T).where("deleted_at","is",null).executeTakeFirst();if(!v)return null;let M=await xc(X,v.id),{entity:V,mutationApi:k,id:j,pk:C}=LA(v,M);return $.set(j,i6.create(V,k,C)),K.set(C,j),V},J=async(X,w,T)=>{let G=await X.selectFrom("entities").innerJoin("string_fields","string_fields.entity_id","entities.id").innerJoin("field_definitions","field_definitions.id","string_fields.field_definition_id").select(["entities.id","entities.object_id","entities.name","entities.created_at","entities.updated_at","string_fields.value as path"]).where("entities.type_code","=","p").where("entities.deleted_at","is",null).where("field_definitions.name","=","path").where("field_definitions.store_id","is",null).where("field_definitions.is_system","=",1).where("string_fields.value","=",T).executeTakeFirst();if(!G)return null;let{entity:P,mutationApi:v,id:M,pk:V}=LA(G,G.path),k=$.get(M);if(k)return k.getEntity();return $.set(M,i6.create(P,v,V)),K.set(V,M),P},W=(X)=>{let w=$.get(X);if(w)K.delete(w.getPk());$.delete(X)},Z=async(X,w,{id:T,name:G},P)=>{let v=VR(T);c.factory(v===null,h.validation,`Invalid project ID: ${T}`,"INVALID_ID");let M=await X.selectFrom("entities").selectAll().where("type_code","=","p").where("seq","=",v).where("deleted_at","is",null).executeTakeFirst();c.factory(!M,h.notFound,`Project not found: ${T}`,"PROJECT_NOT_FOUND");let V=M.id,k=F8(),j=await X.updateTable("entities").set({name:G,updated_at:k}).where("id","=",V).returningAll().executeTakeFirstOrThrow(),C=await xc(X,V),{entity:g,mutationApi:y,id:S}=LA(j,C);return P(`cache-update:${S}`,()=>{W(S),$.set(S,i6.create(g,y,V)),K.set(V,S)}),g},O=async(X,w)=>{let T=await X.selectFrom("field_definitions").select("id").where("name","=","code").where("store_id","is",null).where("is_system","=",1).executeTakeFirst();if(!T)return null;return(await X.selectFrom("string_fields").select("value").where("entity_id","=",w).where("field_definition_id","=",T.id).executeTakeFirst())?.value??null};return Object.freeze({createProject:q,readProject:Y,readProjectByObjectId:z,readProjectByPath:J,evictProject:W,updateProject:Z,deleteProject:async(X,w,{id:T},G)=>{let P=VR(T);c.factory(P===null,h.validation,`Invalid project ID: ${T}`,"INVALID_ID");let v=await X.selectFrom("entities").selectAll().where("type_code","=","p").where("seq","=",P).where("deleted_at","is",null).executeTakeFirst();c.factory(!v,h.notFound,`Project not found: ${T}`,"PROJECT_NOT_FOUND");let M=v.id,V=F8(),k=await X.selectFrom("project_stores").innerJoin("entities","entities.id","project_stores.store_id").innerJoin("entity_types","entity_types.id","entities.entity_type_id").select(["entities.id as storePk","entities.object_id as storeObjectId","entity_types.subtype"]).where("project_stores.project_id","=",M).where("entities.deleted_at","is",null).execute(),j=null,C=null,g=null,y=null;for(let E of k)if(E.subtype==="demux")g=E.storePk,y=E.storeObjectId;else if(E.subtype==="local"){if(await O(X,E.storePk)==="A")j=E.storePk,C=E.storeObjectId}let S=j?await X.selectFrom("entities").select(["id","object_id"]).where("store_id","=",j).where("deleted_at","is",null).execute():[],x=S.map((E)=>E.id),R=S.map((E)=>E.object_id);if(x.length>0)await X.updateTable("entities").set({deleted_at:V}).where("id","in",x).execute();let D=0;if(j)await X.updateTable("entities").set({deleted_at:V}).where("id","=",j).execute(),D++;if(g)await X.updateTable("entities").set({deleted_at:V}).where("id","=",g).execute(),D++;return await X.updateTable("entities").set({deleted_at:V}).where("id","=",M).execute(),G(`cache-evict:${T}`,()=>{for(let E of R);W(T)}),{id:T,deleted:!0,storeCount:D,entityCount:x.length,storeAObjectId:C,demuxObjectId:y,storeAEntityIds:R}}})},GA1=Object.freeze({create:Ui8});var Fi8=()=>{let $=new Map,K=new Map;return Object.freeze({get:(T)=>$.get(T),getByPk:(T)=>{let G=K.get(T);return G?$.get(G):void 0},has:(T)=>$.has(T),set:(T,G)=>{$.set(T,G),K.set(G.getPk(),T)},remove:(T)=>{let G=$.get(T);if(G)K.delete(G.getPk());$.delete(T)},getIdByPk:(T)=>K.get(T),setIdByPk:(T,G)=>K.set(T,G),clear:()=>{$.clear(),K.clear()},entries:()=>$.entries(),size:()=>$.size})},gc=Object.freeze({create:Fi8});var pA1=Z6(x6(),1);import{createHash as Qn8}from"crypto";F$();var ci8=($)=>{let{id:K,name:q,createdAt:Y,updatedAt:z,deletedAt:J}=$,{entityFns:W,mutationFns:Z}=d_.create({id:K,name:q,createdAt:Y,updatedAt:z,deletedAt:J}),O=new Map,w=Object.freeze({...W,getField:(v)=>{return O.get(v)},getFields:()=>{let v={};for(let[M,V]of O.entries())v[M]=V;return v}}),P=Object.freeze({...Z,setField:(v,M)=>{O.set(v,M)},removeField:(v)=>{O.delete(v)}});return{entityFns:w,mutationFns:P}},SX=Object.freeze({create:ci8});var Qi8=($)=>{let{id:K,name:q,parentId:Y,path:z,createdAt:J,updatedAt:W,deletedAt:Z}=$,{entityFns:O,mutationFns:H}=SX.create({id:K,name:q,createdAt:J,updatedAt:W,deletedAt:Z}),G=Object.freeze({...O,getParentId:()=>Y,getPath:()=>z,getIsFolder:()=>!1}),M=Object.freeze({...H,setParentId:(V)=>{Y=V},setPath:(V)=>{z=V}});return{entityFns:G,mutationFns:M}},a_=Object.freeze({create:Qi8});var JS4=Object.freeze(["name","updatedAt","parentId","path"]),TA1=($)=>{let{entityFns:K,mutationFns:q}=a_.create($),Y=$.subtype||null,z=()=>"f",J=()=>Y,W=()=>K.getParentId()===null,Z=()=>!0,H=Object.freeze({...K,getTypeCode:z,getSubtype:J,isRoot:W,getIsFolder:Z,toJSON:()=>{let w={};for(let[T,G]of Object.entries(K.getFields()))w[T]=G.toJSON();return{id:K.getObjectId(),parentId:K.getParentId(),name:K.getName(),path:K.getPath(),type:z(),subtype:J(),createdAt:K.getCreatedAt(),updatedAt:K.getUpdatedAt(),isFolder:Z(),isRoot:W(),fields:w}}}),X=Object.freeze({...q});return{entity:H,mutationApi:X}},pi8=($,K,q,Y)=>{return TA1({id:K,parentId:q,name:$.name,path:Y,subtype:$.subtype||null,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null})},h5=Object.freeze({create:TA1,createFromRow:pi8});var OS4=Object.freeze(["name","updatedAt","parentId","path"]),PA1=($)=>{let{entityFns:K,mutationFns:q}=a_.create($),O=Object.freeze({...K,getTypeCode:()=>"s",getSubtype:()=>null,isStory:()=>!0,getIsFolder:()=>!1,toJSON:()=>{let X={};for(let[w,T]of Object.entries(K.getFields()))X[w]=T.toJSON();return{id:K.getObjectId(),parentId:K.getParentId(),name:K.getName(),path:K.getPath(),createdAt:K.getCreatedAt(),updatedAt:K.getUpdatedAt(),type:"s",isStory:!0,isFolder:!1,fields:X}}}),H=Object.freeze({...q});return{entity:O,mutationApi:H}},li8=($,K,q,Y)=>{return PA1({id:K,parentId:q,name:$.name,path:Y,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null})},v0=Object.freeze({create:PA1,createFromRow:li8});var wS4=Object.freeze(["name","updatedAt","parentId","path"]),vA1=($)=>{let{subtype:K,...q}=$,{entityFns:Y,mutationFns:z}=a_.create(q),J=()=>"e",W=()=>K??null,O=Object.freeze({...Y,getTypeCode:J,getSubtype:W,toJSON:()=>{let X={};for(let[w,T]of Object.entries(Y.getFields()))X[w]=T.toJSON();return{id:Y.getObjectId(),parentId:Y.getParentId(),name:Y.getName(),path:Y.getPath(),createdAt:Y.getCreatedAt(),updatedAt:Y.getUpdatedAt(),isFolder:Y.getIsFolder(),type:J(),subtype:W(),fields:X}}}),H=Object.freeze({...z});return{entity:O,mutationApi:H}},ii8=($,K,q,Y)=>{return vA1({id:K,parentId:q,name:$.name,path:Y,createdAt:$.created_at,updatedAt:$.updated_at,subtype:$.subtype||null})},hX=Object.freeze({create:vA1,createFromRow:ii8});var PS4=Object.freeze(["name","updatedAt","parentId","path"]),AA1=($)=>{let{entityFns:K,mutationFns:q}=a_.create($),Z=Object.freeze({...K,getTypeCode:()=>"j",isJob:()=>!0,getIsFolder:()=>!1,toJSON:()=>{let H={};for(let[X,w]of Object.entries(K.getFields()))H[X]=w.toJSON();return{id:K.getObjectId(),parentId:K.getParentId(),name:K.getName(),path:K.getPath(),createdAt:K.getCreatedAt(),updatedAt:K.getUpdatedAt(),type:"j",isJob:!0,isFolder:!1,fields:H}}}),O=Object.freeze({...q});return{entity:Z,mutationApi:O}},ni8=($,K,q,Y)=>{return AA1({id:K,parentId:q,name:$.name,path:Y,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null})},yW=Object.freeze({create:AA1,createFromRow:ni8});var VS4=Object.freeze(["name","updatedAt"]),di8=($)=>{let{entityFns:K,mutationFns:q}=SX.create({id:$.id,name:$.name,createdAt:$.createdAt,updatedAt:$.updatedAt}),Y=()=>"a",z=()=>!0,J=()=>K.getField("hash")?.getValue(),W=()=>K.getField("mimeType")?.getValue(),Z=()=>K.getField("sizeBytes")?.getValue(),O=()=>K.getField("originalFilename")?.getValue()??null,H=()=>K.getField("widthPx")?.getValue()??null,X=()=>K.getField("heightPx")?.getValue()??null,w=()=>K.getField("displayWidth")?.getValue()??null,T=()=>K.getField("displayHeight")?.getValue()??null,P=Object.freeze({...K,getTypeCode:Y,isAsset:z,getHash:J,getMimeType:W,getSizeBytes:Z,getOriginalFilename:O,getWidthPx:H,getHeightPx:X,getDisplayWidth:w,getDisplayHeight:T,toJSON:()=>({id:K.getObjectId(),type:"a",hash:J(),mimeType:W(),sizeBytes:Z(),originalFilename:O(),widthPx:H(),heightPx:X(),displayWidth:w(),displayHeight:T(),createdAt:K.getCreatedAt(),updatedAt:K.getUpdatedAt()})}),v=Object.freeze({...q});return{entity:P,mutationApi:v}},IX=Object.freeze({create:di8});var VA1=Object.freeze(["string","object_ref","int","text","date","float"]),ai8=($)=>{let{id:K,name:q,ownerEntityId:Y,label:z,description:J,primitiveType:W,required:Z,multiplicity:O,isSystem:H,allowed:X,jsonSchema:w,createdAt:T,updatedAt:G,isVirtual:P,editable:v}=$;if(!VA1.includes(W))throw Error(`Invalid primitive type: "${W}". Valid types are: ${VA1.join(", ")}`);let{entityFns:M,mutationFns:V}=d_.create({id:K,name:q,createdAt:T,updatedAt:G}),k=()=>Y,j=()=>z,C=()=>J,g=()=>W,y=()=>Z,S=()=>O,x=()=>H,R=()=>X??null,D=()=>w??null,E=()=>P??!1,I=()=>v??!0,F=Object.freeze({...M,getOwnerEntityId:k,getLabel:j,getDescription:C,getPrimitiveType:g,getRequired:y,getMultiplicity:S,getIsSystem:x,getAllowed:R,getJsonSchema:D,getIsVirtual:E,getEditable:I,toJSON:()=>({id:M.getObjectId(),ownerEntityId:k(),name:M.getName(),label:j(),description:C(),primitiveType:g(),required:y(),multiplicity:S(),isSystem:x(),allowed:R(),jsonSchema:D(),isVirtual:E(),editable:I(),createdAt:M.getCreatedAt(),updatedAt:M.getUpdatedAt()})}),Y1=Object.freeze({...V});return{entity:F,mutationApi:Y1}},o_=Object.freeze({create:ai8});var oi8=({definition:$,values:K=[]})=>{let q=$,Y=[...K];if(q.getMultiplicity()==="single"&&Y.length>1)throw Error(`Field "${q.getName()}" is single-valued but received ${Y.length} values`);let z=(G=0)=>{return Y[G]},J=()=>{return[...Y]},W=()=>{return q},Z=()=>{return q.getMultiplicity()==="multi"};return Object.freeze({getValue:z,getValues:J,getDefinition:W,isMultiValued:Z,isRequired:()=>{return q.getRequired()},getType:()=>{return q.getPrimitiveType()},getLabel:()=>{return q.getLabel()||q.getName()},getName:()=>{return q.getName()},toJSON:()=>{if(Z())return Y;else return Y[0]}})},l3=Object.freeze({create:oi8});F6();F6();var ri8=($)=>{let K=$.trim();c.factory(!K,h.validation,"Folder name cannot be empty","EMPTY_NAME"),c.factory(K.length>255,h.validation,"Folder name cannot exceed 255 characters","NAME_TOO_LONG");let q=/[/\\:*?"<>|]/;return c.factory(q.test(K),h.validation,'Folder name contains invalid characters: /\\:*?"<>|',"INVALID_CHARS"),K},si8=($)=>{return $.getParentId()===null},d9=Object.freeze({validateFolderName:ri8,isRootFolder:si8});F6();var ti8=($)=>{if(!$||$.length<3)return null;let K=$[0],q=$[1],Y=parseInt($.slice(2),10);if(isNaN(Y))return null;return{storeCode:K,typeCode:q,seq:Y}},ei8=($,K,q)=>`${$}${K}${q}`,$n8=($,K)=>{c.factory($!==K,h.validation,`Store code mismatch: expected ${K}, got ${$}`,"STORE_CODE_MISMATCH")},Kn8=($)=>typeof $==="string"&&$[0]==="_",M2=Object.freeze({parseId:ti8,buildId:ei8,validateStoreCode:$n8,isVirtualId:Kn8});var _n8=($)=>{let{publishedVersionNumber:K,hasDraft:q,draftContent:Y,publishedContent:z,...J}=$,{entityFns:W,mutationFns:Z}=a_.create(J),O=K??null,H=q??!1,X=Y??null,w=z??null,T=null,g=Object.freeze({...W,getPublishedVersionNumber:()=>O,hasDraftContent:()=>H,getDraftContent:()=>X,getPublishedContent:()=>w,getEditState:()=>T,hasPublished:()=>O>0,isBeingEdited:()=>T!==null,getVersionCount:()=>O??0}),E=Object.freeze({...Z,setPublishedVersionNumber:(I)=>{O=I},setHasDraft:(I)=>{H=I},setDraftContent:(I)=>{X=I},setPublishedContent:(I)=>{w=I},setEditState:(I)=>{T=I}});return{entityFns:g,mutationFns:E}},MR=Object.freeze({create:_n8});var xS4=Object.freeze(["name","updatedAt","parentId","path","publishedVersionNumber","hasDraft","draftContent","publishedContent","editState"]),MA1=($)=>{let{subtype:K,...q}=$,{entityFns:Y,mutationFns:z}=MR.create(q),J=()=>"d",W=()=>K??null,O=Object.freeze({...Y,getTypeCode:J,getSubtype:W,toJSON:()=>{let X={};for(let[w,T]of Object.entries(Y.getFields()))X[w]=T.toJSON();return{id:Y.getObjectId(),parentId:Y.getParentId(),name:Y.getName(),path:Y.getPath(),publishedVersionNumber:Y.getPublishedVersionNumber(),hasDraft:Y.hasDraftContent(),draftContent:Y.getDraftContent(),publishedContent:Y.getPublishedContent(),editState:Y.getEditState(),createdAt:Y.getCreatedAt(),updatedAt:Y.getUpdatedAt(),versionCount:Y.getVersionCount(),isFolder:Y.getIsFolder(),type:J(),subtype:W(),hasPublished:Y.hasPublished(),isBeingEdited:Y.isBeingEdited(),fields:X}}}),H=Object.freeze({...z});return{entity:O,mutationApi:H}},qn8=($,K,q,Y,z,J,W=null,Z=null)=>{return MA1({id:K,parentId:q,name:$.name,path:Y,publishedVersionNumber:z,hasDraft:J,draftContent:W,publishedContent:Z,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null,subtype:$.subtype||null})},NR=Object.freeze({create:MA1,createFromRow:qn8});var yS4=Object.freeze(["name","updatedAt","parentId","path","publishedVersionNumber","hasDraft","draftContent","publishedContent","editState"]),NA1=($)=>{let{subtype:K,...q}=$,{entityFns:Y,mutationFns:z}=MR.create(q),J=()=>"t",W=()=>K??null,O=Object.freeze({...Y,getTypeCode:J,getSubtype:W,toJSON:()=>{let X={};for(let[w,T]of Object.entries(Y.getFields()))X[w]=T.toJSON();return{id:Y.getObjectId(),parentId:Y.getParentId(),name:Y.getName(),path:Y.getPath(),publishedVersionNumber:Y.getPublishedVersionNumber(),hasDraft:Y.hasDraftContent(),draftContent:Y.getDraftContent(),publishedContent:Y.getPublishedContent(),editState:Y.getEditState(),createdAt:Y.getCreatedAt(),updatedAt:Y.getUpdatedAt(),versionCount:Y.getVersionCount(),isFolder:Y.getIsFolder(),type:J(),subtype:W(),hasPublished:Y.hasPublished(),isBeingEdited:Y.isBeingEdited(),fields:X}}}),H=Object.freeze({...z});return{entity:O,mutationApi:H}},Yn8=($,K,q,Y,z,J,W=null,Z=null)=>{return NA1({id:K,parentId:q,name:$.name,path:Y,publishedVersionNumber:z,hasDraft:J,draftContent:W,publishedContent:Z,createdAt:$.created_at,updatedAt:$.updated_at,deletedAt:$.deleted_at??null,subtype:$.subtype||null})},jR=Object.freeze({create:NA1,createFromRow:Yn8});var mS4=Object.freeze(["name","updatedAt"]),jA1=($)=>{let{id:K,documentId:q,versionNumber:Y,publishedAt:z,content:J,createdAt:W,updatedAt:Z}=$,{entityFns:O,mutationFns:H}=SX.create({id:K,name:null,createdAt:W,updatedAt:Z}),X=()=>q,w=()=>Y,T=()=>z,G=()=>J,V=Object.freeze({...O,getDocumentId:X,getVersionNumber:w,getPublishedAt:T,getContent:G,isDraft:()=>z===null,getTypeCode:()=>"v",toJSON:()=>({id:O.getObjectId(),documentId:X(),versionNumber:w(),publishedAt:T(),content:G(),createdAt:O.getCreatedAt(),updatedAt:O.getUpdatedAt()})}),k=Object.freeze({...H});return{entity:V,mutationApi:k}},zn8=($,K,q,Y,z,J=null)=>{return jA1({id:K,documentId:q,versionNumber:Y,publishedAt:z,content:J,createdAt:$.created_at,updatedAt:$.updated_at})},fR=Object.freeze({create:jA1,createFromRow:zn8});F6();var fA1=($)=>{let K=M2.parseId($);if(!K)throw h.notFound(`Invalid entity ID format: ${$}`,"NOT_FOUND");let{storeCode:q,typeCode:Y,seq:z}=K;return{entityId:`${Y}${z}`,storeCode:q,typeCode:Y,seq:z}},Jn8=($)=>{let{typeCode:K}=fA1($);return K},uc={d:NR.createFromRow,t:jR.createFromRow,v:fR.createFromRow,f:h5.createFromRow},Wn8=($)=>{if($==="s")return uc.d;if(!$)return uc.d;let K=uc[$];if(!K)throw Error(`Unknown content type: ${$}`);return K},Zn8=($)=>{return{d:"document",t:"template",v:"version"}[$]||"content"},n6=Object.freeze({resolveEntityId:fA1,getTypeFromId:Jn8,getEntityFactory:Wn8,getContentTypeLabel:Zn8,buildId:M2.buildId,parseId:M2.parseId});var c$=Object.freeze([{name:"name",label:"Name",primitiveType:"string",editable:!0,columnName:"name",description:"Entity display name",sortOrder:-4,colSpan:2,hiddenForTypes:["v"]},{name:"parent",label:"Parent",primitiveType:"object_ref",editable:!0,columnName:"parent_folder_id",description:"Parent folder reference",sortOrder:-1,colSpan:1,hiddenForTypes:["v","j","s"]},{name:"created_at",label:"Created At",primitiveType:"date",editable:!1,columnName:"created_at",description:"Creation timestamp",sortOrder:-3,colSpan:1},{name:"updated_at",label:"Updated At",primitiveType:"date",editable:!1,columnName:"updated_at",description:"Last modification timestamp",sortOrder:-2,colSpan:1},{name:"ancestor",label:"Ancestor",primitiveType:"ancestor_ref",searchOnly:!0,editable:!1,description:"Ancestor folder/story reference for subtree search"},{name:"id",label:"ID",primitiveType:"string",editable:!1,columnName:"object_id",searchOnly:!0,description:"Entity object ID for search filtering"}]);for(let $ of c$)if(!$.searchOnly){if(!$.columnName)throw Error(`Virtual field '${$.name}': non-searchOnly fields must have columnName`)}var SA=($)=>c$.some((K)=>K.name===$),kR=($)=>c$.find((K)=>K.name===$),A0=Object.freeze(new Set(c$.map(($)=>$.name)));F6();var q6=Object.freeze({FOLDER_CREATED:"folderCreated",FOLDER_RENAMED:"folderRenamed",FOLDER_MOVED:"folderMoved",FOLDER_DELETED:"folderDeleted",FOLDER_RESTORED:"folderRestored",DOCUMENT_CREATED:"documentCreated",DOCUMENT_RENAMED:"documentRenamed",DOCUMENT_MOVED:"documentMoved",DOCUMENT_DELETED:"documentDeleted",DOCUMENT_RESTORED:"documentRestored",DOCUMENT_PUBLISHED:"documentPublished",DRAFT_SAVED:"draftSaved",DRAFT_DISCARDED:"draftDiscarded",TEMPLATE_CREATED:"templateCreated",TEMPLATE_RENAMED:"templateRenamed",TEMPLATE_MOVED:"templateMoved",TEMPLATE_DELETED:"templateDeleted",TEMPLATE_PUBLISHED:"templatePublished",TEMPLATE_DRAFT_SAVED:"templateDraftSaved",TEMPLATE_DRAFT_DISCARDED:"templateDraftDiscarded",EDIT_STATE_ACQUIRED:"editStateAcquired",EDIT_STATE_REFRESHED:"editStateRefreshed",EDIT_STATE_CLEARED:"editStateCleared",STORY_CREATED:"storyCreated",STORY_RENAMED:"storyRenamed",STORY_DELETED:"storyDeleted",STORY_STATE_CHANGED:"storyStateChanged",JOB_CREATED:"jobCreated",JOB_UPDATED:"jobUpdated",JOB_STATUS_CHANGED:"jobStatusChanged",JOB_COMPLETED:"jobCompleted",JOB_DELETED:"jobDeleted",JOB_RESTORED:"jobRestored",FIELD_ADDED:"fieldAdded",FIELD_VALUE_CHANGED:"fieldValueChanged",FIELD_REMOVED:"fieldRemoved",FIELD_DEFINITION_CREATED:"fieldDefinitionCreated",FIELD_DEFINITION_DELETED:"fieldDefinitionDeleted",ENTITY_TYPE_CREATED:"entityTypeCreated",ENTITY_TYPE_UPDATED:"entityTypeUpdated",ASSET_CREATED:"assetCreated",ASSET_DELETED:"assetDeleted"});var Vz=null,RR=!1,DR=null,xX=[],On8=async($,K=null)=>{if(DR=$,await kA1(),RR=!0,K)Hn8(K)},Hn8=($)=>{xX.forEach((K)=>K()),xX=[],xX.push($.subscribe(q6.ENTITY_TYPE_CREATED,()=>hA()),$.subscribe(q6.ENTITY_TYPE_UPDATED,()=>hA())),xX.push($.subscribe(q6.FIELD_DEFINITION_CREATED,()=>hA()),$.subscribe(q6.FIELD_DEFINITION_DELETED,()=>hA()))},kA1=async()=>{let $=await DR.selectFrom("entity_types").select(["code","subtype","is_pathable","can_have_children","scope","sequence_scope"]).execute();Vz=new Map;for(let q of $){let Y=q.subtype||q.code;Vz.set(Y,{isPathable:q.is_pathable===1,isVersioned:!1,isContainer:q.can_have_children===1,isFieldable:!0,isGlobal:q.scope==="global",sequenceScope:q.sequence_scope})}let K=await DR.selectFrom("class_field_defs").innerJoin("field_definitions","field_definitions.id","class_field_defs.field_definition_id").innerJoin("entity_types","entity_types.id","class_field_defs.class_type_id").select(["entity_types.code","entity_types.subtype","field_definitions.name"]).where("field_definitions.name","in",["draft_version","latest_published_version"]).execute();for(let q of K){let Y=q.subtype||q.code,z=Vz.get(Y);if(z)z.isVersioned=!0}},Xn8=($)=>{if(!RR)throw h.validation("CapabilityRegistry not initialized","REGISTRY_NOT_INITIALIZED");if(Vz===null)throw h.validation("CapabilityRegistry cache invalidated. Call ensureLoaded() before get().","REGISTRY_CACHE_INVALIDATED");let K=Vz.get($);if(!K)throw h.validation(`Unknown typeCode: ${$}. Capability metadata missing.`,"UNKNOWN_TYPE_CODE");return K},wn8=()=>RR,hA=()=>{Vz=null},Gn8=async()=>{if(Vz===null)await kA1()},Tn8=()=>{Vz=null,RR=!1,DR=null,xX.forEach(($)=>$()),xX=[]},Q$=Object.freeze({initialize:On8,get:Xn8,isInitialized:wn8,invalidate:hA,ensureLoaded:Gn8,reset:Tn8});F6();F$();var{parseId:Pn8,buildId:vn8}=M2,An8=({entityCache:$,storePk:K,storeCode:q})=>{let Y=async(O,H,{includeDeleted:X=!1}={})=>{if(!H)return null;if($&&!X){let P=$.get(H);if(P)return P.getPk()}if(!Pn8(H))c.factory(!0,h.validation,`Invalid parent folder ID: ${H}`,"INVALID_ID");let T=O.selectFrom("entities").select("id").where("store_id","=",K).where("object_id","=",H);if(!X)T=T.where("deleted_at","is",null);let G=await T.executeTakeFirst();return G?G.id:null},z=async(O,H)=>{let X=await O.selectFrom("entities").select(["name","parent_folder_id"]).where("id","=",H).executeTakeFirst();c.factory(!X,h.notFound,`Entity not found for PK ${H}`,"ENTITY_NOT_FOUND");let w=await J(O,X.parent_folder_id);return w!=null?`${w}/${X.name}`:X.name},J=async(O,H)=>{if(!H)return null;let X=await O.selectFrom("entities").select("path").where("id","=",H).where("deleted_at","is",null).executeTakeFirst();return X?X.path:null};return{getParentPk:Y,getParentStoredPath:J,computePath:z,cascadePathUpdate:async(O,H,X,w)=>{let T=H.length+1;await j8`UPDATE entities SET path = ${X} || SUBSTR(path, ${T})
|
|
743
743
|
WHERE store_id = ${w} AND path LIKE ${H+"/%"} AND deleted_at IS NULL`.execute(O)},insertFolderRow:async(O,H,X,w,T)=>{let G=F8(),P=await s8.readEntityTypeId(O,{},"f",w),v=await R2.nextSeq(O,"store",K,"f"),M=await Y(O,H),V=vn8(q,"f",v),k=await J(O,M),j=k!=null?`${k}/${X}`:X;return{row:{...await O.insertInto("entities").values({store_id:K,object_id:V,entity_type_id:P,type_code:"f",seq:v,parent_folder_id:M,parent_object_id:H,name:X,path:j,created_at:G,updated_at:G,...T!=null?{deleted_at:T}:{}}).returningAll().executeTakeFirstOrThrow(),subtype:w},id:V}}}},yc=async($,K,q,Y={})=>{let{includeDeleted:z=!1,deletedAt:J=null}=Y,W=[],Z=[K];while(Z.length>0){let O=Z.shift(),H=$.selectFrom("entities").select(["id","type_code"]).where("store_id","=",q).where("parent_folder_id","=",O);if(!z)H=H.where("deleted_at","is",null);else if(J)H=H.where("deleted_at","=",J);let X=await H.execute();for(let w of X)if(W.push(w.id),["f","s","j"].includes(w.type_code))Z.push(w.id)}return W};var IA=async($,K,q,Y,z,J)=>{let W=await yc($,K,q),Z=[K,...W],O=J();await $.updateTable("entities").set({deleted_at:O}).where("id","in",Z).execute();let H=await $.selectFrom("entities").select(["id","type_code","entity_type_id"]).where("id","in",Z).where("type_code","in",["d","t"]).execute();if(H.length>0){let w=await $.selectFrom("field_definitions as fd").innerJoin("class_field_defs as cfd","cfd.field_definition_id","fd.id").select("fd.id").where("fd.name","=","document").where("cfd.class_type_id","=",z).where("fd.is_system","=",1).executeTakeFirst();if(w){let T=H.map((P)=>P.id),G=await $.selectFrom("obj_ref_fields as orf").innerJoin("entities as ve","ve.id","orf.entity_id").select("orf.entity_id as version_pk").where("orf.field_definition_id","=",w.id).where("orf.target_entity_id","in",T).where("ve.deleted_at","is",null).execute();if(G.length>0){let P=G.map((v)=>v.version_pk);await $.updateTable("entities").set({deleted_at:O}).where("id","in",P).execute()}for(let P of H){let v=await s8.readEntityTypeId($,{},P.type_code,null),V=(await $.selectFrom("field_definitions as fd").innerJoin("class_field_defs as cfd","cfd.field_definition_id","fd.id").select("fd.id").where("fd.name","in",["draft_version","latest_published_version"]).where("cfd.class_type_id","=",v).where("fd.is_system","=",1).execute()).map((k)=>k.id);if(V.length>0)await $.deleteFrom("obj_ref_fields").where("entity_id","=",P.id).where("field_definition_id","in",V).execute()}}}let X=[];for(let w of W){let T=Y.getIdByPk(w);if(T)X.push(T);else{let G=await $.selectFrom("entities").select("object_id").where("id","=",w).executeTakeFirst();if(G)X.push(G.object_id)}}return{descendantCount:W.length,descendantIds:X,deletedPks:Z}},DA1=async($,K,q)=>{let Y=q;while(Y!==null){if(Y===K)throw h.validation("Cannot move entity into its own descendant","CYCLE_DETECTED");let z=await $.selectFrom("entities").select("parent_object_id").where("object_id","=",Y).where("deleted_at","is",null).executeTakeFirst();if(!z)break;Y=z.parent_object_id}},RA1=async($,K)=>{let q=await $.selectFrom("entities").select(["id","store_id"]).where("object_id","=",K).where("deleted_at","is",null).executeTakeFirst();if(!q)return[];let{store_id:Y,id:z}=q,J=[],W=[z];while(W.length>0){let Z=W.shift(),O=await $.selectFrom("entities").select(["id","object_id","type_code"]).where("store_id","=",Y).where("parent_folder_id","=",Z).where("deleted_at","is",null).execute();for(let H of O)if(J.push(H.object_id),["f","s","j"].includes(H.type_code))W.push(H.id)}return J},CA1={create:An8};var EA1=Z6(x6(),1);F6();var bW=EA1.default("caw:stores:db:fields"),xA=($)=>{let q={int:"int_fields",string:"string_fields",text:"text_fields",date:"date_fields",float:"float_fields",object_ref:"obj_ref_fields"}[$];if(!q)throw Error(`Unknown primitive type: ${$}`);return q},bc=($)=>{if(!$)return{allowed:null,jsonSchema:null};try{let K=JSON.parse($);return{allowed:K.allowed??null,jsonSchema:K.jsonSchema??null}}catch(K){return{allowed:null,jsonSchema:null}}},Mn8=async($,K,q,Y)=>{if(Y==="text")await j8`
|
|
744
744
|
DELETE FROM text_fields_fts
|
|
745
745
|
WHERE entity_id = ${K} AND field_definition_id = ${q}
|
|
@@ -1117,4 +1117,4 @@ Populated:
|
|
|
1117
1117
|
Errors:
|
|
1118
1118
|
`;for(let G of X.slice(0,10))T+=` - Version PK ${G.versionPk}: ${G.error}
|
|
1119
1119
|
`;if(X.length>10)T+=` ... and ${X.length-10} more errors
|
|
1120
|
-
`}return{content:[{type:"text",text:T}]}}catch(W){return p1(W)}},XP8={name:"backfill_content_refs",title:"Backfill Content Refs",description:"Backfill content reference fields (attachments, includes, hyperlinks) on existing version entities. If confirm=false, returns preview. If confirm=true, performs backfill.",schema:xq4,execute:gq4};var wP8=[XP8];m8();var uq4=f.object({store:f.string().optional().describe('Store code (default: "A")'),limit:f.coerce.number().optional().describe("Maximum number of events to return (default: 50)"),offset:f.coerce.number().optional().describe("Pagination offset (default: 0)")}),yq4=async({core:$,projectId:K},{store:q,limit:Y,offset:z})=>{try{let J=await $.listDeletedEvents(K,{store:q??"A",limit:Y??50,offset:z??0});return{content:[{type:"text",text:JSON.stringify(J,null,2)}]}}catch(J){return p1(J)}},GP8={name:"list_deleted_events",title:"List Deletion Events",description:"List deletion events grouped by timestamp. Each event represents a single delete action (e.g. deleting a folder and all its contents). Returns events with deletedAt timestamp, root entity info, item count, and days until purge.",schema:uq4,execute:yq4};m8();var bq4=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Bq4=f.object({deleted_at:f.string().describe('Deletion event timestamp (ISO 8601, e.g. "2026-03-15T10:23:45.678Z")'),store:f.string().optional().describe('Store code (default: "A")'),limit:f.coerce.number().optional().describe("Maximum number of items to return (default: 50)"),offset:f.coerce.number().optional().describe("Pagination offset (default: 0)")}),mq4=async({core:$,projectId:K},{deleted_at:q,store:Y,limit:z,offset:J})=>{try{if(!bq4.test(q))return{content:[{type:"text",text:JSON.stringify({error:`Invalid deleted_at timestamp: ${q}`,code:"INVALID_PARAMETER"},null,2)}],isError:!0};let W=await $.getDeletedEvent(K,{deletedAt:q,store:Y??"A",limit:z??50,offset:J??0});return{content:[{type:"text",text:JSON.stringify(W,null,2)}]}}catch(W){return p1(W)}},TP8={name:"get_deleted_event",title:"Get Deletion Event",description:"Get the items in a specific deletion event identified by its timestamp. Returns root entity info and a paginated list of all entities deleted in that event.",schema:Bq4,execute:mq4};m8();var Uq4=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Fq4=f.object({deleted_at:f.string().describe('Deletion event timestamp (ISO 8601, e.g. "2026-03-15T10:23:45.678Z")'),store:f.string().optional().describe('Store code (default: "A")')}),cq4=async({core:$,projectId:K},{deleted_at:q,store:Y})=>{try{if(!Uq4.test(q))return{content:[{type:"text",text:JSON.stringify({error:`Invalid deleted_at timestamp: ${q}`,code:"INVALID_PARAMETER"},null,2)}],isError:!0};let z=await $.restoreDeletedEvent(K,{deletedAt:q,store:Y??"A"});return{content:[{type:"text",text:JSON.stringify(z,null,2)}]}}catch(z){return p1(z)}},PP8={name:"restore_deleted_event",title:"Restore Deletion Event",description:'Restore all entities in a deletion event (identified by its timestamp). All entities deleted in the same action are restored together. If the root entity has a name collision, it is renamed with a "-restored" suffix.',schema:Fq4,execute:cq4};var vP8=[GP8,TP8,PP8];m8();var Qq4=f.object({}),pq4=async({core:$,projectId:K})=>{try{let q=await $.getSystemSettings(K);return{content:[{type:"text",text:JSON.stringify(q,null,2)}]}}catch(q){return p1(q)}},AP8={name:"get_system_settings",title:"Get System Settings",description:"Returns all system settings for the project (autoArchiveDelayDays, maxConcurrentJobs, trashRetentionDays, maxResumeAttempts, defaultResumePromptRef, scratchDocDelayDays, jobDelayDays)",schema:Qq4,execute:pq4};m8();var lq4=f.object({settings:dq(f.object({autoArchiveDelayDays:f.number().int().optional(),maxConcurrentJobs:f.number().int().optional(),trashRetentionDays:f.number().int().optional(),maxResumeAttempts:f.number().int().optional(),defaultResumePromptRef:f.string().nullable().optional(),scratchDocDelayDays:f.number().int().optional(),jobDelayDays:f.number().int().optional()})).describe("Partial settings object. Only provided keys are updated.")}),iq4=async({core:$,projectId:K},{settings:q})=>{try{let Y=await $.updateSystemSettings(K,{settings:q});return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}catch(Y){return p1(Y)}},VP8={name:"update_system_settings",title:"Update System Settings",description:"Update system settings for the project. Accepts partial updates — only provided keys are changed. Settings: autoArchiveDelayDays, maxConcurrentJobs, trashRetentionDays, maxResumeAttempts, defaultResumePromptRef, scratchDocDelayDays, jobDelayDays. Validates values: integer fields must be positive integers; defaultResumePromptRef must be a template ID string or null (to clear).",schema:lq4,execute:iq4};var MP8=[AP8,VP8];var nq4=NP8.default("caw:mcp"),dq4=({core:$,projectId:K})=>{let q=new i61({name:"caw-server",version:"1.0.174"},{capabilities:{tools:{}}}),Y=[...$T8,...YT8,...GT8,...ET8,...xT8,...lT8,...rT8,...tT8,...WP8,...HP8,...wP8,...vP8,...MP8];for(let z of Y)q.registerTool(z.name,{title:z.title,description:z.description,inputSchema:z.schema},async(J,W)=>{try{let Z=W?.sessionId||W?.requestInfo?.headers?.["mcp-session-id"];return await z.execute({core:$,projectId:K,sessionId:Z,extra:W},J)}catch(Z){if(Z.isDomainError)nq4("Tool %s domain error: %o",z.name,Z);else console.error(`Tool ${z.name} failed:`,Z);return p1(Z)}});return q},jP8=Object.freeze({createMcpServer:dq4});var oq4=d61.default("caw:mcp"),TK=d61.default("caw:mcp:session"),rq4=({core:$})=>{let K=new Map;return Object.freeze({handleRequest:async(W,Z,{projectId:O})=>{let H=W.headers["mcp-session-id"];if(H){let P=K.get(H);if(!P)return TK("Session not found: %s",H),Z.status(404).json({jsonrpc:"2.0",error:{code:-32001,message:"Session not found. Server may have been restarted. If so, ask user to reconnect"},id:null});if(P.projectId!==O)return TK("Session %s belongs to project %s, not %s",H,P.projectId,O),Z.status(404).json({jsonrpc:"2.0",error:{code:-32001,message:"Session not found. Server may have been restarted. If so, ask user to reconnect"},id:null});TK("Routing request to existing session: %s",H),P.lastActivity=Date.now();try{return await P.transport.handleRequest(W,Z,W.body)}catch(v){console.error("MCP transport request failed:",v)}}TK("Creating new MCP session for project: %s",O);let X=null,w=new I81({sessionIdGenerator:()=>{return X=aq4(),TK("Generated session ID: %s",X),X},onsessioninitialized:(P)=>{TK("Session initialized: %s",P),Z.setHeader("Mcp-Session-Id",P),G.sessionId=P,K.set(P,G),TK("Session stored: %s",P)}});TK("Creating new server for session");let T=jP8.createMcpServer({core:$,projectId:O});try{await T.connect(w)}catch(P){return console.error("MCP server connect failed:",P),w.close?.(),T.close?.(),Z.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}let G={sessionId:null,transport:w,server:T,projectId:O,createdAt:Date.now(),lastActivity:Date.now()};Z.on("finish",()=>{if(Z.statusCode!==200&&X&&K.has(X))TK("Request failed (status %d), cleaning up session: %s",Z.statusCode,X),K.delete(X),w.close?.(),T.close?.()});try{await w.handleRequest(W,Z,W.body)}catch(P){console.error("MCP transport request failed:",P)}},getSession:(W)=>{return K.get(W)},closeSession:(W)=>{let Z=K.get(W);if(!Z){TK("Cannot close session - not found: %s",W);return}TK("Closing session: %s",W),Z.transport.close?.(),Z.server.close?.(),K.delete(W)},cleanupIdle:(W)=>{let Z=Date.now(),O=0;for(let[H,X]of K.entries())if(Z-X.lastActivity>W)TK("Cleaning up idle session: %s (idle for %dms)",H,Z-X.lastActivity),X.transport.close?.(),X.server.close?.(),K.delete(H),O++;if(O>0)oq4("Cleaned up %d idle sessions",O)}})},fP8=Object.freeze({create:rq4});var sq4=86400000,tq4=300000,eq4=({mcpSessionManager:$})=>{let{jobFns:K,controlFns:q}=l7.create({name:"cleanup-idle-mcp-sessions",interval:tq4,execute:async()=>{$.cleanupIdle(sq4)}});return{job:Object.freeze(K),control:q}},kP8=Object.freeze({create:eq4});var Au=Wv8.default("caw:server"),y04=async({port:$,envDir:K,databaseFilepath:q,assetsDir:Y,lazilyCreateDb:z,enableRest:J,enableSse:W,enableStatic:Z,enableCrons:O,enableMcp:H=!0,enableCli:X=!0,staticPath:w,kyselyFactory:T})=>{let G=await N08.create({envDir:K,databaseFilepath:q,assetsDir:Y,lazilyCreateDb:z,kyselyFactory:T}),P=O41.default();if(P.use(O41.default.json({limit:"5mb"})),P.get("/health",(j,C)=>{C.json({status:"ok"})}),P.get("/api/info",(j,C)=>{C.json({version:"1.0.174",hookFailureCount:CU1()})}),J)P.use("/api",EJ8),D08.create(P,{core:G}),E08.create(P,{core:G}),L08.create(P,{core:G}),h08.create(P,{core:G}),g08.create(P,{core:G}),b08.create(P,{core:G}),m08.create(P,{core:G}),F08.create(P,{core:G}),Q08.create(P,{core:G}),GJ8.create(P,{core:G}),PJ8.create(P,{core:G}),AJ8.create(P,{core:G}),MJ8.create(P,{core:G}),fJ8.create(P,{core:G});if(W)DJ8.create(P,{core:G}),CJ8.create(P,{core:G});if(Z&&w)f08.create(P,{staticPath:w});if(H){Au("Initializing MCP subsystem...");let j=fP8.create({core:G});G.registerCronJob(kP8,{mcpSessionManager:j}),SJ8.create(P,{core:G,mcpSessionManager:j}),Au("MCP subsystem initialized")}if(X){Au("Initializing CLI Adapter subsystem...");let j=(await Promise.resolve().then(() => (dP8(),nP8))).default,C=(await Promise.resolve().then(() => (sP8(),rP8))).default,g=(await Promise.resolve().then(() => (qv8(),_v8))).default,y=(await Promise.resolve().then(() => (Jv8(),zv8))).default,S=g.create({mcpClientFactory:j.create(),aliasGenerator:C.create(),core:G});await S.init(),G.subscribeServerEvents({onProjectCreated:(x)=>S.addProject({objectId:x.id,name:x.name,path:x.path})}),y.create(P,{cliSessionManager:S}),Au("CLI Adapter subsystem initialized")}if(O)G.startAllCrons();P.use((j,C,g,y)=>{g.status(j.status||j.statusCode||500).json({error:j.message,type:j.type})});let v=null,M=new Set;return Object.freeze({app:P,core:G,start:async()=>{return new Promise((j)=>{v=P.listen($,()=>{let C=v.address().port;j(C)}),v.on("connection",(C)=>{M.add(C),C.on("close",()=>{M.delete(C)})})})},stop:async()=>{if(G.stopAllCrons(),v){for(let j of M)j.destroy();return M.clear(),new Promise((j)=>{v.close(()=>{j()})})}}})},Zv8=Object.freeze({create:y04});var B04=3131,m04=Vu.join(Vu.dirname(b04(import.meta.url)),"public_html"),U04=!0,F04=!0,c04=!0,Q04=!0,p04=!1,l04=!0,i04=!0,n04=!0,EJ=($,K)=>$!==void 0?$==="true":K,d04=()=>{let $=process.env.CAW_ENV_DIR;if(!$)console.error("ERROR: CAW_ENV_DIR environment variable is required"),console.error("Set it to the path of your environment folder, e.g.:"),console.error(' export CAW_ENV_DIR="$HOME/.caw/dev"'),process.exit(1);return{envDir:$,databaseFilepath:Vu.join($,"caw.db"),assetsDir:Vu.join($,"assets")}},a04=async($)=>{let K=await Zv8.create($),q=await K.start();console.log(`Server listening on port ${q}`),process.on("SIGINT",()=>K.stop("SIGINT")),process.on("SIGTERM",()=>K.stop("SIGTERM"))},o04=()=>{let{envDir:$,databaseFilepath:K,assetsDir:q}=d04(),Y=process.env.CAW_PORT?Number(process.env.CAW_PORT):B04,z=process.env.STATIC_PATH||m04,J=EJ(process.env.LAZY_CREATE_DB,U04),W=EJ(process.env.ENABLE_REST,F04),Z=EJ(process.env.ENABLE_MCP,c04),O=EJ(process.env.ENABLE_CLI,Q04),H=EJ(process.env.ENABLE_WEBLLM_WSS,p04),X=EJ(process.env.ENABLE_SSE,l04),w=EJ(process.env.ENABLE_STATIC,i04),T=EJ(process.env.ENABLE_CRONS,n04);return Object.freeze({port:Y,staticPath:z,envDir:$,databaseFilepath:K,assetsDir:q,lazilyCreateDb:J,enableRest:W,enableMcp:Z,enableCli:O,enableWebllmWss:H,enableSse:X,enableStatic:w,enableCrons:T})};await a04(o04()).catch(($)=>{console.error("ERROR: Failed to start server:",$),process.exit(1)});
|
|
1120
|
+
`}return{content:[{type:"text",text:T}]}}catch(W){return p1(W)}},XP8={name:"backfill_content_refs",title:"Backfill Content Refs",description:"Backfill content reference fields (attachments, includes, hyperlinks) on existing version entities. If confirm=false, returns preview. If confirm=true, performs backfill.",schema:xq4,execute:gq4};var wP8=[XP8];m8();var uq4=f.object({store:f.string().optional().describe('Store code (default: "A")'),limit:f.coerce.number().optional().describe("Maximum number of events to return (default: 50)"),offset:f.coerce.number().optional().describe("Pagination offset (default: 0)")}),yq4=async({core:$,projectId:K},{store:q,limit:Y,offset:z})=>{try{let J=await $.listDeletedEvents(K,{store:q??"A",limit:Y??50,offset:z??0});return{content:[{type:"text",text:JSON.stringify(J,null,2)}]}}catch(J){return p1(J)}},GP8={name:"list_deleted_events",title:"List Deletion Events",description:"List deletion events grouped by timestamp. Each event represents a single delete action (e.g. deleting a folder and all its contents). Returns events with deletedAt timestamp, root entity info, item count, and days until purge.",schema:uq4,execute:yq4};m8();var bq4=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Bq4=f.object({deleted_at:f.string().describe('Deletion event timestamp (ISO 8601, e.g. "2026-03-15T10:23:45.678Z")'),store:f.string().optional().describe('Store code (default: "A")'),limit:f.coerce.number().optional().describe("Maximum number of items to return (default: 50)"),offset:f.coerce.number().optional().describe("Pagination offset (default: 0)")}),mq4=async({core:$,projectId:K},{deleted_at:q,store:Y,limit:z,offset:J})=>{try{if(!bq4.test(q))return{content:[{type:"text",text:JSON.stringify({error:`Invalid deleted_at timestamp: ${q}`,code:"INVALID_PARAMETER"},null,2)}],isError:!0};let W=await $.getDeletedEvent(K,{deletedAt:q,store:Y??"A",limit:z??50,offset:J??0});return{content:[{type:"text",text:JSON.stringify(W,null,2)}]}}catch(W){return p1(W)}},TP8={name:"get_deleted_event",title:"Get Deletion Event",description:"Get the items in a specific deletion event identified by its timestamp. Returns root entity info and a paginated list of all entities deleted in that event.",schema:Bq4,execute:mq4};m8();var Uq4=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Fq4=f.object({deleted_at:f.string().describe('Deletion event timestamp (ISO 8601, e.g. "2026-03-15T10:23:45.678Z")'),store:f.string().optional().describe('Store code (default: "A")')}),cq4=async({core:$,projectId:K},{deleted_at:q,store:Y})=>{try{if(!Uq4.test(q))return{content:[{type:"text",text:JSON.stringify({error:`Invalid deleted_at timestamp: ${q}`,code:"INVALID_PARAMETER"},null,2)}],isError:!0};let z=await $.restoreDeletedEvent(K,{deletedAt:q,store:Y??"A"});return{content:[{type:"text",text:JSON.stringify(z,null,2)}]}}catch(z){return p1(z)}},PP8={name:"restore_deleted_event",title:"Restore Deletion Event",description:'Restore all entities in a deletion event (identified by its timestamp). All entities deleted in the same action are restored together. If the root entity has a name collision, it is renamed with a "-restored" suffix.',schema:Fq4,execute:cq4};var vP8=[GP8,TP8,PP8];m8();var Qq4=f.object({}),pq4=async({core:$,projectId:K})=>{try{let q=await $.getSystemSettings(K);return{content:[{type:"text",text:JSON.stringify(q,null,2)}]}}catch(q){return p1(q)}},AP8={name:"get_system_settings",title:"Get System Settings",description:"Returns all system settings for the project (autoArchiveDelayDays, maxConcurrentJobs, trashRetentionDays, maxResumeAttempts, defaultResumePromptRef, scratchDocDelayDays, jobDelayDays)",schema:Qq4,execute:pq4};m8();var lq4=f.object({settings:dq(f.object({autoArchiveDelayDays:f.number().int().optional(),maxConcurrentJobs:f.number().int().optional(),trashRetentionDays:f.number().int().optional(),maxResumeAttempts:f.number().int().optional(),defaultResumePromptRef:f.string().nullable().optional(),scratchDocDelayDays:f.number().int().optional(),jobDelayDays:f.number().int().optional()})).describe("Partial settings object. Only provided keys are updated.")}),iq4=async({core:$,projectId:K},{settings:q})=>{try{let Y=await $.updateSystemSettings(K,{settings:q});return{content:[{type:"text",text:JSON.stringify(Y,null,2)}]}}catch(Y){return p1(Y)}},VP8={name:"update_system_settings",title:"Update System Settings",description:"Update system settings for the project. Accepts partial updates — only provided keys are changed. Settings: autoArchiveDelayDays, maxConcurrentJobs, trashRetentionDays, maxResumeAttempts, defaultResumePromptRef, scratchDocDelayDays, jobDelayDays. Validates values: integer fields must be positive integers; defaultResumePromptRef must be a template ID string or null (to clear).",schema:lq4,execute:iq4};var MP8=[AP8,VP8];var nq4=NP8.default("caw:mcp"),dq4=({core:$,projectId:K})=>{let q=new i61({name:"caw-server",version:"1.0.175"},{capabilities:{tools:{}}}),Y=[...$T8,...YT8,...GT8,...ET8,...xT8,...lT8,...rT8,...tT8,...WP8,...HP8,...wP8,...vP8,...MP8];for(let z of Y)q.registerTool(z.name,{title:z.title,description:z.description,inputSchema:z.schema},async(J,W)=>{try{let Z=W?.sessionId||W?.requestInfo?.headers?.["mcp-session-id"];return await z.execute({core:$,projectId:K,sessionId:Z,extra:W},J)}catch(Z){if(Z.isDomainError)nq4("Tool %s domain error: %o",z.name,Z);else console.error(`Tool ${z.name} failed:`,Z);return p1(Z)}});return q},jP8=Object.freeze({createMcpServer:dq4});var oq4=d61.default("caw:mcp"),TK=d61.default("caw:mcp:session"),rq4=({core:$})=>{let K=new Map;return Object.freeze({handleRequest:async(W,Z,{projectId:O})=>{let H=W.headers["mcp-session-id"];if(H){let P=K.get(H);if(!P)return TK("Session not found: %s",H),Z.status(404).json({jsonrpc:"2.0",error:{code:-32001,message:"Session not found. Server may have been restarted. If so, ask user to reconnect"},id:null});if(P.projectId!==O)return TK("Session %s belongs to project %s, not %s",H,P.projectId,O),Z.status(404).json({jsonrpc:"2.0",error:{code:-32001,message:"Session not found. Server may have been restarted. If so, ask user to reconnect"},id:null});TK("Routing request to existing session: %s",H),P.lastActivity=Date.now();try{return await P.transport.handleRequest(W,Z,W.body)}catch(v){console.error("MCP transport request failed:",v)}}TK("Creating new MCP session for project: %s",O);let X=null,w=new I81({sessionIdGenerator:()=>{return X=aq4(),TK("Generated session ID: %s",X),X},onsessioninitialized:(P)=>{TK("Session initialized: %s",P),Z.setHeader("Mcp-Session-Id",P),G.sessionId=P,K.set(P,G),TK("Session stored: %s",P)}});TK("Creating new server for session");let T=jP8.createMcpServer({core:$,projectId:O});try{await T.connect(w)}catch(P){return console.error("MCP server connect failed:",P),w.close?.(),T.close?.(),Z.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}let G={sessionId:null,transport:w,server:T,projectId:O,createdAt:Date.now(),lastActivity:Date.now()};Z.on("finish",()=>{if(Z.statusCode!==200&&X&&K.has(X))TK("Request failed (status %d), cleaning up session: %s",Z.statusCode,X),K.delete(X),w.close?.(),T.close?.()});try{await w.handleRequest(W,Z,W.body)}catch(P){console.error("MCP transport request failed:",P)}},getSession:(W)=>{return K.get(W)},closeSession:(W)=>{let Z=K.get(W);if(!Z){TK("Cannot close session - not found: %s",W);return}TK("Closing session: %s",W),Z.transport.close?.(),Z.server.close?.(),K.delete(W)},cleanupIdle:(W)=>{let Z=Date.now(),O=0;for(let[H,X]of K.entries())if(Z-X.lastActivity>W)TK("Cleaning up idle session: %s (idle for %dms)",H,Z-X.lastActivity),X.transport.close?.(),X.server.close?.(),K.delete(H),O++;if(O>0)oq4("Cleaned up %d idle sessions",O)}})},fP8=Object.freeze({create:rq4});var sq4=86400000,tq4=300000,eq4=({mcpSessionManager:$})=>{let{jobFns:K,controlFns:q}=l7.create({name:"cleanup-idle-mcp-sessions",interval:tq4,execute:async()=>{$.cleanupIdle(sq4)}});return{job:Object.freeze(K),control:q}},kP8=Object.freeze({create:eq4});var Au=Wv8.default("caw:server"),y04=async({port:$,envDir:K,databaseFilepath:q,assetsDir:Y,lazilyCreateDb:z,enableRest:J,enableSse:W,enableStatic:Z,enableCrons:O,enableMcp:H=!0,enableCli:X=!0,staticPath:w,kyselyFactory:T})=>{let G=await N08.create({envDir:K,databaseFilepath:q,assetsDir:Y,lazilyCreateDb:z,kyselyFactory:T}),P=O41.default();if(P.use(O41.default.json({limit:"5mb"})),P.get("/health",(j,C)=>{C.json({status:"ok"})}),P.get("/api/info",(j,C)=>{C.json({version:"1.0.175",hookFailureCount:CU1()})}),J)P.use("/api",EJ8),D08.create(P,{core:G}),E08.create(P,{core:G}),L08.create(P,{core:G}),h08.create(P,{core:G}),g08.create(P,{core:G}),b08.create(P,{core:G}),m08.create(P,{core:G}),F08.create(P,{core:G}),Q08.create(P,{core:G}),GJ8.create(P,{core:G}),PJ8.create(P,{core:G}),AJ8.create(P,{core:G}),MJ8.create(P,{core:G}),fJ8.create(P,{core:G});if(W)DJ8.create(P,{core:G}),CJ8.create(P,{core:G});if(Z&&w)f08.create(P,{staticPath:w});if(H){Au("Initializing MCP subsystem...");let j=fP8.create({core:G});G.registerCronJob(kP8,{mcpSessionManager:j}),SJ8.create(P,{core:G,mcpSessionManager:j}),Au("MCP subsystem initialized")}if(X){Au("Initializing CLI Adapter subsystem...");let j=(await Promise.resolve().then(() => (dP8(),nP8))).default,C=(await Promise.resolve().then(() => (sP8(),rP8))).default,g=(await Promise.resolve().then(() => (qv8(),_v8))).default,y=(await Promise.resolve().then(() => (Jv8(),zv8))).default,S=g.create({mcpClientFactory:j.create(),aliasGenerator:C.create(),core:G});await S.init(),G.subscribeServerEvents({onProjectCreated:(x)=>S.addProject({objectId:x.id,name:x.name,path:x.path})}),y.create(P,{cliSessionManager:S}),Au("CLI Adapter subsystem initialized")}if(O)G.startAllCrons();P.use((j,C,g,y)=>{g.status(j.status||j.statusCode||500).json({error:j.message,type:j.type})});let v=null,M=new Set;return Object.freeze({app:P,core:G,start:async()=>{return new Promise((j)=>{v=P.listen($,()=>{let C=v.address().port;j(C)}),v.on("connection",(C)=>{M.add(C),C.on("close",()=>{M.delete(C)})})})},stop:async()=>{if(G.stopAllCrons(),v){for(let j of M)j.destroy();return M.clear(),new Promise((j)=>{v.close(()=>{j()})})}}})},Zv8=Object.freeze({create:y04});var B04=3131,m04=Vu.join(Vu.dirname(b04(import.meta.url)),"public_html"),U04=!0,F04=!0,c04=!0,Q04=!0,p04=!1,l04=!0,i04=!0,n04=!0,EJ=($,K)=>$!==void 0?$==="true":K,d04=()=>{let $=process.env.CAW_ENV_DIR;if(!$)console.error("ERROR: CAW_ENV_DIR environment variable is required"),console.error("Set it to the path of your environment folder, e.g.:"),console.error(' export CAW_ENV_DIR="$HOME/.caw/dev"'),process.exit(1);return{envDir:$,databaseFilepath:Vu.join($,"caw.db"),assetsDir:Vu.join($,"assets")}},a04=async($)=>{let K=await Zv8.create($),q=await K.start();console.log(`Server listening on port ${q}`),process.on("SIGINT",()=>K.stop("SIGINT")),process.on("SIGTERM",()=>K.stop("SIGTERM"))},o04=()=>{let{envDir:$,databaseFilepath:K,assetsDir:q}=d04(),Y=process.env.CAW_PORT?Number(process.env.CAW_PORT):B04,z=process.env.STATIC_PATH||m04,J=EJ(process.env.LAZY_CREATE_DB,U04),W=EJ(process.env.ENABLE_REST,F04),Z=EJ(process.env.ENABLE_MCP,c04),O=EJ(process.env.ENABLE_CLI,Q04),H=EJ(process.env.ENABLE_WEBLLM_WSS,p04),X=EJ(process.env.ENABLE_SSE,l04),w=EJ(process.env.ENABLE_STATIC,i04),T=EJ(process.env.ENABLE_CRONS,n04);return Object.freeze({port:Y,staticPath:z,envDir:$,databaseFilepath:K,assetsDir:q,lazilyCreateDb:J,enableRest:W,enableMcp:Z,enableCli:O,enableWebllmWss:H,enableSse:X,enableStatic:w,enableCrons:T})};await a04(o04()).catch(($)=>{console.error("ERROR: Failed to start server:",$),process.exit(1)});
|