@automagik/genie 4.260429.24 → 4.260429.26

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/genie.js CHANGED
@@ -675,13 +675,13 @@ ${bin} set-option -w pane-active-border-style "fg=$COLOR"
675
675
  tell.location
676
676
  from (select lo_tell64($1) as location) tell
677
677
  ) seek
678
- `};return resolve3(lo),new Promise(async(r)=>finish=r);async function readable({highWaterMark=16384,start=0,end=1/0}={}){let max=end-start;return start&&await lo.seek(start),new Stream2.Readable({highWaterMark,async read(size){let l=size>max?size-max:size;max-=size;let[{data}]=await lo.read(l);if(this.push(data),data.length<size)this.push(null)}})}async function writable({highWaterMark=16384,start=0}={}){return start&&await lo.seek(start),new Stream2.Writable({highWaterMark,write(chunk,encoding,callback){lo.write(chunk).then(()=>callback(),callback)}})}}).catch(reject)})}var init_large=()=>{};var exports_src={};__export(exports_src,{default:()=>src_default});import os from"os";import fs from"fs";function Postgres(a,b2){let options=parseOptions(a,b2),subscribe=options.no_subscribe||Subscribe(Postgres,{...options}),ending=!1,queries=queue_default(),connecting=queue_default(),reserved=queue_default(),closed=queue_default(),ended=queue_default(),open3=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open:open3,busy,full},connections=[...Array(options.max)].map(()=>connection_default(options,queues,{onopen,onend,onclose})),sql=Sql(handler);return Object.assign(sql,{get parameters(){return options.parameters},largeObject:largeObject.bind(null,sql),subscribe,CLOSE,END:CLOSE,PostgresError,options,reserve,listen,begin,close,end}),sql;function Sql(handler2){return handler2.debug=options.debug,Object.entries(options.types).reduce((acc,[name,type2])=>{return acc[name]=(x)=>new Parameter(x,type2.to),acc},typed),Object.assign(sql2,{types:typed,typed,unsafe,notify,array,json:json2,file}),sql2;function typed(value,type2){return new Parameter(value,type2)}function sql2(strings,...args){return strings&&Array.isArray(strings.raw)?new Query(strings,args,handler2,cancel):typeof strings==="string"&&!args.length?new Identifier(options.transform.column.to?options.transform.column.to(strings):strings):new Builder(strings,args)}function unsafe(string,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([string],args,handler2,cancel,{prepare:!1,...options2,simple:"simple"in options2?options2.simple:args.length===0})}function file(path2,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([],args,(query2)=>{fs.readFile(path2,"utf8",(err,string)=>{if(err)return query2.reject(err);query2.strings=[string],handler2(query2)})},cancel,{...options2,simple:"simple"in options2?options2.simple:args.length===0})}}async function listen(name,fn,onlisten){let listener={fn,onlisten},sql2=listen.sql||(listen.sql=Postgres({...options,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(listen.channels).forEach(([name2,{listeners}])=>{delete listen.channels[name2],Promise.all(listeners.map((l)=>listen(name2,l.fn,l.onlisten).catch(()=>{})))})},onnotify(c,x){c in listen.channels&&listen.channels[c].listeners.forEach((l)=>l.fn(x))}})),channels=listen.channels||(listen.channels={});if(name in channels){channels[name].listeners.push(listener);let result3=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result3.state,unlisten}}channels[name]={result:sql2`listen ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`,listeners:[listener]};let result2=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result2.state,unlisten};async function unlisten(){if(name in channels===!1)return;if(channels[name].listeners=channels[name].listeners.filter((x)=>x!==listener),channels[name].listeners.length)return;return delete channels[name],sql2`unlisten ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`}}async function notify(channel,payload){return await sql`select pg_notify(${channel}, ${""+payload})`}async function reserve(){let queue=queue_default(),c=open3.length?open3.shift():await new Promise((resolve3,reject)=>{let query={reserve:resolve3,reject};queries.push(query),closed.length&&connect(closed.shift(),query)});move(c,reserved),c.reserved=()=>queue.length?c.execute(queue.shift()):move(c,reserved),c.reserved.release=!0;let sql2=Sql(handler2);return sql2.release=()=>{c.reserved=null,onopen(c)},sql2;function handler2(q){c.queue===full?queue.push(q):c.execute(q)||move(c,full)}}async function begin(options2,fn){!fn&&(fn=options2,options2="");let queries2=queue_default(),savepoints=0,connection2,prepare=null;try{return await sql.unsafe("begin "+options2.replace(/[^a-z ]/ig,""),[],{onexecute}).execute(),await Promise.race([scope(connection2,fn),new Promise((_,reject)=>connection2.onclose=reject)])}catch(error){throw error}async function scope(c,fn2,name){let sql2=Sql(handler2);sql2.savepoint=savepoint,sql2.prepare=(x)=>prepare=x.replace(/[^a-z0-9$-_. ]/gi);let uncaughtError,result2;name&&await sql2`savepoint ${sql2(name)}`;try{if(result2=await new Promise((resolve3,reject)=>{let x=fn2(sql2);Promise.resolve(Array.isArray(x)?Promise.all(x):x).then(resolve3,reject)}),uncaughtError)throw uncaughtError}catch(e){throw await(name?sql2`rollback to ${sql2(name)}`:sql2`rollback`),e instanceof PostgresError&&e.code==="25P02"&&uncaughtError||e}if(!name)prepare?await sql2`prepare transaction '${sql2.unsafe(prepare)}'`:await sql2`commit`;return result2;function savepoint(name2,fn3){if(name2&&Array.isArray(name2.raw))return savepoint((sql3)=>sql3.apply(sql3,arguments));return arguments.length===1&&(fn3=name2,name2=null),scope(c,fn3,"s"+savepoints+++(name2?"_"+name2:""))}function handler2(q){q.catch((e)=>uncaughtError||(uncaughtError=e)),c.queue===full?queries2.push(q):c.execute(q)||move(c,full)}}function onexecute(c){connection2=c,move(c,reserved),c.reserved=()=>queries2.length?c.execute(queries2.shift()):move(c,reserved)}}function move(c,queue){return c.queue.remove(c),queue.push(c),c.queue=queue,queue===open3?c.idleTimer.start():c.idleTimer.cancel(),c}function json2(x){return new Parameter(x,3802)}function array(x,type2){if(!Array.isArray(x))return array(Array.from(arguments));return new Parameter(x,type2||(x.length?inferType(x)||25:0),options.shared.typeArrayMap)}function handler(query){if(ending)return query.reject(Errors.connection("CONNECTION_ENDED",options,options));if(open3.length)return go(open3.shift(),query);if(closed.length)return connect(closed.shift(),query);busy.length?go(busy.shift(),query):queries.push(query)}function go(c,query){return c.execute(query)?move(c,busy):move(c,full)}function cancel(query){return new Promise((resolve3,reject)=>{query.state?query.active?connection_default(options).cancel(query.state,resolve3,reject):query.cancelled={resolve:resolve3,reject}:(queries.remove(query),query.cancelled=!0,query.reject(Errors.generic("57014","canceling statement due to user request")),resolve3())})}async function end({timeout=null}={}){if(ending)return ending;await 1;let timer2;return ending=Promise.race([new Promise((r)=>timeout!==null&&(timer2=setTimeout(destroy,timeout*1000,r))),Promise.all(connections.map((c)=>c.end()).concat(listen.sql?listen.sql.end({timeout:0}):[],subscribe.sql?subscribe.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(timer2))}async function close(){await Promise.all(connections.map((c)=>c.end()))}async function destroy(resolve3){await Promise.all(connections.map((c)=>c.terminate()));while(queries.length)queries.shift().reject(Errors.connection("CONNECTION_DESTROYED",options));resolve3()}function connect(c,query){return move(c,connecting),c.connect(query),c}function onend(c){move(c,ended)}function onopen(c){if(queries.length===0)return move(c,open3);let max=Math.ceil(queries.length/(connecting.length+1)),ready=!0;while(ready&&queries.length&&max-- >0){let query=queries.shift();if(query.reserve)return query.reserve(c);ready=c.execute(query)}ready?move(c,busy):move(c,full)}function onclose(c,e){move(c,closed),c.reserved=null,c.onclose&&(c.onclose(e),c.onclose=null),options.onclose&&options.onclose(c.id),queries.length&&connect(c,queries.shift())}}function parseOptions(a,b2){if(a&&a.shared)return a;let env=process.env,o=(!a||typeof a==="string"?b2:a)||{},{url,multihost}=parseUrl(a),query=[...url.searchParams].reduce((a2,[b3,c])=>(a2[b3]=c,a2),{}),host=o.hostname||o.host||multihost||url.hostname||env.PGHOST||"localhost",port=o.port||url.port||env.PGPORT||5432,user=o.user||o.username||url.username||env.PGUSERNAME||env.PGUSER||osUsername();o.no_prepare&&(o.prepare=!1),query.sslmode&&(query.ssl=query.sslmode,delete query.sslmode),"timeout"in o&&(console.log("The timeout option is deprecated, use idle_timeout instead"),o.idle_timeout=o.timeout),query.sslrootcert==="system"&&(query.ssl="verify-full");let ints=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],defaults={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime,max_pipeline:100,backoff,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(host)?host:host.split(",").map((x)=>x.split(":")[0]),port:Array.isArray(port)?port:host.split(",").map((x)=>parseInt(x.split(":")[1]||port)),path:o.path||host.indexOf("/")>-1&&host+"/.s.PGSQL."+port,database:o.database||o.db||(url.pathname||"").slice(1)||env.PGDATABASE||user,user,pass:o.pass||o.password||url.password||env.PGPASSWORD||"",...Object.entries(defaults).reduce((acc,[k,d])=>{let value=k in o?o[k]:(k in query)?query[k]==="disable"||query[k]==="false"?!1:query[k]:env["PG"+k.toUpperCase()]||d;return acc[k]=typeof value==="string"&&ints.includes(k)?+value:value,acc},{}),connection:{application_name:env.PGAPPNAME||"postgres.js",...o.connection,...Object.entries(query).reduce((acc,[k,v])=>((k in defaults)||(acc[k]=v),acc),{})},types:o.types||{},target_session_attrs:tsa(o,url,env),onnotice:o.onnotice,onnotify:o.onnotify,onclose:o.onclose,onparameter:o.onparameter,socket:o.socket,transform:parseTransform(o.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...mergeUserTypes(o.types)}}function tsa(o,url,env){let x=o.target_session_attrs||url.searchParams.get("target_session_attrs")||env.PGTARGETSESSIONATTRS;if(!x||["read-write","read-only","primary","standby","prefer-standby"].includes(x))return x;throw Error("target_session_attrs "+x+" is not supported")}function backoff(retries){return(0.5+Math.random()/2)*Math.min(3**retries/100,20)}function max_lifetime(){return 60*(30+Math.random()*30)}function parseTransform(x){return{undefined:x.undefined,column:{from:typeof x.column==="function"?x.column:x.column&&x.column.from,to:x.column&&x.column.to},value:{from:typeof x.value==="function"?x.value:x.value&&x.value.from,to:x.value&&x.value.to},row:{from:typeof x.row==="function"?x.row:x.row&&x.row.from,to:x.row&&x.row.to}}}function parseUrl(url){if(!url||typeof url!=="string")return{url:{searchParams:new Map}};let host=url;host=host.slice(host.indexOf("://")+3).split(/[?/]/)[0],host=decodeURIComponent(host.slice(host.indexOf("@")+1));let urlObj=new URL(url.replace(host,host.split(",")[0]));return{url:{username:decodeURIComponent(urlObj.username),password:decodeURIComponent(urlObj.password),host:urlObj.host,hostname:urlObj.hostname,port:urlObj.port,pathname:urlObj.pathname,searchParams:urlObj.searchParams},multihost:host.indexOf(",")>-1&&host}}function osUsername(){try{return os.userInfo().username}catch(_){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}var src_default;var init_src=__esm(()=>{init_types3();init_connection();init_query();init_queue();init_errors2();init_large();Object.assign(Postgres,{PostgresError,toPascal,pascal,toCamel,camel,toKebab,kebab,fromPascal,fromCamel,fromKebab,BigInt:{to:20,from:[20],parse:(x)=>BigInt(x),serialize:(x)=>x.toString()}});src_default=Postgres});var exports_db={};__export(exports_db,{shutdown:()=>shutdown,runRetention:()=>runRetention,resetConnection:()=>resetConnection,isConnected:()=>isConnected,isAvailable:()=>isAvailable,getLockfilePath:()=>getLockfilePath,getDataDir:()=>getDataDir,getConnection:()=>getConnection,getActivePort:()=>getActivePort,ensurePgserve:()=>ensurePgserve,checkRootGuard:()=>checkRootGuard,autoStartDaemon:()=>autoStartDaemon,__setSpawnDaemonForTest:()=>__setSpawnDaemonForTest});import{execSync as execSync3,spawn}from"child_process";import{existsSync as existsSync13,mkdirSync as mkdirSync6,readFileSync as readFileSync9,renameSync,unlinkSync as unlinkSync3,writeFileSync as writeFileSync6}from"fs";import{homedir as homedir11}from"os";import{join as join17}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}function checkRootGuard(){if(process.getuid?.()!==0)return null;if(process.env.GENIE_ALLOW_ROOT==="1")return null;return"pgserve cannot start under uid 0 (root) \u2014 PostgreSQL refuses to run as root for security reasons. "+"Run genie as a non-root user, or set GENIE_ALLOW_ROOT=1 to attempt anyway. See: https://github.com/automagik-dev/genie/issues/1226"}function isPgAutostartDisabled(){let value=process.env.GENIE_PG_NO_AUTOSTART;return value!==void 0&&TRUTHY_ENV.has(value.trim().toLowerCase())}function selfHealPostgres(dataDir){try{execSync3(`pkill -9 -f "postgres.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000}),execSync3(`pkill -9 -f "pgserve.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000})}catch{}let pidFile=join17(dataDir,"postmaster.pid");if(existsSync13(pidFile))try{unlinkSync3(pidFile)}catch{}try{execSync3("ipcs -m 2>/dev/null | awk '$6 == 0 {print $2}' | xargs -I{} ipcrm -m {} 2>/dev/null || true",{stdio:"ignore",timeout:5000})}catch{}}function getPort(){let envPort=process.env.GENIE_PG_PORT;if(envPort){let parsed=Number.parseInt(envPort,10);if(!Number.isNaN(parsed)&&parsed>0&&parsed<65536)return parsed}return DEFAULT_PORT}async function isPostgresHealthy(port){try{return await Promise.race([(async()=>{let pg=(await Promise.resolve().then(() => (init_src(),exports_src))).default,probe=pg({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:1,connect_timeout:3,idle_timeout:1});try{return await probe`SELECT 1`,await probe.end({timeout:2}),!0}catch{try{await probe.end({timeout:1})}catch{}return!1}})(),new Promise((resolve3)=>{setTimeout(()=>resolve3(!1),4000).unref()})])}catch{return!1}}function readLockfile(){try{let content=readFileSync9(LOCKFILE_PATH,"utf-8").trim(),port=Number.parseInt(content,10);if(!Number.isNaN(port)&&port>0&&port<65536)return port}catch{}return null}function writeLockfile(port){try{mkdirSync6(GENIE_HOME,{recursive:!0});let tmpPath=`${LOCKFILE_PATH}.tmp.${process.pid}`;writeFileSync6(tmpPath,String(port),"utf-8"),renameSync(tmpPath,LOCKFILE_PATH)}catch{}}function removeLockfile(){try{unlinkSync3(LOCKFILE_PATH)}catch{}}async function runRetention(sql){try{await sql.unsafe(`
678
+ `};return resolve3(lo),new Promise(async(r)=>finish=r);async function readable({highWaterMark=16384,start=0,end=1/0}={}){let max=end-start;return start&&await lo.seek(start),new Stream2.Readable({highWaterMark,async read(size){let l=size>max?size-max:size;max-=size;let[{data}]=await lo.read(l);if(this.push(data),data.length<size)this.push(null)}})}async function writable({highWaterMark=16384,start=0}={}){return start&&await lo.seek(start),new Stream2.Writable({highWaterMark,write(chunk,encoding,callback){lo.write(chunk).then(()=>callback(),callback)}})}}).catch(reject)})}var init_large=()=>{};var exports_src={};__export(exports_src,{default:()=>src_default});import os from"os";import fs from"fs";function Postgres(a,b2){let options=parseOptions(a,b2),subscribe=options.no_subscribe||Subscribe(Postgres,{...options}),ending=!1,queries=queue_default(),connecting=queue_default(),reserved=queue_default(),closed=queue_default(),ended=queue_default(),open3=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open:open3,busy,full},connections=[...Array(options.max)].map(()=>connection_default(options,queues,{onopen,onend,onclose})),sql=Sql(handler);return Object.assign(sql,{get parameters(){return options.parameters},largeObject:largeObject.bind(null,sql),subscribe,CLOSE,END:CLOSE,PostgresError,options,reserve,listen,begin,close,end}),sql;function Sql(handler2){return handler2.debug=options.debug,Object.entries(options.types).reduce((acc,[name,type2])=>{return acc[name]=(x)=>new Parameter(x,type2.to),acc},typed),Object.assign(sql2,{types:typed,typed,unsafe,notify,array,json:json2,file}),sql2;function typed(value,type2){return new Parameter(value,type2)}function sql2(strings,...args){return strings&&Array.isArray(strings.raw)?new Query(strings,args,handler2,cancel):typeof strings==="string"&&!args.length?new Identifier(options.transform.column.to?options.transform.column.to(strings):strings):new Builder(strings,args)}function unsafe(string,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([string],args,handler2,cancel,{prepare:!1,...options2,simple:"simple"in options2?options2.simple:args.length===0})}function file(path2,args=[],options2={}){return arguments.length===2&&!Array.isArray(args)&&(options2=args,args=[]),new Query([],args,(query2)=>{fs.readFile(path2,"utf8",(err,string)=>{if(err)return query2.reject(err);query2.strings=[string],handler2(query2)})},cancel,{...options2,simple:"simple"in options2?options2.simple:args.length===0})}}async function listen(name,fn,onlisten){let listener={fn,onlisten},sql2=listen.sql||(listen.sql=Postgres({...options,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(listen.channels).forEach(([name2,{listeners}])=>{delete listen.channels[name2],Promise.all(listeners.map((l)=>listen(name2,l.fn,l.onlisten).catch(()=>{})))})},onnotify(c,x){c in listen.channels&&listen.channels[c].listeners.forEach((l)=>l.fn(x))}})),channels=listen.channels||(listen.channels={});if(name in channels){channels[name].listeners.push(listener);let result3=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result3.state,unlisten}}channels[name]={result:sql2`listen ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`,listeners:[listener]};let result2=await channels[name].result;return listener.onlisten&&listener.onlisten(),{state:result2.state,unlisten};async function unlisten(){if(name in channels===!1)return;if(channels[name].listeners=channels[name].listeners.filter((x)=>x!==listener),channels[name].listeners.length)return;return delete channels[name],sql2`unlisten ${sql2.unsafe('"'+name.replace(/"/g,'""')+'"')}`}}async function notify(channel,payload){return await sql`select pg_notify(${channel}, ${""+payload})`}async function reserve(){let queue=queue_default(),c=open3.length?open3.shift():await new Promise((resolve3,reject)=>{let query={reserve:resolve3,reject};queries.push(query),closed.length&&connect(closed.shift(),query)});move(c,reserved),c.reserved=()=>queue.length?c.execute(queue.shift()):move(c,reserved),c.reserved.release=!0;let sql2=Sql(handler2);return sql2.release=()=>{c.reserved=null,onopen(c)},sql2;function handler2(q){c.queue===full?queue.push(q):c.execute(q)||move(c,full)}}async function begin(options2,fn){!fn&&(fn=options2,options2="");let queries2=queue_default(),savepoints=0,connection2,prepare=null;try{return await sql.unsafe("begin "+options2.replace(/[^a-z ]/ig,""),[],{onexecute}).execute(),await Promise.race([scope(connection2,fn),new Promise((_,reject)=>connection2.onclose=reject)])}catch(error){throw error}async function scope(c,fn2,name){let sql2=Sql(handler2);sql2.savepoint=savepoint,sql2.prepare=(x)=>prepare=x.replace(/[^a-z0-9$-_. ]/gi);let uncaughtError,result2;name&&await sql2`savepoint ${sql2(name)}`;try{if(result2=await new Promise((resolve3,reject)=>{let x=fn2(sql2);Promise.resolve(Array.isArray(x)?Promise.all(x):x).then(resolve3,reject)}),uncaughtError)throw uncaughtError}catch(e){throw await(name?sql2`rollback to ${sql2(name)}`:sql2`rollback`),e instanceof PostgresError&&e.code==="25P02"&&uncaughtError||e}if(!name)prepare?await sql2`prepare transaction '${sql2.unsafe(prepare)}'`:await sql2`commit`;return result2;function savepoint(name2,fn3){if(name2&&Array.isArray(name2.raw))return savepoint((sql3)=>sql3.apply(sql3,arguments));return arguments.length===1&&(fn3=name2,name2=null),scope(c,fn3,"s"+savepoints+++(name2?"_"+name2:""))}function handler2(q){q.catch((e)=>uncaughtError||(uncaughtError=e)),c.queue===full?queries2.push(q):c.execute(q)||move(c,full)}}function onexecute(c){connection2=c,move(c,reserved),c.reserved=()=>queries2.length?c.execute(queries2.shift()):move(c,reserved)}}function move(c,queue){return c.queue.remove(c),queue.push(c),c.queue=queue,queue===open3?c.idleTimer.start():c.idleTimer.cancel(),c}function json2(x){return new Parameter(x,3802)}function array(x,type2){if(!Array.isArray(x))return array(Array.from(arguments));return new Parameter(x,type2||(x.length?inferType(x)||25:0),options.shared.typeArrayMap)}function handler(query){if(ending)return query.reject(Errors.connection("CONNECTION_ENDED",options,options));if(open3.length)return go(open3.shift(),query);if(closed.length)return connect(closed.shift(),query);busy.length?go(busy.shift(),query):queries.push(query)}function go(c,query){return c.execute(query)?move(c,busy):move(c,full)}function cancel(query){return new Promise((resolve3,reject)=>{query.state?query.active?connection_default(options).cancel(query.state,resolve3,reject):query.cancelled={resolve:resolve3,reject}:(queries.remove(query),query.cancelled=!0,query.reject(Errors.generic("57014","canceling statement due to user request")),resolve3())})}async function end({timeout=null}={}){if(ending)return ending;await 1;let timer2;return ending=Promise.race([new Promise((r)=>timeout!==null&&(timer2=setTimeout(destroy,timeout*1000,r))),Promise.all(connections.map((c)=>c.end()).concat(listen.sql?listen.sql.end({timeout:0}):[],subscribe.sql?subscribe.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(timer2))}async function close(){await Promise.all(connections.map((c)=>c.end()))}async function destroy(resolve3){await Promise.all(connections.map((c)=>c.terminate()));while(queries.length)queries.shift().reject(Errors.connection("CONNECTION_DESTROYED",options));resolve3()}function connect(c,query){return move(c,connecting),c.connect(query),c}function onend(c){move(c,ended)}function onopen(c){if(queries.length===0)return move(c,open3);let max=Math.ceil(queries.length/(connecting.length+1)),ready=!0;while(ready&&queries.length&&max-- >0){let query=queries.shift();if(query.reserve)return query.reserve(c);ready=c.execute(query)}ready?move(c,busy):move(c,full)}function onclose(c,e){move(c,closed),c.reserved=null,c.onclose&&(c.onclose(e),c.onclose=null),options.onclose&&options.onclose(c.id),queries.length&&connect(c,queries.shift())}}function parseOptions(a,b2){if(a&&a.shared)return a;let env=process.env,o=(!a||typeof a==="string"?b2:a)||{},{url,multihost}=parseUrl(a),query=[...url.searchParams].reduce((a2,[b3,c])=>(a2[b3]=c,a2),{}),host=o.hostname||o.host||multihost||url.hostname||env.PGHOST||"localhost",port=o.port||url.port||env.PGPORT||5432,user=o.user||o.username||url.username||env.PGUSERNAME||env.PGUSER||osUsername();o.no_prepare&&(o.prepare=!1),query.sslmode&&(query.ssl=query.sslmode,delete query.sslmode),"timeout"in o&&(console.log("The timeout option is deprecated, use idle_timeout instead"),o.idle_timeout=o.timeout),query.sslrootcert==="system"&&(query.ssl="verify-full");let ints=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],defaults={max:globalThis.Cloudflare?3:10,ssl:!1,sslnegotiation:null,idle_timeout:null,connect_timeout:30,max_lifetime,max_pipeline:100,backoff,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(host)?host:host.split(",").map((x)=>x.split(":")[0]),port:Array.isArray(port)?port:host.split(",").map((x)=>parseInt(x.split(":")[1]||port)),path:o.path||host.indexOf("/")>-1&&host+"/.s.PGSQL."+port,database:o.database||o.db||(url.pathname||"").slice(1)||env.PGDATABASE||user,user,pass:o.pass||o.password||url.password||env.PGPASSWORD||"",...Object.entries(defaults).reduce((acc,[k,d])=>{let value=k in o?o[k]:(k in query)?query[k]==="disable"||query[k]==="false"?!1:query[k]:env["PG"+k.toUpperCase()]||d;return acc[k]=typeof value==="string"&&ints.includes(k)?+value:value,acc},{}),connection:{application_name:env.PGAPPNAME||"postgres.js",...o.connection,...Object.entries(query).reduce((acc,[k,v])=>((k in defaults)||(acc[k]=v),acc),{})},types:o.types||{},target_session_attrs:tsa(o,url,env),onnotice:o.onnotice,onnotify:o.onnotify,onclose:o.onclose,onparameter:o.onparameter,socket:o.socket,transform:parseTransform(o.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...mergeUserTypes(o.types)}}function tsa(o,url,env){let x=o.target_session_attrs||url.searchParams.get("target_session_attrs")||env.PGTARGETSESSIONATTRS;if(!x||["read-write","read-only","primary","standby","prefer-standby"].includes(x))return x;throw Error("target_session_attrs "+x+" is not supported")}function backoff(retries){return(0.5+Math.random()/2)*Math.min(3**retries/100,20)}function max_lifetime(){return 60*(30+Math.random()*30)}function parseTransform(x){return{undefined:x.undefined,column:{from:typeof x.column==="function"?x.column:x.column&&x.column.from,to:x.column&&x.column.to},value:{from:typeof x.value==="function"?x.value:x.value&&x.value.from,to:x.value&&x.value.to},row:{from:typeof x.row==="function"?x.row:x.row&&x.row.from,to:x.row&&x.row.to}}}function parseUrl(url){if(!url||typeof url!=="string")return{url:{searchParams:new Map}};let host=url;host=host.slice(host.indexOf("://")+3).split(/[?/]/)[0],host=decodeURIComponent(host.slice(host.indexOf("@")+1));let urlObj=new URL(url.replace(host,host.split(",")[0]));return{url:{username:decodeURIComponent(urlObj.username),password:decodeURIComponent(urlObj.password),host:urlObj.host,hostname:urlObj.hostname,port:urlObj.port,pathname:urlObj.pathname,searchParams:urlObj.searchParams},multihost:host.indexOf(",")>-1&&host}}function osUsername(){try{return os.userInfo().username}catch(_){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}var src_default;var init_src=__esm(()=>{init_types3();init_connection();init_query();init_queue();init_errors2();init_large();Object.assign(Postgres,{PostgresError,toPascal,pascal,toCamel,camel,toKebab,kebab,fromPascal,fromCamel,fromKebab,BigInt:{to:20,from:[20],parse:(x)=>BigInt(x),serialize:(x)=>x.toString()}});src_default=Postgres});var exports_db={};__export(exports_db,{shutdown:()=>shutdown,runRetention:()=>runRetention,resetConnection:()=>resetConnection,isConnected:()=>isConnected,isAvailable:()=>isAvailable,getLockfilePath:()=>getLockfilePath,getDataDir:()=>getDataDir,getConnection:()=>getConnection,getActivePort:()=>getActivePort,ensurePgserve:()=>ensurePgserve,checkRootGuard:()=>checkRootGuard,autoStartDaemon:()=>autoStartDaemon,__setSpawnDaemonForTest:()=>__setSpawnDaemonForTest});import{execSync as execSync3,spawn}from"child_process";import{existsSync as existsSync13,mkdirSync as mkdirSync6,readFileSync as readFileSync9,renameSync,unlinkSync as unlinkSync3,writeFileSync as writeFileSync6}from"fs";import{homedir as homedir11}from"os";import{join as join17}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}function checkRootGuard(){if(process.getuid?.()!==0)return null;if(process.env.GENIE_ALLOW_ROOT==="1")return null;return"pgserve cannot start under uid 0 (root) \u2014 PostgreSQL refuses to run as root for security reasons. "+"Run genie as a non-root user, or set GENIE_ALLOW_ROOT=1 to attempt anyway. See: https://github.com/automagik-dev/genie/issues/1226"}function isPgAutostartDisabled(){let value=process.env.GENIE_PG_NO_AUTOSTART;return value!==void 0&&TRUTHY_ENV.has(value.trim().toLowerCase())}function selfHealPostgres(dataDir){try{execSync3(`pkill -9 -f "postgres.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000}),execSync3(`pkill -9 -f "pgserve.*${dataDir.replace(/\//g,"\\/")}" 2>/dev/null || true`,{stdio:"ignore",timeout:5000})}catch{}let pidFile=join17(dataDir,"postmaster.pid");if(existsSync13(pidFile))try{unlinkSync3(pidFile)}catch{}try{execSync3("ipcs -m 2>/dev/null | awk '$6 == 0 {print $2}' | xargs -I{} ipcrm -m {} 2>/dev/null || true",{stdio:"ignore",timeout:5000})}catch{}}function signalPgserveTree(child,signal){let pid=child.pid;if(pid===void 0){try{child.kill(signal)}catch{}return}try{if(process.platform==="win32")child.kill(signal);else process.kill(-pid,signal)}catch{try{child.kill(signal)}catch{}}}async function terminatePgserveTree(child){if(signalPgserveTree(child,"SIGTERM"),!await new Promise((resolve3)=>{if(child.exitCode!==null||child.signalCode!==null){resolve3(!0);return}let timer2=setTimeout(()=>resolve3(!1),1000);timer2.unref(),child.once("exit",()=>{clearTimeout(timer2),resolve3(!0)})}))signalPgserveTree(child,"SIGKILL")}function getPort(){let envPort=process.env.GENIE_PG_PORT;if(envPort){let parsed=Number.parseInt(envPort,10);if(!Number.isNaN(parsed)&&parsed>0&&parsed<65536)return parsed}return DEFAULT_PORT}async function isPostgresHealthy(port){try{return await Promise.race([(async()=>{let pg=(await Promise.resolve().then(() => (init_src(),exports_src))).default,probe=pg({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:1,connect_timeout:3,idle_timeout:1});try{return await probe`SELECT 1`,await probe.end({timeout:2}),!0}catch{try{await probe.end({timeout:1})}catch{}return!1}})(),new Promise((resolve3)=>{setTimeout(()=>resolve3(!1),4000).unref()})])}catch{return!1}}function readLockfile(){try{let content=readFileSync9(LOCKFILE_PATH,"utf-8").trim(),port=Number.parseInt(content,10);if(!Number.isNaN(port)&&port>0&&port<65536)return port}catch{}return null}function writeLockfile(port){try{mkdirSync6(GENIE_HOME,{recursive:!0});let tmpPath=`${LOCKFILE_PATH}.tmp.${process.pid}`;writeFileSync6(tmpPath,String(port),"utf-8"),renameSync(tmpPath,LOCKFILE_PATH)}catch{}}function removeLockfile(){try{unlinkSync3(LOCKFILE_PATH)}catch{}}async function runRetention(sql){try{await sql.unsafe(`
679
679
  DELETE FROM heartbeats WHERE created_at < now() - interval '7 days';
680
680
  DELETE FROM machine_snapshots WHERE created_at < now() - interval '30 days';
681
681
  DELETE FROM audit_events WHERE entity_type LIKE 'otel_%' AND created_at < now() - interval '30 days';
682
682
  DELETE FROM genie_runtime_events WHERE created_at < now() - interval '14 days';
683
683
  `),retentionRan=!0}catch(retErr){retentionRan=!0;let msg=retErr instanceof Error?retErr.message:String(retErr);process.stderr.write(`[genie] retention cleanup warning: ${msg}
684
- `)}}async function ensurePgserve(){if(activePort===null){let testPort=await resolveTestPort();if(testPort!==null)return activePort=testPort,process.env.GENIE_PG_AVAILABLE="true",testPort}if(ensurePromise)return ensurePromise;ensurePromise=_ensurePgserve();try{return await ensurePromise}finally{ensurePromise=null}}function __setSpawnDaemonForTest(fn){spawnDaemon=fn??(()=>{let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"serve","start","--headless","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref()})}function readPidFile(pidPath){try{return readFileSync9(pidPath,"utf-8").trim()||null}catch{return null}}function parsePidFile(raw){let sepIdx=raw.indexOf(":"),pid,recordedStartTime;if(sepIdx<0)pid=Number.parseInt(raw,10),recordedStartTime=null;else{pid=Number.parseInt(raw.slice(0,sepIdx),10);let tail=raw.slice(sepIdx+1).trim();recordedStartTime=tail===""||tail==="unknown"?null:tail}if(Number.isNaN(pid)||pid<=0)return null;return{pid,recordedStartTime}}function isServeAlive(pid,recordedStartTime){try{process.kill(pid,0)}catch{return!1}if(recordedStartTime===null)return!1;let currentStartTime=getProcessStartTime(pid);return currentStartTime!==null&&currentStartTime===recordedStartTime}function unlinkQuiet(path2){try{unlinkSync3(path2)}catch{}}async function autoStartDaemon(){let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join17(home,"serve.pid"),raw=readPidFile(pidPath);if(!raw){lastAutoStartOutcome="missing",lastAutoStartPid=null,spawnDaemon();return}let parsed=parsePidFile(raw);if(!parsed){unlinkQuiet(pidPath),lastAutoStartOutcome="stale",lastAutoStartPid=null,spawnDaemon();return}if(isServeAlive(parsed.pid,parsed.recordedStartTime)){lastAutoStartOutcome="alive",lastAutoStartPid=parsed.pid;return}unlinkQuiet(pidPath),lastAutoStartOutcome="stale",lastAutoStartPid=parsed.pid,spawnDaemon()}async function resolveTestPort(){let raw=process.env.GENIE_TEST_PG_PORT;if(!raw)return null;let parsed=Number.parseInt(raw,10);if(Number.isNaN(parsed)||parsed<=0||parsed>=65536||!await isPostgresHealthy(parsed))throw Error(`GENIE_TEST_PG_PORT=${raw} set but not reachable`);return parsed}async function tryExistingPort(port){let portFromFile=readLockfile();if(portFromFile!==null&&await isPostgresHealthy(portFromFile))return activePort=portFromFile,process.env.GENIE_PG_AVAILABLE="true",portFromFile;if(await isPostgresHealthy(port))return activePort=port,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;return null}async function spawnPgserveDirect(port){mkdirSync6(DATA_DIR,{recursive:!0}),selfHealPostgres(DATA_DIR);try{let startedPort=await startPgserveOnPort(port);return registerExitHandler(),startedPort}catch(err){process.env.GENIE_PG_AVAILABLE="false";let message=err instanceof Error?err.message:String(err);throw Error(`pgserve failed to start: ${maskCredentials(message)}`)}}async function waitForDaemonPort(){let deadline=Date.now()+16000;while(Date.now()<deadline){let p=readLockfile();if(p!==null&&await isPostgresHealthy(p))return activePort=p,process.env.GENIE_PG_AVAILABLE="true",p;await new Promise((r)=>setTimeout(r,500))}return null}function throwDaemonTimeout(outcomeAtStart,pidAtStart){process.env.GENIE_PG_AVAILABLE="false";let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join17(home,"serve.pid"),hasPidFile=existsSync13(pidPath),currentPort=readLockfile()??getPort();if(outcomeAtStart==="stale")throw Error(`Stale ~/.genie/serve.pid (PID ${pidAtStart??"unknown"} was not our serve). Removed and retried \u2014 if this persists, run: genie serve start`);if(!hasPidFile)throw Error("genie serve not running. Run: genie serve start");throw Error(`genie serve is running (PID ${pidAtStart??outcomeAtStart??"unknown"}) but pgserve did not respond on port ${currentPort} within 16s. Try: genie serve restart, or check ~/.genie/logs/scheduler.log`)}async function _ensurePgserve(){if(activePort!==null)return activePort;let port=getPort(),existing=await tryExistingPort(port);if(existing!==null)return existing;if(process.env.CI==="true")throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve not available in CI");if(isPgAutostartDisabled())throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve unavailable and GENIE_PG_NO_AUTOSTART=1");let rootErr=checkRootGuard();if(rootErr!==null)throw process.env.GENIE_PG_AVAILABLE="false",Error(rootErr);if(process.env.GENIE_IS_DAEMON==="1")return spawnPgserveDirect(port);await autoStartDaemon();let outcomeAtStart=lastAutoStartOutcome,pidAtStart=lastAutoStartPid,waited=await waitForDaemonPort();if(waited!==null)return waited;throwDaemonTimeout(outcomeAtStart,pidAtStart)}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync13(resolved))return resolved}catch{}let globalBin=join17(homedir11(),".bun","bin","pgserve");if(existsSync13(globalBin))return globalBin;try{return execSync3("which pgserve",{encoding:"utf-8",timeout:3000}).trim()}catch{return"pgserve"}}async function startPgserveOnPort(port){mkdirSync6(DATA_DIR,{recursive:!0});let child=spawn(findPgserveBin(),["--port",String(port),"--host",DEFAULT_HOST,"--data",DATA_DIR,"--log","warn","--no-stats","--no-cluster","--pgvector"],{detached:!0,stdio:"ignore"});child.unref(),pgserveChild=child;let timeout=Number(process.env.GENIE_PGSERVE_TIMEOUT)||30000,deadline=Date.now()+timeout;while(Date.now()<deadline){if(await isPostgresHealthy(port))return activePort=port,ownsLockfile=!0,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;await new Promise((r)=>setTimeout(r,500))}try{child.kill("SIGTERM")}catch{}throw Error(`pgserve failed to start on port ${port} (timeout after ${timeout/1000}s)`)}function registerExitHandler(){if(exitHandlerRegistered)return;exitHandlerRegistered=!0;let cleanup=()=>{if(pgserveChild){try{pgserveChild.kill("SIGTERM")}catch{}pgserveChild=null}if(ownsLockfile)removeLockfile(),ownsLockfile=!1};process.on("exit",cleanup),process.on("SIGINT",()=>{cleanup(),process.exit(130)}),process.on("SIGTERM",()=>{cleanup(),process.exit(143)})}async function healthCheckCachedClient(){if(!sqlClient)return null;try{return await sqlClient`SELECT 1`,sqlClient}catch{let dying=sqlClient;if(!dying)return null;return sqlClient=null,activePort=null,dying.end({timeout:5}).catch(()=>{}),null}}async function runPostConnectSetup(client,isTestMode,timings){let _t2=Date.now(),skipBoot=isTestMode||process.env.GENIE_SKIP_DB_BOOT==="1";if(!skipBoot)await runMigrations(client);let _t3=Date.now();if(!skipBoot&&(needsSeed()||await needsSeededTeams(client)))await runSeed(client);let _t4=Date.now(),_t5=_t4;if(process.env.GENIE_PROFILE_DB)console.error(`[db-profile] pgserve=${timings.t1-timings.t0}ms migrate=${_t3-_t2}ms seed=${_t4-_t3}ms retention=skipped total=${_t5-timings.t0}ms`)}async function getConnection(){let cached=await healthCheckCachedClient();if(cached)return cached;if(buildPromise)return buildPromise;buildPromise=_buildConnection();try{return await buildPromise}finally{buildPromise=null}}async function _buildConnection(){let _t0=Date.now(),port=await ensurePgserve(),_t1=Date.now(),pgModule=(await Promise.resolve().then(() => (init_src(),exports_src))).default,testDbName=process.env.GENIE_TEST_DB_NAME,database=testDbName&&testDbName.length>0?testDbName:DB_NAME,isTestMode=Boolean(testDbName);sqlClient=pgModule({host:DEFAULT_HOST,port,database,username:"postgres",password:"postgres",max:50,idle_timeout:1,connect_timeout:5,onnotice:()=>{},connection:{client_min_messages:"warning"}});try{await runPostConnectSetup(sqlClient,isTestMode,{t0:_t0,t1:_t1})}catch(err){let dying=sqlClient;throw sqlClient=null,activePort=null,dying?.end({timeout:2}).catch(()=>{}),err}return sqlClient}function isConnected(){return sqlClient!==null}async function resetConnection(){if(sqlClient){let dying=sqlClient;sqlClient=null,await dying.end({timeout:5})}}async function isAvailable(){try{return await(await getConnection())`SELECT 1`,!0}catch{return!1}}async function shutdown(){if(sqlClient)await sqlClient.end({timeout:5}),sqlClient=null;if(ownsLockfile)removeLockfile(),ownsLockfile=!1}function getDataDir(){return DATA_DIR}function getActivePort(){return activePort??getPort()}function getLockfilePath(){return LOCKFILE_PATH}var DEFAULT_PORT=19642,DEFAULT_HOST="127.0.0.1",GENIE_HOME,DATA_DIR,LOCKFILE_PATH,DB_NAME="genie",TRUTHY_ENV,pgserveChild=null,sqlClient=null,activePort=null,ensurePromise=null,buildPromise=null,ownsLockfile=!1,exitHandlerRegistered=!1,retentionRan=!1,lastAutoStartOutcome=null,lastAutoStartPid=null,spawnDaemon=()=>{let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"serve","start","--headless","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref()};var init_db=__esm(()=>{init_db_migrations();init_pg_seed();init_process_identity();GENIE_HOME=process.env.GENIE_HOME??join17(homedir11(),".genie"),DATA_DIR=join17(GENIE_HOME,"data","pgserve"),LOCKFILE_PATH=join17(GENIE_HOME,"pgserve.port"),TRUTHY_ENV=new Set(["1","true","yes","on"])});import{createHmac as createHmac2}from"crypto";import{homedir as homedir12}from"os";function hashEntity(namespace,value){let key=process.env.GENIE_REDACTION_KEY??"genie-redaction-fallback";return`tier-a:${namespace}:${createHmac2("sha256",key).update(value).digest("hex").slice(0,16)}`}function dropSecretShaped(text){let out=text;for(let{name,pattern}of SECRET_PATTERNS)out=out.replace(pattern,`<REDACTED:${name}>`);return out}function stripEnvVars(text){return text.replace(ENV_ASSIGN,(_m,name)=>`${name}=<REDACTED>`)}function tokenizePath(p){let home=homedir12(),out=p;if(home&&out.startsWith(home))out=`~${out.slice(home.length)}`;let segments=out.split("/").filter(Boolean);if(segments.length>6){let head=segments.slice(0,3).join("/"),tail=segments.slice(-2).join("/");out=`${out.startsWith("/")?"/":""}${head}/\u2026/${tail}`}return out=out.replace(/\b[0-9a-f]{12,}\b/g,"<id>"),out}function redactFreeText(value){return stripEnvVars(dropSecretShaped(value))}function capPayload(body){let serialized;try{serialized=JSON.stringify(body)}catch{return{overflow:!0,content_hash:"unserializable",body:{overflow:!0}}}if(Buffer.byteLength(serialized,"utf8")<=MAX_PAYLOAD_BYTES)return{overflow:!1,body};let key=process.env.GENIE_REDACTION_KEY??"genie-redaction-fallback",digest=createHmac2("sha256",key).update(serialized).digest("hex").slice(0,16);return{overflow:!0,content_hash:digest,body:{overflow:!0,content_hash:digest,original_bytes:Buffer.byteLength(serialized,"utf8")}}}var SECRET_PATTERNS,SENSITIVE_ENV_NAME="[A-Z][A-Z0-9_]*(?:_KEY|_SECRET|_TOKEN|_PASSWORD|_PASS|_AUTH|_API_KEY)",ENV_ASSIGN,MAX_PAYLOAD_BYTES=65536;var init_redactors=__esm(()=>{SECRET_PATTERNS=[{name:"anthropic-key",pattern:/sk-ant-[A-Za-z0-9_-]{20,}/g},{name:"openai-key",pattern:/sk-[A-Za-z0-9]{20,}/g},{name:"github-token",pattern:/gh[pousr]_[A-Za-z0-9]{30,}/g},{name:"aws-access-key",pattern:/AKIA[0-9A-Z]{16}/g},{name:"aws-secret",pattern:/(?<![A-Za-z0-9])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9])/g},{name:"bearer-token",pattern:/(?:Bearer|bearer)\s+[A-Za-z0-9._\-~+/=]{20,}/g},{name:"jwt",pattern:/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g},{name:"pem-header",pattern:/-----BEGIN [A-Z ]+ PRIVATE KEY-----/g},{name:"sensitive-path",pattern:/\/(?:[^\s"',;():]+\/)*\.(?:secrets|ssh|aws|gnupg|keys)(?:\/[^\s"',;():]*)?/g}];ENV_ASSIGN=new RegExp(`\\b(${SENSITIVE_ENV_NAME})\\s*[=:]\\s*([^\\s"',;]+)`,"g")});function tagTier(schema2,tier,note){let desc=`tier:${tier}${note?`; ${note}`:""}`;return schema2.describe(desc)}var exports_agent_lifecycle={};__export(exports_agent_lifecycle,{schema:()=>schema2,TYPE:()=>TYPE,SCHEMA_VERSION:()=>SCHEMA_VERSION,KIND:()=>KIND});var SCHEMA_VERSION=1,TYPE="agent.lifecycle",KIND="span",AgentIdSchema,TeamSchema,ExecutorSchema,SessionIdSchema,CwdSchema,ExitReasonSchema,DurationSchema,schema2;var init_agent_lifecycle=__esm(()=>{init_zod();init_redactors();AgentIdSchema=tagTier(exports_external.string().min(1).max(256),"B","agent name \u2014 public"),TeamSchema=tagTier(exports_external.string().min(1).max(256).optional(),"B"),ExecutorSchema=tagTier(exports_external.enum(["claude-code","claude-sdk","codex","shell"]),"C"),SessionIdSchema=tagTier(exports_external.string().min(1).max(128).transform((v)=>hashEntity("session",v)),"A","session id hashed"),CwdSchema=tagTier(exports_external.string().max(1024).transform(tokenizePath),"B"),ExitReasonSchema=tagTier(exports_external.enum(["stopped","killed","crashed","idle-suspend","completed"]),"C"),DurationSchema=tagTier(exports_external.number().int().min(0),"C","ms"),schema2=exports_external.object({agent_id:AgentIdSchema,team:TeamSchema,executor:ExecutorSchema,session_id:SessionIdSchema.optional(),cwd:CwdSchema.optional(),exit_reason:ExitReasonSchema.optional(),duration_ms:DurationSchema.optional()}).strict()});var exports_agent_resume_attempted={};__export(exports_agent_resume_attempted,{schema:()=>schema3,TYPE:()=>TYPE2,SCHEMA_VERSION:()=>SCHEMA_VERSION2,KIND:()=>KIND2});var SCHEMA_VERSION2=1,TYPE2="agent.resume.attempted",KIND2="event",AGENT_STATES,EntityIdSchema,AttemptNumberSchema,StateSchema,LastErrorSchema,TriggerSchema,schema3;var init_agent_resume_attempted=__esm(()=>{init_zod();init_redactors();AGENT_STATES=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema=tagTier(exports_external.enum(AGENT_STATES),"C"),LastErrorSchema=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),schema3=exports_external.object({entity_id:EntityIdSchema,attempt_number:AttemptNumberSchema,state_before:StateSchema,state_after:StateSchema,last_error:LastErrorSchema,trigger:TriggerSchema}).strict()});var exports_agent_resume_failed={};__export(exports_agent_resume_failed,{schema:()=>schema4,TYPE:()=>TYPE3,SCHEMA_VERSION:()=>SCHEMA_VERSION3,KIND:()=>KIND3});var SCHEMA_VERSION3=1,TYPE3="agent.resume.failed",KIND3="event",AGENT_STATES2,EntityIdSchema2,AttemptNumberSchema2,StateSchema2,LastErrorSchema2,TriggerSchema2,ExhaustedSchema,schema4;var init_agent_resume_failed=__esm(()=>{init_zod();init_redactors();AGENT_STATES2=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema2=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema2=tagTier(exports_external.enum(AGENT_STATES2),"C"),LastErrorSchema2=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema2=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),ExhaustedSchema=tagTier(exports_external.boolean(),"C"),schema4=exports_external.object({entity_id:EntityIdSchema2,attempt_number:AttemptNumberSchema2,state_before:StateSchema2,state_after:StateSchema2,last_error:LastErrorSchema2,trigger:TriggerSchema2,exhausted:ExhaustedSchema}).strict()});var exports_agent_resume_succeeded={};__export(exports_agent_resume_succeeded,{schema:()=>schema5,TYPE:()=>TYPE4,SCHEMA_VERSION:()=>SCHEMA_VERSION4,KIND:()=>KIND4});var SCHEMA_VERSION4=1,TYPE4="agent.resume.succeeded",KIND4="event",AGENT_STATES3,EntityIdSchema3,AttemptNumberSchema3,StateSchema3,LastErrorSchema3,TriggerSchema3,schema5;var init_agent_resume_succeeded=__esm(()=>{init_zod();init_redactors();AGENT_STATES3=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema3=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema3=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema3=tagTier(exports_external.enum(AGENT_STATES3),"C"),LastErrorSchema3=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema3=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),schema5=exports_external.object({entity_id:EntityIdSchema3,attempt_number:AttemptNumberSchema3,state_before:StateSchema3,state_after:StateSchema3,last_error:LastErrorSchema3,trigger:TriggerSchema3}).strict()});var exports_audit_export={};__export(exports_audit_export,{schema:()=>schema6,TYPE:()=>TYPE5,SCHEMA_VERSION:()=>SCHEMA_VERSION5,KIND:()=>KIND5,DEFAULT_TIER:()=>DEFAULT_TIER});var SCHEMA_VERSION5=1,TYPE5="audit.export",KIND5="event",DEFAULT_TIER="audit",ExporterActorSchema,SinceIdSchema,RowCountSchema,BreakCountSchema,BundleSignaturePrefixSchema,TenantIdSchema,ReasonSchema,schema6;var init_audit_export=__esm(()=>{init_zod();init_redactors();ExporterActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A"),SinceIdSchema=tagTier(exports_external.number().int().min(0),"C"),RowCountSchema=tagTier(exports_external.number().int().min(0),"C"),BreakCountSchema=tagTier(exports_external.number().int().min(0),"C","chain breaks detected in the exported range"),BundleSignaturePrefixSchema=tagTier(exports_external.string().min(1).max(16),"C","first 16 hex of the bundle HMAC signature (full is on disk)"),TenantIdSchema=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)),"B","IR justification for the export"),schema6=exports_external.object({exporter_actor:ExporterActorSchema,since_id:SinceIdSchema,row_count:RowCountSchema,break_count:BreakCountSchema,bundle_signature_prefix:BundleSignaturePrefixSchema,tenant_id:TenantIdSchema,reason:ReasonSchema}).strict()});var exports_audit_un_hash={};__export(exports_audit_un_hash,{schema:()=>schema7,TYPE:()=>TYPE6,SCHEMA_VERSION:()=>SCHEMA_VERSION6,KIND:()=>KIND6,DEFAULT_TIER:()=>DEFAULT_TIER2});var SCHEMA_VERSION6=1,TYPE6="audit.un_hash",KIND6="event",DEFAULT_TIER2="audit",AdminActorSchema,NamespaceSchema,HashedValueSchema,ResolvedMarkerSchema,ReasonSchema2,TicketRefSchema,schema7;var init_audit_un_hash=__esm(()=>{init_zod();init_redactors();AdminActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A","admin who performed the un-hash (Tier-A hashed)"),NamespaceSchema=tagTier(exports_external.string().min(1).max(64),"C"),HashedValueSchema=tagTier(exports_external.string().min(1).max(256),"B","tier-a:ns:... source hash requested"),ResolvedMarkerSchema=tagTier(exports_external.boolean(),"C","true if un-hash succeeded"),ReasonSchema2=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)),"B","IR justification for the un-hash"),TicketRefSchema=tagTier(exports_external.string().max(128).optional(),"C","incident ticket reference"),schema7=exports_external.object({admin_actor:AdminActorSchema,namespace:NamespaceSchema,hashed_value:HashedValueSchema,resolved:ResolvedMarkerSchema,reason:ReasonSchema2,ticket_ref:TicketRefSchema}).strict()});var exports_cache_hit={};__export(exports_cache_hit,{schema:()=>schema8,TYPE:()=>TYPE7,SCHEMA_VERSION:()=>SCHEMA_VERSION7,KIND:()=>KIND7});var SCHEMA_VERSION7=1,TYPE7="cache.hit",KIND7="event",CacheSchema,HitSchema,KeyHintSchema,LatencyUsSchema,schema8;var init_cache_hit=__esm(()=>{init_zod();init_redactors();CacheSchema=tagTier(exports_external.string().min(1).max(128),"C"),HitSchema=tagTier(exports_external.boolean(),"C"),KeyHintSchema=tagTier(exports_external.string().max(128).transform((v)=>redactFreeText(v)).optional(),"B"),LatencyUsSchema=tagTier(exports_external.number().int().min(0).max(1e7).optional(),"C","microseconds"),schema8=exports_external.object({cache:CacheSchema,hit:HitSchema,key_hint:KeyHintSchema,latency_us:LatencyUsSchema}).strict()});var exports_cache_invalidate={};__export(exports_cache_invalidate,{schema:()=>schema9,TYPE:()=>TYPE8,SCHEMA_VERSION:()=>SCHEMA_VERSION8,KIND:()=>KIND8});var SCHEMA_VERSION8=1,TYPE8="cache.invalidate",KIND8="event",CacheSchema2,KeysInvalidatedSchema,ReasonSchema3,ScopeSchema,schema9;var init_cache_invalidate=__esm(()=>{init_zod();CacheSchema2=tagTier(exports_external.string().min(1).max(128),"C","cache name \u2014 public"),KeysInvalidatedSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),ReasonSchema3=tagTier(exports_external.enum(["ttl","manual","capacity","rotation","upstream_change"]).optional(),"C"),ScopeSchema=tagTier(exports_external.enum(["key","bucket","all"]).optional(),"C"),schema9=exports_external.object({cache:CacheSchema2,keys_invalidated:KeysInvalidatedSchema,reason:ReasonSchema3,scope:ScopeSchema}).strict()});var exports_cli_command={};__export(exports_cli_command,{schema:()=>schema10,TYPE:()=>TYPE9,SCHEMA_VERSION:()=>SCHEMA_VERSION9,KIND:()=>KIND9});var SCHEMA_VERSION9=1,TYPE9="cli.command",KIND9="span",CommandSchema,ArgsSchema,CwdSchema2,ExitCodeSchema,DurationSchema2,UserAgentSchema,schema10;var init_cli_command=__esm(()=>{init_zod();init_redactors();CommandSchema=tagTier(exports_external.string().max(256),"C","subcommand name only"),ArgsSchema=tagTier(exports_external.array(exports_external.string()).max(32).transform((args)=>args.map((a)=>redactFreeText(a))),"B","argv \u2014 secrets stripped, paths kept"),CwdSchema2=tagTier(exports_external.string().max(1024).transform(tokenizePath),"B","working directory tokenized"),ExitCodeSchema=tagTier(exports_external.number().int().min(-1).max(255),"C"),DurationSchema2=tagTier(exports_external.number().int().min(0).max(3600000),"C","milliseconds"),UserAgentSchema=tagTier(exports_external.string().max(256).optional(),"C"),schema10=exports_external.object({command:CommandSchema,args:ArgsSchema,cwd:CwdSchema2,exit_code:ExitCodeSchema.optional(),duration_ms:DurationSchema2.optional(),user_agent:UserAgentSchema}).strict().transform((v)=>({...v}))});var exports_consumer_heartbeat={};__export(exports_consumer_heartbeat,{schema:()=>schema11,TYPE:()=>TYPE10,SCHEMA_VERSION:()=>SCHEMA_VERSION10,KIND:()=>KIND10});var SCHEMA_VERSION10=1,TYPE10="consumer.heartbeat",KIND10="event",ConsumerIdSchema,LastEventIdSchema,BacklogDepthSchema,RoleSchema,UptimeSecondsSchema,schema11;var init_consumer_heartbeat=__esm(()=>{init_zod();init_redactors();ConsumerIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("consumer",v)),"A"),LastEventIdSchema=tagTier(exports_external.number().int().min(0).max(9007199254740991),"C"),BacklogDepthSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),RoleSchema=tagTier(exports_external.enum(["admin","operator","subscriber","audit"]).optional(),"C"),UptimeSecondsSchema=tagTier(exports_external.number().int().min(0).max(31536000).optional(),"C"),schema11=exports_external.object({consumer_id:ConsumerIdSchema,last_event_id_processed:LastEventIdSchema,backlog_depth:BacklogDepthSchema,role:RoleSchema,uptime_seconds:UptimeSecondsSchema}).strict()});var exports_consumer_lagged={};__export(exports_consumer_lagged,{schema:()=>schema12,TYPE:()=>TYPE11,SCHEMA_VERSION:()=>SCHEMA_VERSION11,KIND:()=>KIND11,DEFAULT_TIER:()=>DEFAULT_TIER3});var SCHEMA_VERSION11=1,TYPE11="consumer.lagged",KIND11="event",DEFAULT_TIER3="audit",CountSchema,SpillPathSchema,SeveritySchema,schema12;var init_consumer_lagged=__esm(()=>{init_zod();CountSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),SpillPathSchema=tagTier(exports_external.string().max(512),"B"),SeveritySchema=tagTier(exports_external.enum(["warn","error","fatal"]),"C"),schema12=exports_external.object({severity_class:SeveritySchema,spill_path:SpillPathSchema,rows_spilled:CountSchema,queue_depth:CountSchema,queue_cap:CountSchema}).strict()});var exports_correlation_orphan_rate={};__export(exports_correlation_orphan_rate,{schema:()=>schema13,TYPE:()=>TYPE12,SCHEMA_VERSION:()=>SCHEMA_VERSION12,KIND:()=>KIND12});var SCHEMA_VERSION12=1,TYPE12="correlation.orphan.rate",KIND12="event",RateSchema,CountSchema2,schema13;var init_correlation_orphan_rate=__esm(()=>{init_zod();RateSchema=tagTier(exports_external.number().min(0).max(1),"C"),CountSchema2=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema13=exports_external.object({window_samples:CountSchema2,orphans:CountSchema2,rate:RateSchema}).strict()});var exports_detector_disabled={};__export(exports_detector_disabled,{schema:()=>schema14,TYPE:()=>TYPE13,SCHEMA_VERSION:()=>SCHEMA_VERSION13,KIND:()=>KIND13});var SCHEMA_VERSION13=1,TYPE13="detector.disabled",KIND13="event",DetectorIdSchema,CauseSchema,BudgetSchema,FireCountSchema,BucketEndTsSchema,schema14;var init_detector_disabled=__esm(()=>{init_zod();DetectorIdSchema=tagTier(exports_external.string().min(1).max(128),"C"),CauseSchema=tagTier(exports_external.literal("fire_budget_exceeded"),"C"),BudgetSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C","events per hour bucket"),FireCountSchema=tagTier(exports_external.number().int().min(0).max(1e6),"C","fires observed in this bucket"),BucketEndTsSchema=tagTier(exports_external.string().datetime({offset:!0}),"C","ISO-8601 timestamp when the current hour bucket expires"),schema14=exports_external.object({detector_id:DetectorIdSchema,cause:CauseSchema,budget:BudgetSchema,fire_count:FireCountSchema,bucket_end_ts:BucketEndTsSchema}).strict()});var exports_emit_backpressure_critical={};__export(exports_emit_backpressure_critical,{schema:()=>schema15,TYPE:()=>TYPE14,SCHEMA_VERSION:()=>SCHEMA_VERSION14,KIND:()=>KIND14,DEFAULT_TIER:()=>DEFAULT_TIER4});var SCHEMA_VERSION14=1,TYPE14="emit.backpressure.critical",KIND14="event",DEFAULT_TIER4="audit",SecondsSchema,CountSchema3,schema15;var init_emit_backpressure_critical=__esm(()=>{init_zod();SecondsSchema=tagTier(exports_external.number().min(0).max(86400),"C"),CountSchema3=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema15=exports_external.object({spill_duration_seconds:SecondsSchema,spill_rows_total:CountSchema3,queue_depth:CountSchema3,queue_cap:CountSchema3,recommended_action:tagTier(exports_external.enum(["scale_consumers","inspect_pg","restart_bridge"]).optional(),"C")}).strict()});var exports_emitter_latency_p99={};__export(exports_emitter_latency_p99,{schema:()=>schema16,TYPE:()=>TYPE15,SCHEMA_VERSION:()=>SCHEMA_VERSION15,KIND:()=>KIND15});var SCHEMA_VERSION15=1,TYPE15="emitter.latency_p99",KIND15="event",MillisSchema,SampleCountSchema,schema16;var init_emitter_latency_p99=__esm(()=>{init_zod();MillisSchema=tagTier(exports_external.number().min(0).max(600000),"C"),SampleCountSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C"),schema16=exports_external.object({window_samples:SampleCountSchema,p50_ms:MillisSchema,p95_ms:MillisSchema,p99_ms:MillisSchema,max_ms:MillisSchema}).strict()});var exports_emitter_queue_depth={};__export(exports_emitter_queue_depth,{schema:()=>schema17,TYPE:()=>TYPE16,SCHEMA_VERSION:()=>SCHEMA_VERSION16,KIND:()=>KIND16});var SCHEMA_VERSION16=1,TYPE16="emitter.queue.depth",KIND16="event",DepthSchema,CapSchema,UtilizationSchema,schema17;var init_emitter_queue_depth=__esm(()=>{init_zod();DepthSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),CapSchema=tagTier(exports_external.number().int().min(1).max(1e7),"C"),UtilizationSchema=tagTier(exports_external.number().min(0).max(1),"C"),schema17=exports_external.object({depth:DepthSchema,cap:CapSchema,utilization:UtilizationSchema,enqueued_total:tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C"),flushed_total:tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C")}).strict()});var exports_emitter_rejected={};__export(exports_emitter_rejected,{schema:()=>schema18,TYPE:()=>TYPE17,SCHEMA_VERSION:()=>SCHEMA_VERSION17,KIND:()=>KIND17});var SCHEMA_VERSION17=1,TYPE17="emitter.rejected",KIND17="event",OffendingTypeSchema,ReasonSchema4,CountSchema4,schema18;var init_emitter_rejected=__esm(()=>{init_zod();OffendingTypeSchema=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema4=tagTier(exports_external.enum(["schema_parse","unregistered","kind_mismatch","overflow_cap","queue_full"]),"C"),CountSchema4=tagTier(exports_external.number().int().min(1).max(1e7),"C"),schema18=exports_external.object({offending_type:OffendingTypeSchema,reason:ReasonSchema4,count:CountSchema4}).strict()});var exports_emitter_shedding_load={};__export(exports_emitter_shedding_load,{schema:()=>schema19,TYPE:()=>TYPE18,SCHEMA_VERSION:()=>SCHEMA_VERSION18,KIND:()=>KIND18});var SCHEMA_VERSION18=1,TYPE18="emitter.shedding_load",KIND18="event",CountSchema5,schema19;var init_emitter_shedding_load=__esm(()=>{init_zod();CountSchema5=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema19=exports_external.object({dropped_debug:CountSchema5,dropped_info:CountSchema5,spilled_warn_plus:CountSchema5,window_seconds:tagTier(exports_external.number().int().min(1).max(3600),"C")}).strict()});var exports_error_raised={};__export(exports_error_raised,{schema:()=>schema20,TYPE:()=>TYPE19,SCHEMA_VERSION:()=>SCHEMA_VERSION19,KIND:()=>KIND19});var SCHEMA_VERSION19=1,TYPE19="error.raised",KIND19="event",ErrorClassSchema,MessageSchema,StackSchema,SubsystemSchema,SeveritySchema2,RetryableSchema,schema20;var init_error_raised=__esm(()=>{init_zod();init_redactors();ErrorClassSchema=tagTier(exports_external.string().min(1).max(256),"C","exception class name"),MessageSchema=tagTier(exports_external.string().max(4096).transform(redactFreeText),"B"),StackSchema=tagTier(exports_external.string().max(16384).transform((stack)=>stack.split(`
684
+ `)}}async function ensurePgserve(){if(activePort===null){let testPort=await resolveTestPort();if(testPort!==null)return activePort=testPort,process.env.GENIE_PG_AVAILABLE="true",testPort}if(ensurePromise)return ensurePromise;ensurePromise=_ensurePgserve();try{return await ensurePromise}finally{ensurePromise=null}}function __setSpawnDaemonForTest(fn){spawnDaemon=fn??(()=>{let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"serve","start","--headless","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref()})}function readPidFile(pidPath){try{return readFileSync9(pidPath,"utf-8").trim()||null}catch{return null}}function parsePidFile(raw){let sepIdx=raw.indexOf(":"),pid,recordedStartTime;if(sepIdx<0)pid=Number.parseInt(raw,10),recordedStartTime=null;else{pid=Number.parseInt(raw.slice(0,sepIdx),10);let tail=raw.slice(sepIdx+1).trim();recordedStartTime=tail===""||tail==="unknown"?null:tail}if(Number.isNaN(pid)||pid<=0)return null;return{pid,recordedStartTime}}function isServeAlive(pid,recordedStartTime){try{process.kill(pid,0)}catch{return!1}if(recordedStartTime===null)return!1;let currentStartTime=getProcessStartTime(pid);return currentStartTime!==null&&currentStartTime===recordedStartTime}function unlinkQuiet(path2){try{unlinkSync3(path2)}catch{}}async function autoStartDaemon(){let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join17(home,"serve.pid"),raw=readPidFile(pidPath);if(!raw){lastAutoStartOutcome="missing",lastAutoStartPid=null,spawnDaemon();return}let parsed=parsePidFile(raw);if(!parsed){unlinkQuiet(pidPath),lastAutoStartOutcome="stale",lastAutoStartPid=null,spawnDaemon();return}if(isServeAlive(parsed.pid,parsed.recordedStartTime)){lastAutoStartOutcome="alive",lastAutoStartPid=parsed.pid;return}unlinkQuiet(pidPath),lastAutoStartOutcome="stale",lastAutoStartPid=parsed.pid,spawnDaemon()}async function resolveTestPort(){let raw=process.env.GENIE_TEST_PG_PORT;if(!raw)return null;let parsed=Number.parseInt(raw,10);if(Number.isNaN(parsed)||parsed<=0||parsed>=65536||!await isPostgresHealthy(parsed))throw Error(`GENIE_TEST_PG_PORT=${raw} set but not reachable`);return parsed}async function tryExistingPort(port){let portFromFile=readLockfile();if(portFromFile!==null&&await isPostgresHealthy(portFromFile))return activePort=portFromFile,process.env.GENIE_PG_AVAILABLE="true",portFromFile;if(await isPostgresHealthy(port))return activePort=port,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;return null}async function spawnPgserveDirect(port){mkdirSync6(DATA_DIR,{recursive:!0}),selfHealPostgres(DATA_DIR);try{let startedPort=await startPgserveOnPort(port);return registerExitHandler(),startedPort}catch(err){process.env.GENIE_PG_AVAILABLE="false";let message=err instanceof Error?err.message:String(err);throw Error(`pgserve failed to start: ${maskCredentials(message)}`)}}async function waitForDaemonPort(){let deadline=Date.now()+16000;while(Date.now()<deadline){let p=readLockfile();if(p!==null&&await isPostgresHealthy(p))return activePort=p,process.env.GENIE_PG_AVAILABLE="true",p;await new Promise((r)=>setTimeout(r,500))}return null}function throwDaemonTimeout(outcomeAtStart,pidAtStart){process.env.GENIE_PG_AVAILABLE="false";let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join17(home,"serve.pid"),hasPidFile=existsSync13(pidPath),currentPort=readLockfile()??getPort();if(outcomeAtStart==="stale")throw Error(`Stale ~/.genie/serve.pid (PID ${pidAtStart??"unknown"} was not our serve). Removed and retried \u2014 if this persists, run: genie serve start`);if(!hasPidFile)throw Error("genie serve not running. Run: genie serve start");throw Error(`genie serve is running (PID ${pidAtStart??outcomeAtStart??"unknown"}) but pgserve did not respond on port ${currentPort} within 16s. Try: genie serve restart, or check ~/.genie/logs/scheduler.log`)}async function _ensurePgserve(){if(activePort!==null)return activePort;let port=getPort(),existing=await tryExistingPort(port);if(existing!==null)return existing;if(process.env.CI==="true")throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve not available in CI");if(isPgAutostartDisabled())throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve unavailable and GENIE_PG_NO_AUTOSTART=1");let rootErr=checkRootGuard();if(rootErr!==null)throw process.env.GENIE_PG_AVAILABLE="false",Error(rootErr);if(process.env.GENIE_IS_DAEMON==="1")return spawnPgserveDirect(port);await autoStartDaemon();let outcomeAtStart=lastAutoStartOutcome,pidAtStart=lastAutoStartPid,waited=await waitForDaemonPort();if(waited!==null)return waited;throwDaemonTimeout(outcomeAtStart,pidAtStart)}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync13(resolved))return resolved}catch{}let globalBin=join17(homedir11(),".bun","bin","pgserve");if(existsSync13(globalBin))return globalBin;try{return execSync3("which pgserve",{encoding:"utf-8",timeout:3000}).trim()}catch{return"pgserve"}}async function startPgserveOnPort(port){mkdirSync6(DATA_DIR,{recursive:!0});let child=spawn(findPgserveBin(),["--port",String(port),"--host",DEFAULT_HOST,"--data",DATA_DIR,"--log","warn","--no-stats","--no-cluster","--pgvector"],{detached:!0,stdio:"ignore"});child.unref(),pgserveChild=child;let timeout=Number(process.env.GENIE_PGSERVE_TIMEOUT)||30000,deadline=Date.now()+timeout;while(Date.now()<deadline){if(await isPostgresHealthy(port))return activePort=port,ownsLockfile=!0,process.env.GENIE_PG_AVAILABLE="true",writeLockfile(port),port;await new Promise((r)=>setTimeout(r,500))}if(await terminatePgserveTree(child),pgserveChild===child)pgserveChild=null;throw selfHealPostgres(DATA_DIR),Error(`pgserve failed to start on port ${port} (timeout after ${timeout/1000}s)`)}function registerExitHandler(){if(exitHandlerRegistered)return;exitHandlerRegistered=!0;let cleanup=()=>{if(pgserveChild)signalPgserveTree(pgserveChild,"SIGTERM"),pgserveChild=null;if(ownsLockfile)removeLockfile(),ownsLockfile=!1};process.on("exit",cleanup),process.on("SIGINT",()=>{cleanup(),process.exit(130)}),process.on("SIGTERM",()=>{cleanup(),process.exit(143)})}async function healthCheckCachedClient(){if(!sqlClient)return null;try{return await sqlClient`SELECT 1`,sqlClient}catch{let dying=sqlClient;if(!dying)return null;return sqlClient=null,activePort=null,dying.end({timeout:5}).catch(()=>{}),null}}async function runPostConnectSetup(client,isTestMode,timings){let _t2=Date.now(),skipBoot=isTestMode||process.env.GENIE_SKIP_DB_BOOT==="1";if(!skipBoot)await runMigrations(client);let _t3=Date.now();if(!skipBoot&&(needsSeed()||await needsSeededTeams(client)))await runSeed(client);let _t4=Date.now(),_t5=_t4;if(process.env.GENIE_PROFILE_DB)console.error(`[db-profile] pgserve=${timings.t1-timings.t0}ms migrate=${_t3-_t2}ms seed=${_t4-_t3}ms retention=skipped total=${_t5-timings.t0}ms`)}async function getConnection(){let cached=await healthCheckCachedClient();if(cached)return cached;if(buildPromise)return buildPromise;buildPromise=_buildConnection();try{return await buildPromise}finally{buildPromise=null}}async function _buildConnection(){let _t0=Date.now(),port=await ensurePgserve(),_t1=Date.now(),pgModule=(await Promise.resolve().then(() => (init_src(),exports_src))).default,testDbName=process.env.GENIE_TEST_DB_NAME,database=testDbName&&testDbName.length>0?testDbName:DB_NAME,isTestMode=Boolean(testDbName);sqlClient=pgModule({host:DEFAULT_HOST,port,database,username:"postgres",password:"postgres",max:50,idle_timeout:1,connect_timeout:5,onnotice:()=>{},connection:{client_min_messages:"warning"}});try{await runPostConnectSetup(sqlClient,isTestMode,{t0:_t0,t1:_t1})}catch(err){let dying=sqlClient;throw sqlClient=null,activePort=null,dying?.end({timeout:2}).catch(()=>{}),err}return sqlClient}function isConnected(){return sqlClient!==null}async function resetConnection(){if(sqlClient){let dying=sqlClient;sqlClient=null,await dying.end({timeout:5})}}async function isAvailable(){try{return await(await getConnection())`SELECT 1`,!0}catch{return!1}}async function shutdown(){if(sqlClient)await sqlClient.end({timeout:5}),sqlClient=null;if(ownsLockfile)removeLockfile(),ownsLockfile=!1}function getDataDir(){return DATA_DIR}function getActivePort(){return activePort??getPort()}function getLockfilePath(){return LOCKFILE_PATH}var DEFAULT_PORT=19642,DEFAULT_HOST="127.0.0.1",GENIE_HOME,DATA_DIR,LOCKFILE_PATH,DB_NAME="genie",TRUTHY_ENV,pgserveChild=null,sqlClient=null,activePort=null,ensurePromise=null,buildPromise=null,ownsLockfile=!1,exitHandlerRegistered=!1,retentionRan=!1,lastAutoStartOutcome=null,lastAutoStartPid=null,spawnDaemon=()=>{let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie";spawn(bunPath,[genieBin,"serve","start","--headless","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref()};var init_db=__esm(()=>{init_db_migrations();init_pg_seed();init_process_identity();GENIE_HOME=process.env.GENIE_HOME??join17(homedir11(),".genie"),DATA_DIR=join17(GENIE_HOME,"data","pgserve"),LOCKFILE_PATH=join17(GENIE_HOME,"pgserve.port"),TRUTHY_ENV=new Set(["1","true","yes","on"])});import{createHmac as createHmac2}from"crypto";import{homedir as homedir12}from"os";function hashEntity(namespace,value){let key=process.env.GENIE_REDACTION_KEY??"genie-redaction-fallback";return`tier-a:${namespace}:${createHmac2("sha256",key).update(value).digest("hex").slice(0,16)}`}function dropSecretShaped(text){let out=text;for(let{name,pattern}of SECRET_PATTERNS)out=out.replace(pattern,`<REDACTED:${name}>`);return out}function stripEnvVars(text){return text.replace(ENV_ASSIGN,(_m,name)=>`${name}=<REDACTED>`)}function tokenizePath(p){let home=homedir12(),out=p;if(home&&out.startsWith(home))out=`~${out.slice(home.length)}`;let segments=out.split("/").filter(Boolean);if(segments.length>6){let head=segments.slice(0,3).join("/"),tail=segments.slice(-2).join("/");out=`${out.startsWith("/")?"/":""}${head}/\u2026/${tail}`}return out=out.replace(/\b[0-9a-f]{12,}\b/g,"<id>"),out}function redactFreeText(value){return stripEnvVars(dropSecretShaped(value))}function capPayload(body){let serialized;try{serialized=JSON.stringify(body)}catch{return{overflow:!0,content_hash:"unserializable",body:{overflow:!0}}}if(Buffer.byteLength(serialized,"utf8")<=MAX_PAYLOAD_BYTES)return{overflow:!1,body};let key=process.env.GENIE_REDACTION_KEY??"genie-redaction-fallback",digest=createHmac2("sha256",key).update(serialized).digest("hex").slice(0,16);return{overflow:!0,content_hash:digest,body:{overflow:!0,content_hash:digest,original_bytes:Buffer.byteLength(serialized,"utf8")}}}var SECRET_PATTERNS,SENSITIVE_ENV_NAME="[A-Z][A-Z0-9_]*(?:_KEY|_SECRET|_TOKEN|_PASSWORD|_PASS|_AUTH|_API_KEY)",ENV_ASSIGN,MAX_PAYLOAD_BYTES=65536;var init_redactors=__esm(()=>{SECRET_PATTERNS=[{name:"anthropic-key",pattern:/sk-ant-[A-Za-z0-9_-]{20,}/g},{name:"openai-key",pattern:/sk-[A-Za-z0-9]{20,}/g},{name:"github-token",pattern:/gh[pousr]_[A-Za-z0-9]{30,}/g},{name:"aws-access-key",pattern:/AKIA[0-9A-Z]{16}/g},{name:"aws-secret",pattern:/(?<![A-Za-z0-9])[A-Za-z0-9/+=]{40}(?![A-Za-z0-9])/g},{name:"bearer-token",pattern:/(?:Bearer|bearer)\s+[A-Za-z0-9._\-~+/=]{20,}/g},{name:"jwt",pattern:/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g},{name:"pem-header",pattern:/-----BEGIN [A-Z ]+ PRIVATE KEY-----/g},{name:"sensitive-path",pattern:/\/(?:[^\s"',;():]+\/)*\.(?:secrets|ssh|aws|gnupg|keys)(?:\/[^\s"',;():]*)?/g}];ENV_ASSIGN=new RegExp(`\\b(${SENSITIVE_ENV_NAME})\\s*[=:]\\s*([^\\s"',;]+)`,"g")});function tagTier(schema2,tier,note){let desc=`tier:${tier}${note?`; ${note}`:""}`;return schema2.describe(desc)}var exports_agent_lifecycle={};__export(exports_agent_lifecycle,{schema:()=>schema2,TYPE:()=>TYPE,SCHEMA_VERSION:()=>SCHEMA_VERSION,KIND:()=>KIND});var SCHEMA_VERSION=1,TYPE="agent.lifecycle",KIND="span",AgentIdSchema,TeamSchema,ExecutorSchema,SessionIdSchema,CwdSchema,ExitReasonSchema,DurationSchema,schema2;var init_agent_lifecycle=__esm(()=>{init_zod();init_redactors();AgentIdSchema=tagTier(exports_external.string().min(1).max(256),"B","agent name \u2014 public"),TeamSchema=tagTier(exports_external.string().min(1).max(256).optional(),"B"),ExecutorSchema=tagTier(exports_external.enum(["claude-code","claude-sdk","codex","shell"]),"C"),SessionIdSchema=tagTier(exports_external.string().min(1).max(128).transform((v)=>hashEntity("session",v)),"A","session id hashed"),CwdSchema=tagTier(exports_external.string().max(1024).transform(tokenizePath),"B"),ExitReasonSchema=tagTier(exports_external.enum(["stopped","killed","crashed","idle-suspend","completed"]),"C"),DurationSchema=tagTier(exports_external.number().int().min(0),"C","ms"),schema2=exports_external.object({agent_id:AgentIdSchema,team:TeamSchema,executor:ExecutorSchema,session_id:SessionIdSchema.optional(),cwd:CwdSchema.optional(),exit_reason:ExitReasonSchema.optional(),duration_ms:DurationSchema.optional()}).strict()});var exports_agent_resume_attempted={};__export(exports_agent_resume_attempted,{schema:()=>schema3,TYPE:()=>TYPE2,SCHEMA_VERSION:()=>SCHEMA_VERSION2,KIND:()=>KIND2});var SCHEMA_VERSION2=1,TYPE2="agent.resume.attempted",KIND2="event",AGENT_STATES,EntityIdSchema,AttemptNumberSchema,StateSchema,LastErrorSchema,TriggerSchema,schema3;var init_agent_resume_attempted=__esm(()=>{init_zod();init_redactors();AGENT_STATES=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema=tagTier(exports_external.enum(AGENT_STATES),"C"),LastErrorSchema=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),schema3=exports_external.object({entity_id:EntityIdSchema,attempt_number:AttemptNumberSchema,state_before:StateSchema,state_after:StateSchema,last_error:LastErrorSchema,trigger:TriggerSchema}).strict()});var exports_agent_resume_failed={};__export(exports_agent_resume_failed,{schema:()=>schema4,TYPE:()=>TYPE3,SCHEMA_VERSION:()=>SCHEMA_VERSION3,KIND:()=>KIND3});var SCHEMA_VERSION3=1,TYPE3="agent.resume.failed",KIND3="event",AGENT_STATES2,EntityIdSchema2,AttemptNumberSchema2,StateSchema2,LastErrorSchema2,TriggerSchema2,ExhaustedSchema,schema4;var init_agent_resume_failed=__esm(()=>{init_zod();init_redactors();AGENT_STATES2=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema2=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema2=tagTier(exports_external.enum(AGENT_STATES2),"C"),LastErrorSchema2=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema2=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),ExhaustedSchema=tagTier(exports_external.boolean(),"C"),schema4=exports_external.object({entity_id:EntityIdSchema2,attempt_number:AttemptNumberSchema2,state_before:StateSchema2,state_after:StateSchema2,last_error:LastErrorSchema2,trigger:TriggerSchema2,exhausted:ExhaustedSchema}).strict()});var exports_agent_resume_succeeded={};__export(exports_agent_resume_succeeded,{schema:()=>schema5,TYPE:()=>TYPE4,SCHEMA_VERSION:()=>SCHEMA_VERSION4,KIND:()=>KIND4});var SCHEMA_VERSION4=1,TYPE4="agent.resume.succeeded",KIND4="event",AGENT_STATES3,EntityIdSchema3,AttemptNumberSchema3,StateSchema3,LastErrorSchema3,TriggerSchema3,schema5;var init_agent_resume_succeeded=__esm(()=>{init_zod();init_redactors();AGENT_STATES3=["spawning","working","idle","permission","question","done","error","suspended","unknown"],EntityIdSchema3=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A","agent id hashed"),AttemptNumberSchema3=tagTier(exports_external.number().int().min(1).max(64),"C"),StateSchema3=tagTier(exports_external.enum(AGENT_STATES3),"C"),LastErrorSchema3=tagTier(exports_external.string().max(500).transform((v)=>redactFreeText(v)).optional(),"B","truncated to 500 chars"),TriggerSchema3=tagTier(exports_external.enum(["scheduler","manual","boot"]),"C"),schema5=exports_external.object({entity_id:EntityIdSchema3,attempt_number:AttemptNumberSchema3,state_before:StateSchema3,state_after:StateSchema3,last_error:LastErrorSchema3,trigger:TriggerSchema3}).strict()});var exports_audit_export={};__export(exports_audit_export,{schema:()=>schema6,TYPE:()=>TYPE5,SCHEMA_VERSION:()=>SCHEMA_VERSION5,KIND:()=>KIND5,DEFAULT_TIER:()=>DEFAULT_TIER});var SCHEMA_VERSION5=1,TYPE5="audit.export",KIND5="event",DEFAULT_TIER="audit",ExporterActorSchema,SinceIdSchema,RowCountSchema,BreakCountSchema,BundleSignaturePrefixSchema,TenantIdSchema,ReasonSchema,schema6;var init_audit_export=__esm(()=>{init_zod();init_redactors();ExporterActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A"),SinceIdSchema=tagTier(exports_external.number().int().min(0),"C"),RowCountSchema=tagTier(exports_external.number().int().min(0),"C"),BreakCountSchema=tagTier(exports_external.number().int().min(0),"C","chain breaks detected in the exported range"),BundleSignaturePrefixSchema=tagTier(exports_external.string().min(1).max(16),"C","first 16 hex of the bundle HMAC signature (full is on disk)"),TenantIdSchema=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)),"B","IR justification for the export"),schema6=exports_external.object({exporter_actor:ExporterActorSchema,since_id:SinceIdSchema,row_count:RowCountSchema,break_count:BreakCountSchema,bundle_signature_prefix:BundleSignaturePrefixSchema,tenant_id:TenantIdSchema,reason:ReasonSchema}).strict()});var exports_audit_un_hash={};__export(exports_audit_un_hash,{schema:()=>schema7,TYPE:()=>TYPE6,SCHEMA_VERSION:()=>SCHEMA_VERSION6,KIND:()=>KIND6,DEFAULT_TIER:()=>DEFAULT_TIER2});var SCHEMA_VERSION6=1,TYPE6="audit.un_hash",KIND6="event",DEFAULT_TIER2="audit",AdminActorSchema,NamespaceSchema,HashedValueSchema,ResolvedMarkerSchema,ReasonSchema2,TicketRefSchema,schema7;var init_audit_un_hash=__esm(()=>{init_zod();init_redactors();AdminActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A","admin who performed the un-hash (Tier-A hashed)"),NamespaceSchema=tagTier(exports_external.string().min(1).max(64),"C"),HashedValueSchema=tagTier(exports_external.string().min(1).max(256),"B","tier-a:ns:... source hash requested"),ResolvedMarkerSchema=tagTier(exports_external.boolean(),"C","true if un-hash succeeded"),ReasonSchema2=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)),"B","IR justification for the un-hash"),TicketRefSchema=tagTier(exports_external.string().max(128).optional(),"C","incident ticket reference"),schema7=exports_external.object({admin_actor:AdminActorSchema,namespace:NamespaceSchema,hashed_value:HashedValueSchema,resolved:ResolvedMarkerSchema,reason:ReasonSchema2,ticket_ref:TicketRefSchema}).strict()});var exports_cache_hit={};__export(exports_cache_hit,{schema:()=>schema8,TYPE:()=>TYPE7,SCHEMA_VERSION:()=>SCHEMA_VERSION7,KIND:()=>KIND7});var SCHEMA_VERSION7=1,TYPE7="cache.hit",KIND7="event",CacheSchema,HitSchema,KeyHintSchema,LatencyUsSchema,schema8;var init_cache_hit=__esm(()=>{init_zod();init_redactors();CacheSchema=tagTier(exports_external.string().min(1).max(128),"C"),HitSchema=tagTier(exports_external.boolean(),"C"),KeyHintSchema=tagTier(exports_external.string().max(128).transform((v)=>redactFreeText(v)).optional(),"B"),LatencyUsSchema=tagTier(exports_external.number().int().min(0).max(1e7).optional(),"C","microseconds"),schema8=exports_external.object({cache:CacheSchema,hit:HitSchema,key_hint:KeyHintSchema,latency_us:LatencyUsSchema}).strict()});var exports_cache_invalidate={};__export(exports_cache_invalidate,{schema:()=>schema9,TYPE:()=>TYPE8,SCHEMA_VERSION:()=>SCHEMA_VERSION8,KIND:()=>KIND8});var SCHEMA_VERSION8=1,TYPE8="cache.invalidate",KIND8="event",CacheSchema2,KeysInvalidatedSchema,ReasonSchema3,ScopeSchema,schema9;var init_cache_invalidate=__esm(()=>{init_zod();CacheSchema2=tagTier(exports_external.string().min(1).max(128),"C","cache name \u2014 public"),KeysInvalidatedSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),ReasonSchema3=tagTier(exports_external.enum(["ttl","manual","capacity","rotation","upstream_change"]).optional(),"C"),ScopeSchema=tagTier(exports_external.enum(["key","bucket","all"]).optional(),"C"),schema9=exports_external.object({cache:CacheSchema2,keys_invalidated:KeysInvalidatedSchema,reason:ReasonSchema3,scope:ScopeSchema}).strict()});var exports_cli_command={};__export(exports_cli_command,{schema:()=>schema10,TYPE:()=>TYPE9,SCHEMA_VERSION:()=>SCHEMA_VERSION9,KIND:()=>KIND9});var SCHEMA_VERSION9=1,TYPE9="cli.command",KIND9="span",CommandSchema,ArgsSchema,CwdSchema2,ExitCodeSchema,DurationSchema2,UserAgentSchema,schema10;var init_cli_command=__esm(()=>{init_zod();init_redactors();CommandSchema=tagTier(exports_external.string().max(256),"C","subcommand name only"),ArgsSchema=tagTier(exports_external.array(exports_external.string()).max(32).transform((args)=>args.map((a)=>redactFreeText(a))),"B","argv \u2014 secrets stripped, paths kept"),CwdSchema2=tagTier(exports_external.string().max(1024).transform(tokenizePath),"B","working directory tokenized"),ExitCodeSchema=tagTier(exports_external.number().int().min(-1).max(255),"C"),DurationSchema2=tagTier(exports_external.number().int().min(0).max(3600000),"C","milliseconds"),UserAgentSchema=tagTier(exports_external.string().max(256).optional(),"C"),schema10=exports_external.object({command:CommandSchema,args:ArgsSchema,cwd:CwdSchema2,exit_code:ExitCodeSchema.optional(),duration_ms:DurationSchema2.optional(),user_agent:UserAgentSchema}).strict().transform((v)=>({...v}))});var exports_consumer_heartbeat={};__export(exports_consumer_heartbeat,{schema:()=>schema11,TYPE:()=>TYPE10,SCHEMA_VERSION:()=>SCHEMA_VERSION10,KIND:()=>KIND10});var SCHEMA_VERSION10=1,TYPE10="consumer.heartbeat",KIND10="event",ConsumerIdSchema,LastEventIdSchema,BacklogDepthSchema,RoleSchema,UptimeSecondsSchema,schema11;var init_consumer_heartbeat=__esm(()=>{init_zod();init_redactors();ConsumerIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("consumer",v)),"A"),LastEventIdSchema=tagTier(exports_external.number().int().min(0).max(9007199254740991),"C"),BacklogDepthSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),RoleSchema=tagTier(exports_external.enum(["admin","operator","subscriber","audit"]).optional(),"C"),UptimeSecondsSchema=tagTier(exports_external.number().int().min(0).max(31536000).optional(),"C"),schema11=exports_external.object({consumer_id:ConsumerIdSchema,last_event_id_processed:LastEventIdSchema,backlog_depth:BacklogDepthSchema,role:RoleSchema,uptime_seconds:UptimeSecondsSchema}).strict()});var exports_consumer_lagged={};__export(exports_consumer_lagged,{schema:()=>schema12,TYPE:()=>TYPE11,SCHEMA_VERSION:()=>SCHEMA_VERSION11,KIND:()=>KIND11,DEFAULT_TIER:()=>DEFAULT_TIER3});var SCHEMA_VERSION11=1,TYPE11="consumer.lagged",KIND11="event",DEFAULT_TIER3="audit",CountSchema,SpillPathSchema,SeveritySchema,schema12;var init_consumer_lagged=__esm(()=>{init_zod();CountSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),SpillPathSchema=tagTier(exports_external.string().max(512),"B"),SeveritySchema=tagTier(exports_external.enum(["warn","error","fatal"]),"C"),schema12=exports_external.object({severity_class:SeveritySchema,spill_path:SpillPathSchema,rows_spilled:CountSchema,queue_depth:CountSchema,queue_cap:CountSchema}).strict()});var exports_correlation_orphan_rate={};__export(exports_correlation_orphan_rate,{schema:()=>schema13,TYPE:()=>TYPE12,SCHEMA_VERSION:()=>SCHEMA_VERSION12,KIND:()=>KIND12});var SCHEMA_VERSION12=1,TYPE12="correlation.orphan.rate",KIND12="event",RateSchema,CountSchema2,schema13;var init_correlation_orphan_rate=__esm(()=>{init_zod();RateSchema=tagTier(exports_external.number().min(0).max(1),"C"),CountSchema2=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema13=exports_external.object({window_samples:CountSchema2,orphans:CountSchema2,rate:RateSchema}).strict()});var exports_detector_disabled={};__export(exports_detector_disabled,{schema:()=>schema14,TYPE:()=>TYPE13,SCHEMA_VERSION:()=>SCHEMA_VERSION13,KIND:()=>KIND13});var SCHEMA_VERSION13=1,TYPE13="detector.disabled",KIND13="event",DetectorIdSchema,CauseSchema,BudgetSchema,FireCountSchema,BucketEndTsSchema,schema14;var init_detector_disabled=__esm(()=>{init_zod();DetectorIdSchema=tagTier(exports_external.string().min(1).max(128),"C"),CauseSchema=tagTier(exports_external.literal("fire_budget_exceeded"),"C"),BudgetSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C","events per hour bucket"),FireCountSchema=tagTier(exports_external.number().int().min(0).max(1e6),"C","fires observed in this bucket"),BucketEndTsSchema=tagTier(exports_external.string().datetime({offset:!0}),"C","ISO-8601 timestamp when the current hour bucket expires"),schema14=exports_external.object({detector_id:DetectorIdSchema,cause:CauseSchema,budget:BudgetSchema,fire_count:FireCountSchema,bucket_end_ts:BucketEndTsSchema}).strict()});var exports_emit_backpressure_critical={};__export(exports_emit_backpressure_critical,{schema:()=>schema15,TYPE:()=>TYPE14,SCHEMA_VERSION:()=>SCHEMA_VERSION14,KIND:()=>KIND14,DEFAULT_TIER:()=>DEFAULT_TIER4});var SCHEMA_VERSION14=1,TYPE14="emit.backpressure.critical",KIND14="event",DEFAULT_TIER4="audit",SecondsSchema,CountSchema3,schema15;var init_emit_backpressure_critical=__esm(()=>{init_zod();SecondsSchema=tagTier(exports_external.number().min(0).max(86400),"C"),CountSchema3=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema15=exports_external.object({spill_duration_seconds:SecondsSchema,spill_rows_total:CountSchema3,queue_depth:CountSchema3,queue_cap:CountSchema3,recommended_action:tagTier(exports_external.enum(["scale_consumers","inspect_pg","restart_bridge"]).optional(),"C")}).strict()});var exports_emitter_latency_p99={};__export(exports_emitter_latency_p99,{schema:()=>schema16,TYPE:()=>TYPE15,SCHEMA_VERSION:()=>SCHEMA_VERSION15,KIND:()=>KIND15});var SCHEMA_VERSION15=1,TYPE15="emitter.latency_p99",KIND15="event",MillisSchema,SampleCountSchema,schema16;var init_emitter_latency_p99=__esm(()=>{init_zod();MillisSchema=tagTier(exports_external.number().min(0).max(600000),"C"),SampleCountSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C"),schema16=exports_external.object({window_samples:SampleCountSchema,p50_ms:MillisSchema,p95_ms:MillisSchema,p99_ms:MillisSchema,max_ms:MillisSchema}).strict()});var exports_emitter_queue_depth={};__export(exports_emitter_queue_depth,{schema:()=>schema17,TYPE:()=>TYPE16,SCHEMA_VERSION:()=>SCHEMA_VERSION16,KIND:()=>KIND16});var SCHEMA_VERSION16=1,TYPE16="emitter.queue.depth",KIND16="event",DepthSchema,CapSchema,UtilizationSchema,schema17;var init_emitter_queue_depth=__esm(()=>{init_zod();DepthSchema=tagTier(exports_external.number().int().min(0).max(1e7),"C"),CapSchema=tagTier(exports_external.number().int().min(1).max(1e7),"C"),UtilizationSchema=tagTier(exports_external.number().min(0).max(1),"C"),schema17=exports_external.object({depth:DepthSchema,cap:CapSchema,utilization:UtilizationSchema,enqueued_total:tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C"),flushed_total:tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C")}).strict()});var exports_emitter_rejected={};__export(exports_emitter_rejected,{schema:()=>schema18,TYPE:()=>TYPE17,SCHEMA_VERSION:()=>SCHEMA_VERSION17,KIND:()=>KIND17});var SCHEMA_VERSION17=1,TYPE17="emitter.rejected",KIND17="event",OffendingTypeSchema,ReasonSchema4,CountSchema4,schema18;var init_emitter_rejected=__esm(()=>{init_zod();OffendingTypeSchema=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema4=tagTier(exports_external.enum(["schema_parse","unregistered","kind_mismatch","overflow_cap","queue_full"]),"C"),CountSchema4=tagTier(exports_external.number().int().min(1).max(1e7),"C"),schema18=exports_external.object({offending_type:OffendingTypeSchema,reason:ReasonSchema4,count:CountSchema4}).strict()});var exports_emitter_shedding_load={};__export(exports_emitter_shedding_load,{schema:()=>schema19,TYPE:()=>TYPE18,SCHEMA_VERSION:()=>SCHEMA_VERSION18,KIND:()=>KIND18});var SCHEMA_VERSION18=1,TYPE18="emitter.shedding_load",KIND18="event",CountSchema5,schema19;var init_emitter_shedding_load=__esm(()=>{init_zod();CountSchema5=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema19=exports_external.object({dropped_debug:CountSchema5,dropped_info:CountSchema5,spilled_warn_plus:CountSchema5,window_seconds:tagTier(exports_external.number().int().min(1).max(3600),"C")}).strict()});var exports_error_raised={};__export(exports_error_raised,{schema:()=>schema20,TYPE:()=>TYPE19,SCHEMA_VERSION:()=>SCHEMA_VERSION19,KIND:()=>KIND19});var SCHEMA_VERSION19=1,TYPE19="error.raised",KIND19="event",ErrorClassSchema,MessageSchema,StackSchema,SubsystemSchema,SeveritySchema2,RetryableSchema,schema20;var init_error_raised=__esm(()=>{init_zod();init_redactors();ErrorClassSchema=tagTier(exports_external.string().min(1).max(256),"C","exception class name"),MessageSchema=tagTier(exports_external.string().max(4096).transform(redactFreeText),"B"),StackSchema=tagTier(exports_external.string().max(16384).transform((stack)=>stack.split(`
685
685
  `).map((line)=>tokenizePath(redactFreeText(line))).join(`
686
686
  `)),"B","stack paths tokenized"),SubsystemSchema=tagTier(exports_external.string().min(1).max(128),"C"),SeveritySchema2=tagTier(exports_external.enum(["warn","error","fatal"]),"C"),RetryableSchema=tagTier(exports_external.boolean().optional(),"C"),schema20=exports_external.object({error_class:ErrorClassSchema,message:MessageSchema,stack:StackSchema.optional(),subsystem:SubsystemSchema,severity:SeveritySchema2,retryable:RetryableSchema}).strict()});var exports_executor_row_written={};__export(exports_executor_row_written,{schema:()=>schema21,TYPE:()=>TYPE20,SCHEMA_VERSION:()=>SCHEMA_VERSION20,KIND:()=>KIND20});var SCHEMA_VERSION20=1,TYPE20="executor.row.written",KIND20="event",TableSchema,RowIdSchema,OperationSchema,ExecutorSchema2,DiffSchema,schema21;var init_executor_row_written=__esm(()=>{init_zod();init_redactors();TableSchema=tagTier(exports_external.string().min(1).max(128),"C","PG table name \u2014 public"),RowIdSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("row",v)),"A"),OperationSchema=tagTier(exports_external.enum(["insert","update","delete","upsert"]),"C"),ExecutorSchema2=tagTier(exports_external.string().max(128).optional(),"C"),DiffSchema=tagTier(exports_external.record(exports_external.string(),exports_external.union([exports_external.string(),exports_external.number(),exports_external.boolean(),exports_external.null()])).default({}),"B","shallow scalar diff only \u2014 payloads never stored here"),schema21=exports_external.object({table:TableSchema,row_id:RowIdSchema,operation:OperationSchema,executor:ExecutorSchema2,before:DiffSchema,after:DiffSchema}).strict()});var exports_executor_write={};__export(exports_executor_write,{schema:()=>schema22,TYPE:()=>TYPE21,SCHEMA_VERSION:()=>SCHEMA_VERSION21,KIND:()=>KIND21});var SCHEMA_VERSION21=1,TYPE21="executor.write",KIND21="span",ExecutorSchema3,TargetSchema,TableSchema2,OperationSchema2,RowsAffectedSchema,DurationSchema3,OutcomeSchema,ErrorHintSchema,schema22;var init_executor_write=__esm(()=>{init_zod();init_redactors();ExecutorSchema3=tagTier(exports_external.enum(["claude-code","claude-sdk","codex","shell"]),"C"),TargetSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("executor_target",v)),"A","target entity hashed"),TableSchema2=tagTier(exports_external.string().max(128).optional(),"C","PG table name \u2014 public"),OperationSchema2=tagTier(exports_external.enum(["insert","update","delete","upsert","copy","truncate"]),"C"),RowsAffectedSchema=tagTier(exports_external.number().int().min(0).max(1e7).optional(),"C"),DurationSchema3=tagTier(exports_external.number().int().min(0).max(60000).optional(),"C","ms"),OutcomeSchema=tagTier(exports_external.enum(["ok","constraint_violation","timeout","error"]).optional(),"C"),ErrorHintSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B"),schema22=exports_external.object({executor:ExecutorSchema3,target:TargetSchema,table:TableSchema2,operation:OperationSchema2,rows_affected:RowsAffectedSchema,duration_ms:DurationSchema3,outcome:OutcomeSchema,error_hint:ErrorHintSchema}).strict()});var exports_hook_delivery={};__export(exports_hook_delivery,{schema:()=>schema23,TYPE:()=>TYPE22,SCHEMA_VERSION:()=>SCHEMA_VERSION22,KIND:()=>KIND22});var SCHEMA_VERSION22=1,TYPE22="hook.delivery",KIND22="span",HookNameSchema,HookEventSchema,AgentIdSchema2,ToolSchema,StatusSchema,DurationSchema4,ExitCodeSchema2,StderrExcerptSchema,schema23;var init_hook_delivery=__esm(()=>{init_zod();init_redactors();HookNameSchema=tagTier(exports_external.string().min(1).max(128),"C","hook name \u2014 public"),HookEventSchema=tagTier(exports_external.string().min(1).max(64),"C","CC hook event name \u2014 public"),AgentIdSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),ToolSchema=tagTier(exports_external.string().max(128).optional(),"C"),StatusSchema=tagTier(exports_external.enum(["ok","timeout","rejected","error"]).optional(),"C"),DurationSchema4=tagTier(exports_external.number().int().min(0).max(60000).optional(),"C","ms (<=15s timeout)"),ExitCodeSchema2=tagTier(exports_external.number().int().min(-1).max(255).optional(),"C"),StderrExcerptSchema=tagTier(exports_external.string().max(4096).transform((v)=>redactFreeText(v)).optional(),"B","redacted stderr excerpt"),schema23=exports_external.object({hook_name:HookNameSchema,agent_id:AgentIdSchema2,tool:ToolSchema,event:HookEventSchema.optional(),status:StatusSchema,duration_ms:DurationSchema4,exit_code:ExitCodeSchema2,stderr_excerpt:StderrExcerptSchema}).strict()});var exports_mailbox_delivery={};__export(exports_mailbox_delivery,{schema:()=>schema24,TYPE:()=>TYPE23,SCHEMA_VERSION:()=>SCHEMA_VERSION23,KIND:()=>KIND23});var SCHEMA_VERSION23=1,TYPE23="mailbox.delivery",KIND23="span",AgentIdSchema3=(ns)=>tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity(ns,v)),"A"),FromSchema,ToSchema,ChannelSchema,OutcomeSchema2,MessageIdSchema,BodyExcerptSchema,DurationSchema5,schema24;var init_mailbox_delivery=__esm(()=>{init_zod();init_redactors();FromSchema=tagTier(exports_external.string().max(128),"C","sender role \u2014 public"),ToSchema=tagTier(exports_external.string().max(128),"C","recipient role \u2014 public"),ChannelSchema=tagTier(exports_external.enum(["tmux","native-inbox","file","broadcast"]),"C"),OutcomeSchema2=tagTier(exports_external.enum(["delivered","queued","pane_dead","rejected","timeout"]).optional(),"C"),MessageIdSchema=AgentIdSchema3("msg").optional(),BodyExcerptSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B","first 512 chars, redacted"),DurationSchema5=tagTier(exports_external.number().int().min(0).max(60000).optional(),"C","ms"),schema24=exports_external.object({from:FromSchema,to:ToSchema,channel:ChannelSchema,outcome:OutcomeSchema2,message_id:MessageIdSchema,body_excerpt:BodyExcerptSchema,duration_ms:DurationSchema5}).strict()});var exports_notify_delivery_lag={};__export(exports_notify_delivery_lag,{schema:()=>schema25,TYPE:()=>TYPE24,SCHEMA_VERSION:()=>SCHEMA_VERSION24,KIND:()=>KIND24});var SCHEMA_VERSION24=1,TYPE24="notify.delivery.lag",KIND24="event",NonceSchema,LagMillisSchema,ChannelSchema2,schema25;var init_notify_delivery_lag=__esm(()=>{init_zod();init_redactors();NonceSchema=tagTier(exports_external.string().min(1).max(128).transform((v)=>hashEntity("notify-probe",v)),"A"),LagMillisSchema=tagTier(exports_external.number().min(0).max(300000),"C"),ChannelSchema2=tagTier(exports_external.string().min(1).max(128),"C"),schema25=exports_external.object({channel:ChannelSchema2,probe_id:NonceSchema,lag_ms:LagMillisSchema,timed_out:tagTier(exports_external.boolean(),"C")}).strict()});var exports_permissions_deny={};__export(exports_permissions_deny,{schema:()=>schema26,TYPE:()=>TYPE25,SCHEMA_VERSION:()=>SCHEMA_VERSION25,KIND:()=>KIND25});var SCHEMA_VERSION25=1,TYPE25="permissions.deny",KIND25="event",ActorSchema,AttemptedRoleSchema,ScopeSchema2,ReasonSchema5,SourceIpSchema,schema26;var init_permissions_deny=__esm(()=>{init_zod();init_redactors();ActorSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A"),AttemptedRoleSchema=tagTier(exports_external.string().min(1).max(64),"C"),ScopeSchema2=tagTier(exports_external.string().min(1).max(128),"C"),ReasonSchema5=tagTier(exports_external.enum(["token_expired","token_invalid","signature_invalid","scope_mismatch","tenant_mismatch","rate_limited","revoked","unknown"]),"C"),SourceIpSchema=tagTier(exports_external.string().max(64).transform((v)=>hashEntity("ip",v)).optional(),"A"),schema26=exports_external.object({actor:ActorSchema,attempted_role:AttemptedRoleSchema,scope:ScopeSchema2,reason:ReasonSchema5,source_ip:SourceIpSchema}).strict()});var exports_permissions_grant={};__export(exports_permissions_grant,{schema:()=>schema27,TYPE:()=>TYPE26,SCHEMA_VERSION:()=>SCHEMA_VERSION26,KIND:()=>KIND26});var SCHEMA_VERSION26=1,TYPE26="permissions.grant",KIND26="event",ActorSchema2,RoleSchema2,ScopeSchema3,ExpiresAtSchema,GrantedBySchema,schema27;var init_permissions_grant=__esm(()=>{init_zod();init_redactors();ActorSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("actor",v)),"A"),RoleSchema2=tagTier(exports_external.enum(["admin","operator","subscriber","audit"]),"C"),ScopeSchema3=tagTier(exports_external.string().min(1).max(128),"C",'e.g. "genie_events.agent.*" \u2014 public'),ExpiresAtSchema=tagTier(exports_external.string().datetime().optional(),"C"),GrantedBySchema=tagTier(exports_external.string().max(256).transform((v)=>hashEntity("actor",v)).optional(),"A"),schema27=exports_external.object({actor:ActorSchema2,role:RoleSchema2,scope:ScopeSchema3,expires_at:ExpiresAtSchema,granted_by:GrantedBySchema}).strict()});var exports_resume_attempt={};__export(exports_resume_attempt,{schema:()=>schema28,TYPE:()=>TYPE27,SCHEMA_VERSION:()=>SCHEMA_VERSION27,KIND:()=>KIND27});var SCHEMA_VERSION27=1,TYPE27="resume.attempt",KIND27="span",AgentIdSchema4,AttemptNumberSchema4,StrategySchema,SessionIdSchema2,SucceededSchema,FailureReasonSchema,DurationSchema6,schema28;var init_resume_attempt=__esm(()=>{init_zod();init_redactors();AgentIdSchema4=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),AttemptNumberSchema4=tagTier(exports_external.number().int().min(1).max(16),"C"),StrategySchema=tagTier(exports_external.enum(["tmux-attach","claude-resume-session","cold-start","session-backfill"]),"C"),SessionIdSchema2=tagTier(exports_external.string().max(128).transform((v)=>hashEntity("session",v)).optional(),"A"),SucceededSchema=tagTier(exports_external.boolean().optional(),"C"),FailureReasonSchema=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B"),DurationSchema6=tagTier(exports_external.number().int().min(0).max(300000).optional(),"C","ms"),schema28=exports_external.object({agent_id:AgentIdSchema4,attempt_number:AttemptNumberSchema4,strategy:StrategySchema,session_id:SessionIdSchema2,succeeded:SucceededSchema,failure_reason:FailureReasonSchema,duration_ms:DurationSchema6}).strict()});var exports_rot_detected={};__export(exports_rot_detected,{schema:()=>schema29,TYPE:()=>TYPE28,SCHEMA_VERSION:()=>SCHEMA_VERSION28,KIND:()=>KIND28});var SCHEMA_VERSION28=1,TYPE28="rot.detected",KIND28="event",PatternIdSchema,EntityIdSchema4,ObservedValueSchema,ObservedStateSchema,schema29;var init_rot_detected=__esm(()=>{init_zod();init_redactors();PatternIdSchema=tagTier(exports_external.string().min(1).max(128).regex(/^[a-z0-9][a-z0-9._-]*$/,"pattern_id must be kebab/dot/underscore lowercase"),"C"),EntityIdSchema4=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("entity",v)),"A"),ObservedValueSchema=tagTier(exports_external.union([exports_external.string().max(4096).transform(redactFreeText),exports_external.number().finite(),exports_external.boolean(),exports_external.null(),exports_external.array(exports_external.string().max(1024).transform(redactFreeText)).max(256),exports_external.array(exports_external.number().finite()).max(256)]),"B","evidence scalar \u2014 free text runs through redactFreeText"),ObservedStateSchema=tagTier(exports_external.record(exports_external.string().min(1).max(64).regex(/^[a-z0-9_]+$/,"observed_state key must be snake_case"),ObservedValueSchema).refine((obj)=>Object.keys(obj).length<=32,{message:"observed_state_json cannot exceed 32 keys"}),"B","per-pattern evidence record \u2014 keys documented by each detector module"),schema29=exports_external.object({pattern_id:PatternIdSchema,entity_id:EntityIdSchema4,observed_state_json:ObservedStateSchema}).strict()});var exports_rot_executor_ghost_detected={};__export(exports_rot_executor_ghost_detected,{schema:()=>schema30,TYPE:()=>TYPE29,SCHEMA_VERSION:()=>SCHEMA_VERSION29,KIND:()=>KIND29});var SCHEMA_VERSION29=1,TYPE29="rot.executor-ghost.detected",KIND29="event",ResolutionSourceSchema,EnvIdSchema,ResolvedIdSchema,AgentNameSchema,RecoveredSchema,schema30;var init_rot_executor_ghost_detected=__esm(()=>{init_zod();ResolutionSourceSchema=tagTier(exports_external.enum(["resolver","reconciler"]),"C"),EnvIdSchema=tagTier(exports_external.string().uuid(),"C"),ResolvedIdSchema=tagTier(exports_external.string().uuid(),"C"),AgentNameSchema=tagTier(exports_external.string().min(1).max(256),"C"),RecoveredSchema=tagTier(exports_external.boolean(),"C"),schema30=exports_external.object({resolution_source:ResolutionSourceSchema,env_id:EnvIdSchema,resolved_id:ResolvedIdSchema,agent_name:AgentNameSchema,recovered:RecoveredSchema}).strict()});var exports_rot_inbox_watcher_spawn_loop_detected={};__export(exports_rot_inbox_watcher_spawn_loop_detected,{schema:()=>schema31,TYPE:()=>TYPE30,SCHEMA_VERSION:()=>SCHEMA_VERSION30,KIND:()=>KIND30});var SCHEMA_VERSION30=1,TYPE30="rot.inbox-watcher-spawn-loop.detected",KIND30="event",TeamNameSchema,SessionKeySchema,FailureCountSchema,LastErrorMessageSchema,schema31;var init_rot_inbox_watcher_spawn_loop_detected=__esm(()=>{init_zod();init_redactors();TeamNameSchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>redactFreeText(v)),"C"),SessionKeySchema=tagTier(exports_external.string().min(1).max(256).transform((v)=>redactFreeText(v)),"C"),FailureCountSchema=tagTier(exports_external.number().int().min(1).max(100),"C"),LastErrorMessageSchema=tagTier(exports_external.string().min(1).max(2048).transform((v)=>redactFreeText(v)),"B","redacted error message from the final failed ensureTeamLead() call"),schema31=exports_external.object({team_name:TeamNameSchema,session_key:SessionKeySchema,failure_count:FailureCountSchema,last_error_message:LastErrorMessageSchema}).strict()});var exports_rot_team_ls_drift_detected={};__export(exports_rot_team_ls_drift_detected,{schema:()=>schema32,TYPE:()=>TYPE31,SCHEMA_VERSION:()=>SCHEMA_VERSION31,KIND:()=>KIND31});var SCHEMA_VERSION31=1,TYPE31="rot.team-ls-drift.detected",KIND31="event",DivergenceKindSchema,DivergentCountSchema,ObservedStateJsonSchema,ObservedStateJsonTruncatedSchema,schema32;var init_rot_team_ls_drift_detected=__esm(()=>{init_zod();init_redactors();DivergenceKindSchema=tagTier(exports_external.enum(["missing_in_disband","missing_in_ls","status_mismatch"]),"C"),DivergentCountSchema=tagTier(exports_external.number().int().min(1).max(1e4),"C"),ObservedStateJsonSchema=tagTier(exports_external.string().min(2).max(16384).transform((v)=>redactFreeText(v)),"B","JSON-encoded snapshot of both data sources for triage"),ObservedStateJsonTruncatedSchema=tagTier(exports_external.literal(!0).optional(),"C","set when detail was dropped to honor the observed_state_json cap"),schema32=exports_external.object({divergence_kind:DivergenceKindSchema,divergent_count:DivergentCountSchema,observed_state_json:ObservedStateJsonSchema,observed_state_json_truncated:ObservedStateJsonTruncatedSchema}).strict()});var exports_runbook_triggered={};__export(exports_runbook_triggered,{schema:()=>schema33,TYPE:()=>TYPE32,SCHEMA_VERSION:()=>SCHEMA_VERSION32,KIND:()=>KIND32});var SCHEMA_VERSION32=1,TYPE32="runbook.triggered",KIND32="event",RuleSchema,EvidenceCountSchema,CorrelationIdSchema,WindowMinutesSchema,RecommendedSqlSchema,EvidenceSummarySchema,schema33;var init_runbook_triggered=__esm(()=>{init_zod();init_redactors();RuleSchema=tagTier(exports_external.string().min(1).max(64).regex(/^R\d+$/,"rule id must be R<int>"),"C"),EvidenceCountSchema=tagTier(exports_external.number().int().min(1).max(1e6),"C"),CorrelationIdSchema=tagTier(exports_external.string().max(128).transform((v)=>hashEntity("trace",v)).optional(),"A"),WindowMinutesSchema=tagTier(exports_external.number().int().min(1).max(1440).optional(),"C"),RecommendedSqlSchema=tagTier(exports_external.string().max(4096).transform((v)=>redactFreeText(v)).optional(),"B","mitigation SQL \u2014 redacted free text"),EvidenceSummarySchema=tagTier(exports_external.string().max(1024).transform((v)=>redactFreeText(v)).optional(),"B"),schema33=exports_external.object({rule:RuleSchema,evidence_count:EvidenceCountSchema,window_minutes:WindowMinutesSchema,correlation_id:CorrelationIdSchema,recommended_sql:RecommendedSqlSchema,evidence_summary:EvidenceSummarySchema}).strict()});var exports_schema_violation={};__export(exports_schema_violation,{schema:()=>schema34,TYPE:()=>TYPE33,SCHEMA_VERSION:()=>SCHEMA_VERSION33,KIND:()=>KIND33});var SCHEMA_VERSION33=1,TYPE33="schema.violation",KIND33="event",OffendingTypeSchema2,RejectedBytesSchema,IssueSchema,schema34;var init_schema_violation=__esm(()=>{init_zod();init_redactors();OffendingTypeSchema2=tagTier(exports_external.string().min(1).max(128),"C"),RejectedBytesSchema=tagTier(exports_external.number().int().min(0).max(1048576),"C"),IssueSchema=tagTier(exports_external.object({path:exports_external.string().max(256),code:exports_external.string().max(64),message:exports_external.string().max(512).transform(redactFreeText)}),"B"),schema34=exports_external.object({offending_type:OffendingTypeSchema2,issues:tagTier(exports_external.array(IssueSchema).max(32),"B"),rejected_bytes:RejectedBytesSchema,source_subsystem:tagTier(exports_external.string().max(128).optional(),"C")}).strict()});var exports_session_id_written={};__export(exports_session_id_written,{schema:()=>schema35,TYPE:()=>TYPE34,SCHEMA_VERSION:()=>SCHEMA_VERSION34,KIND:()=>KIND34});var SCHEMA_VERSION34=1,TYPE34="session.id.written",KIND34="event",AgentIdSchema5,SessionIdSchema3,ExecutorSchema4,OriginSchema,DiffSchema2,schema35;var init_session_id_written=__esm(()=>{init_zod();init_redactors();AgentIdSchema5=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),SessionIdSchema3=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("session",v)),"A"),ExecutorSchema4=tagTier(exports_external.enum(["claude-code","claude-sdk","codex","shell"]),"C"),OriginSchema=tagTier(exports_external.enum(["spawn","resume","backfill","reconcile"]),"C"),DiffSchema2=tagTier(exports_external.record(exports_external.string(),exports_external.union([exports_external.string(),exports_external.number(),exports_external.boolean(),exports_external.null()])).default({}),"B","shallow scalar diff \u2014 session_id hashed before arriving here"),schema35=exports_external.object({agent_id:AgentIdSchema5,session_id:SessionIdSchema3,executor:ExecutorSchema4,origin:OriginSchema,before:DiffSchema2,after:DiffSchema2}).strict()});var exports_session_reconciled={};__export(exports_session_reconciled,{schema:()=>schema36,TYPE:()=>TYPE35,SCHEMA_VERSION:()=>SCHEMA_VERSION35,KIND:()=>KIND35});var SCHEMA_VERSION35=1,TYPE35="session.reconciled",KIND35="event",AgentIdSchema6,SessionIdSchema4,ReasonSchema6,DiffSchema3,schema36;var init_session_reconciled=__esm(()=>{init_zod();init_redactors();AgentIdSchema6=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),SessionIdSchema4=tagTier(exports_external.string().max(256).transform((v)=>hashEntity("session",v)),"A"),ReasonSchema6=tagTier(exports_external.enum(["transcript-discovered","stale-pg-session","idle-timeout","manual","backfill"]),"C"),DiffSchema3=tagTier(exports_external.record(exports_external.string(),exports_external.union([exports_external.string(),exports_external.number(),exports_external.boolean(),exports_external.null()])).default({}),"B"),schema36=exports_external.object({agent_id:AgentIdSchema6,old_session_id:SessionIdSchema4.optional(),new_session_id:SessionIdSchema4,reason:ReasonSchema6,before:DiffSchema3,after:DiffSchema3}).strict()});var exports_state_transition={};__export(exports_state_transition,{schema:()=>schema37,TYPE:()=>TYPE36,SCHEMA_VERSION:()=>SCHEMA_VERSION36,KIND:()=>KIND36});var SCHEMA_VERSION36=1,TYPE36="state_transition",KIND36="event",EntityKindSchema,EntityIdSchema5,FromSchema2,ToSchema2,ReasonSchema7,ActorSchema3,DiffSchema4,schema37;var init_state_transition=__esm(()=>{init_zod();init_redactors();EntityKindSchema=tagTier(exports_external.enum(["task","wish","worker","team","team_lead","group","mailbox_message"]),"C"),EntityIdSchema5=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("entity",v)),"A","entity id hashed"),FromSchema2=tagTier(exports_external.string().min(1).max(64),"C"),ToSchema2=tagTier(exports_external.string().min(1).max(64),"C"),ReasonSchema7=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B","redacted free-text"),ActorSchema3=tagTier(exports_external.string().max(128).transform((v)=>redactFreeText(v)).optional(),"B"),DiffSchema4=tagTier(exports_external.record(exports_external.string(),exports_external.union([exports_external.string(),exports_external.number(),exports_external.boolean(),exports_external.null()])).default({}),"B","shallow scalar diff only"),schema37=exports_external.object({entity_kind:EntityKindSchema,entity_id:EntityIdSchema5,from:FromSchema2,to:ToSchema2,reason:ReasonSchema7,actor:ActorSchema3,before:DiffSchema4,after:DiffSchema4}).strict()});var exports_stream_gap_detected={};__export(exports_stream_gap_detected,{schema:()=>schema38,TYPE:()=>TYPE37,SCHEMA_VERSION:()=>SCHEMA_VERSION37,KIND:()=>KIND37});var SCHEMA_VERSION37=1,TYPE37="stream.gap.detected",KIND37="event",ConsumerIdSchema2,IdSchema,CountSchema6,schema38;var init_stream_gap_detected=__esm(()=>{init_zod();init_redactors();ConsumerIdSchema2=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("consumer",v)),"A"),IdSchema=tagTier(exports_external.number().int().min(0).max(Number.MAX_SAFE_INTEGER),"C"),CountSchema6=tagTier(exports_external.number().int().min(1).max(1e7),"C"),schema38=exports_external.object({consumer_id:ConsumerIdSchema2,from_id:IdSchema,to_id:IdSchema,missing_count:CountSchema6}).strict()});var exports_team_create={};__export(exports_team_create,{schema:()=>schema39,TYPE:()=>TYPE38,SCHEMA_VERSION:()=>SCHEMA_VERSION38,KIND:()=>KIND38,DEFAULT_TIER:()=>DEFAULT_TIER5});var SCHEMA_VERSION38=1,TYPE38="team.create",KIND38="event",DEFAULT_TIER5="audit",TeamNameSchema2,WishSlugSchema,RepoPathHashSchema,ActorSchema4,MemberCountSchema,AutoSchema,schema39;var init_team_create=__esm(()=>{init_zod();init_redactors();TeamNameSchema2=tagTier(exports_external.string().min(1).max(128),"C","team name \u2014 public label"),WishSlugSchema=tagTier(exports_external.string().max(128).optional(),"C"),RepoPathHashSchema=tagTier(exports_external.string().min(1).max(1024).transform((v)=>hashEntity("repo",v)),"A"),ActorSchema4=tagTier(exports_external.string().max(256).transform((v)=>hashEntity("actor",v)),"A"),MemberCountSchema=tagTier(exports_external.number().int().min(0).max(256).optional(),"C"),AutoSchema=tagTier(exports_external.boolean().optional(),"C","true if created by auto-spawn hook"),schema39=exports_external.object({team_name:TeamNameSchema2,wish_slug:WishSlugSchema,repo_path_hash:RepoPathHashSchema,actor:ActorSchema4,member_count:MemberCountSchema,auto:AutoSchema}).strict()});var exports_team_disband={};__export(exports_team_disband,{schema:()=>schema40,TYPE:()=>TYPE39,SCHEMA_VERSION:()=>SCHEMA_VERSION39,KIND:()=>KIND39,DEFAULT_TIER:()=>DEFAULT_TIER6});var SCHEMA_VERSION39=1,TYPE39="team.disband",KIND39="event",DEFAULT_TIER6="audit",TeamNameSchema3,ActorSchema5,RemainingMembersSchema,ReasonSchema8,schema40;var init_team_disband=__esm(()=>{init_zod();init_redactors();TeamNameSchema3=tagTier(exports_external.string().min(1).max(128),"C"),ActorSchema5=tagTier(exports_external.string().max(256).transform((v)=>hashEntity("actor",v)).optional(),"A"),RemainingMembersSchema=tagTier(exports_external.number().int().min(0).max(256).optional(),"C"),ReasonSchema8=tagTier(exports_external.string().max(512).transform((v)=>redactFreeText(v)).optional(),"B"),schema40=exports_external.object({team_name:TeamNameSchema3,actor:ActorSchema5,remaining_members:RemainingMembersSchema,reason:ReasonSchema8}).strict()});var exports_tmux_pane_placed={};__export(exports_tmux_pane_placed,{schema:()=>schema41,TYPE:()=>TYPE40,SCHEMA_VERSION:()=>SCHEMA_VERSION40,KIND:()=>KIND40});var SCHEMA_VERSION40=1,TYPE40="tmux.pane.placed",KIND40="event",AgentIdSchema7,SessionSchema,WindowIndexSchema,PaneIndexSchema,PaneIdSchema,ActionSchema,schema41;var init_tmux_pane_placed=__esm(()=>{init_zod();init_redactors();AgentIdSchema7=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),SessionSchema=tagTier(exports_external.string().min(1).max(128),"C","tmux session name \u2014 public"),WindowIndexSchema=tagTier(exports_external.number().int().min(0).max(256),"C"),PaneIndexSchema=tagTier(exports_external.number().int().min(0).max(256),"C"),PaneIdSchema=tagTier(exports_external.string().max(64).optional(),"C","tmux pane id \u2014 public"),ActionSchema=tagTier(exports_external.enum(["spawn","attach","replace","split"]),"C"),schema41=exports_external.object({agent_id:AgentIdSchema7,session:SessionSchema,window_index:WindowIndexSchema,pane_index:PaneIndexSchema,pane_id:PaneIdSchema,action:ActionSchema}).strict()});var exports_wish_dispatch={};__export(exports_wish_dispatch,{schema:()=>schema42,TYPE:()=>TYPE41,SCHEMA_VERSION:()=>SCHEMA_VERSION41,KIND:()=>KIND41});var SCHEMA_VERSION41=1,TYPE41="wish.dispatch",KIND41="span",WishSlugSchema2,WaveSchema,GroupIdSchema,GroupNameSchema,ActorSchema6,OutcomeSchema3,DurationSchema7,DryRunSchema,schema42;var init_wish_dispatch=__esm(()=>{init_zod();init_redactors();WishSlugSchema2=tagTier(exports_external.string().min(1).max(128),"C","wish slug \u2014 public"),WaveSchema=tagTier(exports_external.number().int().min(0).max(32),"C"),GroupIdSchema=tagTier(exports_external.string().min(1).max(128).transform((v)=>hashEntity("group",v)),"A","group id hashed"),GroupNameSchema=tagTier(exports_external.string().max(128),"C"),ActorSchema6=tagTier(exports_external.string().max(128).transform((v)=>redactFreeText(v)).optional(),"B"),OutcomeSchema3=tagTier(exports_external.enum(["started","completed","failed","blocked"]).optional(),"C"),DurationSchema7=tagTier(exports_external.number().int().min(0).max(86400000).optional(),"C","ms"),DryRunSchema=tagTier(exports_external.boolean().optional(),"C"),schema42=exports_external.object({wish_slug:WishSlugSchema2,wave:WaveSchema.optional(),group_id:GroupIdSchema.optional(),group_name:GroupNameSchema.optional(),actor:ActorSchema6,outcome:OutcomeSchema3,duration_ms:DurationSchema7,dry_run:DryRunSchema}).strict()});function entry(mod){return{type:mod.TYPE,kind:mod.KIND,schema:mod.schema,schema_version:mod.SCHEMA_VERSION,tier_defaults:mod.DEFAULT_TIER??"default"}}function getEntry(type2){return EventRegistry[type2]??null}function isRegistered(type2){return Object.hasOwn(EventRegistry,type2)}var EventRegistry;var init_registry=__esm(()=>{init_agent_lifecycle();init_agent_resume_attempted();init_agent_resume_failed();init_agent_resume_succeeded();init_audit_export();init_audit_un_hash();init_cache_hit();init_cache_invalidate();init_cli_command();init_consumer_heartbeat();init_consumer_lagged();init_correlation_orphan_rate();init_detector_disabled();init_emit_backpressure_critical();init_emitter_latency_p99();init_emitter_queue_depth();init_emitter_rejected();init_emitter_shedding_load();init_error_raised();init_executor_row_written();init_executor_write();init_hook_delivery();init_mailbox_delivery();init_notify_delivery_lag();init_permissions_deny();init_permissions_grant();init_resume_attempt();init_rot_detected();init_rot_executor_ghost_detected();init_rot_inbox_watcher_spawn_loop_detected();init_rot_team_ls_drift_detected();init_runbook_triggered();init_schema_violation();init_session_id_written();init_session_reconciled();init_state_transition();init_stream_gap_detected();init_team_create();init_team_disband();init_tmux_pane_placed();init_wish_dispatch();EventRegistry={[TYPE9]:entry(exports_cli_command),[TYPE]:entry(exports_agent_lifecycle),[TYPE41]:entry(exports_wish_dispatch),[TYPE22]:entry(exports_hook_delivery),[TYPE27]:entry(exports_resume_attempt),[TYPE21]:entry(exports_executor_write),[TYPE23]:entry(exports_mailbox_delivery),[TYPE19]:entry(exports_error_raised),[TYPE36]:entry(exports_state_transition),[TYPE33]:entry(exports_schema_violation),[TYPE34]:entry(exports_session_id_written),[TYPE35]:entry(exports_session_reconciled),[TYPE40]:entry(exports_tmux_pane_placed),[TYPE20]:entry(exports_executor_row_written),[TYPE8]:entry(exports_cache_invalidate),[TYPE7]:entry(exports_cache_hit),[TYPE32]:entry(exports_runbook_triggered),[TYPE10]:entry(exports_consumer_heartbeat),[TYPE26]:entry(exports_permissions_grant),[TYPE25]:entry(exports_permissions_deny),[TYPE38]:entry(exports_team_create),[TYPE39]:entry(exports_team_disband),[TYPE6]:entry(exports_audit_un_hash),[TYPE5]:entry(exports_audit_export),[TYPE17]:entry(exports_emitter_rejected),[TYPE16]:entry(exports_emitter_queue_depth),[TYPE15]:entry(exports_emitter_latency_p99),[TYPE24]:entry(exports_notify_delivery_lag),[TYPE37]:entry(exports_stream_gap_detected),[TYPE12]:entry(exports_correlation_orphan_rate),[TYPE18]:entry(exports_emitter_shedding_load),[TYPE11]:entry(exports_consumer_lagged),[TYPE14]:entry(exports_emit_backpressure_critical),[TYPE13]:entry(exports_detector_disabled),[TYPE28]:entry(exports_rot_detected),[TYPE31]:entry(exports_rot_team_ls_drift_detected),[TYPE29]:entry(exports_rot_executor_ghost_detected),[TYPE30]:entry(exports_rot_inbox_watcher_spawn_loop_detected),[TYPE2]:entry(exports_agent_resume_attempted),[TYPE4]:entry(exports_agent_resume_succeeded),[TYPE3]:entry(exports_agent_resume_failed)}});var exports_emit={};__export(exports_emit,{startSpan:()=>startSpan,shutdownEmitter:()=>shutdownEmitter,resumeEmitter:()=>resumeEmitter,isSpillJournalEmpty:()=>isSpillJournalEmpty,getEmitStats:()=>getEmitStats,flushNow:()=>flushNow,endSpan:()=>endSpan,emitEvent:()=>emitEvent,drainSpillJournalNow:()=>drainSpillJournalNow,__setSpillPathForTests:()=>__setSpillPathForTests,__resetEmitForTests:()=>__resetEmitForTests,__TEST_QUEUE_CAP:()=>__TEST_QUEUE_CAP,__TEST_BACKPRESSURE_WAIT_MS:()=>__TEST_BACKPRESSURE_WAIT_MS});import{createHash as createHash2,randomUUID as randomUUID3}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync14,fsyncSync,mkdirSync as mkdirSync7,openSync,readFileSync as readFileSync10,renameSync as renameSync2,statSync as statSync2,unlinkSync as unlinkSync4}from"fs";import{homedir as homedir13}from"os";import{dirname as dirname5,join as join18}from"path";function getEmitStats(){return{...stats,queue_depth:queue.length}}function defaultSpillPath(){let home=process.env.GENIE_HOME??join18(homedir13(),".genie");return join18(home,"data","emit-spill.jsonl")}function __setSpillPathForTests(path2){spillPathOverride=path2}function spillPath(){return spillPathOverride??defaultSpillPath()}function ensureSpillDir(path2){let dir=dirname5(path2);if(!existsSync14(dir))mkdirSync7(dir,{recursive:!0})}function writeSpillRow(row){let path2=spillPath();ensureSpillDir(path2);let line=`${JSON.stringify(row)}
687
687
  `,fd=openSync(path2,"a");try{appendFileSync(fd,line);try{fsyncSync(fd)}catch{}}finally{closeSync(fd)}if(stats.spilled_warn_plus++,firstSpillAt===null)firstSpillAt=Date.now()}function countSpillRows(){let path2=spillPath();if(!existsSync14(path2))return 0;try{let contents=readFileSync10(path2,"utf8");if(!contents)return 0;return contents.split(`
@@ -2419,7 +2419,7 @@ The user's message:
2419
2419
 
2420
2420
  ---
2421
2421
 
2422
- ${initialMessage}`:turnContext,permissions=entry2.permissions?.allow?.length||entry2.permissions?.deny?.length?{allow:entry2.permissions.allow,deny:entry2.permissions.deny}:void 0;return{provider:entry2.provider??"claude",team:agentName,role:agentName,sessionId:resumeClaudeSessionId?void 0:randomUUID9(),resume:resumeClaudeSessionId,model:entry2.model,promptMode:entry2.promptMode,systemPromptFile:join53(entry2.dir,"AGENTS.md"),initialPrompt:fullInitialPrompt,skipHooks:!0,permissions,disallowedTools:entry2.disallowedTools,nativeTeam:{enabled:!0,agentName,color:entry2.color??void 0}}}class ClaudeCodeOmniExecutor{sessions=new Map;safePgCall=null;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(_fn){}async injectNudge(session,text){let paneId=session.tmux?.paneId;if(!paneId)return;let nudgeText=`[system] ${text}`;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(nudgeText)} Enter`)}async spawn(agentName,chatId,env,initialMessage){let resolved=await resolve5(agentName);if(!resolved)throw Error(`Agent "${agentName}" not found in genie directory`);let entry2=resolved.entry,tmuxSession=resolveBridgeTmuxSession(agentName,entry2.bridgeTmuxSession,env.GENIE_TMUX_SESSION),chatName=await lookupChatName(chatId,env.OMNI_INSTANCE??""),windowName=sanitizeWindowName2(chatId,chatName??void 0),{paneId,created}=await ensureTeamWindow(tmuxSession,windowName,entry2.dir),instanceId=env.OMNI_INSTANCE??"",agent=this.safePgCall?await this.safePgCall("tmux-find-or-create-agent",()=>findOrCreateAgent(`${agentName}:${chatId}`,"omni","omni"),null,{chatId}):null,existingExecutor=agent?await this.safePgCall?.("tmux-find-existing-executor",()=>findLatestByMetadata({agentId:agent.id,source:"omni",chatId}),null,{chatId})??null:null,resumeClaudeSessionId=existingExecutor?.claudeSessionId??void 0,claudeSessionId=resumeClaudeSessionId;if(created){let omniEnv={...env,GENIE_OMNI_CHAT_ID:chatId,GENIE_OMNI_AGENT:agentName},params=buildOmniSpawnParams(agentName,chatId,entry2,omniEnv,initialMessage,resumeClaudeSessionId);claudeSessionId=resumeClaudeSessionId??params.sessionId??void 0;let launch=buildLaunchCommand(params),allEnv={...omniEnv,...launch.env},envPrefix=Object.entries(allEnv).map(([k,v])=>`${k}=${shellQuote(v)}`).join(" "),cmd=envPrefix?`${envPrefix} ${launch.command}`:launch.command;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(cmd)} Enter`)}let sessionKey2=`${agentName}:${chatId}`,registration=await this.registerOrRelinkExecutor(agent,existingExecutor,chatId,instanceId,tmuxSession,windowName,paneId,entry2.dir,claudeSessionId);if(this.sessions.set(sessionKey2,{executorId:registration?.executorId??null,agentId:registration?.agentId??null,repoPath:entry2.dir}),registration?.executorId)await this.updateState(registration.executorId,"running",chatId);let now=Date.now();return{id:sessionKey2,agentName,chatId,executorType:"tmux",createdAt:now,lastActivityAt:now,tmux:{session:tmuxSession,window:windowName,paneId,claudeSessionId}}}async registerOrRelinkExecutor(agent,existingExecutor,chatId,instanceId,tmuxSession,tmuxWindow,tmuxPaneId,repoPath,claudeSessionId){if(!this.safePgCall||!agent)return null;if(await this.safePgCall("tmux-update-agent-pane",async()=>{await(await Promise.resolve().then(() => (init_db(),exports_db)).then((m)=>m.getConnection()))`
2422
+ ${initialMessage}`:turnContext,permissions=entry2.permissions?.allow?.length||entry2.permissions?.deny?.length?{allow:entry2.permissions.allow,deny:entry2.permissions.deny}:void 0;return{provider:entry2.provider??"claude",team:agentName,role:agentName,sessionId:resumeClaudeSessionId?void 0:randomUUID9(),resume:resumeClaudeSessionId,model:entry2.model,promptMode:entry2.promptMode,systemPromptFile:join53(entry2.dir,"AGENTS.md"),initialPrompt:fullInitialPrompt,skipHooks:!0,permissions,disallowedTools:entry2.disallowedTools,nativeTeam:{enabled:!0,agentName,color:entry2.color??void 0}}}function resolveOmniPaneProcessName(provider){return provider==="codex"?"codex":"claude"}class ClaudeCodeOmniExecutor{sessions=new Map;safePgCall=null;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(_fn){}async injectNudge(session,text){let paneId=session.tmux?.paneId;if(!paneId)return;let nudgeText=`[system] ${text}`;await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(nudgeText)} Enter`)}async launchOmniProcessInPane(agentName,chatId,entry2,env,paneId,initialMessage,resumeClaudeSessionId){let omniEnv={...env,GENIE_OMNI_CHAT_ID:chatId,GENIE_OMNI_AGENT:agentName},params=buildOmniSpawnParams(agentName,chatId,entry2,omniEnv,initialMessage,resumeClaudeSessionId),claudeSessionId=resumeClaudeSessionId??params.sessionId??void 0,launch=buildLaunchCommand(params),allEnv={...omniEnv,...launch.env},envPrefix=Object.entries(allEnv).map(([k,v])=>`${k}=${shellQuote(v)}`).join(" "),cmd=envPrefix?`${envPrefix} ${launch.command}`:launch.command;return await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(cmd)} Enter`),claudeSessionId}async spawn(agentName,chatId,env,initialMessage){let resolved=await resolve5(agentName);if(!resolved)throw Error(`Agent "${agentName}" not found in genie directory`);let entry2=resolved.entry,tmuxSession=resolveBridgeTmuxSession(agentName,entry2.bridgeTmuxSession,env.GENIE_TMUX_SESSION),chatName=await lookupChatName(chatId,env.OMNI_INSTANCE??""),windowName=sanitizeWindowName2(chatId,chatName??void 0),{paneId,created}=await ensureTeamWindow(tmuxSession,windowName,entry2.dir),instanceId=env.OMNI_INSTANCE??"",agent=this.safePgCall?await this.safePgCall("tmux-find-or-create-agent",()=>findOrCreateAgent(`${agentName}:${chatId}`,"omni","omni"),null,{chatId}):null,existingExecutor=agent?await this.safePgCall?.("tmux-find-existing-executor",()=>findLatestByMetadata({agentId:agent.id,source:"omni",chatId}),null,{chatId})??null:null,resumeClaudeSessionId=existingExecutor?.claudeSessionId??void 0,processName=resolveOmniPaneProcessName(entry2.provider),processRunning=!created&&await isPaneProcessRunning(paneId,processName),claudeSessionId=created||!processRunning?await this.launchOmniProcessInPane(agentName,chatId,entry2,env,paneId,initialMessage,resumeClaudeSessionId):resumeClaudeSessionId,sessionKey2=`${agentName}:${chatId}`,registration=await this.registerOrRelinkExecutor(agent,existingExecutor,chatId,instanceId,tmuxSession,windowName,paneId,entry2.dir,claudeSessionId);if(this.sessions.set(sessionKey2,{executorId:registration?.executorId??null,agentId:registration?.agentId??null,repoPath:entry2.dir}),registration?.executorId)await this.updateState(registration.executorId,"running",chatId);let now=Date.now();return{id:sessionKey2,agentName,chatId,executorType:"tmux",createdAt:now,lastActivityAt:now,tmux:{session:tmuxSession,window:windowName,paneId,claudeSessionId,processName}}}async registerOrRelinkExecutor(agent,existingExecutor,chatId,instanceId,tmuxSession,tmuxWindow,tmuxPaneId,repoPath,claudeSessionId){if(!this.safePgCall||!agent)return null;if(await this.safePgCall("tmux-update-agent-pane",async()=>{await(await Promise.resolve().then(() => (init_db(),exports_db)).then((m)=>m.getConnection()))`
2423
2423
  UPDATE agents
2424
2424
  SET pane_id = ${tmuxPaneId},
2425
2425
  session = ${tmuxSession},
@@ -2441,7 +2441,7 @@ ${initialMessage}`:turnContext,permissions=entry2.permissions?.allow?.length||en
2441
2441
 
2442
2442
  ---
2443
2443
 
2444
- [${senderName}]: ${message.content}`,paneId=session.tmux?.paneId;if(paneId&&/^%\d+$/.test(paneId)&&await isPaneAlive(paneId))try{await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(body)}`),await new Promise((resolve10)=>setTimeout(resolve10,200)),await executeTmux2(`send-keys -t '${paneId}' Enter`)}catch(err){console.error(`[claude-code] deliver: send-keys failed for ${session.id} (pane ${paneId}):`,err instanceof Error?err.message:err)}else console.error(`[claude-code] deliver: pane unavailable for ${session.id} (paneId=${paneId??"null"}), message lost`);if(session.lastActivityAt=Date.now(),state?.executorId)await this.updateState(state.executorId,"idle",session.chatId)}async shutdown(session){let state=this.sessions.get(session.id);try{if(session.tmux)await killWindow(session.tmux.session,session.tmux.window)}finally{if(state?.executorId&&this.safePgCall)await this.safePgCall("tmux-terminate-executor",()=>terminateExecutor(state.executorId),void 0,{executorId:state.executorId,chatId:session.chatId});if(state?.agentId&&this.safePgCall)await this.safePgCall("tmux-unregister-agent",()=>unregister(state.agentId),void 0,{chatId:session.chatId});this.sessions.delete(session.id)}}async isAlive(session){let paneId=session.tmux?.paneId;if(!paneId)return!1;try{if(!await isPaneAlive(paneId))return!1;return await isPaneProcessRunning(paneId,"claude")}catch{return!1}}}var init_claude_code2=__esm(()=>{init_agent_directory();init_agent_registry();init_executor_registry();init_provider_adapters();init_team_lead_command();init_tmux()});async function recordAuditEvent2(safePgCall,type2,attrs){let entityType=attrs.entity_type??"executor",entityId=attrs.entity_id??attrs.executor_id??"",actor=attrs.actor??attrs.agent_id??null,{entity_type:_et,entity_id:_eid,actor:_a,...details}=attrs;await safePgCall(`audit:${type2}`,(sql)=>sql`INSERT INTO audit_events (entity_type, entity_id, event_type, actor, details)
2444
+ [${senderName}]: ${message.content}`,paneId=session.tmux?.paneId;if(paneId&&/^%\d+$/.test(paneId)&&await isPaneAlive(paneId))try{await executeTmux2(`send-keys -t '${paneId}' ${shellQuote(body)}`),await new Promise((resolve10)=>setTimeout(resolve10,200)),await executeTmux2(`send-keys -t '${paneId}' Enter`)}catch(err){console.error(`[claude-code] deliver: send-keys failed for ${session.id} (pane ${paneId}):`,err instanceof Error?err.message:err)}else console.error(`[claude-code] deliver: pane unavailable for ${session.id} (paneId=${paneId??"null"}), message lost`);if(session.lastActivityAt=Date.now(),state?.executorId)await this.updateState(state.executorId,"idle",session.chatId)}async shutdown(session){let state=this.sessions.get(session.id);try{if(session.tmux)await killWindow(session.tmux.session,session.tmux.window)}finally{if(state?.executorId&&this.safePgCall)await this.safePgCall("tmux-terminate-executor",()=>terminateExecutor(state.executorId),void 0,{executorId:state.executorId,chatId:session.chatId});if(state?.agentId&&this.safePgCall)await this.safePgCall("tmux-unregister-agent",()=>unregister(state.agentId),void 0,{chatId:session.chatId});this.sessions.delete(session.id)}}async isAlive(session){let paneId=session.tmux?.paneId;if(!paneId)return!1;try{if(!await isPaneAlive(paneId))return!1;return await isPaneProcessRunning(paneId,session.tmux?.processName??"claude")}catch{return!1}}}var init_claude_code2=__esm(()=>{init_agent_directory();init_agent_registry();init_executor_registry();init_provider_adapters();init_team_lead_command();init_tmux()});async function recordAuditEvent2(safePgCall,type2,attrs){let entityType=attrs.entity_type??"executor",entityId=attrs.entity_id??attrs.executor_id??"",actor=attrs.actor??attrs.agent_id??null,{entity_type:_et,entity_id:_eid,actor:_a,...details}=attrs;await safePgCall(`audit:${type2}`,(sql)=>sql`INSERT INTO audit_events (entity_type, entity_id, event_type, actor, details)
2445
2445
  VALUES (${entityType}, ${entityId}, ${type2}, ${actor}, ${JSON.stringify(details)})`,void 0,{executorId:entityId,chatId:attrs.chat_id??""})}async function loadSystemPrompt(entry2){let identityPath=loadIdentity(entry2);if(!identityPath)return;let{readFileSync:readFileSync25}=await import("fs");try{return readFileSync25(identityPath,"utf-8")}catch{return}}async function resolveSystemPrompt(entry2,state){let prompt2=await loadSystemPrompt(entry2),isTurnBased=Boolean(state.env.OMNI_INSTANCE);return{prompt:prompt2,isTurnBased}}function buildTurnContextPrefix(state,message,chatId){if(!state.env.OMNI_INSTANCE)return"";return buildTurnBasedPrompt(message.sender,state.env.OMNI_INSTANCE,state.env.OMNI_CHAT??chatId)}function extractTextFromAssistant(msg){if(!msg.message)return[];return msg.message.content.filter((b2)=>b2.type==="text"&&b2.text).map((b2)=>b2.text)}async function collectQueryResult(queryMessages){let textParts=[],sessionId;try{for await(let msg of queryMessages){if(msg.type==="assistant")textParts.push(...extractTextFromAssistant(msg));if(msg.type==="result"&&msg.subtype==="success")sessionId=msg.session_id}}catch(err){if(err.name==="AbortError")return{text:""};throw err}return{text:textParts.join(`
2446
2446
  `).trim(),sessionId}}function buildReplyPayload(agent,chatId,instanceId,extra={}){return JSON.stringify({content:"",agent,chat_id:chatId,instance_id:instanceId,timestamp:new Date().toISOString(),...extra})}function resolveAction(params,env){if(params.skip)return{type:"skip",extra:{reason:params.reason},label:"Turn closed (skip)."};if(params.react)return{type:"react",extra:{react:String(params.react),message_id:env.OMNI_MESSAGE??""},label:`Reacted ${params.react} + turn closed.`};if(params.media)return{type:"media",extra:{content:params.caption?String(params.caption):params.text?String(params.text):"",media:String(params.media)},label:"Media sent + turn closed."};if(params.text)return{type:"text",extra:{content:String(params.text)},label:"Turn closed. Message delivered."};return{type:"skip",extra:{},label:"Turn closed (skip)."}}function handleDoneTool(params,env,natsPublish){let instanceId=env.OMNI_INSTANCE??"",chatId=env.OMNI_CHAT??"",agent=env.OMNI_AGENT??"",action=resolveAction(params,env);if(action.type==="skip"){if(natsPublish&&instanceId&&chatId)natsPublish(`omni.turn.done.${instanceId}.${chatId}`,JSON.stringify({action:"skip",...action.extra}));return action.label}if(!natsPublish||!instanceId||!chatId)return console.warn("[claude-sdk] No NATS publish available \u2014 reply dropped"),"Turn close attempted but NATS publish not available.";return natsPublish(`omni.reply.${instanceId}.${chatId}`,buildReplyPayload(agent,chatId,instanceId,action.extra)),action.label}function parseSendMessageInput(input){if(!input||typeof input!=="object")return{};let obj=input,recipient=typeof obj.recipient==="string"?obj.recipient:typeof obj.to==="string"?obj.to:void 0,body=typeof obj.message==="string"?obj.message:typeof obj.content==="string"?obj.content:void 0;return{recipient,body}}function createSendMessageOmniHook(env,natsPublish){return async(input)=>{let hookInput=input;if(hookInput.tool_name!=="SendMessage")return{};let{recipient,body}=parseSendMessageInput(hookInput.tool_input);if(recipient!=="omni")return{};let instanceId=env.OMNI_INSTANCE??"",chatId=env.OMNI_CHAT??"",agent=env.OMNI_AGENT??"";if(!instanceId||!chatId)return{};if(!body||body.trim()==="")return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:'SendMessage(recipient: "omni") requires a non-empty `message` field. Retry with the reply text.'}};if(!natsPublish)return console.warn("[claude-sdk] SendMessage(to: omni) intercepted but NATS publish unavailable \u2014 message dropped"),{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Omni bridge unavailable \u2014 message could not be delivered."}};return natsPublish(`omni.reply.${instanceId}.${chatId}`,buildReplyPayload(agent,chatId,instanceId,{content:body})),{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"Message delivered to user via omni bridge."}}}}async function createDoneMcpServer(env,natsPublish){let{createSdkMcpServer,tool}=await import("@anthropic-ai/claude-agent-sdk");return createSdkMcpServer({name:"genie-omni-tools",tools:[tool("done","Close this turn. REQUIRED after processing the user message. Sends a final response, reacts, or skips. Call exactly once per turn.",{text:exports_external.string().optional().describe("Final message to the user"),media:exports_external.string().optional().describe("File path for media attachment"),caption:exports_external.string().optional().describe("Caption for media"),react:exports_external.string().optional().describe("Emoji reaction (instead of text)"),skip:exports_external.boolean().optional().describe("Close turn without sending anything"),reason:exports_external.string().optional().describe("Internal reason for skipping")},async(args)=>{return{content:[{type:"text",text:handleDoneTool(args,env,natsPublish)}]}})]})}class ClaudeSdkOmniExecutor{sessions=new Map;safePgCall=null;natsPublish=null;deliveryQueues=new Map;pendingNudges=new Map;setSafePgCall(fn){this.safePgCall=fn}setNatsPublish(fn){this.natsPublish=fn}async injectNudge(session,text){if(!this.sessions.has(session.id))return;this.pendingNudges.set(session.id,text)}async spawn(agentName,chatId,env,_initialMessage){if(!await resolve5(agentName))throw Error(`Agent "${agentName}" not found in genie directory`);let provider=new ClaudeSdkProvider,abortController=new AbortController,sessionId=`${agentName}:${chatId}`,registration=await this.registerInWorldA(agentName,chatId,env.OMNI_INSTANCE??"");if(this.sessions.set(sessionId,{abortController,running:!0,provider,executorId:registration?.executorId??null,claudeSessionId:registration?.claudeSessionId,dbSessionId:null,turnIndex:0,env}),registration?.executorId)await this.updateState(registration.executorId,"running",chatId);let now=Date.now();return{id:sessionId,agentName,chatId,executorType:"sdk",createdAt:now,lastActivityAt:now,sdk:{claudeSessionId:registration?.claudeSessionId,executorId:registration?.executorId}}}async registerInWorldA(agentName,chatId,instanceId){if(!this.safePgCall)return null;let agent=await this.safePgCall("sdk-find-or-create-agent",()=>findOrCreateAgent(agentName,"omni","omni"),null,{chatId});if(!agent)return null;let existing=await this.safePgCall("sdk-find-existing-executor",()=>findLatestByMetadata({agentId:agent.id,source:"omni",chatId}),null,{chatId});if(existing)return await this.safePgCall("sdk-relink-executor",()=>relinkExecutorToAgent(existing.id,agent.id),void 0,{executorId:existing.id,chatId}),await recordAuditEvent2(this.safePgCall,"session.resumed",{executor_id:existing.id,agent_id:agentName,chat_id:chatId,claude_session_id:existing.claudeSessionId}),{executorId:existing.id,claudeSessionId:existing.claudeSessionId??void 0};let executor=await this.safePgCall("sdk-create-executor",()=>createAndLinkExecutor(agent.id,"claude","api",{claudeSessionId:void 0,metadata:{source:"omni",chat_id:chatId,instance_id:instanceId}}),null,{chatId});if(executor)await recordAuditEvent2(this.safePgCall,"session.created_fresh",{executor_id:executor.id,agent_id:agentName,chat_id:chatId});return executor?{executorId:executor.id}:null}async updateState(executorId,state,chatId){if(!this.safePgCall)return;await this.safePgCall("sdk-update-executor-state",()=>updateExecutorState(executorId,state),void 0,{executorId,chatId})}async deliver(session,message){let state=this.sessions.get(session.id);if(!state)throw Error(`No SDK session found for ${session.id}`);let current=(this.deliveryQueues.get(session.id)??Promise.resolve()).then(()=>this._processDelivery(session,state,message));this.deliveryQueues.set(session.id,current.catch(()=>{}))}async _processDelivery(session,state,message){let resolved=await resolve5(session.agentName);if(!resolved)throw Error(`Agent "${session.agentName}" not found in genie directory`);let entry2=resolved.entry,permissionConfig=resolvePermissionConfig(entry2.permissions),{prompt:systemPrompt,isTurnBased}=await resolveSystemPrompt(entry2,state);if(state.executorId)await this.updateState(state.executorId,"working",session.chatId);if(this.safePgCall)await recordAuditEvent2(this.safePgCall,"deliver.start",{executor_id:state.executorId??session.id,agent_id:session.agentName,chat_id:message.chatId,instance_id:message.instanceId});let doneMcp=await createDoneMcpServer(state.env,this.natsPublish),sendMessageHooks=isTurnBased?{PreToolUse:[{matcher:"SendMessage",hooks:[createSendMessageOmniHook(state.env,this.natsPublish)]}]}:void 0,extraOptions={abortController:state.abortController,mcpServers:{"genie-omni-tools":doneMcp},...sendMessageHooks&&{hooks:sendMessageHooks}};if(state.claudeSessionId)extraOptions.resume=state.claudeSessionId;let turnPrefix=buildTurnContextPrefix(state,message,session.chatId),queryContent=message.content,pendingNudge=this.pendingNudges.get(session.id);if(pendingNudge)queryContent=`[system] ${pendingNudge}
2447
2447
 
@@ -2501,7 +2501,7 @@ ${queryContent}`;let{messages:queryMessages}=state.provider.runQuery({agentId:se
2501
2501
  `);applyTuiStyle(),setupTuiKeybindings();try{execSync10(tuiTmux(`select-pane -t ${panes[0]}`),{stdio:"ignore"})}catch{}return{leftPane:panes[0],rightPane:panes[1]||panes[0]}}function sendTuiLaunchScript(leftPane,rightPane,workspaceRoot){let home=genieHome3(),bunPath=process.execPath||"bun",genieBin=process.argv[1]||"genie",scriptPath=join55(home,"tui-launch.sh"),logsDir=join55(home,"logs"),crashLog=join55(logsDir,"tui-crash.log"),envVars=["GENIE_TUI_PANE=left",`GENIE_TUI_RIGHT=${rightPane}`];if(workspaceRoot)envVars.push(`GENIE_TUI_WORKSPACE=${workspaceRoot}`);let content=["#!/bin/sh",`mkdir -p '${logsDir}'`,`exec 2>> '${crashLog}'`,`printf -- '--- tui-launch %s pid=%s ---\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" >&2`,`export ${envVars.join(`
2502
2502
  export `)}`,`exec ${bunPath} ${genieBin}`,""].join(`
2503
2503
  `);writeFileSync16(scriptPath,content,{mode:493});try{execSync10(tuiTmux(`send-keys -t '${leftPane}' '${scriptPath}' Enter`),{stdio:"ignore"})}catch{}}function killTuiSession(){try{execSync10(tuiTmux("kill-server"),{stdio:"ignore"})}catch{}}function listAgentSessions(){try{return execSync10(genieTmuxCmd("list-sessions -F '#{session_name}'"),{encoding:"utf-8"}).trim().split(`
2504
- `).filter(Boolean)}catch{return[]}}function isServeRunning(){let entry2=readServePid();return entry2!==null&&isProcessAlive(entry2.pid)}async function autoStartServe(){if(isStoppingLockActive()){console.log("genie serve is shutting down \u2014 skipping auto-start.");return}if(isServeRunning())return;let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie",{spawn:spawnChild}=await import("child_process");spawnChild(bunPath,[genieBin,"serve","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref();let deadline=Date.now()+15000;while(Date.now()<deadline)if(await new Promise((resolve10)=>setTimeout(resolve10,500)),isServeRunning()&&isTuiSessionReady())return;if(!isServeRunning())throw Error("genie serve failed to start within 15s. Run `genie serve` manually.")}function isTuiSessionReady(){try{return execSync10(tuiTmux(`has-session -t ${TUI_SESSION}`),{stdio:"ignore"}),!0}catch{return!1}}function ensureTuiSession(workspaceRoot){if(isTuiDisabled()){noticeTuiSkipped("session ensure");return}if(isTuiSessionReady())return;let{leftPane,rightPane}=startTuiTmuxServer();sendTuiLaunchScript(leftPane,rightPane,workspaceRoot)}async function startAgentSync(){try{let{findWorkspace:findWorkspace2,genieHome:genieHome4}=(init_workspace(),__toCommonJS(exports_workspace)),ws=findWorkspace2();if(!ws){let{join:join56}=__require("path"),configPath2=join56(genieHome4(),"config.json");return console.warn(` Agent sync: DISABLED \u2014 no workspace found from cwd or ${configPath2}`),console.warn(" Fix: `cd <workspace> && genie serve restart`, or run `genie init` to bootstrap one"),null}let{syncAgentDirectory:syncAgentDirectory2,watchAgentDirectory:watchAgentDirectory2}=await Promise.resolve().then(() => (init_agent_sync(),exports_agent_sync)),syncResult=await syncAgentDirectory2(ws.root);if(syncResult.registered.length+syncResult.updated.length>0)console.log(` Agent sync: ${syncResult.registered.length} registered, ${syncResult.updated.length} updated (workspace: ${ws.root})`);else console.log(` Agent sync: up to date (workspace: ${ws.root})`);if(syncResult.errors.length>0){console.warn(` Agent sync: ${syncResult.errors.length} error(s) \u2014 these agents were NOT registered:`);for(let e of syncResult.errors)console.warn(` ${e.name}: ${e.error}`)}let watcher2=watchAgentDirectory2(ws.root,{onSync:(name,action)=>{console.log(` [agent-watcher] ${name}: ${action}`)}});if(watcher2)console.log(" Agent watcher started (watching agents/ directory)");else console.warn(" Agent watcher: FAILED to start \u2014 new agents will not be auto-registered");return watcher2}catch(err){let msg=err instanceof Error?err.message:String(err);return console.error(` Agent sync failed: ${msg}`),null}}async function startPgserve(){console.log(" Starting pgserve...");try{let{ensurePgserve:ensurePgserve2}=await Promise.resolve().then(() => (init_db(),exports_db)),port=await ensurePgserve2();console.log(` pgserve ready on port ${port}`);try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("pgserve-owner",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` pgserve failed: ${msg}`)}}async function startScheduler(){console.log(" Starting scheduler daemon...");try{let{startDaemon:startDaemon2}=await Promise.resolve().then(() => (init_scheduler_daemon(),exports_scheduler_daemon));handles.schedulerHandle=startDaemon2(),console.log(" Scheduler started (includes event-router + inbox-watcher)");try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("scheduler",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Scheduler failed: ${msg}`)}try{let{startDerivedSignalsEngine:startDerivedSignalsEngine2}=await Promise.resolve().then(() => (init_derived_signals(),exports_derived_signals));handles.derivedSignals=await startDerivedSignalsEngine2(),console.log(" Derived-signal rule engine subscribed")}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Derived-signal engine failed: ${msg}`)}}function claimServePidOrExit(){let path3=servePidPath();mkdirSync18(genieHome3(),{recursive:!0});let startTime=getProcessStartTime(process.pid)??"unknown",payload=`${process.pid}:${startTime}`;for(let attempt=0;attempt<2;attempt++)try{let fd=openSync5(path3,"wx",420);try{writeSync2(fd,payload)}finally{closeSync5(fd)}return}catch(err){if(err.code!=="EEXIST")throw err;let existing=readServePid();if(existing&&existing.startTime!==null&&isProcessAlive(existing.pid))console.log(`genie serve already running (PID ${existing.pid})`),warnIfHookSocketMissing(),process.exit(0);forceRemoveServePid()}console.error("Could not claim serve.pid after 2 attempts \u2014 another genie serve is racing this one. "+"Wait a moment and retry, or run `genie serve status`."),process.exit(1)}function resolveServeMode(headless){let tuiDisabled=isTuiDisabled();if(tuiDisabled&&!headless)noticeTuiSkipped("serve");return{skipTui:Boolean(headless)||tuiDisabled,mode:headless?"headless":tuiDisabled?"no-tui":"full"}}async function loadBrainStartupConfig(deps){return deps.loadConfig?.()??(await Promise.resolve().then(() => (init_genie_config2(),exports_genie_config))).loadGenieConfigSync()}async function importBrainForStartup(deps){if(deps.importBrain)return deps.importBrain();return import("@khal-os/brain")}async function getBrainStartupPgPort(deps){return deps.getActivePort?.()??(await Promise.resolve().then(() => (init_db(),exports_db))).getActivePort()}function assignBrainHandles(deps,brainHandles){if(deps.setBrainHandles){deps.setBrainHandles(brainHandles);return}handles.brainHandles=brainHandles}function isMissingBrainModule(message){return message.includes("Cannot find")||message.includes("not found")||message.includes("MODULE_NOT_FOUND")}async function startBrainServer(deps,config,log2,warn){let brain=await importBrainForStartup(deps);if(!brain.startEmbeddedBrainServer)return[];let pgPort=await getBrainStartupPgPort(deps);if(!pgPort)return log2(" Brain server: pgserve not available (skipped)"),[];let resolveVaults=deps.resolveVaults??resolveBrainVaults,startVaults=deps.startVaults??startResolvedBrainVaults,resolution=await resolveVaults({brain,config,warn});if(resolution.paths.length===0)return log2(` Brain server: no ${resolution.source} brain vaults found (skipped)`),[];log2(` Starting brain server (${resolution.paths.length} ${resolution.source} vault(s))...`);let brainHandles=await startVaults(resolution,brain,pgPort,{warn,log:log2});if(assignBrainHandles(deps,brainHandles),brainHandles.length===0)log2(" Brain server: no vaults started");return brainHandles}async function startBrainServerIfEnabled(deps={}){let config=await loadBrainStartupConfig(deps),brainEmbedded=config.brain?.embedded!==!1,log2=deps.log??console.log,warn=deps.warn??console.warn;if(!brainEmbedded)return log2(" Brain server: skipped (brain.embedded=false \u2014 managed externally)"),[];try{return await startBrainServer(deps,config,log2,warn)}catch(err){let msg=err instanceof Error?err.message:String(err);if(isMissingBrainModule(msg))return[];return warn(` Brain server: failed: ${msg}`),[]}}function logAgentSessionInfo(){let sessions=listAgentSessions();if(sessions.length>0)console.log(` Agent server (-L genie): ${sessions.length} sessions`);else console.log(" Agent server (-L genie): no sessions yet (created on first spawn)")}function startTuiSessionIfEnabled(skipTui){if(skipTui)return;console.log(" Setting up TUI session...");let{leftPane,rightPane}=startTuiTmuxServer(),ws=(()=>{try{let{findWorkspace:findWorkspace2}=(init_workspace(),__toCommonJS(exports_workspace));return findWorkspace2()}catch{return null}})();sendTuiLaunchScript(leftPane,rightPane,ws?.root),console.log(" TUI server ready (session: genie-tui)")}async function startDetectorSchedulerSafely(){try{await Promise.resolve().then(() => (init_built_in(),exports_built_in));let{start:startDetectorScheduler}=await Promise.resolve().then(() => (init_detector_scheduler(),exports_detector_scheduler)),{listDetectors:listDetectors2}=await Promise.resolve().then(() => (init_detectors(),exports_detectors));handles.detectorScheduler=startDetectorScheduler();let registered=listDetectors2().map((d)=>d.id);console.log(` Detector scheduler started (measurement only, 60s \xB1 5s cadence) \u2014 registered: [${registered.join(", ")}]`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Detector scheduler: failed \u2014 ${msg}`)}}async function startExecutorReadEndpointSafely(){try{let{startExecutorReadEndpoint:startExecutorReadEndpoint2,getExecutorReadPort:getExecutorReadPort2}=await Promise.resolve().then(() => (init_executor_read(),exports_executor_read));if(await startExecutorReadEndpoint2())console.log(` Executor read endpoint ready on port ${getExecutorReadPort2()}`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Executor read endpoint: failed \u2014 ${msg}`)}}async function startOmniApprovalHandlerSafely(){try{let{startOmniApprovalHandler:startOmniApprovalHandler2}=await Promise.resolve().then(() => (init_omni_approval_handler(),exports_omni_approval_handler)),handler=await startOmniApprovalHandler2();if(handler)handles.omniApprovalHandler=handler,console.log(" Omni approval handler started")}catch{}}async function startOmniBridgeSafely(){let{OmniBridge:OmniBridge2}=await Promise.resolve().then(() => (init_omni_bridge(),exports_omni_bridge)),bridge=new OmniBridge2({natsUrl:process.env.GENIE_NATS_URL??"localhost:4222",maxConcurrent:Number(process.env.GENIE_MAX_CONCURRENT??"20"),idleTimeoutMs:Number(process.env.GENIE_IDLE_TIMEOUT_MS??"900000")});try{await bridge.start(),handles.omniBridge=bridge,console.log(" Omni bridge started")}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.GENIE_OMNI_REQUIRED==="1")console.error(` Omni bridge: FAILED \u2014 ${msg}`),process.exit(1);console.warn(` Omni bridge: degraded \u2014 ${msg}; set GENIE_OMNI_REQUIRED=1 to make this fatal`)}}async function stopSchedulerHandles(){handles.agentWatcher?.close();let schedulerHandle=handles.schedulerHandle;if(schedulerHandle){schedulerHandle.stop();try{await schedulerHandle.done}catch{}handles.schedulerHandle=null}if(handles.detectorScheduler)handles.detectorScheduler.stop(),handles.detectorScheduler=null;if(handles.derivedSignals)await handles.derivedSignals.stop().catch(()=>{}),handles.derivedSignals=null}async function stopOmniAndBrainServices(){if(handles.omniApprovalHandler)await handles.omniApprovalHandler.stop().catch(()=>{}),handles.omniApprovalHandler=null;if(handles.omniBridge)await handles.omniBridge.stop().catch(()=>{}),handles.omniBridge=null;if(Promise.resolve().then(() => (init_executor_read(),exports_executor_read)).then((m)=>m.stopExecutorReadEndpoint().catch(()=>{})),handles.brainHandles.length>0){for(let handle of handles.brainHandles)await handle.stop().catch(()=>{});handles.brainHandles=[]}}function killRegisteredServices(){try{let{killAllServices:killAllServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));killAllServices2()}catch{}}function removePgservePortLockfile(){try{let lockfilePath=join55(genieHome3(),"pgserve.port");if(existsSync44(lockfilePath))unlinkSync11(lockfilePath)}catch{}}function sigKillRegisteredServices(){try{let{getRegisteredServices:getRegisteredServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));for(let svc of getRegisteredServices2())try{process.kill(svc.pid,"SIGKILL")}catch{}}catch{}}async function startHookSocketSafely(){try{let{startHookSocket:startHookSocket2}=await Promise.resolve().then(() => (init_hook_socket(),exports_hook_socket));handles.hookSocket=await startHookSocket2()}catch(err){console.warn(` Hook socket: DISABLED \u2014 ${err.message}`),handles.hookSocket=null}}async function stopHookSocketSafely(){if(!handles.hookSocket)return;try{await handles.hookSocket.stop()}catch{}handles.hookSocket=null}function buildShutdownFn(headless){let shutdownStarted=!1;return{shutdown:async()=>{if(shutdownStarted)return;if(shutdownStarted=!0,console.log(`
2504
+ `).filter(Boolean)}catch{return[]}}function isServeRunning(){let entry2=readServePid();return entry2!==null&&isProcessAlive(entry2.pid)}async function autoStartServe(){if(isStoppingLockActive()){console.log("genie serve is shutting down \u2014 skipping auto-start.");return}if(isServeRunning())return;let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie",{spawn:spawnChild}=await import("child_process");spawnChild(bunPath,[genieBin,"serve","--foreground"],{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1"}}).unref();let deadline=Date.now()+15000;while(Date.now()<deadline)if(await new Promise((resolve10)=>setTimeout(resolve10,500)),isServeRunning()&&isTuiSessionReady())return;if(!isServeRunning())throw Error("genie serve failed to start within 15s. Run `genie serve` manually.")}function isTuiSessionReady(){try{return execSync10(tuiTmux(`has-session -t ${TUI_SESSION}`),{stdio:"ignore"}),!0}catch{return!1}}function ensureTuiSession(workspaceRoot){if(isTuiDisabled()){noticeTuiSkipped("session ensure");return}if(isTuiSessionReady())return;let{leftPane,rightPane}=startTuiTmuxServer();sendTuiLaunchScript(leftPane,rightPane,workspaceRoot)}async function startAgentSync(){try{let{findWorkspace:findWorkspace2,genieHome:genieHome4}=(init_workspace(),__toCommonJS(exports_workspace)),ws=findWorkspace2();if(!ws){let{join:join56}=__require("path"),configPath2=join56(genieHome4(),"config.json");return console.warn(` Agent sync: DISABLED \u2014 no workspace found from cwd or ${configPath2}`),console.warn(" Fix: `cd <workspace> && genie serve restart`, or run `genie init` to bootstrap one"),null}let{syncAgentDirectory:syncAgentDirectory2,watchAgentDirectory:watchAgentDirectory2}=await Promise.resolve().then(() => (init_agent_sync(),exports_agent_sync)),syncResult=await syncAgentDirectory2(ws.root);if(syncResult.registered.length+syncResult.updated.length>0)console.log(` Agent sync: ${syncResult.registered.length} registered, ${syncResult.updated.length} updated (workspace: ${ws.root})`);else console.log(` Agent sync: up to date (workspace: ${ws.root})`);if(syncResult.errors.length>0){console.warn(` Agent sync: ${syncResult.errors.length} error(s) \u2014 these agents were NOT registered:`);for(let e of syncResult.errors)console.warn(` ${e.name}: ${e.error}`)}let watcher2=watchAgentDirectory2(ws.root,{onSync:(name,action)=>{console.log(` [agent-watcher] ${name}: ${action}`)}});if(watcher2)console.log(" Agent watcher started (watching agents/ directory)");else console.warn(" Agent watcher: FAILED to start \u2014 new agents will not be auto-registered");return watcher2}catch(err){let msg=err instanceof Error?err.message:String(err);return console.error(` Agent sync failed: ${msg}`),null}}async function startPgserve(){console.log(" Starting pgserve...");try{let{ensurePgserve:ensurePgserve2}=await Promise.resolve().then(() => (init_db(),exports_db)),port=await ensurePgserve2();console.log(` pgserve ready on port ${port}`);try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("pgserve-owner",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` pgserve failed: ${msg}`),process.env.GENIE_PG_NO_AUTOSTART="1",console.error(" pgserve retries disabled for this serve process; fix pgserve and restart `genie serve`.")}}async function startScheduler(){console.log(" Starting scheduler daemon...");try{let{startDaemon:startDaemon2}=await Promise.resolve().then(() => (init_scheduler_daemon(),exports_scheduler_daemon));handles.schedulerHandle=startDaemon2(),console.log(" Scheduler started (includes event-router + inbox-watcher)");try{let{registerService:registerService2}=await Promise.resolve().then(() => (init_service_registry(),exports_service_registry));registerService2("scheduler",process.pid)}catch{}}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Scheduler failed: ${msg}`)}try{let{startDerivedSignalsEngine:startDerivedSignalsEngine2}=await Promise.resolve().then(() => (init_derived_signals(),exports_derived_signals));handles.derivedSignals=await startDerivedSignalsEngine2(),console.log(" Derived-signal rule engine subscribed")}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(` Derived-signal engine failed: ${msg}`)}}function claimServePidOrExit(){let path3=servePidPath();mkdirSync18(genieHome3(),{recursive:!0});let startTime=getProcessStartTime(process.pid)??"unknown",payload=`${process.pid}:${startTime}`;for(let attempt=0;attempt<2;attempt++)try{let fd=openSync5(path3,"wx",420);try{writeSync2(fd,payload)}finally{closeSync5(fd)}return}catch(err){if(err.code!=="EEXIST")throw err;let existing=readServePid();if(existing&&existing.startTime!==null&&isProcessAlive(existing.pid))console.log(`genie serve already running (PID ${existing.pid})`),warnIfHookSocketMissing(),process.exit(0);forceRemoveServePid()}console.error("Could not claim serve.pid after 2 attempts \u2014 another genie serve is racing this one. "+"Wait a moment and retry, or run `genie serve status`."),process.exit(1)}function resolveServeMode(headless){let tuiDisabled=isTuiDisabled();if(tuiDisabled&&!headless)noticeTuiSkipped("serve");return{skipTui:Boolean(headless)||tuiDisabled,mode:headless?"headless":tuiDisabled?"no-tui":"full"}}async function loadBrainStartupConfig(deps){return deps.loadConfig?.()??(await Promise.resolve().then(() => (init_genie_config2(),exports_genie_config))).loadGenieConfigSync()}async function importBrainForStartup(deps){if(deps.importBrain)return deps.importBrain();return import("@khal-os/brain")}async function getBrainStartupPgPort(deps){return deps.getActivePort?.()??(await Promise.resolve().then(() => (init_db(),exports_db))).getActivePort()}function assignBrainHandles(deps,brainHandles){if(deps.setBrainHandles){deps.setBrainHandles(brainHandles);return}handles.brainHandles=brainHandles}function isMissingBrainModule(message){return message.includes("Cannot find")||message.includes("not found")||message.includes("MODULE_NOT_FOUND")}async function startBrainServer(deps,config,log2,warn){let brain=await importBrainForStartup(deps);if(!brain.startEmbeddedBrainServer)return[];let pgPort=await getBrainStartupPgPort(deps);if(!pgPort)return log2(" Brain server: pgserve not available (skipped)"),[];let resolveVaults=deps.resolveVaults??resolveBrainVaults,startVaults=deps.startVaults??startResolvedBrainVaults,resolution=await resolveVaults({brain,config,warn});if(resolution.paths.length===0)return log2(` Brain server: no ${resolution.source} brain vaults found (skipped)`),[];log2(` Starting brain server (${resolution.paths.length} ${resolution.source} vault(s))...`);let brainHandles=await startVaults(resolution,brain,pgPort,{warn,log:log2});if(assignBrainHandles(deps,brainHandles),brainHandles.length===0)log2(" Brain server: no vaults started");return brainHandles}async function startBrainServerIfEnabled(deps={}){let config=await loadBrainStartupConfig(deps),brainEmbedded=config.brain?.embedded!==!1,log2=deps.log??console.log,warn=deps.warn??console.warn;if(!brainEmbedded)return log2(" Brain server: skipped (brain.embedded=false \u2014 managed externally)"),[];try{return await startBrainServer(deps,config,log2,warn)}catch(err){let msg=err instanceof Error?err.message:String(err);if(isMissingBrainModule(msg))return[];return warn(` Brain server: failed: ${msg}`),[]}}function logAgentSessionInfo(){let sessions=listAgentSessions();if(sessions.length>0)console.log(` Agent server (-L genie): ${sessions.length} sessions`);else console.log(" Agent server (-L genie): no sessions yet (created on first spawn)")}function startTuiSessionIfEnabled(skipTui){if(skipTui)return;console.log(" Setting up TUI session...");let{leftPane,rightPane}=startTuiTmuxServer(),ws=(()=>{try{let{findWorkspace:findWorkspace2}=(init_workspace(),__toCommonJS(exports_workspace));return findWorkspace2()}catch{return null}})();sendTuiLaunchScript(leftPane,rightPane,ws?.root),console.log(" TUI server ready (session: genie-tui)")}async function startDetectorSchedulerSafely(){try{await Promise.resolve().then(() => (init_built_in(),exports_built_in));let{start:startDetectorScheduler}=await Promise.resolve().then(() => (init_detector_scheduler(),exports_detector_scheduler)),{listDetectors:listDetectors2}=await Promise.resolve().then(() => (init_detectors(),exports_detectors));handles.detectorScheduler=startDetectorScheduler();let registered=listDetectors2().map((d)=>d.id);console.log(` Detector scheduler started (measurement only, 60s \xB1 5s cadence) \u2014 registered: [${registered.join(", ")}]`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Detector scheduler: failed \u2014 ${msg}`)}}async function startExecutorReadEndpointSafely(){try{let{startExecutorReadEndpoint:startExecutorReadEndpoint2,getExecutorReadPort:getExecutorReadPort2}=await Promise.resolve().then(() => (init_executor_read(),exports_executor_read));if(await startExecutorReadEndpoint2())console.log(` Executor read endpoint ready on port ${getExecutorReadPort2()}`)}catch(err){let msg=err instanceof Error?err.message:String(err);console.warn(` Executor read endpoint: failed \u2014 ${msg}`)}}async function startOmniApprovalHandlerSafely(){try{let{startOmniApprovalHandler:startOmniApprovalHandler2}=await Promise.resolve().then(() => (init_omni_approval_handler(),exports_omni_approval_handler)),handler=await startOmniApprovalHandler2();if(handler)handles.omniApprovalHandler=handler,console.log(" Omni approval handler started")}catch{}}async function startOmniBridgeSafely(){let{OmniBridge:OmniBridge2}=await Promise.resolve().then(() => (init_omni_bridge(),exports_omni_bridge)),bridge=new OmniBridge2({natsUrl:process.env.GENIE_NATS_URL??"localhost:4222",maxConcurrent:Number(process.env.GENIE_MAX_CONCURRENT??"20"),idleTimeoutMs:Number(process.env.GENIE_IDLE_TIMEOUT_MS??"900000")});try{await bridge.start(),handles.omniBridge=bridge,console.log(" Omni bridge started")}catch(err){let msg=err instanceof Error?err.message:String(err);if(process.env.GENIE_OMNI_REQUIRED==="1")console.error(` Omni bridge: FAILED \u2014 ${msg}`),process.exit(1);console.warn(` Omni bridge: degraded \u2014 ${msg}; set GENIE_OMNI_REQUIRED=1 to make this fatal`)}}async function stopSchedulerHandles(){handles.agentWatcher?.close();let schedulerHandle=handles.schedulerHandle;if(schedulerHandle){schedulerHandle.stop();try{await schedulerHandle.done}catch{}handles.schedulerHandle=null}if(handles.detectorScheduler)handles.detectorScheduler.stop(),handles.detectorScheduler=null;if(handles.derivedSignals)await handles.derivedSignals.stop().catch(()=>{}),handles.derivedSignals=null}async function stopOmniAndBrainServices(){if(handles.omniApprovalHandler)await handles.omniApprovalHandler.stop().catch(()=>{}),handles.omniApprovalHandler=null;if(handles.omniBridge)await handles.omniBridge.stop().catch(()=>{}),handles.omniBridge=null;if(Promise.resolve().then(() => (init_executor_read(),exports_executor_read)).then((m)=>m.stopExecutorReadEndpoint().catch(()=>{})),handles.brainHandles.length>0){for(let handle of handles.brainHandles)await handle.stop().catch(()=>{});handles.brainHandles=[]}}function killRegisteredServices(){try{let{killAllServices:killAllServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));killAllServices2()}catch{}}function removePgservePortLockfile(){try{let lockfilePath=join55(genieHome3(),"pgserve.port");if(existsSync44(lockfilePath))unlinkSync11(lockfilePath)}catch{}}function sigKillRegisteredServices(){try{let{getRegisteredServices:getRegisteredServices2}=(init_service_registry(),__toCommonJS(exports_service_registry));for(let svc of getRegisteredServices2())try{process.kill(svc.pid,"SIGKILL")}catch{}}catch{}}async function startHookSocketSafely(){try{let{startHookSocket:startHookSocket2}=await Promise.resolve().then(() => (init_hook_socket(),exports_hook_socket));handles.hookSocket=await startHookSocket2()}catch(err){console.warn(` Hook socket: DISABLED \u2014 ${err.message}`),handles.hookSocket=null}}async function stopHookSocketSafely(){if(!handles.hookSocket)return;try{await handles.hookSocket.stop()}catch{}handles.hookSocket=null}function buildShutdownFn(headless){let shutdownStarted=!1;return{shutdown:async()=>{if(shutdownStarted)return;if(shutdownStarted=!0,console.log(`
2505
2505
  Shutting down genie serve...`),await stopHookSocketSafely(),await stopSchedulerHandles(),await stopOmniAndBrainServices(),killRegisteredServices(),!headless)killTuiSession();removePgservePortLockfile(),removeServePid(),console.log("genie serve stopped.")},hasStarted:()=>shutdownStarted}}function installGracefulExitHandlers(shutdown2,hasStarted){let gracefulExit=(exitCode)=>{if(hasStarted())return;let forceTimer=setTimeout(()=>{console.error("Graceful shutdown timeout (10s). Force-killing remaining processes."),sigKillRegisteredServices(),removeServePid(),process.exit(1)},1e4);forceTimer.unref(),shutdown2().catch(()=>{}).finally(()=>{clearTimeout(forceTimer),removeServePid(),process.exit(exitCode)})};process.on("SIGTERM",()=>gracefulExit(143)),process.on("SIGINT",()=>gracefulExit(130)),process.on("SIGHUP",()=>gracefulExit(129)),process.on("exit",()=>{removeServePid()}),process.on("uncaughtException",(err)=>{console.error("Uncaught exception in genie serve:",err),gracefulExit(1)})}function writeStartupStatus(status){let statusPath=process.env.GENIE_SERVE_STARTUP_STATUS;if(!statusPath)return;try{mkdirSync18(dirname14(statusPath),{recursive:!0}),writeFileSync16(statusPath,`${JSON.stringify(status)}
2506
2506
  `,"utf-8")}catch{}}function readStartupStatus(statusPath){try{let parsed=JSON.parse(readFileSync26(statusPath,"utf-8"));if(typeof parsed.ok!=="boolean")return null;return{ok:parsed.ok,code:typeof parsed.code==="number"?parsed.code:void 0,lines:Array.isArray(parsed.lines)?parsed.lines.filter((line)=>typeof line==="string"):void 0}}catch{return null}}async function waitForStartupStatus(statusPath,childPid,timeoutMs){let deadline=Date.now()+timeoutMs;while(Date.now()<deadline){let status=readStartupStatus(statusPath);if(status)return status;if(!isProcessAlive(childPid))return{ok:!1,code:1};await new Promise((resolve10)=>setTimeout(resolve10,100))}return null}function exitBackgroundStartFailed(){console.error("Error: genie serve exited immediately."),process.exit(1)}function exitStartupStatusFailure(status){for(let line of status.lines??[])console.error(line);process.exit(status.code??1)}function exitStartupStatusMissing(childPid){console.error("Error: genie serve did not report startup precondition status within 16s.");try{process.kill(childPid,"SIGTERM")}catch{}process.exit(1)}async function confirmBackgroundStarted(childPid,startupStatusPath){if(startupStatusPath){let status=await waitForStartupStatus(startupStatusPath,childPid,16000);if(forceRemovePath(startupStatusPath),status?.ok===!1)exitStartupStatusFailure(status);if(status?.ok!==!0)exitStartupStatusMissing(childPid);if(!isProcessAlive(childPid))exitBackgroundStartFailed();console.log(`genie serve started (PID ${childPid})`);return}if(await new Promise((resolve10)=>setTimeout(resolve10,1000)),!isProcessAlive(childPid))exitBackgroundStartFailed();console.log(`genie serve started (PID ${childPid})`)}async function startForeground(headless,autoFix=!0){claimServePidOrExit(),removePgservePortLockfile();let{skipTui,mode}=resolveServeMode(headless);process.env.GENIE_IS_DAEMON="1",console.log(`genie serve starting (PID ${process.pid}, mode: ${mode})`);let preconditionLines=[],preconditionLog=process.env.GENIE_SERVE_STARTUP_STATUS?(line)=>{preconditionLines.push(line),console.log(line)}:void 0;try{if(!await runStartPreconditions(autoFix,preconditionLog))writeStartupStatus({ok:!1,code:2,lines:preconditionLines}),removeServePid(),process.exit(2)}catch(err){let msg=err instanceof Error?err.message:String(err);console.error(`genie serve start preconditions failed: ${msg}`),writeStartupStatus({ok:!1,code:1,lines:[...preconditionLines,`genie serve start preconditions failed: ${msg}`]}),removeServePid(),process.exit(1)}if(writeStartupStatus({ok:!0}),!skipTui)await ensureTmux();if(await startPgserve(),await startBrainServerIfEnabled(),!headless)logAgentSessionInfo();handles.agentWatcher=await startAgentSync(),startTuiSessionIfEnabled(skipTui),await startScheduler(),await startDetectorSchedulerSafely(),await startExecutorReadEndpointSafely(),await startOmniApprovalHandlerSafely(),await startOmniBridgeSafely(),await startHookSocketSafely(),console.log(`
2507
2507
  genie serve is running (${mode}). ${headless?"Send SIGTERM to stop.":"Press Ctrl+C to stop."}`);let{shutdown:shutdown2,hasStarted}=buildShutdownFn(headless);if(installGracefulExitHandlers(shutdown2,hasStarted),handles.schedulerHandle)await handles.schedulerHandle.done;else await new Promise(()=>{});removeServePid()}async function startBackground(headless,autoFix=!0){let existingEntry=readServePid();if(existingEntry&&isProcessAlive(existingEntry.pid))console.log(`genie serve already running (PID ${existingEntry.pid})`),process.exit(0);if(existingEntry)forceRemoveServePid();let bunPath=process.execPath??"bun",genieBin=process.argv[1]??"genie",startupStatusPath=autoFix?void 0:serveStartupStatusPath(),args=[genieBin,"serve","--foreground"];if(headless)args.push("--headless");if(!autoFix)args.push("--no-fix");let child=spawn4(bunPath,args,{detached:!0,stdio:"ignore",env:{...process.env,GENIE_IS_DAEMON:"1",...startupStatusPath?{GENIE_SERVE_STARTUP_STATUS:startupStatusPath}:{}}});if(child.unref(),child.pid)await confirmBackgroundStarted(child.pid,startupStatusPath);else console.error("Error: failed to spawn genie serve"),process.exit(1)}function forceRemoveServePid(){forceRemovePath(servePidPath())}function forceRemovePath(path3){try{unlinkSync11(path3)}catch{}}async function stopServe(){let entry2=readServePid();if(!entry2){console.log("genie serve is not running (no PID file).");return}writeStoppingLockSync();try{let pid=entry2.pid;if(!isProcessAlive(pid)){console.log(`Stale PID file (PID ${pid} not running). Cleaning up.`),forceRemoveServePid(),killTuiSession();return}console.log(`Stopping genie serve (PID ${pid})...`);try{process.kill(-pid,"SIGTERM")}catch{try{process.kill(pid,"SIGTERM")}catch{}}let deadline=Date.now()+1e4;while(Date.now()<deadline&&isProcessAlive(pid))await new Promise((resolve10)=>setTimeout(resolve10,250));if(isProcessAlive(pid)){console.log("Did not stop within 10s. Sending SIGKILL.");try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}killTuiSession(),forceRemoveServePid(),console.log("genie serve stopped.")}finally{clearStoppingLock()}}async function printPgserveHealth(){try{let{isAvailable:isAvailable2,getActivePort:getActivePort2}=await Promise.resolve().then(() => (init_db(),exports_db)),dbOk=await isAvailable2();console.log(` pgserve: ${dbOk?`healthy (port ${getActivePort2()})`:"unreachable"}`)}catch{console.log(" pgserve: unavailable")}}function hookSocketPath(){return process.env.GENIE_HOOK_SOCK??join55(genieHome3(),"hook.sock")}function warnIfHookSocketMissing(){let sock=hookSocketPath();if(existsSync44(sock))return;let lines=[` WARNING: hook UDS not found at ${sock}.`," Daemon-mode hook dispatch is INACTIVE \u2014 every hook will fall back"," to the legacy F1 bun-fork path (hookify-perf-foundation gains lost)."," Remediation: `genie serve stop && genie serve start` to refresh the"," daemon and re-create the socket."];console.warn(lines.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@automagik/genie",
3
- "version": "4.260429.24",
3
+ "version": "4.260429.26",
4
4
  "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: the npm distribution is being soft-deprecated — the canonical install is `curl -fsSL https://get.automagik.dev/genie | bash` (cosign + SLSA verified). See https://automagik.dev/genie/security/distribution-sovereignty",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "genie",
3
- "version": "4.260429.24",
3
+ "version": "4.260429.26",
4
4
  "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.",
5
5
  "author": {
6
6
  "name": "Namastex Labs"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "genie-plugin",
3
- "version": "4.260429.24",
3
+ "version": "4.260429.26",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for genie bundled CLIs",
6
6
  "type": "module",