@automagik/genie 4.260421.23 → 4.260421.25
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
|
@@ -51,12 +51,12 @@ ${content}`;if(params.extraArgs){let fileIdx=params.extraArgs.indexOf("--append-
|
|
|
51
51
|
${readFileSync5(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(fileIdx,2)}writeFileSync5(promptFile,content);let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(promptFile))}else if(params.systemPromptFile){let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(params.systemPromptFile))}}function appendOtelEnv(env,params){if(!params.otelPort||process.env.OTEL_EXPORTER_OTLP_ENDPOINT)return;if(env.CLAUDE_CODE_ENABLE_TELEMETRY="1",env.OTEL_LOGS_EXPORTER="otlp",env.OTEL_METRICS_EXPORTER="otlp",env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",env.OTEL_EXPORTER_OTLP_ENDPOINT=`http://127.0.0.1:${params.otelPort}`,env.OTEL_LOG_TOOL_DETAILS="1",params.otelLogPrompts!==!1)env.OTEL_LOG_USER_PROMPTS="1";let resourceParts=[];if(params.role)resourceParts.push(`agent.name=${params.role}`);if(params.team)resourceParts.push(`team.name=${params.team}`);if(params.otelWishSlug)resourceParts.push(`wish.slug=${params.otelWishSlug}`);if(params.role)resourceParts.push(`agent.role=${params.role}`);if(resourceParts.length>0)env.OTEL_RESOURCE_ATTRIBUTES=resourceParts.join(",")}function appendTraceContext(parts,env,params){let ctx=getAmbient();if(params.initialPrompt){let prompt=ctx?injectPromptPreamble(params.initialPrompt,ctx):params.initialPrompt;parts.push(escapeShellArg2(prompt))}if(ctx)env[TRACE_ENV_VAR]=mintToken(ctx),env[TRACE_ID_ENV_VAR]=ctx.trace_id}function buildClaudeCommand(params){preflightCheck("claude");let parts=[resolveShellBinary("claude")??"claude","--dangerously-skip-permissions"],env={};if(env.GENIE_WORKER="1",params.role)env.GENIE_AGENT_NAME=params.role;if(params.team)env.GENIE_TEAM=params.team;if(params.executorId)env.GENIE_EXECUTOR_ID=params.executorId;if(params.agentId)env.GENIE_AGENT_ID=params.agentId;if(appendOtelEnv(env,params),params.nativeTeam?.enabled)appendNativeTeamFlags(parts,env,params.nativeTeam,params);if(params.resume)parts.push("--resume",escapeShellArg2(params.resume));else if(params.sessionId)parts.push("--session-id",escapeShellArg2(params.sessionId));if(params.role)parts.push("--agent",escapeShellArg2(params.role));if(params.model)parts.push("--model",escapeShellArg2(params.model));if(params.name)parts.push("--name",escapeShellArg2(params.name));appendSystemPromptFlags(parts,params);let settingsObj={};if(!params.skipHooks){let hookEntry={type:"command",command:buildDispatchCommand(),timeout:15};settingsObj.hooks={PreToolUse:[{matcher:"*",hooks:[hookEntry]}],PostToolUse:[{matcher:"*",hooks:[hookEntry]}],UserPromptSubmit:[{hooks:[hookEntry]}],Stop:[{hooks:[hookEntry]}]}}if(params.permissions){let perms={};if(params.permissions.allow?.length)perms.allow=params.permissions.allow;if(params.permissions.deny?.length)perms.deny=params.permissions.deny;if(Object.keys(perms).length>0)settingsObj.permissions=perms}if(Object.keys(settingsObj).length>0)parts.push("--settings",escapeShellArg2(JSON.stringify(settingsObj)));if(params.disallowedTools?.length)for(let tool of params.disallowedTools)parts.push("--disallowedTools",escapeShellArg2(tool));if(params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));return appendTraceContext(parts,env,params),{command:parts.join(" "),provider:"claude",env:Object.keys(env).length>0?env:void 0,meta:{role:params.role,skill:params.skill}}}function buildCodexCommand(params){preflightCheck("codex");let parts=["codex"],env={};if(params.executorId)env.GENIE_EXECUTOR_ID=params.executorId;if(params.agentId)env.GENIE_AGENT_ID=params.agentId;if(params.role)env.GENIE_AGENT_NAME=params.role;if(params.team)env.GENIE_TEAM=params.team;if(parts.push("--yolo"),parts.push("--no-alt-screen"),params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg));let promptParts=[`Genie worker. Team: ${params.team}.`];if(params.role)promptParts.push(`Role: ${params.role}.`);if(params.skill)promptParts.push(`Execute the ${params.skill} skill instructions.`);let prompt=promptParts.join(" ");return parts.push(escapeShellArg2(prompt)),{command:parts.join(" "),provider:"codex",env:Object.keys(env).length>0?env:void 0,meta:{role:params.role,skill:params.skill}}}function buildLaunchCommand(params){let validated=validateSpawnParams(params);switch(validated.provider){case"claude":return buildClaudeCommand(validated);case"codex":return buildCodexCommand(validated);case"claude-sdk":return{command:"claude-sdk-in-process",provider:"claude-sdk",meta:{role:validated.role,skill:validated.skill}};default:throw Error(`Unknown provider "${validated.provider}". Valid providers: claude, codex, claude-sdk`)}}var CLAUDE_TEAM_COLORS,spawnParamsSchema;var init_provider_adapters=__esm(()=>{init_zod();init_inject();init_trace_context();CLAUDE_TEAM_COLORS=["red","blue","green","yellow","purple","orange","pink","cyan"],spawnParamsSchema=exports_external.object({provider:exports_external.enum(["claude","codex","claude-sdk","app-pty"]),team:exports_external.string().min(1,"Team name is required"),role:exports_external.string().optional(),skill:exports_external.string().optional(),agentId:exports_external.string().optional(),executorId:exports_external.string().uuid().optional(),extraArgs:exports_external.array(exports_external.string()).optional(),nativeTeam:exports_external.object({enabled:exports_external.boolean(),parentSessionId:exports_external.string().optional(),color:exports_external.string().optional(),agentType:exports_external.string().optional(),planModeRequired:exports_external.boolean().optional(),permissionMode:exports_external.string().optional(),agentName:exports_external.string().optional()}).optional(),sessionId:exports_external.string().uuid().optional(),resume:exports_external.string().optional(),systemPromptFile:exports_external.string().optional(),systemPrompt:exports_external.string().optional(),promptMode:exports_external.enum(["system","append"]).optional(),model:exports_external.string().optional(),initialPrompt:exports_external.string().optional(),name:exports_external.string().optional(),otelPort:exports_external.number().optional(),otelLogPrompts:exports_external.boolean().optional(),otelWishSlug:exports_external.string().optional(),newWindow:exports_external.boolean().optional(),windowTarget:exports_external.string().optional()})});var exports_audit={};__export(exports_audit,{recordAuditEvent:()=>recordAuditEvent,queryToolUsage:()=>queryToolUsage,queryTimeline:()=>queryTimeline,querySummary:()=>querySummary,queryErrorPatterns:()=>queryErrorPatterns,queryCostBreakdown:()=>queryCostBreakdown,queryAuditEvents:()=>queryAuditEvents,getActor:()=>getActor,generateTraceId:()=>generateTraceId,followAuditEvents:()=>followAuditEvents});async function recordAuditEvent(entityType,entityId,eventType,actor,details){try{if(!await isAvailable())return;let sql=await getConnection();await sql`
|
|
52
52
|
INSERT INTO audit_events (entity_type, entity_id, event_type, actor, details)
|
|
53
53
|
VALUES (${entityType}, ${entityId}, ${eventType}, ${actor??null}, ${sql.json(details??{})})
|
|
54
|
-
`}catch{}}function parseSince(since){let match=since.match(/^(\d+)([smhd])$/);if(!match)return since;let amount=Number.parseInt(match[1],10),unit=match[2],ms={s:1000,m:60000,h:3600000,d:86400000}[unit]??3600000;return new Date(Date.now()-amount*ms).toISOString()}async function queryAuditEvents(options={}){let sql=await getConnection(),conditions=[],values=[],paramIdx=1;if(options.type)conditions.push(`event_type = $${paramIdx
|
|
54
|
+
`}catch{}}function parseSince(since){let match=since.match(/^(\d+)([smhd])$/);if(!match)return since;let amount=Number.parseInt(match[1],10),unit=match[2],ms={s:1000,m:60000,h:3600000,d:86400000}[unit]??3600000;return new Date(Date.now()-amount*ms).toISOString()}async function queryAuditEvents(options={}){let sql=await getConnection(),conditions=[],values=[],paramIdx=1;if(options.type)conditions.push(`(event_type = $${paramIdx} OR entity_type = $${paramIdx})`),paramIdx++,values.push(options.type);if(options.entity)conditions.push(`(entity_type = $${paramIdx} OR entity_id = $${paramIdx})`),paramIdx++,values.push(options.entity);if(options.since)conditions.push(`created_at >= $${paramIdx++}::timestamptz`),values.push(parseSince(options.since));if(options.errorsOnly)conditions.push("event_type LIKE '%error%' OR (details::text LIKE '%error%')");let where=conditions.length>0?`WHERE ${conditions.join(" AND ")}`:"",limit=options.limit??50;return await sql.unsafe(`SELECT id, entity_type, entity_id, event_type, actor, details, created_at
|
|
55
55
|
FROM audit_events ${where}
|
|
56
56
|
ORDER BY created_at DESC
|
|
57
57
|
LIMIT ${limit}`,values)}async function followAuditEvents(options,onEvent){let sql=await getConnection(),seed=await sql`
|
|
58
58
|
SELECT COALESCE(MAX(id), 0)::int AS max_id FROM audit_events
|
|
59
|
-
`,lastSeenId=Number(seed[0]?.max_id??0),active=!0,drainChain=Promise.resolve(),drain=async()=>{if(!active)return;let conditions=["id > $1"],values=[lastSeenId],paramIdx=2;if(options.type)conditions.push(`event_type = $${paramIdx
|
|
59
|
+
`,lastSeenId=Number(seed[0]?.max_id??0),active=!0,drainChain=Promise.resolve(),drain=async()=>{if(!active)return;let conditions=["id > $1"],values=[lastSeenId],paramIdx=2;if(options.type)conditions.push(`(event_type = $${paramIdx} OR entity_type = $${paramIdx})`),paramIdx++,values.push(options.type);if(options.entity)conditions.push(`(entity_type = $${paramIdx} OR entity_id = $${paramIdx})`),paramIdx++,values.push(options.entity);if(options.errorsOnly)conditions.push("(event_type LIKE '%error%' OR details::text LIKE '%error%')");let where=`WHERE ${conditions.join(" AND ")}`,rows=await sql.unsafe(`SELECT id, entity_type, entity_id, event_type, actor, details, created_at
|
|
60
60
|
FROM audit_events ${where}
|
|
61
61
|
ORDER BY id ASC
|
|
62
62
|
LIMIT 200`,values);for(let row of rows)lastSeenId=row.id,onEvent(row)},queueDrain=()=>{drainChain=drainChain.then(drain).catch(()=>{})},listener=await sql.listen("genie_audit_event",()=>{queueDrain()}),pollTimer=setInterval(queueDrain,2000);return await drain(),{stop:async()=>{active=!1,clearInterval(pollTimer),await drainChain,await listener.unlisten()}}}async function queryErrorPatterns(since){let sql=await getConnection(),sinceTs=since?parseSince(since):new Date(Date.now()-86400000).toISOString(),messageExpr=`COALESCE(
|
|
@@ -506,13 +506,13 @@ ${bin} set-option -w pane-active-border-style "fg=$COLOR"
|
|
|
506
506
|
tell.location
|
|
507
507
|
from (select lo_tell64($1) as location) tell
|
|
508
508
|
) seek
|
|
509
|
-
`};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(),open2=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open:open2,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=open2.length?open2.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===open2?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(open2.length)return go(open2.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,open2);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,resetConnection:()=>resetConnection,isConnected:()=>isConnected,isAvailable:()=>isAvailable,getLockfilePath:()=>getLockfilePath,getDataDir:()=>getDataDir,getConnection:()=>getConnection,getActivePort:()=>getActivePort,ensurePgserve:()=>ensurePgserve,autoStartDaemon:()=>autoStartDaemon,__setSpawnDaemonForTest:()=>__setSpawnDaemonForTest});import{execSync as execSync3,spawn}from"child_process";import{existsSync as existsSync13,mkdirSync as mkdirSync6,readFileSync as readFileSync8,renameSync,unlinkSync as unlinkSync3,writeFileSync as writeFileSync5}from"fs";import{homedir as homedir10}from"os";import{join as join15}from"path";function maskCredentials(url){return url.replace(/\/\/.*@/,"//***@")}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=join15(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=readFileSync8(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}`;writeFileSync5(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(`
|
|
509
|
+
`};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(),open2=queue_default(),busy=queue_default(),full=queue_default(),queues={connecting,reserved,closed,ended,open:open2,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=open2.length?open2.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===open2?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(open2.length)return go(open2.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,open2);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,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 readFileSync8,renameSync,unlinkSync as unlinkSync3,writeFileSync as writeFileSync5}from"fs";import{homedir as homedir10}from"os";import{join as join15}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 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=join15(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=readFileSync8(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}`;writeFileSync5(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(`
|
|
510
510
|
DELETE FROM heartbeats WHERE created_at < now() - interval '7 days';
|
|
511
511
|
DELETE FROM machine_snapshots WHERE created_at < now() - interval '30 days';
|
|
512
512
|
DELETE FROM audit_events WHERE entity_type LIKE 'otel_%' AND created_at < now() - interval '30 days';
|
|
513
513
|
DELETE FROM genie_runtime_events WHERE created_at < now() - interval '14 days';
|
|
514
514
|
`),retentionRan=!0}catch(retErr){retentionRan=!0;let msg=retErr instanceof Error?retErr.message:String(retErr);process.stderr.write(`[genie] retention cleanup warning: ${msg}
|
|
515
|
-
`)}}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"],{detached:!0,stdio:"ignore",env:{...process.env}}).unref()})}async function autoStartDaemon(){let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join15(home,"serve.pid"),raw=null;try{raw=readFileSync8(pidPath,"utf-8").trim()}catch{raw=null}if(!raw){lastAutoStartOutcome="missing",lastAutoStartPid=null,spawnDaemon();return}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){try{unlinkSync3(pidPath)}catch{}lastAutoStartOutcome="stale",lastAutoStartPid=null,spawnDaemon();return}let pidAlive=!1;try{process.kill(pid,0),pidAlive=!0}catch{pidAlive=!1}if(pidAlive&&recordedStartTime!==null){let currentStartTime=getProcessStartTime(pid);if(currentStartTime!==null&¤tStartTime===recordedStartTime){lastAutoStartOutcome="alive",lastAutoStartPid=pid;return}}try{unlinkSync3(pidPath)}catch{}lastAutoStartOutcome="stale",lastAutoStartPid=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 _ensurePgserve(){if(activePort!==null)return activePort;let port=getPort(),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;if(process.env.CI==="true")throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve not available in CI");if(process.env.GENIE_IS_DAEMON==="1"){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)}`)}}await autoStartDaemon();let outcomeAtStart=lastAutoStartOutcome,pidAtStart=lastAutoStartPid,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))}process.env.GENIE_PG_AVAILABLE="false";let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join15(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`)}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync13(resolved))return resolved}catch{}let globalBin=join15(homedir10(),".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;return sqlClient=null,activePort=null,dying.end({timeout:5}).catch(()=>{}),null}}async function runPostConnectSetup(client,testSchema,timings){let _t2=Date.now();if(!testSchema)await runMigrations(client);let _t3=Date.now();if(!testSchema&&needsSeed())await runSeed(client);let _t4=Date.now();if(!testSchema&&!retentionRan)await runRetention(client);let _t5=Date.now();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=${_t5-_t4}ms 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,testSchema=process.env.GENIE_TEST_SCHEMA;sqlClient=pgModule({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:50,idle_timeout:1,connect_timeout:5,onnotice:()=>{},connection:{client_min_messages:"warning",...testSchema?{search_path:`${testSchema}, public`}:{}}});try{await runPostConnectSetup(sqlClient,testSchema,{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",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"],{detached:!0,stdio:"ignore",env:{...process.env}}).unref()};var init_db=__esm(()=>{init_db_migrations();init_pg_seed();init_process_identity();GENIE_HOME=process.env.GENIE_HOME??join15(homedir10(),".genie"),DATA_DIR=join15(GENIE_HOME,"data","pgserve"),LOCKFILE_PATH=join15(GENIE_HOME,"pgserve.port")});import{createHmac as createHmac2}from"crypto";import{homedir as homedir11}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=homedir11(),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_audit_export={};__export(exports_audit_export,{schema:()=>schema3,TYPE:()=>TYPE2,SCHEMA_VERSION:()=>SCHEMA_VERSION2,KIND:()=>KIND2,DEFAULT_TIER:()=>DEFAULT_TIER});var SCHEMA_VERSION2=1,TYPE2="audit.export",KIND2="event",DEFAULT_TIER="audit",ExporterActorSchema,SinceIdSchema,RowCountSchema,BreakCountSchema,BundleSignaturePrefixSchema,TenantIdSchema,ReasonSchema,schema3;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"),schema3=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:()=>schema4,TYPE:()=>TYPE3,SCHEMA_VERSION:()=>SCHEMA_VERSION3,KIND:()=>KIND3,DEFAULT_TIER:()=>DEFAULT_TIER2});var SCHEMA_VERSION3=1,TYPE3="audit.un_hash",KIND3="event",DEFAULT_TIER2="audit",AdminActorSchema,NamespaceSchema,HashedValueSchema,ResolvedMarkerSchema,ReasonSchema2,TicketRefSchema,schema4;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"),schema4=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:()=>schema5,TYPE:()=>TYPE4,SCHEMA_VERSION:()=>SCHEMA_VERSION4,KIND:()=>KIND4});var SCHEMA_VERSION4=1,TYPE4="cache.hit",KIND4="event",CacheSchema,HitSchema,KeyHintSchema,LatencyUsSchema,schema5;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"),schema5=exports_external.object({cache:CacheSchema,hit:HitSchema,key_hint:KeyHintSchema,latency_us:LatencyUsSchema}).strict()});var exports_cache_invalidate={};__export(exports_cache_invalidate,{schema:()=>schema6,TYPE:()=>TYPE5,SCHEMA_VERSION:()=>SCHEMA_VERSION5,KIND:()=>KIND5});var SCHEMA_VERSION5=1,TYPE5="cache.invalidate",KIND5="event",CacheSchema2,KeysInvalidatedSchema,ReasonSchema3,ScopeSchema,schema6;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"),schema6=exports_external.object({cache:CacheSchema2,keys_invalidated:KeysInvalidatedSchema,reason:ReasonSchema3,scope:ScopeSchema}).strict()});var exports_cli_command={};__export(exports_cli_command,{schema:()=>schema7,TYPE:()=>TYPE6,SCHEMA_VERSION:()=>SCHEMA_VERSION6,KIND:()=>KIND6});var SCHEMA_VERSION6=1,TYPE6="cli.command",KIND6="span",CommandSchema,ArgsSchema,CwdSchema2,ExitCodeSchema,DurationSchema2,UserAgentSchema,schema7;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"),schema7=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:()=>schema8,TYPE:()=>TYPE7,SCHEMA_VERSION:()=>SCHEMA_VERSION7,KIND:()=>KIND7});var SCHEMA_VERSION7=1,TYPE7="consumer.heartbeat",KIND7="event",ConsumerIdSchema,LastEventIdSchema,BacklogDepthSchema,RoleSchema,UptimeSecondsSchema,schema8;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"),schema8=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:()=>schema9,TYPE:()=>TYPE8,SCHEMA_VERSION:()=>SCHEMA_VERSION8,KIND:()=>KIND8,DEFAULT_TIER:()=>DEFAULT_TIER3});var SCHEMA_VERSION8=1,TYPE8="consumer.lagged",KIND8="event",DEFAULT_TIER3="audit",CountSchema,SpillPathSchema,SeveritySchema,schema9;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"),schema9=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:()=>schema10,TYPE:()=>TYPE9,SCHEMA_VERSION:()=>SCHEMA_VERSION9,KIND:()=>KIND9});var SCHEMA_VERSION9=1,TYPE9="correlation.orphan.rate",KIND9="event",RateSchema,CountSchema2,schema10;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"),schema10=exports_external.object({window_samples:CountSchema2,orphans:CountSchema2,rate:RateSchema}).strict()});var exports_detector_disabled={};__export(exports_detector_disabled,{schema:()=>schema11,TYPE:()=>TYPE10,SCHEMA_VERSION:()=>SCHEMA_VERSION10,KIND:()=>KIND10});var SCHEMA_VERSION10=1,TYPE10="detector.disabled",KIND10="event",DetectorIdSchema,CauseSchema,BudgetSchema,FireCountSchema,BucketEndTsSchema,schema11;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"),schema11=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:()=>schema12,TYPE:()=>TYPE11,SCHEMA_VERSION:()=>SCHEMA_VERSION11,KIND:()=>KIND11,DEFAULT_TIER:()=>DEFAULT_TIER4});var SCHEMA_VERSION11=1,TYPE11="emit.backpressure.critical",KIND11="event",DEFAULT_TIER4="audit",SecondsSchema,CountSchema3,schema12;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"),schema12=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:()=>schema13,TYPE:()=>TYPE12,SCHEMA_VERSION:()=>SCHEMA_VERSION12,KIND:()=>KIND12});var SCHEMA_VERSION12=1,TYPE12="emitter.latency_p99",KIND12="event",MillisSchema,SampleCountSchema,schema13;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"),schema13=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:()=>schema14,TYPE:()=>TYPE13,SCHEMA_VERSION:()=>SCHEMA_VERSION13,KIND:()=>KIND13});var SCHEMA_VERSION13=1,TYPE13="emitter.queue.depth",KIND13="event",DepthSchema,CapSchema,UtilizationSchema,schema14;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"),schema14=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:()=>schema15,TYPE:()=>TYPE14,SCHEMA_VERSION:()=>SCHEMA_VERSION14,KIND:()=>KIND14});var SCHEMA_VERSION14=1,TYPE14="emitter.rejected",KIND14="event",OffendingTypeSchema,ReasonSchema4,CountSchema4,schema15;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"),schema15=exports_external.object({offending_type:OffendingTypeSchema,reason:ReasonSchema4,count:CountSchema4}).strict()});var exports_emitter_shedding_load={};__export(exports_emitter_shedding_load,{schema:()=>schema16,TYPE:()=>TYPE15,SCHEMA_VERSION:()=>SCHEMA_VERSION15,KIND:()=>KIND15});var SCHEMA_VERSION15=1,TYPE15="emitter.shedding_load",KIND15="event",CountSchema5,schema16;var init_emitter_shedding_load=__esm(()=>{init_zod();CountSchema5=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema16=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:()=>schema17,TYPE:()=>TYPE16,SCHEMA_VERSION:()=>SCHEMA_VERSION16,KIND:()=>KIND16});var SCHEMA_VERSION16=1,TYPE16="error.raised",KIND16="event",ErrorClassSchema,MessageSchema,StackSchema,SubsystemSchema,SeveritySchema2,RetryableSchema,schema17;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(`
|
|
515
|
+
`)}}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"],{detached:!0,stdio:"ignore",env:{...process.env}}).unref()})}async function autoStartDaemon(){let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join15(home,"serve.pid"),raw=null;try{raw=readFileSync8(pidPath,"utf-8").trim()}catch{raw=null}if(!raw){lastAutoStartOutcome="missing",lastAutoStartPid=null,spawnDaemon();return}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){try{unlinkSync3(pidPath)}catch{}lastAutoStartOutcome="stale",lastAutoStartPid=null,spawnDaemon();return}let pidAlive=!1;try{process.kill(pid,0),pidAlive=!0}catch{pidAlive=!1}if(pidAlive&&recordedStartTime!==null){let currentStartTime=getProcessStartTime(pid);if(currentStartTime!==null&¤tStartTime===recordedStartTime){lastAutoStartOutcome="alive",lastAutoStartPid=pid;return}}try{unlinkSync3(pidPath)}catch{}lastAutoStartOutcome="stale",lastAutoStartPid=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 _ensurePgserve(){if(activePort!==null)return activePort;let port=getPort(),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;if(process.env.CI==="true")throw process.env.GENIE_PG_AVAILABLE="false",Error("pgserve not available in CI");let rootErr=checkRootGuard();if(rootErr!==null)throw process.env.GENIE_PG_AVAILABLE="false",Error(rootErr);if(process.env.GENIE_IS_DAEMON==="1"){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)}`)}}await autoStartDaemon();let outcomeAtStart=lastAutoStartOutcome,pidAtStart=lastAutoStartPid,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))}process.env.GENIE_PG_AVAILABLE="false";let home=process.env.GENIE_HOME??GENIE_HOME,pidPath=join15(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`)}function findPgserveBin(){try{let resolved=__require.resolve("pgserve/bin/pgserve-wrapper.cjs");if(existsSync13(resolved))return resolved}catch{}let globalBin=join15(homedir10(),".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;return sqlClient=null,activePort=null,dying.end({timeout:5}).catch(()=>{}),null}}async function runPostConnectSetup(client,testSchema,timings){let _t2=Date.now();if(!testSchema)await runMigrations(client);let _t3=Date.now();if(!testSchema&&needsSeed())await runSeed(client);let _t4=Date.now();if(!testSchema&&!retentionRan)await runRetention(client);let _t5=Date.now();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=${_t5-_t4}ms 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,testSchema=process.env.GENIE_TEST_SCHEMA;sqlClient=pgModule({host:DEFAULT_HOST,port,database:DB_NAME,username:"postgres",password:"postgres",max:50,idle_timeout:1,connect_timeout:5,onnotice:()=>{},connection:{client_min_messages:"warning",...testSchema?{search_path:`${testSchema}, public`}:{}}});try{await runPostConnectSetup(sqlClient,testSchema,{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",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"],{detached:!0,stdio:"ignore",env:{...process.env}}).unref()};var init_db=__esm(()=>{init_db_migrations();init_pg_seed();init_process_identity();GENIE_HOME=process.env.GENIE_HOME??join15(homedir10(),".genie"),DATA_DIR=join15(GENIE_HOME,"data","pgserve"),LOCKFILE_PATH=join15(GENIE_HOME,"pgserve.port")});import{createHmac as createHmac2}from"crypto";import{homedir as homedir11}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=homedir11(),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_audit_export={};__export(exports_audit_export,{schema:()=>schema3,TYPE:()=>TYPE2,SCHEMA_VERSION:()=>SCHEMA_VERSION2,KIND:()=>KIND2,DEFAULT_TIER:()=>DEFAULT_TIER});var SCHEMA_VERSION2=1,TYPE2="audit.export",KIND2="event",DEFAULT_TIER="audit",ExporterActorSchema,SinceIdSchema,RowCountSchema,BreakCountSchema,BundleSignaturePrefixSchema,TenantIdSchema,ReasonSchema,schema3;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"),schema3=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:()=>schema4,TYPE:()=>TYPE3,SCHEMA_VERSION:()=>SCHEMA_VERSION3,KIND:()=>KIND3,DEFAULT_TIER:()=>DEFAULT_TIER2});var SCHEMA_VERSION3=1,TYPE3="audit.un_hash",KIND3="event",DEFAULT_TIER2="audit",AdminActorSchema,NamespaceSchema,HashedValueSchema,ResolvedMarkerSchema,ReasonSchema2,TicketRefSchema,schema4;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"),schema4=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:()=>schema5,TYPE:()=>TYPE4,SCHEMA_VERSION:()=>SCHEMA_VERSION4,KIND:()=>KIND4});var SCHEMA_VERSION4=1,TYPE4="cache.hit",KIND4="event",CacheSchema,HitSchema,KeyHintSchema,LatencyUsSchema,schema5;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"),schema5=exports_external.object({cache:CacheSchema,hit:HitSchema,key_hint:KeyHintSchema,latency_us:LatencyUsSchema}).strict()});var exports_cache_invalidate={};__export(exports_cache_invalidate,{schema:()=>schema6,TYPE:()=>TYPE5,SCHEMA_VERSION:()=>SCHEMA_VERSION5,KIND:()=>KIND5});var SCHEMA_VERSION5=1,TYPE5="cache.invalidate",KIND5="event",CacheSchema2,KeysInvalidatedSchema,ReasonSchema3,ScopeSchema,schema6;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"),schema6=exports_external.object({cache:CacheSchema2,keys_invalidated:KeysInvalidatedSchema,reason:ReasonSchema3,scope:ScopeSchema}).strict()});var exports_cli_command={};__export(exports_cli_command,{schema:()=>schema7,TYPE:()=>TYPE6,SCHEMA_VERSION:()=>SCHEMA_VERSION6,KIND:()=>KIND6});var SCHEMA_VERSION6=1,TYPE6="cli.command",KIND6="span",CommandSchema,ArgsSchema,CwdSchema2,ExitCodeSchema,DurationSchema2,UserAgentSchema,schema7;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"),schema7=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:()=>schema8,TYPE:()=>TYPE7,SCHEMA_VERSION:()=>SCHEMA_VERSION7,KIND:()=>KIND7});var SCHEMA_VERSION7=1,TYPE7="consumer.heartbeat",KIND7="event",ConsumerIdSchema,LastEventIdSchema,BacklogDepthSchema,RoleSchema,UptimeSecondsSchema,schema8;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"),schema8=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:()=>schema9,TYPE:()=>TYPE8,SCHEMA_VERSION:()=>SCHEMA_VERSION8,KIND:()=>KIND8,DEFAULT_TIER:()=>DEFAULT_TIER3});var SCHEMA_VERSION8=1,TYPE8="consumer.lagged",KIND8="event",DEFAULT_TIER3="audit",CountSchema,SpillPathSchema,SeveritySchema,schema9;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"),schema9=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:()=>schema10,TYPE:()=>TYPE9,SCHEMA_VERSION:()=>SCHEMA_VERSION9,KIND:()=>KIND9});var SCHEMA_VERSION9=1,TYPE9="correlation.orphan.rate",KIND9="event",RateSchema,CountSchema2,schema10;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"),schema10=exports_external.object({window_samples:CountSchema2,orphans:CountSchema2,rate:RateSchema}).strict()});var exports_detector_disabled={};__export(exports_detector_disabled,{schema:()=>schema11,TYPE:()=>TYPE10,SCHEMA_VERSION:()=>SCHEMA_VERSION10,KIND:()=>KIND10});var SCHEMA_VERSION10=1,TYPE10="detector.disabled",KIND10="event",DetectorIdSchema,CauseSchema,BudgetSchema,FireCountSchema,BucketEndTsSchema,schema11;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"),schema11=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:()=>schema12,TYPE:()=>TYPE11,SCHEMA_VERSION:()=>SCHEMA_VERSION11,KIND:()=>KIND11,DEFAULT_TIER:()=>DEFAULT_TIER4});var SCHEMA_VERSION11=1,TYPE11="emit.backpressure.critical",KIND11="event",DEFAULT_TIER4="audit",SecondsSchema,CountSchema3,schema12;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"),schema12=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:()=>schema13,TYPE:()=>TYPE12,SCHEMA_VERSION:()=>SCHEMA_VERSION12,KIND:()=>KIND12});var SCHEMA_VERSION12=1,TYPE12="emitter.latency_p99",KIND12="event",MillisSchema,SampleCountSchema,schema13;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"),schema13=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:()=>schema14,TYPE:()=>TYPE13,SCHEMA_VERSION:()=>SCHEMA_VERSION13,KIND:()=>KIND13});var SCHEMA_VERSION13=1,TYPE13="emitter.queue.depth",KIND13="event",DepthSchema,CapSchema,UtilizationSchema,schema14;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"),schema14=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:()=>schema15,TYPE:()=>TYPE14,SCHEMA_VERSION:()=>SCHEMA_VERSION14,KIND:()=>KIND14});var SCHEMA_VERSION14=1,TYPE14="emitter.rejected",KIND14="event",OffendingTypeSchema,ReasonSchema4,CountSchema4,schema15;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"),schema15=exports_external.object({offending_type:OffendingTypeSchema,reason:ReasonSchema4,count:CountSchema4}).strict()});var exports_emitter_shedding_load={};__export(exports_emitter_shedding_load,{schema:()=>schema16,TYPE:()=>TYPE15,SCHEMA_VERSION:()=>SCHEMA_VERSION15,KIND:()=>KIND15});var SCHEMA_VERSION15=1,TYPE15="emitter.shedding_load",KIND15="event",CountSchema5,schema16;var init_emitter_shedding_load=__esm(()=>{init_zod();CountSchema5=tagTier(exports_external.number().int().min(0).max(1e7),"C"),schema16=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:()=>schema17,TYPE:()=>TYPE16,SCHEMA_VERSION:()=>SCHEMA_VERSION16,KIND:()=>KIND16});var SCHEMA_VERSION16=1,TYPE16="error.raised",KIND16="event",ErrorClassSchema,MessageSchema,StackSchema,SubsystemSchema,SeveritySchema2,RetryableSchema,schema17;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(`
|
|
516
516
|
`).map((line)=>tokenizePath(redactFreeText(line))).join(`
|
|
517
517
|
`)),"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"),schema17=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:()=>schema18,TYPE:()=>TYPE17,SCHEMA_VERSION:()=>SCHEMA_VERSION17,KIND:()=>KIND17});var SCHEMA_VERSION17=1,TYPE17="executor.row.written",KIND17="event",TableSchema,RowIdSchema,OperationSchema,ExecutorSchema2,DiffSchema,schema18;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"),schema18=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:()=>schema19,TYPE:()=>TYPE18,SCHEMA_VERSION:()=>SCHEMA_VERSION18,KIND:()=>KIND18});var SCHEMA_VERSION18=1,TYPE18="executor.write",KIND18="span",ExecutorSchema3,TargetSchema,TableSchema2,OperationSchema2,RowsAffectedSchema,DurationSchema3,OutcomeSchema,ErrorHintSchema,schema19;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"),schema19=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:()=>schema20,TYPE:()=>TYPE19,SCHEMA_VERSION:()=>SCHEMA_VERSION19,KIND:()=>KIND19});var SCHEMA_VERSION19=1,TYPE19="hook.delivery",KIND19="span",HookNameSchema,AgentIdSchema2,ToolSchema,StatusSchema,DurationSchema4,ExitCodeSchema2,StderrExcerptSchema,schema20;var init_hook_delivery=__esm(()=>{init_zod();init_redactors();HookNameSchema=tagTier(exports_external.string().min(1).max(128),"C","hook 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"),schema20=exports_external.object({hook_name:HookNameSchema,agent_id:AgentIdSchema2,tool:ToolSchema,status:StatusSchema,duration_ms:DurationSchema4,exit_code:ExitCodeSchema2,stderr_excerpt:StderrExcerptSchema}).strict()});var exports_mailbox_delivery={};__export(exports_mailbox_delivery,{schema:()=>schema21,TYPE:()=>TYPE20,SCHEMA_VERSION:()=>SCHEMA_VERSION20,KIND:()=>KIND20});var SCHEMA_VERSION20=1,TYPE20="mailbox.delivery",KIND20="span",AgentIdSchema3=(ns)=>tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity(ns,v)),"A"),FromSchema,ToSchema,ChannelSchema,OutcomeSchema2,MessageIdSchema,BodyExcerptSchema,DurationSchema5,schema21;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"),schema21=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:()=>schema22,TYPE:()=>TYPE21,SCHEMA_VERSION:()=>SCHEMA_VERSION21,KIND:()=>KIND21});var SCHEMA_VERSION21=1,TYPE21="notify.delivery.lag",KIND21="event",NonceSchema,LagMillisSchema,ChannelSchema2,schema22;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"),schema22=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:()=>schema23,TYPE:()=>TYPE22,SCHEMA_VERSION:()=>SCHEMA_VERSION22,KIND:()=>KIND22});var SCHEMA_VERSION22=1,TYPE22="permissions.deny",KIND22="event",ActorSchema,AttemptedRoleSchema,ScopeSchema2,ReasonSchema5,SourceIpSchema,schema23;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"),schema23=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:()=>schema24,TYPE:()=>TYPE23,SCHEMA_VERSION:()=>SCHEMA_VERSION23,KIND:()=>KIND23});var SCHEMA_VERSION23=1,TYPE23="permissions.grant",KIND23="event",ActorSchema2,RoleSchema2,ScopeSchema3,ExpiresAtSchema,GrantedBySchema,schema24;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"),schema24=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:()=>schema25,TYPE:()=>TYPE24,SCHEMA_VERSION:()=>SCHEMA_VERSION24,KIND:()=>KIND24});var SCHEMA_VERSION24=1,TYPE24="resume.attempt",KIND24="span",AgentIdSchema4,AttemptNumberSchema,StrategySchema,SessionIdSchema2,SucceededSchema,FailureReasonSchema,DurationSchema6,schema25;var init_resume_attempt=__esm(()=>{init_zod();init_redactors();AgentIdSchema4=tagTier(exports_external.string().min(1).max(256).transform((v)=>hashEntity("agent",v)),"A"),AttemptNumberSchema=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"),schema25=exports_external.object({agent_id:AgentIdSchema4,attempt_number:AttemptNumberSchema,strategy:StrategySchema,session_id:SessionIdSchema2,succeeded:SucceededSchema,failure_reason:FailureReasonSchema,duration_ms:DurationSchema6}).strict()});var exports_rot_detected={};__export(exports_rot_detected,{schema:()=>schema26,TYPE:()=>TYPE25,SCHEMA_VERSION:()=>SCHEMA_VERSION25,KIND:()=>KIND25});var SCHEMA_VERSION25=1,TYPE25="rot.detected",KIND25="event",PatternIdSchema,EntityIdSchema,ObservedValueSchema,ObservedStateSchema,schema26;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"),EntityIdSchema=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"),schema26=exports_external.object({pattern_id:PatternIdSchema,entity_id:EntityIdSchema,observed_state_json:ObservedStateSchema}).strict()});var exports_rot_executor_ghost_detected={};__export(exports_rot_executor_ghost_detected,{schema:()=>schema27,TYPE:()=>TYPE26,SCHEMA_VERSION:()=>SCHEMA_VERSION26,KIND:()=>KIND26});var SCHEMA_VERSION26=1,TYPE26="rot.executor-ghost.detected",KIND26="event",ResolutionSourceSchema,EnvIdSchema,ResolvedIdSchema,AgentNameSchema,RecoveredSchema,schema27;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"),schema27=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:()=>schema28,TYPE:()=>TYPE27,SCHEMA_VERSION:()=>SCHEMA_VERSION27,KIND:()=>KIND27});var SCHEMA_VERSION27=1,TYPE27="rot.inbox-watcher-spawn-loop.detected",KIND27="event",TeamNameSchema,SessionKeySchema,FailureCountSchema,LastErrorMessageSchema,schema28;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"),schema28=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:()=>schema29,TYPE:()=>TYPE28,SCHEMA_VERSION:()=>SCHEMA_VERSION28,KIND:()=>KIND28});var SCHEMA_VERSION28=1,TYPE28="rot.team-ls-drift.detected",KIND28="event",DivergenceKindSchema,DivergentCountSchema,ObservedStateJsonSchema,schema29;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"),schema29=exports_external.object({divergence_kind:DivergenceKindSchema,divergent_count:DivergentCountSchema,observed_state_json:ObservedStateJsonSchema}).strict()});var exports_runbook_triggered={};__export(exports_runbook_triggered,{schema:()=>schema30,TYPE:()=>TYPE29,SCHEMA_VERSION:()=>SCHEMA_VERSION29,KIND:()=>KIND29});var SCHEMA_VERSION29=1,TYPE29="runbook.triggered",KIND29="event",RuleSchema,EvidenceCountSchema,CorrelationIdSchema,WindowMinutesSchema,RecommendedSqlSchema,EvidenceSummarySchema,schema30;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"),schema30=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:()=>schema31,TYPE:()=>TYPE30,SCHEMA_VERSION:()=>SCHEMA_VERSION30,KIND:()=>KIND30});var SCHEMA_VERSION30=1,TYPE30="schema.violation",KIND30="event",OffendingTypeSchema2,RejectedBytesSchema,IssueSchema,schema31;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"),schema31=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:()=>schema32,TYPE:()=>TYPE31,SCHEMA_VERSION:()=>SCHEMA_VERSION31,KIND:()=>KIND31});var SCHEMA_VERSION31=1,TYPE31="session.id.written",KIND31="event",AgentIdSchema5,SessionIdSchema3,ExecutorSchema4,OriginSchema,DiffSchema2,schema32;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"),schema32=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:()=>schema33,TYPE:()=>TYPE32,SCHEMA_VERSION:()=>SCHEMA_VERSION32,KIND:()=>KIND32});var SCHEMA_VERSION32=1,TYPE32="session.reconciled",KIND32="event",AgentIdSchema6,SessionIdSchema4,ReasonSchema6,DiffSchema3,schema33;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"),schema33=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:()=>schema34,TYPE:()=>TYPE33,SCHEMA_VERSION:()=>SCHEMA_VERSION33,KIND:()=>KIND33});var SCHEMA_VERSION33=1,TYPE33="state_transition",KIND33="event",EntityKindSchema,EntityIdSchema2,FromSchema2,ToSchema2,ReasonSchema7,ActorSchema3,DiffSchema4,schema34;var init_state_transition=__esm(()=>{init_zod();init_redactors();EntityKindSchema=tagTier(exports_external.enum(["task","wish","worker","team","team_lead","group","mailbox_message"]),"C"),EntityIdSchema2=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"),schema34=exports_external.object({entity_kind:EntityKindSchema,entity_id:EntityIdSchema2,from:FromSchema2,to:ToSchema2,reason:ReasonSchema7,actor:ActorSchema3,before:DiffSchema4,after:DiffSchema4}).strict()});var exports_stream_gap_detected={};__export(exports_stream_gap_detected,{schema:()=>schema35,TYPE:()=>TYPE34,SCHEMA_VERSION:()=>SCHEMA_VERSION34,KIND:()=>KIND34});var SCHEMA_VERSION34=1,TYPE34="stream.gap.detected",KIND34="event",ConsumerIdSchema2,IdSchema,CountSchema6,schema35;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"),schema35=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:()=>schema36,TYPE:()=>TYPE35,SCHEMA_VERSION:()=>SCHEMA_VERSION35,KIND:()=>KIND35,DEFAULT_TIER:()=>DEFAULT_TIER5});var SCHEMA_VERSION35=1,TYPE35="team.create",KIND35="event",DEFAULT_TIER5="audit",TeamNameSchema2,WishSlugSchema,RepoPathHashSchema,ActorSchema4,MemberCountSchema,AutoSchema,schema36;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"),schema36=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:()=>schema37,TYPE:()=>TYPE36,SCHEMA_VERSION:()=>SCHEMA_VERSION36,KIND:()=>KIND36,DEFAULT_TIER:()=>DEFAULT_TIER6});var SCHEMA_VERSION36=1,TYPE36="team.disband",KIND36="event",DEFAULT_TIER6="audit",TeamNameSchema3,ActorSchema5,RemainingMembersSchema,ReasonSchema8,schema37;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"),schema37=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:()=>schema38,TYPE:()=>TYPE37,SCHEMA_VERSION:()=>SCHEMA_VERSION37,KIND:()=>KIND37});var SCHEMA_VERSION37=1,TYPE37="tmux.pane.placed",KIND37="event",AgentIdSchema7,SessionSchema,WindowIndexSchema,PaneIndexSchema,PaneIdSchema,ActionSchema,schema38;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"),schema38=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:()=>schema39,TYPE:()=>TYPE38,SCHEMA_VERSION:()=>SCHEMA_VERSION38,KIND:()=>KIND38});var SCHEMA_VERSION38=1,TYPE38="wish.dispatch",KIND38="span",WishSlugSchema2,WaveSchema,GroupIdSchema,GroupNameSchema,ActorSchema6,OutcomeSchema3,DurationSchema7,DryRunSchema,schema39;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"),schema39=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_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={[TYPE6]:entry(exports_cli_command),[TYPE]:entry(exports_agent_lifecycle),[TYPE38]:entry(exports_wish_dispatch),[TYPE19]:entry(exports_hook_delivery),[TYPE24]:entry(exports_resume_attempt),[TYPE18]:entry(exports_executor_write),[TYPE20]:entry(exports_mailbox_delivery),[TYPE16]:entry(exports_error_raised),[TYPE33]:entry(exports_state_transition),[TYPE30]:entry(exports_schema_violation),[TYPE31]:entry(exports_session_id_written),[TYPE32]:entry(exports_session_reconciled),[TYPE37]:entry(exports_tmux_pane_placed),[TYPE17]:entry(exports_executor_row_written),[TYPE5]:entry(exports_cache_invalidate),[TYPE4]:entry(exports_cache_hit),[TYPE29]:entry(exports_runbook_triggered),[TYPE7]:entry(exports_consumer_heartbeat),[TYPE23]:entry(exports_permissions_grant),[TYPE22]:entry(exports_permissions_deny),[TYPE35]:entry(exports_team_create),[TYPE36]:entry(exports_team_disband),[TYPE3]:entry(exports_audit_un_hash),[TYPE2]:entry(exports_audit_export),[TYPE14]:entry(exports_emitter_rejected),[TYPE13]:entry(exports_emitter_queue_depth),[TYPE12]:entry(exports_emitter_latency_p99),[TYPE21]:entry(exports_notify_delivery_lag),[TYPE34]:entry(exports_stream_gap_detected),[TYPE9]:entry(exports_correlation_orphan_rate),[TYPE15]:entry(exports_emitter_shedding_load),[TYPE8]:entry(exports_consumer_lagged),[TYPE11]:entry(exports_emit_backpressure_critical),[TYPE10]:entry(exports_detector_disabled),[TYPE25]:entry(exports_rot_detected),[TYPE28]:entry(exports_rot_team_ls_drift_detected),[TYPE26]:entry(exports_rot_executor_ghost_detected),[TYPE27]:entry(exports_rot_inbox_watcher_spawn_loop_detected)}});var exports_emit={};__export(exports_emit,{startSpan:()=>startSpan,shutdownEmitter:()=>shutdownEmitter,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 randomUUID4}from"crypto";import{appendFileSync,closeSync,existsSync as existsSync14,fsyncSync,mkdirSync as mkdirSync7,openSync,readFileSync as readFileSync9,renameSync as renameSync2,statSync,unlinkSync as unlinkSync4}from"fs";import{homedir as homedir12}from"os";import{dirname as dirname5,join as join16}from"path";function getEmitStats(){return{...stats,queue_depth:queue.length}}function defaultSpillPath(){let home=process.env.GENIE_HOME??join16(homedir12(),".genie");return join16(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)}
|
|
518
518
|
`,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=readFileSync9(path2,"utf8");if(!contents)return 0;return contents.split(`
|
|
@@ -3700,7 +3700,7 @@ Registering in Omni (${omniUrl})...`);let existingId=await findOmniAgent(name);i
|
|
|
3700
3700
|
text,
|
|
3701
3701
|
data,
|
|
3702
3702
|
created_at::text AS created_at
|
|
3703
|
-
`;function
|
|
3703
|
+
`;function kindFilterToLikePatterns(input){let escaped=input.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_");if(escaped.includes("*"))return[escaped.replace(/\*/g,"%")];if(escaped.includes("."))return[`${escaped}%`];return[`${escaped}%`,`%.${escaped}.%`,`%.${escaped}`]}function parseSince2(since){let match=since.match(/^(\d+)([smhd])$/);if(!match)return since;let amount=Number.parseInt(match[1],10),unit=match[2],ms={s:1000,m:60000,h:3600000,d:86400000}[unit];return new Date(Date.now()-amount*ms).toISOString()}async function queryV2Batch(filter){let sql=await getConnection(),clauses=[],values2=[],param=(v)=>{return values2.push(v),`$${values2.length}`};if(filter.afterId!=null)clauses.push(`id > ${param(filter.afterId)}`);if(filter.kindPrefix){let ors=kindFilterToLikePatterns(filter.kindPrefix).flatMap((p)=>{let placeholder=param(p);return[`subject LIKE ${placeholder} ESCAPE '\\'`,`kind LIKE ${placeholder} ESCAPE '\\'`]});clauses.push(`(${ors.join(" OR ")})`)}if(filter.severity)clauses.push(`(COALESCE(severity, data->>'_severity') = ${param(filter.severity)})`);if(filter.since)clauses.push(`created_at >= ${param(parseSince2(filter.since))}::timestamptz`);let limit=filter.limit??500,where=clauses.length>0?`WHERE ${clauses.join(" AND ")}`:"",rows=await sql.unsafe(`SELECT ${V2_SELECT}
|
|
3704
3704
|
FROM genie_runtime_events
|
|
3705
3705
|
${where}
|
|
3706
3706
|
ORDER BY id ASC
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "genie",
|
|
3
|
-
"version": "4.260421.
|
|
3
|
+
"version": "4.260421.25",
|
|
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"
|